From 01936b346098e4c603f035622dfd24846ac5cb52 Mon Sep 17 00:00:00 2001 From: Serban Iorga Date: Wed, 30 Oct 2024 18:20:09 +0200 Subject: [PATCH 001/166] Publish `polkadot-omni-node` binary (#6057) Closes https://github.com/paritytech/polkadot-sdk/issues/5566 Publish the `polkadot-omni-node` binary This is a best effort. I'm not very familiar with the release / publishing process and also not sure how to test this. @paritytech/release-engineering can you take a look on this PR please ? --------- Co-authored-by: EgorPopelyaev --- .../release-30_publish_release_draft.yml | 6 +-- .../workflows/release-50_publish-docker.yml | 41 ++++++++++--------- .../polkadot-omni-node/build-injected.sh | 14 +++++++ 3 files changed, 38 insertions(+), 23 deletions(-) create mode 100755 docker/scripts/polkadot-omni-node/build-injected.sh diff --git a/.github/workflows/release-30_publish_release_draft.yml b/.github/workflows/release-30_publish_release_draft.yml index 2a5d92ed167a..73d1aeaa4009 100644 --- a/.github/workflows/release-30_publish_release_draft.yml +++ b/.github/workflows/release-30_publish_release_draft.yml @@ -26,7 +26,7 @@ jobs: build-runtimes: uses: "./.github/workflows/release-srtool.yml" with: - excluded_runtimes: "asset-hub-rococo bridge-hub-rococo contracts-rococo coretime-rococo people-rococo rococo rococo-parachain substrate-test bp cumulus-test kitchensink minimal-template parachain-template penpal polkadot-test seedling shell frame-try sp solochain-template" + excluded_runtimes: "asset-hub-rococo bridge-hub-rococo contracts-rococo coretime-rococo people-rococo rococo rococo-parachain substrate-test bp cumulus-test kitchensink minimal-template parachain-template penpal polkadot-test seedling shell frame-try sp solochain-template polkadot-sdk-docs-first" build_opts: "--features on-chain-release-build" build-binaries: @@ -34,7 +34,7 @@ jobs: strategy: matrix: # Tuples of [package, binary-name] - binary: [ [frame-omni-bencher, frame-omni-bencher], [staging-chain-spec-builder, chain-spec-builder] ] + binary: [ [frame-omni-bencher, frame-omni-bencher], [staging-chain-spec-builder, chain-spec-builder], [polkadot-omni-node, polkadot-omni-node] ] steps: - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.0.0 @@ -161,7 +161,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - binary: [frame-omni-bencher, chain-spec-builder] + binary: [frame-omni-bencher, chain-spec-builder, polkadot-omni-node] steps: - name: Download artifacts diff --git a/.github/workflows/release-50_publish-docker.yml b/.github/workflows/release-50_publish-docker.yml index 6e0e8f20aa5e..211fa000f8f5 100644 --- a/.github/workflows/release-50_publish-docker.yml +++ b/.github/workflows/release-50_publish-docker.yml @@ -26,6 +26,7 @@ on: type: choice options: - polkadot + - polkadot-omni-node - polkadot-parachain - chain-spec-builder @@ -80,9 +81,9 @@ jobs: validate-inputs: runs-on: ubuntu-latest outputs: - version: ${{ steps.validate_inputs.outputs.VERSION }} - release_id: ${{ steps.validate_inputs.outputs.RELEASE_ID }} - stable_tag: ${{ steps.validate_inputs.outputs.stable_tag }} + version: ${{ steps.validate_inputs.outputs.VERSION }} + release_id: ${{ steps.validate_inputs.outputs.RELEASE_ID }} + stable_tag: ${{ steps.validate_inputs.outputs.stable_tag }} steps: - name: Checkout sources @@ -105,15 +106,15 @@ jobs: echo "stable_tag=${STABLE_TAG}" >> $GITHUB_OUTPUT fetch-artifacts: # this job will be triggered for the polkadot-parachain rc and release or polkadot rc image build - if: ${{ inputs.binary == 'polkadot-parachain' || inputs.binary == 'chain-spec-builder' || inputs.image_type == 'rc' }} + if: ${{ inputs.binary == 'polkadot-omni-node' || inputs.binary == 'polkadot-parachain' || inputs.binary == 'chain-spec-builder' || inputs.image_type == 'rc' }} runs-on: ubuntu-latest - needs: [validate-inputs] + needs: [ validate-inputs ] steps: - name: Checkout sources uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 - #TODO: this step will be needed when automated triggering will work + #TODO: this step will be needed when automated triggering will work #this step runs only if the workflow is triggered automatically when new release is published # if: ${{ env.EVENT_NAME == 'release' && env.EVENT_ACTION != '' && env.EVENT_ACTION == 'published' }} # run: | @@ -129,7 +130,7 @@ jobs: - name: Fetch rc artifacts or release artifacts from s3 based on version #this step runs only if the workflow is triggered manually - if: ${{ env.EVENT_NAME == 'workflow_dispatch' && inputs.binary != 'chain-spec-builder'}} + if: ${{ env.EVENT_NAME == 'workflow_dispatch' && inputs.binary != 'polkadot-omni-node' && inputs.binary != 'chain-spec-builder'}} run: | . ./.github/scripts/common/lib.sh @@ -143,9 +144,9 @@ jobs: fetch_release_artifacts_from_s3 $BINARY fi - - name: Fetch chain-spec-builder rc artifacts or release artifacts based on release id + - name: Fetch polkadot-omni-node/chain-spec-builder rc artifacts or release artifacts based on release id #this step runs only if the workflow is triggered manually and only for chain-spec-builder - if: ${{ env.EVENT_NAME == 'workflow_dispatch' && inputs.binary == 'chain-spec-builder' }} + if: ${{ env.EVENT_NAME == 'workflow_dispatch' && (inputs.binary == 'polkadot-omni-node' || inputs.binary == 'chain-spec-builder') }} run: | . ./.github/scripts/common/lib.sh @@ -159,9 +160,9 @@ jobs: path: release-artifacts/${{ env.BINARY }}/**/* build-container: # this job will be triggered for the polkadot-parachain rc and release or polkadot rc image build - if: ${{ inputs.binary == 'polkadot-parachain' || inputs.binary == 'chain-spec-builder' || inputs.image_type == 'rc' }} + if: ${{ inputs.binary == 'polkadot-omni-node' || inputs.binary == 'polkadot-parachain' || inputs.binary == 'chain-spec-builder' || inputs.image_type == 'rc' }} runs-on: ubuntu-latest - needs: [fetch-artifacts, validate-inputs] + needs: [ fetch-artifacts, validate-inputs ] environment: release steps: @@ -231,8 +232,8 @@ jobs: echo "Building container for $BINARY" ./docker/scripts/polkadot/build-injected.sh $ARTIFACTS_FOLDER - - name: Build Injected Container image chain-spec-builder - if: ${{ env.BINARY == 'chain-spec-builder' }} + - name: Build Injected Container image for polkadot-omni-node/chain-spec-builder + if: ${{ env.BINARY == 'polkadot-omni-node' || env.BINARY == 'chain-spec-builder' }} env: ARTIFACTS_FOLDER: release-artifacts IMAGE_NAME: ${{ env.BINARY }} @@ -266,8 +267,8 @@ jobs: username: ${{ secrets.POLKADOT_DOCKERHUB_USERNAME }} password: ${{ secrets.POLKADOT_DOCKERHUB_TOKEN }} - - name: Login to Dockerhub to puiblish polkadot-parachain/chain-spec-builder - if: ${{ env.BINARY == 'polkadot-parachain' || env.BINARY == 'chain-spec-builder' }} + - name: Login to Dockerhub to publish polkadot-omni-node/polkadot-parachain/chain-spec-builder + if: ${{ env.BINARY == 'polkadot-omni-node' || env.BINARY == 'polkadot-parachain' || env.BINARY == 'chain-spec-builder' }} uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0 with: username: ${{ secrets.CUMULUS_DOCKERHUB_USERNAME }} @@ -315,7 +316,7 @@ jobs: build-polkadot-release-container: # this job will be triggered for polkadot release build if: ${{ inputs.binary == 'polkadot' && inputs.image_type == 'release' }} runs-on: ubuntu-latest - needs: [fetch-latest-debian-package-version, validate-inputs] + needs: [ fetch-latest-debian-package-version, validate-inputs ] environment: release steps: - name: Checkout sources @@ -327,10 +328,10 @@ jobs: - name: Cache Docker layers uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 with: - path: /tmp/.buildx-cache - key: ${{ runner.os }}-buildx-${{ github.sha }} - restore-keys: | - ${{ runner.os }}-buildx- + path: /tmp/.buildx-cache + key: ${{ runner.os }}-buildx-${{ github.sha }} + restore-keys: | + ${{ runner.os }}-buildx- - name: Login to Docker Hub uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0 diff --git a/docker/scripts/polkadot-omni-node/build-injected.sh b/docker/scripts/polkadot-omni-node/build-injected.sh new file mode 100755 index 000000000000..a39621bac3d6 --- /dev/null +++ b/docker/scripts/polkadot-omni-node/build-injected.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash + +# Sample call: +# $0 /path/to/folder_with_binary +# This script replace the former dedicated Dockerfile +# and shows how to use the generic binary_injected.dockerfile + +PROJECT_ROOT=`git rev-parse --show-toplevel` + +export BINARY=polkadot-omni-node +export ARTIFACTS_FOLDER=$1 +# export TAGS=... + +$PROJECT_ROOT/docker/scripts/build-injected.sh From 2b6b69641ccff4d7aa9c32051bbb2f1e775ef8cc Mon Sep 17 00:00:00 2001 From: Cyrill Leutwiler Date: Wed, 30 Oct 2024 22:56:40 +0100 Subject: [PATCH 002/166] [pallet-revive] implement the block hash API (#6246) - Bound T::Hash to H256 - Implement the block hash API --------- Signed-off-by: xermicus Signed-off-by: Cyrill Leutwiler Co-authored-by: command-bot <> Co-authored-by: GitHub Action --- prdoc/pr_6246.prdoc | 13 + .../revive/fixtures/contracts/block_hash.rs | 37 + .../revive/src/benchmarking/call_builder.rs | 4 +- .../frame/revive/src/benchmarking/mod.rs | 27 + substrate/frame/revive/src/evm/runtime.rs | 4 +- substrate/frame/revive/src/exec.rs | 86 +- substrate/frame/revive/src/lib.rs | 3 + substrate/frame/revive/src/tests.rs | 25 + substrate/frame/revive/src/wasm/mod.rs | 15 +- substrate/frame/revive/src/wasm/runtime.rs | 24 + substrate/frame/revive/src/weights.rs | 825 +++++++++--------- substrate/frame/revive/uapi/src/host.rs | 8 + .../frame/revive/uapi/src/host/riscv32.rs | 5 + 13 files changed, 664 insertions(+), 412 deletions(-) create mode 100644 prdoc/pr_6246.prdoc create mode 100644 substrate/frame/revive/fixtures/contracts/block_hash.rs diff --git a/prdoc/pr_6246.prdoc b/prdoc/pr_6246.prdoc new file mode 100644 index 000000000000..3fc268749f37 --- /dev/null +++ b/prdoc/pr_6246.prdoc @@ -0,0 +1,13 @@ +title: '[pallet-revive] implement the block hash API' +doc: +- audience: Runtime Dev + description: |- + - Bound T::Hash to H256 + - Implement the block hash API +crates: +- name: pallet-revive + bump: major +- name: pallet-revive-fixtures + bump: major +- name: pallet-revive-uapi + bump: major diff --git a/substrate/frame/revive/fixtures/contracts/block_hash.rs b/substrate/frame/revive/fixtures/contracts/block_hash.rs new file mode 100644 index 000000000000..1331c4601463 --- /dev/null +++ b/substrate/frame/revive/fixtures/contracts/block_hash.rs @@ -0,0 +1,37 @@ +// 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] + +use common::input; +use uapi::{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!(block_number: &[u8; 32], block_hash: &[u8; 32],); + + let mut buf = [0; 32]; + api::block_hash(block_number, &mut &mut buf); + + assert_eq!(&buf[..], block_hash); +} diff --git a/substrate/frame/revive/src/benchmarking/call_builder.rs b/substrate/frame/revive/src/benchmarking/call_builder.rs index 8a859a3a5089..c666383abb2f 100644 --- a/substrate/frame/revive/src/benchmarking/call_builder.rs +++ b/substrate/frame/revive/src/benchmarking/call_builder.rs @@ -26,7 +26,7 @@ use crate::{ }; use alloc::{vec, vec::Vec}; use frame_benchmarking::benchmarking; -use sp_core::U256; +use sp_core::{H256, U256}; type StackExt<'a, T> = Stack<'a, T, WasmBlob>; @@ -48,6 +48,7 @@ where T: Config + pallet_balances::Config, BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { fn default() -> Self { Self::new(WasmModule::dummy()) @@ -59,6 +60,7 @@ where T: Config + pallet_balances::Config, BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { /// Setup a new call for the given module. pub fn new(module: WasmModule) -> Self { diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index 1ca4f4e1fb80..dd7e52327b66 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -71,6 +71,7 @@ where T: Config + pallet_balances::Config, BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { /// Create new contract and use a default account id as instantiator. fn new(module: WasmModule, data: Vec) -> Result, &'static str> { @@ -224,6 +225,7 @@ fn default_deposit_limit() -> BalanceOf { ::RuntimeEvent: From>, ::RuntimeCall: From>, as Currency>::Balance: From>, + ::Hash: frame_support::traits::IsType, )] mod benchmarks { use super::*; @@ -783,6 +785,31 @@ mod benchmarks { assert_eq!(U256::from_little_endian(&memory[..]), runtime.ext().block_number()); } + #[benchmark(pov_mode = Measured)] + fn seal_block_hash() { + let mut memory = vec![0u8; 64]; + let mut setup = CallSetup::::default(); + let input = setup.data(); + let (mut ext, _) = setup.ext(); + ext.set_block_number(BlockNumberFor::::from(1u32)); + + let mut runtime = crate::wasm::Runtime::<_, [u8]>::new(&mut ext, input); + + let block_hash = H256::from([1; 32]); + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(0u32), + T::Hash::from(block_hash), + ); + + let result; + #[block] + { + result = runtime.bench_block_hash(memory.as_mut_slice(), 32, 0); + } + assert_ok!(result); + assert_eq!(&memory[..32], &block_hash.0); + } + #[benchmark(pov_mode = Measured)] fn seal_now() { build_runtime!(runtime, memory: [[0u8;32], ]); diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index bb076da3b3a6..6db3f43857ee 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -27,7 +27,7 @@ use frame_support::{ use pallet_transaction_payment::OnChargeTransaction; use scale_info::{StaticTypeInfo, TypeInfo}; use sp_arithmetic::Percent; -use sp_core::{Get, U256}; +use sp_core::{Get, H256, U256}; use sp_runtime::{ generic::{self, CheckedExtrinsic, ExtrinsicFormat}, traits::{ @@ -121,6 +121,7 @@ where BalanceOf: Into + TryFrom, MomentOf: Into, CallOf: From> + TryInto>, + ::Hash: frame_support::traits::IsType, // required by Checkable for `generic::UncheckedExtrinsic` LookupSource: Member + MaybeDisplay, @@ -290,6 +291,7 @@ pub trait EthExtra { ::RuntimeCall: Dispatchable, OnChargeTransactionBalanceOf: Into>, CallOf: From>, + ::Hash: frame_support::traits::IsType, { let tx = rlp::decode::(&payload).map_err(|err| { log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}"); diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index af11a6c43fb9..4b7198d570c1 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -53,7 +53,7 @@ use sp_core::{ }; use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; use sp_runtime::{ - traits::{BadOrigin, Convert, Dispatchable, Zero}, + traits::{BadOrigin, Convert, Dispatchable, Saturating, Zero}, DispatchError, SaturatedConversion, }; @@ -356,6 +356,10 @@ pub trait Ext: sealing::Sealed { /// Returns the current block number. fn block_number(&self) -> U256; + /// Returns the block hash at the given `block_number` or `None` if + /// `block_number` isn't within the range of the previous 256 blocks. + fn block_hash(&self, block_number: U256) -> Option; + /// Returns the maximum allowed size of a storage item. fn max_value_size(&self) -> u32; @@ -739,6 +743,7 @@ where BalanceOf: Into + TryFrom, MomentOf: Into, E: Executable, + T::Hash: frame_support::traits::IsType, { /// Create and run a new call stack by calling into `dest`. /// @@ -1329,6 +1334,24 @@ where pub(crate) fn override_export(&mut self, export: ExportedFunction) { self.top_frame_mut().entry_point = export; } + + #[cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] + pub(crate) fn set_block_number(&mut self, block_number: BlockNumberFor) { + self.block_number = block_number; + } + + fn block_hash(&self, block_number: U256) -> Option { + let Ok(block_number) = BlockNumberFor::::try_from(block_number) else { + return None; + }; + if block_number >= self.block_number { + return None; + } + if block_number < self.block_number.saturating_sub(256u32.into()) { + return None; + } + Some(System::::block_hash(&block_number).into()) + } } impl<'a, T, E> Ext for Stack<'a, T, E> @@ -1337,6 +1360,7 @@ where E: Executable, BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { type T = T; @@ -1648,6 +1672,10 @@ where self.block_number.into() } + fn block_hash(&self, block_number: U256) -> Option { + self.block_hash(block_number) + } + fn max_value_size(&self) -> u32 { limits::PAYLOAD_BYTES } @@ -4753,4 +4781,60 @@ mod tests { .unwrap() }); } + + #[test] + fn block_hash_returns_proper_values() { + let bob_code_hash = MockLoader::insert(Call, |ctx, _| { + ctx.ext.block_number = 1u32.into(); + assert_eq!(ctx.ext.block_hash(U256::from(1)), None); + assert_eq!(ctx.ext.block_hash(U256::from(0)), Some(H256::from([1; 32]))); + + ctx.ext.block_number = 300u32.into(); + assert_eq!(ctx.ext.block_hash(U256::from(300)), None); + assert_eq!(ctx.ext.block_hash(U256::from(43)), None); + assert_eq!(ctx.ext.block_hash(U256::from(44)), Some(H256::from([2; 32]))); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(0u32), + ::Hash::from([1; 32]), + ); + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(1u32), + ::Hash::default(), + ); + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(43u32), + ::Hash::default(), + ); + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(44u32), + ::Hash::from([2; 32]), + ); + frame_system::BlockHash::::insert( + &BlockNumberFor::::from(300u32), + ::Hash::default(), + ); + + place_contract(&BOB, bob_code_hash); + + let origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&origin, 0, 0).unwrap(); + assert_matches!( + MockStack::run_call( + origin, + BOB_ADDR, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + 0, + vec![0], + None, + ), + Ok(_) + ); + }); + } } diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index 164ffcf7a495..d50da45fc3a9 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -755,6 +755,7 @@ pub mod pallet { where BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { /// A raw EVM transaction, typically dispatched by an Ethereum JSON-RPC server. /// @@ -1077,6 +1078,7 @@ impl Pallet where BalanceOf: Into + TryFrom, MomentOf: Into, + T::Hash: frame_support::traits::IsType, { /// A generalized version of [`Self::call`]. /// @@ -1236,6 +1238,7 @@ where ::RuntimeCall: Encode, OnChargeTransactionBalanceOf: Into>, T::Nonce: Into, + T::Hash: frame_support::traits::IsType, { // Get the nonce to encode in the tx. let nonce: T::Nonce = >::account_nonce(&origin); diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 47f1377f4679..7ce2e3d9bf34 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -4624,4 +4624,29 @@ mod run_tests { assert_eq!(::Currency::total_balance(&EVE), 1_100); }); } + + #[test] + fn block_hash_works() { + let (code, _) = compile_module("block_hash").unwrap(); + + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + + // The genesis config sets to the block number to 1 + let block_hash = [1; 32]; + frame_system::BlockHash::::insert( + &crate::BlockNumberFor::::from(0u32), + ::Hash::from(&block_hash), + ); + assert_ok!(builder::call(addr) + .data((U256::zero(), H256::from(block_hash)).encode()) + .build()); + + // A block number out of range returns the zero value + assert_ok!(builder::call(addr).data((U256::from(1), H256::zero()).encode()).build()); + }); + } } diff --git a/substrate/frame/revive/src/wasm/mod.rs b/substrate/frame/revive/src/wasm/mod.rs index 66844dbf1146..6779f551113c 100644 --- a/substrate/frame/revive/src/wasm/mod.rs +++ b/substrate/frame/revive/src/wasm/mod.rs @@ -48,7 +48,7 @@ use frame_support::{ ensure, traits::{fungible::MutateHold, tokens::Precision::BestEffort}, }; -use sp_core::{Get, U256}; +use sp_core::{Get, H256, U256}; use sp_runtime::DispatchError; /// Validated Wasm module ready for execution. @@ -63,7 +63,7 @@ pub struct WasmBlob { code_info: CodeInfo, // This is for not calculating the hash every time we need it. #[codec(skip)] - code_hash: sp_core::H256, + code_hash: H256, } /// Contract code related data, such as: @@ -147,14 +147,14 @@ where api_version: API_VERSION, behaviour_version: Default::default(), }; - let code_hash = sp_core::H256(sp_io::hashing::keccak_256(&code)); + let code_hash = H256(sp_io::hashing::keccak_256(&code)); Ok(WasmBlob { code, code_info, code_hash }) } /// Remove the code from storage and refund the deposit to its owner. /// /// Applies all necessary checks before removing the code. - pub fn remove(origin: &T::AccountId, code_hash: sp_core::H256) -> DispatchResult { + pub fn remove(origin: &T::AccountId, code_hash: H256) -> DispatchResult { >::try_mutate_exists(&code_hash, |existing| { if let Some(code_info) = existing { ensure!(code_info.refcount == 0, >::CodeInUse); @@ -335,10 +335,7 @@ impl Executable for WasmBlob where BalanceOf: Into + TryFrom, { - fn from_storage( - code_hash: sp_core::H256, - gas_meter: &mut GasMeter, - ) -> Result { + fn from_storage(code_hash: H256, gas_meter: &mut GasMeter) -> Result { let code_info = >::get(code_hash).ok_or(Error::::CodeNotFound)?; gas_meter.charge(CodeLoadToken(code_info.code_len))?; let code = >::get(code_hash).ok_or(Error::::CodeNotFound)?; @@ -365,7 +362,7 @@ where self.code.as_ref() } - fn code_hash(&self) -> &sp_core::H256 { + fn code_hash(&self) -> &H256 { &self.code_hash } diff --git a/substrate/frame/revive/src/wasm/runtime.rs b/substrate/frame/revive/src/wasm/runtime.rs index d9e8c6ae9c37..95257bee1c6b 100644 --- a/substrate/frame/revive/src/wasm/runtime.rs +++ b/substrate/frame/revive/src/wasm/runtime.rs @@ -326,6 +326,8 @@ pub enum RuntimeCosts { MinimumBalance, /// Weight of calling `seal_block_number`. BlockNumber, + /// Weight of calling `seal_block_hash`. + BlockHash, /// Weight of calling `seal_now`. Now, /// Weight of calling `seal_weight_to_fee`. @@ -473,6 +475,7 @@ impl Token for RuntimeCosts { ValueTransferred => T::WeightInfo::seal_value_transferred(), MinimumBalance => T::WeightInfo::seal_minimum_balance(), BlockNumber => T::WeightInfo::seal_block_number(), + BlockHash => T::WeightInfo::seal_block_hash(), Now => T::WeightInfo::seal_now(), WeightToFee => T::WeightInfo::seal_weight_to_fee(), Terminate(locked_dependencies) => T::WeightInfo::seal_terminate(locked_dependencies), @@ -1713,6 +1716,27 @@ pub mod env { )?) } + /// Stores the block hash at given block height into the supplied buffer. + /// See [`pallet_revive_uapi::HostFn::block_hash`]. + #[api_version(0)] + fn block_hash( + &mut self, + memory: &mut M, + block_number_ptr: u32, + out_ptr: u32, + ) -> Result<(), TrapReason> { + self.charge_gas(RuntimeCosts::BlockHash)?; + let block_number = memory.read_u256(block_number_ptr)?; + let block_hash = self.ext.block_hash(block_number).unwrap_or(H256::zero()); + Ok(self.write_fixed_sandbox_output( + memory, + out_ptr, + &block_hash.as_bytes(), + false, + already_charged, + )?) + } + /// Computes the SHA2 256-bit hash on the given input buffer. /// See [`pallet_revive_uapi::HostFn::hash_sha2_256`]. #[api_version(0)] diff --git a/substrate/frame/revive/src/weights.rs b/substrate/frame/revive/src/weights.rs index 43927da8d2e5..d1b1a63b4db6 100644 --- a/substrate/frame/revive/src/weights.rs +++ b/substrate/frame/revive/src/weights.rs @@ -79,6 +79,7 @@ pub trait WeightInfo { fn seal_value_transferred() -> Weight; fn seal_minimum_balance() -> Weight; fn seal_block_number() -> Weight; + fn seal_block_hash() -> Weight; fn seal_now() -> Weight; fn seal_weight_to_fee() -> Weight; fn seal_input(n: u32, ) -> Weight; @@ -131,8 +132,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `1594` - // Minimum execution time: 3_055_000 picoseconds. - Weight::from_parts(3_377_000, 1594) + // Minimum execution time: 2_649_000 picoseconds. + Weight::from_parts(2_726_000, 1594) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -142,10 +143,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `425 + k * (69 ±0)` // Estimated: `415 + k * (70 ±0)` - // Minimum execution time: 15_564_000 picoseconds. - Weight::from_parts(14_949_168, 415) - // Standard Error: 1_113 - .saturating_add(Weight::from_parts(1_315_153, 0).saturating_mul(k.into())) + // Minimum execution time: 12_756_000 picoseconds. + Weight::from_parts(13_112_000, 415) + // Standard Error: 988 + .saturating_add(Weight::from_parts(1_131_927, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -169,8 +170,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1465` // Estimated: `7405` - // Minimum execution time: 98_113_000 picoseconds. - Weight::from_parts(101_964_040, 7405) + // Minimum execution time: 86_553_000 picoseconds. + Weight::from_parts(89_689_079, 7405) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -194,10 +195,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `416` // Estimated: `6333` - // Minimum execution time: 207_612_000 picoseconds. - Weight::from_parts(202_394_849, 6333) - // Standard Error: 12 - .saturating_add(Weight::from_parts(4_108, 0).saturating_mul(i.into())) + // Minimum execution time: 180_721_000 picoseconds. + Weight::from_parts(155_866_981, 6333) + // Standard Error: 11 + .saturating_add(Weight::from_parts(4_514, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -220,10 +221,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1296` // Estimated: `4741` - // Minimum execution time: 172_403_000 picoseconds. - Weight::from_parts(151_999_812, 4741) - // Standard Error: 15 - .saturating_add(Weight::from_parts(3_948, 0).saturating_mul(i.into())) + // Minimum execution time: 151_590_000 picoseconds. + Weight::from_parts(128_110_988, 4741) + // Standard Error: 16 + .saturating_add(Weight::from_parts(4_453, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -243,8 +244,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1465` // Estimated: `7405` - // Minimum execution time: 149_755_000 picoseconds. - Weight::from_parts(166_190_000, 7405) + // Minimum execution time: 136_371_000 picoseconds. + Weight::from_parts(140_508_000, 7405) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -255,12 +256,14 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Revive::PristineCode` (r:0 w:1) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. - fn upload_code(_c: u32, ) -> Weight { + fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 58_481_000 picoseconds. - Weight::from_parts(61_009_506, 3574) + // Minimum execution time: 51_255_000 picoseconds. + Weight::from_parts(52_668_809, 3574) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -274,8 +277,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `285` // Estimated: `3750` - // Minimum execution time: 47_485_000 picoseconds. - Weight::from_parts(48_962_000, 3750) + // Minimum execution time: 41_664_000 picoseconds. + Weight::from_parts(42_981_000, 3750) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -287,8 +290,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `529` // Estimated: `6469` - // Minimum execution time: 30_752_000 picoseconds. - Weight::from_parts(32_401_000, 6469) + // Minimum execution time: 27_020_000 picoseconds. + Weight::from_parts(27_973_000, 6469) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -300,8 +303,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 47_042_000 picoseconds. - Weight::from_parts(48_378_000, 3574) + // Minimum execution time: 42_342_000 picoseconds. + Weight::from_parts(43_210_000, 3574) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -313,8 +316,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `56` // Estimated: `3521` - // Minimum execution time: 36_705_000 picoseconds. - Weight::from_parts(37_313_000, 3521) + // Minimum execution time: 31_881_000 picoseconds. + Weight::from_parts(32_340_000, 3521) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -326,8 +329,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 13_275_000 picoseconds. - Weight::from_parts(13_593_000, 3610) + // Minimum execution time: 11_087_000 picoseconds. + Weight::from_parts(11_416_000, 3610) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// The range of component `r` is `[0, 1600]`. @@ -335,24 +338,24 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_708_000 picoseconds. - Weight::from_parts(7_740_679, 0) - // Standard Error: 133 - .saturating_add(Weight::from_parts(175_535, 0).saturating_mul(r.into())) + // Minimum execution time: 6_403_000 picoseconds. + Weight::from_parts(7_751_101, 0) + // Standard Error: 99 + .saturating_add(Weight::from_parts(179_467, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 277_000 picoseconds. - Weight::from_parts(326_000, 0) + // Minimum execution time: 272_000 picoseconds. + Weight::from_parts(306_000, 0) } fn seal_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 260_000 picoseconds. - Weight::from_parts(273_000, 0) + // Minimum execution time: 226_000 picoseconds. + Weight::from_parts(261_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -360,8 +363,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `306` // Estimated: `3771` - // Minimum execution time: 7_700_000 picoseconds. - Weight::from_parts(8_207_000, 3771) + // Minimum execution time: 6_727_000 picoseconds. + Weight::from_parts(7_122_000, 3771) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) @@ -370,16 +373,16 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `403` // Estimated: `3868` - // Minimum execution time: 8_719_000 picoseconds. - Weight::from_parts(9_077_000, 3868) + // Minimum execution time: 7_542_000 picoseconds. + Weight::from_parts(7_846_000, 3868) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 250_000 picoseconds. - Weight::from_parts(273_000, 0) + // Minimum execution time: 243_000 picoseconds. + Weight::from_parts(275_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -389,44 +392,44 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `473` // Estimated: `3938` - // Minimum execution time: 13_910_000 picoseconds. - Weight::from_parts(14_687_000, 3938) + // Minimum execution time: 11_948_000 picoseconds. + Weight::from_parts(12_406_000, 3938) .saturating_add(T::DbWeight::get().reads(2_u64)) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 351_000 picoseconds. - Weight::from_parts(389_000, 0) + // Minimum execution time: 329_000 picoseconds. + Weight::from_parts(362_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 285_000 picoseconds. - Weight::from_parts(307_000, 0) + // Minimum execution time: 276_000 picoseconds. + Weight::from_parts(303_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 264_000 picoseconds. - Weight::from_parts(292_000, 0) + // Minimum execution time: 251_000 picoseconds. + Weight::from_parts(286_000, 0) } fn seal_weight_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 631_000 picoseconds. - Weight::from_parts(684_000, 0) + // Minimum execution time: 611_000 picoseconds. + Weight::from_parts(669_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `0` - // Minimum execution time: 4_754_000 picoseconds. - Weight::from_parts(5_107_000, 0) + // Minimum execution time: 4_439_000 picoseconds. + Weight::from_parts(4_572_000, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -436,8 +439,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `264` // Estimated: `3729` - // Minimum execution time: 11_156_000 picoseconds. - Weight::from_parts(11_558_000, 3729) + // Minimum execution time: 9_336_000 picoseconds. + Weight::from_parts(9_622_000, 3729) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Revive::ImmutableDataOf` (r:1 w:0) @@ -447,10 +450,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `238 + n * (1 ±0)` // Estimated: `3703 + n * (1 ±0)` - // Minimum execution time: 6_637_000 picoseconds. - Weight::from_parts(7_510_923, 3703) - // Standard Error: 12 - .saturating_add(Weight::from_parts(955, 0).saturating_mul(n.into())) + // Minimum execution time: 5_660_000 picoseconds. + Weight::from_parts(6_291_437, 3703) + // Standard Error: 4 + .saturating_add(Weight::from_parts(741, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -461,39 +464,49 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_717_000 picoseconds. - Weight::from_parts(3_109_103, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(666, 0).saturating_mul(n.into())) + // Minimum execution time: 1_909_000 picoseconds. + Weight::from_parts(2_154_705, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(643, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 253_000 picoseconds. - Weight::from_parts(318_000, 0) + // Minimum execution time: 241_000 picoseconds. + Weight::from_parts(283_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` // Minimum execution time: 263_000 picoseconds. - Weight::from_parts(309_000, 0) + Weight::from_parts(294_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 239_000 picoseconds. - Weight::from_parts(278_000, 0) + // Minimum execution time: 218_000 picoseconds. + Weight::from_parts(281_000, 0) + } + /// Storage: `System::BlockHash` (r:1 w:0) + /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `Measured`) + fn seal_block_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `30` + // Estimated: `3495` + // Minimum execution time: 3_373_000 picoseconds. + Weight::from_parts(3_610_000, 3495) + .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 266_000 picoseconds. - Weight::from_parts(300_000, 0) + // Minimum execution time: 247_000 picoseconds. + Weight::from_parts(299_000, 0) } /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) @@ -501,8 +514,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `67` // Estimated: `1552` - // Minimum execution time: 6_300_000 picoseconds. - Weight::from_parts(6_588_000, 1552) + // Minimum execution time: 5_523_000 picoseconds. + Weight::from_parts(5_757_000, 1552) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// The range of component `n` is `[0, 262140]`. @@ -510,20 +523,20 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 457_000 picoseconds. - Weight::from_parts(533_616, 0) + // Minimum execution time: 450_000 picoseconds. + Weight::from_parts(584_658, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(148, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262140]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 287_000 picoseconds. - Weight::from_parts(450_119, 0) + // Minimum execution time: 232_000 picoseconds. + Weight::from_parts(611_960, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(295, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(294, 0).saturating_mul(n.into())) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -540,10 +553,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `321 + n * (88 ±0)` // Estimated: `3787 + n * (2563 ±0)` - // Minimum execution time: 22_885_000 picoseconds. - Weight::from_parts(25_158_434, 3787) - // Standard Error: 9_482 - .saturating_add(Weight::from_parts(4_623_850, 0).saturating_mul(n.into())) + // Minimum execution time: 19_158_000 picoseconds. + Weight::from_parts(20_900_189, 3787) + // Standard Error: 9_648 + .saturating_add(Weight::from_parts(4_239_910, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -556,22 +569,22 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_172_000 picoseconds. - Weight::from_parts(5_112_915, 0) - // Standard Error: 3_042 - .saturating_add(Weight::from_parts(220_337, 0).saturating_mul(t.into())) - // Standard Error: 27 - .saturating_add(Weight::from_parts(1_077, 0).saturating_mul(n.into())) + // Minimum execution time: 4_097_000 picoseconds. + Weight::from_parts(3_956_608, 0) + // Standard Error: 2_678 + .saturating_add(Weight::from_parts(178_555, 0).saturating_mul(t.into())) + // Standard Error: 23 + .saturating_add(Weight::from_parts(1_127, 0).saturating_mul(n.into())) } /// The range of component `i` is `[0, 262144]`. fn seal_debug_message(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 332_000 picoseconds. - Weight::from_parts(830_275, 0) + // Minimum execution time: 277_000 picoseconds. + Weight::from_parts(1_044_051, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(803, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(794, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -579,8 +592,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 9_628_000 picoseconds. - Weight::from_parts(10_193_000, 744) + // Minimum execution time: 7_745_000 picoseconds. + Weight::from_parts(8_370_000, 744) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -589,8 +602,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 45_621_000 picoseconds. - Weight::from_parts(46_237_000, 10754) + // Minimum execution time: 43_559_000 picoseconds. + Weight::from_parts(44_310_000, 10754) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -599,8 +612,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 10_918_000 picoseconds. - Weight::from_parts(11_441_000, 744) + // Minimum execution time: 8_866_000 picoseconds. + Weight::from_parts(9_072_000, 744) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -610,8 +623,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 47_445_000 picoseconds. - Weight::from_parts(49_049_000, 10754) + // Minimum execution time: 44_481_000 picoseconds. + Weight::from_parts(45_157_000, 10754) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -623,12 +636,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + o * (1 ±0)` // Estimated: `247 + o * (1 ±0)` - // Minimum execution time: 11_215_000 picoseconds. - Weight::from_parts(11_943_073, 247) - // Standard Error: 50 - .saturating_add(Weight::from_parts(844, 0).saturating_mul(n.into())) - // Standard Error: 50 - .saturating_add(Weight::from_parts(891, 0).saturating_mul(o.into())) + // Minimum execution time: 9_130_000 picoseconds. + Weight::from_parts(9_709_648, 247) + // Standard Error: 40 + .saturating_add(Weight::from_parts(435, 0).saturating_mul(n.into())) + // Standard Error: 40 + .saturating_add(Weight::from_parts(384, 0).saturating_mul(o.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -640,10 +653,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 10_794_000 picoseconds. - Weight::from_parts(11_993_996, 247) - // Standard Error: 75 - .saturating_add(Weight::from_parts(759, 0).saturating_mul(n.into())) + // Minimum execution time: 8_753_000 picoseconds. + Weight::from_parts(9_558_399, 247) + // Standard Error: 56 + .saturating_add(Weight::from_parts(483, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -655,10 +668,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 10_345_000 picoseconds. - Weight::from_parts(11_428_949, 247) - // Standard Error: 80 - .saturating_add(Weight::from_parts(1_525, 0).saturating_mul(n.into())) + // Minimum execution time: 8_328_000 picoseconds. + Weight::from_parts(9_120_157, 247) + // Standard Error: 58 + .saturating_add(Weight::from_parts(1_637, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -669,10 +682,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 9_858_000 picoseconds. - Weight::from_parts(10_787_656, 247) - // Standard Error: 64 - .saturating_add(Weight::from_parts(789, 0).saturating_mul(n.into())) + // Minimum execution time: 7_977_000 picoseconds. + Weight::from_parts(8_582_869, 247) + // Standard Error: 52 + .saturating_add(Weight::from_parts(854, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -683,10 +696,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 11_303_000 picoseconds. - Weight::from_parts(12_595_161, 247) - // Standard Error: 81 - .saturating_add(Weight::from_parts(1_311, 0).saturating_mul(n.into())) + // Minimum execution time: 9_193_000 picoseconds. + Weight::from_parts(10_112_966, 247) + // Standard Error: 63 + .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -695,36 +708,36 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_618_000 picoseconds. - Weight::from_parts(1_768_000, 0) + // Minimum execution time: 1_398_000 picoseconds. + Weight::from_parts(1_490_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_936_000 picoseconds. - Weight::from_parts(2_146_000, 0) + // Minimum execution time: 1_762_000 picoseconds. + Weight::from_parts(1_926_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_616_000 picoseconds. - Weight::from_parts(1_816_000, 0) + // Minimum execution time: 1_413_000 picoseconds. + Weight::from_parts(1_494_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_716_000 picoseconds. - Weight::from_parts(1_928_000, 0) + // Minimum execution time: 1_606_000 picoseconds. + Weight::from_parts(1_659_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_070_000 picoseconds. - Weight::from_parts(1_201_000, 0) + // Minimum execution time: 1_010_000 picoseconds. + Weight::from_parts(1_117_000, 0) } /// The range of component `n` is `[0, 512]`. /// The range of component `o` is `[0, 512]`. @@ -732,50 +745,50 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_294_000 picoseconds. - Weight::from_parts(2_562_977, 0) - // Standard Error: 16 - .saturating_add(Weight::from_parts(274, 0).saturating_mul(n.into())) - // Standard Error: 16 - .saturating_add(Weight::from_parts(374, 0).saturating_mul(o.into())) + // Minimum execution time: 2_194_000 picoseconds. + Weight::from_parts(2_290_633, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(341, 0).saturating_mul(n.into())) + // Standard Error: 11 + .saturating_add(Weight::from_parts(377, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 512]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_016_000 picoseconds. - Weight::from_parts(2_487_058, 0) - // Standard Error: 27 - .saturating_add(Weight::from_parts(434, 0).saturating_mul(n.into())) + // Minimum execution time: 1_896_000 picoseconds. + Weight::from_parts(2_254_323, 0) + // Standard Error: 17 + .saturating_add(Weight::from_parts(439, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_892_000 picoseconds. - Weight::from_parts(2_207_388, 0) - // Standard Error: 27 - .saturating_add(Weight::from_parts(443, 0).saturating_mul(n.into())) + // Minimum execution time: 1_800_000 picoseconds. + Weight::from_parts(1_948_552, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(360, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_709_000 picoseconds. - Weight::from_parts(2_050_395, 0) - // Standard Error: 19 - .saturating_add(Weight::from_parts(184, 0).saturating_mul(n.into())) + // Minimum execution time: 1_615_000 picoseconds. + Weight::from_parts(1_812_731, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(177, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_516_000 picoseconds. - Weight::from_parts(2_873_575, 0) + // Minimum execution time: 2_430_000 picoseconds. + Weight::from_parts(2_669_757, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -783,8 +796,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 17_252_000 picoseconds. - Weight::from_parts(17_661_000, 3780) + // Minimum execution time: 14_740_000 picoseconds. + Weight::from_parts(15_320_000, 3780) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) @@ -801,10 +814,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1292 + t * (103 ±0)` // Estimated: `4757 + t * (103 ±0)` - // Minimum execution time: 40_689_000 picoseconds. - Weight::from_parts(45_233_426, 4757) + // Minimum execution time: 37_280_000 picoseconds. + Weight::from_parts(41_639_379, 4757) // Standard Error: 0 - .saturating_add(Weight::from_parts(3, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(2, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 103).saturating_mul(t.into())) @@ -817,8 +830,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1064` // Estimated: `4529` - // Minimum execution time: 31_110_000 picoseconds. - Weight::from_parts(32_044_000, 4529) + // Minimum execution time: 27_564_000 picoseconds. + Weight::from_parts(28_809_000, 4529) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) @@ -834,10 +847,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1273` // Estimated: `4732` - // Minimum execution time: 129_979_000 picoseconds. - Weight::from_parts(118_301_199, 4732) - // Standard Error: 10 - .saturating_add(Weight::from_parts(3_697, 0).saturating_mul(i.into())) + // Minimum execution time: 115_581_000 picoseconds. + Weight::from_parts(105_196_218, 4732) + // Standard Error: 11 + .saturating_add(Weight::from_parts(4_134, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -846,64 +859,64 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 696_000 picoseconds. - Weight::from_parts(1_036_915, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_117, 0).saturating_mul(n.into())) + // Minimum execution time: 605_000 picoseconds. + Weight::from_parts(3_425_431, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_461, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_117_000 picoseconds. - Weight::from_parts(631_314, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(3_318, 0).saturating_mul(n.into())) + // Minimum execution time: 1_113_000 picoseconds. + Weight::from_parts(4_611_854, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(3_652, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 686_000 picoseconds. - Weight::from_parts(427_696, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_244, 0).saturating_mul(n.into())) + // Minimum execution time: 610_000 picoseconds. + Weight::from_parts(3_872_321, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_584, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 663_000 picoseconds. - Weight::from_parts(440_191, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_243, 0).saturating_mul(n.into())) + // Minimum execution time: 559_000 picoseconds. + Weight::from_parts(4_721_584, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_570, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 261889]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 49_781_000 picoseconds. - Weight::from_parts(32_846_276, 0) - // Standard Error: 14 - .saturating_add(Weight::from_parts(4_798, 0).saturating_mul(n.into())) + // Minimum execution time: 47_467_000 picoseconds. + Weight::from_parts(36_639_352, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(5_216, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_044_000 picoseconds. - Weight::from_parts(49_512_000, 0) + // Minimum execution time: 48_106_000 picoseconds. + Weight::from_parts(49_352_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_680_000 picoseconds. - Weight::from_parts(12_967_000, 0) + // Minimum execution time: 12_616_000 picoseconds. + Weight::from_parts(12_796_000, 0) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -911,8 +924,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `300` // Estimated: `3765` - // Minimum execution time: 16_707_000 picoseconds. - Weight::from_parts(17_318_000, 3765) + // Minimum execution time: 14_055_000 picoseconds. + Weight::from_parts(14_526_000, 3765) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -922,8 +935,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `337` // Estimated: `3802` - // Minimum execution time: 11_962_000 picoseconds. - Weight::from_parts(12_283_000, 3802) + // Minimum execution time: 10_338_000 picoseconds. + Weight::from_parts(10_677_000, 3802) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -933,8 +946,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `337` // Estimated: `3561` - // Minimum execution time: 10_477_000 picoseconds. - Weight::from_parts(11_018_000, 3561) + // Minimum execution time: 8_740_000 picoseconds. + Weight::from_parts(9_329_000, 3561) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -943,10 +956,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_136_000 picoseconds. - Weight::from_parts(9_712_463, 0) - // Standard Error: 42 - .saturating_add(Weight::from_parts(71_916, 0).saturating_mul(r.into())) + // Minimum execution time: 7_846_000 picoseconds. + Weight::from_parts(9_717_991, 0) + // Standard Error: 49 + .saturating_add(Weight::from_parts(72_062, 0).saturating_mul(r.into())) } } @@ -958,8 +971,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `109` // Estimated: `1594` - // Minimum execution time: 3_055_000 picoseconds. - Weight::from_parts(3_377_000, 1594) + // Minimum execution time: 2_649_000 picoseconds. + Weight::from_parts(2_726_000, 1594) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -969,10 +982,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `425 + k * (69 ±0)` // Estimated: `415 + k * (70 ±0)` - // Minimum execution time: 15_564_000 picoseconds. - Weight::from_parts(14_949_168, 415) - // Standard Error: 1_113 - .saturating_add(Weight::from_parts(1_315_153, 0).saturating_mul(k.into())) + // Minimum execution time: 12_756_000 picoseconds. + Weight::from_parts(13_112_000, 415) + // Standard Error: 988 + .saturating_add(Weight::from_parts(1_131_927, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -996,8 +1009,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1465` // Estimated: `7405` - // Minimum execution time: 98_113_000 picoseconds. - Weight::from_parts(101_964_040, 7405) + // Minimum execution time: 86_553_000 picoseconds. + Weight::from_parts(89_689_079, 7405) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1021,10 +1034,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `416` // Estimated: `6333` - // Minimum execution time: 207_612_000 picoseconds. - Weight::from_parts(202_394_849, 6333) - // Standard Error: 12 - .saturating_add(Weight::from_parts(4_108, 0).saturating_mul(i.into())) + // Minimum execution time: 180_721_000 picoseconds. + Weight::from_parts(155_866_981, 6333) + // Standard Error: 11 + .saturating_add(Weight::from_parts(4_514, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -1047,10 +1060,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1296` // Estimated: `4741` - // Minimum execution time: 172_403_000 picoseconds. - Weight::from_parts(151_999_812, 4741) - // Standard Error: 15 - .saturating_add(Weight::from_parts(3_948, 0).saturating_mul(i.into())) + // Minimum execution time: 151_590_000 picoseconds. + Weight::from_parts(128_110_988, 4741) + // Standard Error: 16 + .saturating_add(Weight::from_parts(4_453, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -1070,8 +1083,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1465` // Estimated: `7405` - // Minimum execution time: 149_755_000 picoseconds. - Weight::from_parts(166_190_000, 7405) + // Minimum execution time: 136_371_000 picoseconds. + Weight::from_parts(140_508_000, 7405) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1082,12 +1095,14 @@ impl WeightInfo for () { /// Storage: `Revive::PristineCode` (r:0 w:1) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. - fn upload_code(_c: u32, ) -> Weight { + fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 58_481_000 picoseconds. - Weight::from_parts(61_009_506, 3574) + // Minimum execution time: 51_255_000 picoseconds. + Weight::from_parts(52_668_809, 3574) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1101,8 +1116,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `285` // Estimated: `3750` - // Minimum execution time: 47_485_000 picoseconds. - Weight::from_parts(48_962_000, 3750) + // Minimum execution time: 41_664_000 picoseconds. + Weight::from_parts(42_981_000, 3750) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1114,8 +1129,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `529` // Estimated: `6469` - // Minimum execution time: 30_752_000 picoseconds. - Weight::from_parts(32_401_000, 6469) + // Minimum execution time: 27_020_000 picoseconds. + Weight::from_parts(27_973_000, 6469) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1127,8 +1142,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 47_042_000 picoseconds. - Weight::from_parts(48_378_000, 3574) + // Minimum execution time: 42_342_000 picoseconds. + Weight::from_parts(43_210_000, 3574) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1140,8 +1155,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `56` // Estimated: `3521` - // Minimum execution time: 36_705_000 picoseconds. - Weight::from_parts(37_313_000, 3521) + // Minimum execution time: 31_881_000 picoseconds. + Weight::from_parts(32_340_000, 3521) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1153,8 +1168,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 13_275_000 picoseconds. - Weight::from_parts(13_593_000, 3610) + // Minimum execution time: 11_087_000 picoseconds. + Weight::from_parts(11_416_000, 3610) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// The range of component `r` is `[0, 1600]`. @@ -1162,24 +1177,24 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_708_000 picoseconds. - Weight::from_parts(7_740_679, 0) - // Standard Error: 133 - .saturating_add(Weight::from_parts(175_535, 0).saturating_mul(r.into())) + // Minimum execution time: 6_403_000 picoseconds. + Weight::from_parts(7_751_101, 0) + // Standard Error: 99 + .saturating_add(Weight::from_parts(179_467, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 277_000 picoseconds. - Weight::from_parts(326_000, 0) + // Minimum execution time: 272_000 picoseconds. + Weight::from_parts(306_000, 0) } fn seal_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 260_000 picoseconds. - Weight::from_parts(273_000, 0) + // Minimum execution time: 226_000 picoseconds. + Weight::from_parts(261_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -1187,8 +1202,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `306` // Estimated: `3771` - // Minimum execution time: 7_700_000 picoseconds. - Weight::from_parts(8_207_000, 3771) + // Minimum execution time: 6_727_000 picoseconds. + Weight::from_parts(7_122_000, 3771) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) @@ -1197,16 +1212,16 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `403` // Estimated: `3868` - // Minimum execution time: 8_719_000 picoseconds. - Weight::from_parts(9_077_000, 3868) + // Minimum execution time: 7_542_000 picoseconds. + Weight::from_parts(7_846_000, 3868) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 250_000 picoseconds. - Weight::from_parts(273_000, 0) + // Minimum execution time: 243_000 picoseconds. + Weight::from_parts(275_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -1216,44 +1231,44 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `473` // Estimated: `3938` - // Minimum execution time: 13_910_000 picoseconds. - Weight::from_parts(14_687_000, 3938) + // Minimum execution time: 11_948_000 picoseconds. + Weight::from_parts(12_406_000, 3938) .saturating_add(RocksDbWeight::get().reads(2_u64)) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 351_000 picoseconds. - Weight::from_parts(389_000, 0) + // Minimum execution time: 329_000 picoseconds. + Weight::from_parts(362_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 285_000 picoseconds. - Weight::from_parts(307_000, 0) + // Minimum execution time: 276_000 picoseconds. + Weight::from_parts(303_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 264_000 picoseconds. - Weight::from_parts(292_000, 0) + // Minimum execution time: 251_000 picoseconds. + Weight::from_parts(286_000, 0) } fn seal_weight_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 631_000 picoseconds. - Weight::from_parts(684_000, 0) + // Minimum execution time: 611_000 picoseconds. + Weight::from_parts(669_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `0` - // Minimum execution time: 4_754_000 picoseconds. - Weight::from_parts(5_107_000, 0) + // Minimum execution time: 4_439_000 picoseconds. + Weight::from_parts(4_572_000, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1263,8 +1278,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `264` // Estimated: `3729` - // Minimum execution time: 11_156_000 picoseconds. - Weight::from_parts(11_558_000, 3729) + // Minimum execution time: 9_336_000 picoseconds. + Weight::from_parts(9_622_000, 3729) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Revive::ImmutableDataOf` (r:1 w:0) @@ -1274,10 +1289,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `238 + n * (1 ±0)` // Estimated: `3703 + n * (1 ±0)` - // Minimum execution time: 6_637_000 picoseconds. - Weight::from_parts(7_510_923, 3703) - // Standard Error: 12 - .saturating_add(Weight::from_parts(955, 0).saturating_mul(n.into())) + // Minimum execution time: 5_660_000 picoseconds. + Weight::from_parts(6_291_437, 3703) + // Standard Error: 4 + .saturating_add(Weight::from_parts(741, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1288,39 +1303,49 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_717_000 picoseconds. - Weight::from_parts(3_109_103, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(666, 0).saturating_mul(n.into())) + // Minimum execution time: 1_909_000 picoseconds. + Weight::from_parts(2_154_705, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(643, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 253_000 picoseconds. - Weight::from_parts(318_000, 0) + // Minimum execution time: 241_000 picoseconds. + Weight::from_parts(283_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` // Minimum execution time: 263_000 picoseconds. - Weight::from_parts(309_000, 0) + Weight::from_parts(294_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 239_000 picoseconds. - Weight::from_parts(278_000, 0) + // Minimum execution time: 218_000 picoseconds. + Weight::from_parts(281_000, 0) + } + /// Storage: `System::BlockHash` (r:1 w:0) + /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `Measured`) + fn seal_block_hash() -> Weight { + // Proof Size summary in bytes: + // Measured: `30` + // Estimated: `3495` + // Minimum execution time: 3_373_000 picoseconds. + Weight::from_parts(3_610_000, 3495) + .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 266_000 picoseconds. - Weight::from_parts(300_000, 0) + // Minimum execution time: 247_000 picoseconds. + Weight::from_parts(299_000, 0) } /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) @@ -1328,8 +1353,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `67` // Estimated: `1552` - // Minimum execution time: 6_300_000 picoseconds. - Weight::from_parts(6_588_000, 1552) + // Minimum execution time: 5_523_000 picoseconds. + Weight::from_parts(5_757_000, 1552) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// The range of component `n` is `[0, 262140]`. @@ -1337,20 +1362,20 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 457_000 picoseconds. - Weight::from_parts(533_616, 0) + // Minimum execution time: 450_000 picoseconds. + Weight::from_parts(584_658, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(148, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262140]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 287_000 picoseconds. - Weight::from_parts(450_119, 0) + // Minimum execution time: 232_000 picoseconds. + Weight::from_parts(611_960, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(295, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(294, 0).saturating_mul(n.into())) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1367,10 +1392,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `321 + n * (88 ±0)` // Estimated: `3787 + n * (2563 ±0)` - // Minimum execution time: 22_885_000 picoseconds. - Weight::from_parts(25_158_434, 3787) - // Standard Error: 9_482 - .saturating_add(Weight::from_parts(4_623_850, 0).saturating_mul(n.into())) + // Minimum execution time: 19_158_000 picoseconds. + Weight::from_parts(20_900_189, 3787) + // Standard Error: 9_648 + .saturating_add(Weight::from_parts(4_239_910, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -1383,22 +1408,22 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_172_000 picoseconds. - Weight::from_parts(5_112_915, 0) - // Standard Error: 3_042 - .saturating_add(Weight::from_parts(220_337, 0).saturating_mul(t.into())) - // Standard Error: 27 - .saturating_add(Weight::from_parts(1_077, 0).saturating_mul(n.into())) + // Minimum execution time: 4_097_000 picoseconds. + Weight::from_parts(3_956_608, 0) + // Standard Error: 2_678 + .saturating_add(Weight::from_parts(178_555, 0).saturating_mul(t.into())) + // Standard Error: 23 + .saturating_add(Weight::from_parts(1_127, 0).saturating_mul(n.into())) } /// The range of component `i` is `[0, 262144]`. fn seal_debug_message(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 332_000 picoseconds. - Weight::from_parts(830_275, 0) + // Minimum execution time: 277_000 picoseconds. + Weight::from_parts(1_044_051, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(803, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(794, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -1406,8 +1431,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 9_628_000 picoseconds. - Weight::from_parts(10_193_000, 744) + // Minimum execution time: 7_745_000 picoseconds. + Weight::from_parts(8_370_000, 744) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1416,8 +1441,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 45_621_000 picoseconds. - Weight::from_parts(46_237_000, 10754) + // Minimum execution time: 43_559_000 picoseconds. + Weight::from_parts(44_310_000, 10754) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1426,8 +1451,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 10_918_000 picoseconds. - Weight::from_parts(11_441_000, 744) + // Minimum execution time: 8_866_000 picoseconds. + Weight::from_parts(9_072_000, 744) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1437,8 +1462,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 47_445_000 picoseconds. - Weight::from_parts(49_049_000, 10754) + // Minimum execution time: 44_481_000 picoseconds. + Weight::from_parts(45_157_000, 10754) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1450,12 +1475,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + o * (1 ±0)` // Estimated: `247 + o * (1 ±0)` - // Minimum execution time: 11_215_000 picoseconds. - Weight::from_parts(11_943_073, 247) - // Standard Error: 50 - .saturating_add(Weight::from_parts(844, 0).saturating_mul(n.into())) - // Standard Error: 50 - .saturating_add(Weight::from_parts(891, 0).saturating_mul(o.into())) + // Minimum execution time: 9_130_000 picoseconds. + Weight::from_parts(9_709_648, 247) + // Standard Error: 40 + .saturating_add(Weight::from_parts(435, 0).saturating_mul(n.into())) + // Standard Error: 40 + .saturating_add(Weight::from_parts(384, 0).saturating_mul(o.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -1467,10 +1492,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 10_794_000 picoseconds. - Weight::from_parts(11_993_996, 247) - // Standard Error: 75 - .saturating_add(Weight::from_parts(759, 0).saturating_mul(n.into())) + // Minimum execution time: 8_753_000 picoseconds. + Weight::from_parts(9_558_399, 247) + // Standard Error: 56 + .saturating_add(Weight::from_parts(483, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1482,10 +1507,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 10_345_000 picoseconds. - Weight::from_parts(11_428_949, 247) - // Standard Error: 80 - .saturating_add(Weight::from_parts(1_525, 0).saturating_mul(n.into())) + // Minimum execution time: 8_328_000 picoseconds. + Weight::from_parts(9_120_157, 247) + // Standard Error: 58 + .saturating_add(Weight::from_parts(1_637, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1496,10 +1521,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 9_858_000 picoseconds. - Weight::from_parts(10_787_656, 247) - // Standard Error: 64 - .saturating_add(Weight::from_parts(789, 0).saturating_mul(n.into())) + // Minimum execution time: 7_977_000 picoseconds. + Weight::from_parts(8_582_869, 247) + // Standard Error: 52 + .saturating_add(Weight::from_parts(854, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1510,10 +1535,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 11_303_000 picoseconds. - Weight::from_parts(12_595_161, 247) - // Standard Error: 81 - .saturating_add(Weight::from_parts(1_311, 0).saturating_mul(n.into())) + // Minimum execution time: 9_193_000 picoseconds. + Weight::from_parts(10_112_966, 247) + // Standard Error: 63 + .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1522,36 +1547,36 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_618_000 picoseconds. - Weight::from_parts(1_768_000, 0) + // Minimum execution time: 1_398_000 picoseconds. + Weight::from_parts(1_490_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_936_000 picoseconds. - Weight::from_parts(2_146_000, 0) + // Minimum execution time: 1_762_000 picoseconds. + Weight::from_parts(1_926_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_616_000 picoseconds. - Weight::from_parts(1_816_000, 0) + // Minimum execution time: 1_413_000 picoseconds. + Weight::from_parts(1_494_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_716_000 picoseconds. - Weight::from_parts(1_928_000, 0) + // Minimum execution time: 1_606_000 picoseconds. + Weight::from_parts(1_659_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_070_000 picoseconds. - Weight::from_parts(1_201_000, 0) + // Minimum execution time: 1_010_000 picoseconds. + Weight::from_parts(1_117_000, 0) } /// The range of component `n` is `[0, 512]`. /// The range of component `o` is `[0, 512]`. @@ -1559,50 +1584,50 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_294_000 picoseconds. - Weight::from_parts(2_562_977, 0) - // Standard Error: 16 - .saturating_add(Weight::from_parts(274, 0).saturating_mul(n.into())) - // Standard Error: 16 - .saturating_add(Weight::from_parts(374, 0).saturating_mul(o.into())) + // Minimum execution time: 2_194_000 picoseconds. + Weight::from_parts(2_290_633, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(341, 0).saturating_mul(n.into())) + // Standard Error: 11 + .saturating_add(Weight::from_parts(377, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 512]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_016_000 picoseconds. - Weight::from_parts(2_487_058, 0) - // Standard Error: 27 - .saturating_add(Weight::from_parts(434, 0).saturating_mul(n.into())) + // Minimum execution time: 1_896_000 picoseconds. + Weight::from_parts(2_254_323, 0) + // Standard Error: 17 + .saturating_add(Weight::from_parts(439, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_892_000 picoseconds. - Weight::from_parts(2_207_388, 0) - // Standard Error: 27 - .saturating_add(Weight::from_parts(443, 0).saturating_mul(n.into())) + // Minimum execution time: 1_800_000 picoseconds. + Weight::from_parts(1_948_552, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(360, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_709_000 picoseconds. - Weight::from_parts(2_050_395, 0) - // Standard Error: 19 - .saturating_add(Weight::from_parts(184, 0).saturating_mul(n.into())) + // Minimum execution time: 1_615_000 picoseconds. + Weight::from_parts(1_812_731, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(177, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_516_000 picoseconds. - Weight::from_parts(2_873_575, 0) + // Minimum execution time: 2_430_000 picoseconds. + Weight::from_parts(2_669_757, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1610,8 +1635,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 17_252_000 picoseconds. - Weight::from_parts(17_661_000, 3780) + // Minimum execution time: 14_740_000 picoseconds. + Weight::from_parts(15_320_000, 3780) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) @@ -1628,10 +1653,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1292 + t * (103 ±0)` // Estimated: `4757 + t * (103 ±0)` - // Minimum execution time: 40_689_000 picoseconds. - Weight::from_parts(45_233_426, 4757) + // Minimum execution time: 37_280_000 picoseconds. + Weight::from_parts(41_639_379, 4757) // Standard Error: 0 - .saturating_add(Weight::from_parts(3, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(2, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 103).saturating_mul(t.into())) @@ -1644,8 +1669,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1064` // Estimated: `4529` - // Minimum execution time: 31_110_000 picoseconds. - Weight::from_parts(32_044_000, 4529) + // Minimum execution time: 27_564_000 picoseconds. + Weight::from_parts(28_809_000, 4529) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) @@ -1661,10 +1686,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1273` // Estimated: `4732` - // Minimum execution time: 129_979_000 picoseconds. - Weight::from_parts(118_301_199, 4732) - // Standard Error: 10 - .saturating_add(Weight::from_parts(3_697, 0).saturating_mul(i.into())) + // Minimum execution time: 115_581_000 picoseconds. + Weight::from_parts(105_196_218, 4732) + // Standard Error: 11 + .saturating_add(Weight::from_parts(4_134, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1673,64 +1698,64 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 696_000 picoseconds. - Weight::from_parts(1_036_915, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_117, 0).saturating_mul(n.into())) + // Minimum execution time: 605_000 picoseconds. + Weight::from_parts(3_425_431, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_461, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_117_000 picoseconds. - Weight::from_parts(631_314, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(3_318, 0).saturating_mul(n.into())) + // Minimum execution time: 1_113_000 picoseconds. + Weight::from_parts(4_611_854, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(3_652, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 686_000 picoseconds. - Weight::from_parts(427_696, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_244, 0).saturating_mul(n.into())) + // Minimum execution time: 610_000 picoseconds. + Weight::from_parts(3_872_321, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_584, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 663_000 picoseconds. - Weight::from_parts(440_191, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_243, 0).saturating_mul(n.into())) + // Minimum execution time: 559_000 picoseconds. + Weight::from_parts(4_721_584, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_570, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 261889]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 49_781_000 picoseconds. - Weight::from_parts(32_846_276, 0) - // Standard Error: 14 - .saturating_add(Weight::from_parts(4_798, 0).saturating_mul(n.into())) + // Minimum execution time: 47_467_000 picoseconds. + Weight::from_parts(36_639_352, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(5_216, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_044_000 picoseconds. - Weight::from_parts(49_512_000, 0) + // Minimum execution time: 48_106_000 picoseconds. + Weight::from_parts(49_352_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_680_000 picoseconds. - Weight::from_parts(12_967_000, 0) + // Minimum execution time: 12_616_000 picoseconds. + Weight::from_parts(12_796_000, 0) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -1738,8 +1763,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `300` // Estimated: `3765` - // Minimum execution time: 16_707_000 picoseconds. - Weight::from_parts(17_318_000, 3765) + // Minimum execution time: 14_055_000 picoseconds. + Weight::from_parts(14_526_000, 3765) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1749,8 +1774,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `337` // Estimated: `3802` - // Minimum execution time: 11_962_000 picoseconds. - Weight::from_parts(12_283_000, 3802) + // Minimum execution time: 10_338_000 picoseconds. + Weight::from_parts(10_677_000, 3802) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1760,8 +1785,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `337` // Estimated: `3561` - // Minimum execution time: 10_477_000 picoseconds. - Weight::from_parts(11_018_000, 3561) + // Minimum execution time: 8_740_000 picoseconds. + Weight::from_parts(9_329_000, 3561) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1770,9 +1795,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_136_000 picoseconds. - Weight::from_parts(9_712_463, 0) - // Standard Error: 42 - .saturating_add(Weight::from_parts(71_916, 0).saturating_mul(r.into())) + // Minimum execution time: 7_846_000 picoseconds. + Weight::from_parts(9_717_991, 0) + // Standard Error: 49 + .saturating_add(Weight::from_parts(72_062, 0).saturating_mul(r.into())) } } diff --git a/substrate/frame/revive/uapi/src/host.rs b/substrate/frame/revive/uapi/src/host.rs index b1f1583bcdde..cf4cdeee0f28 100644 --- a/substrate/frame/revive/uapi/src/host.rs +++ b/substrate/frame/revive/uapi/src/host.rs @@ -105,6 +105,14 @@ pub trait HostFn: private::Sealed { /// - `output`: A reference to the output data buffer to write the block number. fn block_number(output: &mut [u8; 32]); + /// Stores the block hash of the given block number into the supplied buffer. + /// + /// # Parameters + /// + /// - `block_number`: A reference to the block number buffer. + /// - `output`: A reference to the output data buffer to write the block number. + fn block_hash(block_number: &[u8; 32], output: &mut [u8; 32]); + /// Call (possibly transferring some amount of funds) into the specified account. /// /// # Parameters diff --git a/substrate/frame/revive/uapi/src/host/riscv32.rs b/substrate/frame/revive/uapi/src/host/riscv32.rs index dcdf3e92eeac..fc55bfbde186 100644 --- a/substrate/frame/revive/uapi/src/host/riscv32.rs +++ b/substrate/frame/revive/uapi/src/host/riscv32.rs @@ -98,6 +98,7 @@ mod sys { data_len: u32, ); pub fn block_number(out_ptr: *mut u8); + pub fn block_hash(block_number_ptr: *const u8, out_ptr: *mut u8); pub fn hash_sha2_256(input_ptr: *const u8, input_len: u32, out_ptr: *mut u8); pub fn hash_keccak_256(input_ptr: *const u8, input_len: u32, out_ptr: *mut u8); pub fn hash_blake2_256(input_ptr: *const u8, input_len: u32, out_ptr: *mut u8); @@ -579,4 +580,8 @@ impl HostFn for HostFnImpl { } extract_from_slice(output, output_len as usize); } + + fn block_hash(block_number_ptr: &[u8; 32], output: &mut [u8; 32]) { + unsafe { sys::block_hash(block_number_ptr.as_ptr(), output.as_mut_ptr()) }; + } } From 5f782a4c5836f9bd8f279e8dd8d3a0d03a88a64f Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Wed, 30 Oct 2024 23:49:25 +0100 Subject: [PATCH 003/166] [pallet-revive] Add metrics to eth-rpc (#6288) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add metrics for eth-rpc --------- Co-authored-by: GitHub Action Co-authored-by: Alexander Theißen --- Cargo.lock | 129 +----------- prdoc/pr_6288.prdoc | 7 + substrate/client/cli/src/signals.rs | 15 ++ substrate/frame/revive/rpc/Cargo.toml | 9 +- substrate/frame/revive/rpc/Dockerfile | 11 +- .../revive/rpc/examples/js/src/script.ts | 2 +- substrate/frame/revive/rpc/src/cli.rs | 195 ++++++++++-------- substrate/frame/revive/rpc/src/client.rs | 48 ++--- substrate/frame/revive/rpc/src/main.rs | 19 +- substrate/frame/revive/rpc/src/tests.rs | 34 ++- 10 files changed, 194 insertions(+), 275 deletions(-) create mode 100644 prdoc/pr_6288.prdoc diff --git a/Cargo.lock b/Cargo.lock index 166344f0e5f8..a6c2bc1fd318 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -119,21 +119,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - -[[package]] -name = "alloc-stdlib" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" -dependencies = [ - "alloc-no-stdlib", -] - [[package]] name = "allocator-api2" version = "0.2.16" @@ -1165,22 +1150,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "async-compression" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd066d0b4ef8ecb03a55319dc13aa6910616d0f44008a045bb1835af830abff5" -dependencies = [ - "brotli", - "flate2", - "futures-core", - "memchr", - "pin-project-lite", - "tokio", - "zstd 0.13.0", - "zstd-safe 7.0.0", -] - [[package]] name = "async-executor" version = "1.5.1" @@ -2613,27 +2582,6 @@ dependencies = [ "tuplex", ] -[[package]] -name = "brotli" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", - "brotli-decompressor", -] - -[[package]] -name = "brotli-decompressor" -version = "4.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a45bd2e4095a8b518033b128020dd4a55aab1c0a381ba4404a472630f4bc362" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", -] - [[package]] name = "bs58" version = "0.5.1" @@ -7507,12 +7455,6 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" -[[package]] -name = "http-range-header" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08a397c49fec283e3d6211adbe480be95aae5f304cfb923e9970e08956d5168a" - [[package]] name = "httparse" version = "1.8.0" @@ -7993,16 +7935,6 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" -[[package]] -name = "iri-string" -version = "0.7.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc0f0a572e8ffe56e2ff4f769f32ffe919282c3916799f8b68688b6030063bea" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "is-terminal" version = "0.4.9" @@ -9786,16 +9718,6 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -12585,14 +12507,15 @@ dependencies = [ "futures", "hex", "hex-literal", - "hyper 1.3.1", "jsonrpsee 0.24.3", "log", "pallet-revive", "pallet-revive-fixtures", "parity-scale-codec", "rlp 0.6.1", + "sc-cli", "sc-rpc", + "sc-service", "scale-info", "secp256k1", "serde_json", @@ -12601,13 +12524,11 @@ dependencies = [ "sp-runtime 31.0.1", "sp-weights 27.0.0", "substrate-cli-test-utils", + "substrate-prometheus-endpoint", "subxt", "subxt-signer", "thiserror", "tokio", - "tower", - "tower-http 0.5.2", - "tracing-subscriber 0.3.18", ] [[package]] @@ -25309,7 +25230,7 @@ dependencies = [ "futures-util", "http 0.2.9", "http-body 0.4.5", - "http-range-header 0.3.1", + "http-range-header", "mime", "pin-project-lite", "tower-layer", @@ -25323,29 +25244,14 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "async-compression", - "base64 0.21.7", "bitflags 2.6.0", "bytes", - "futures-core", - "futures-util", "http 1.1.0", "http-body 1.0.0", "http-body-util", - "http-range-header 0.4.1", - "httpdate", - "iri-string", - "mime", - "mime_guess", - "percent-encoding", "pin-project-lite", - "tokio", - "tokio-util", - "tower", "tower-layer", "tower-service", - "tracing", - "uuid", ] [[package]] @@ -25762,15 +25668,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "unicase" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" -dependencies = [ - "version_check", -] - [[package]] name = "unicode-bidi" version = "0.3.13" @@ -27612,15 +27509,6 @@ dependencies = [ "zstd-safe 6.0.6", ] -[[package]] -name = "zstd" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bffb3309596d527cfcba7dfc6ed6052f1d39dfbd7c867aa2e865e4a449c10110" -dependencies = [ - "zstd-safe 7.0.0", -] - [[package]] name = "zstd-safe" version = "5.0.2+zstd.1.5.2" @@ -27641,15 +27529,6 @@ dependencies = [ "zstd-sys", ] -[[package]] -name = "zstd-safe" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43747c7422e2924c11144d5229878b98180ef8b06cca4ab5af37afc8a8d8ea3e" -dependencies = [ - "zstd-sys", -] - [[package]] name = "zstd-sys" version = "2.0.8+zstd.1.5.5" diff --git a/prdoc/pr_6288.prdoc b/prdoc/pr_6288.prdoc new file mode 100644 index 000000000000..8c1ed920efc3 --- /dev/null +++ b/prdoc/pr_6288.prdoc @@ -0,0 +1,7 @@ +title: '[pallet-revive] Add metrics to eth-rpc' +doc: +- audience: Runtime Dev + description: Add metrics for eth-rpc +crates: +- name: pallet-revive-eth-rpc + bump: minor diff --git a/substrate/client/cli/src/signals.rs b/substrate/client/cli/src/signals.rs index 4b6a6f957a76..64cae03de7ac 100644 --- a/substrate/client/cli/src/signals.rs +++ b/substrate/client/cli/src/signals.rs @@ -89,4 +89,19 @@ impl Signals { Ok(()) } + + /// Execute the future task and returns it's value if it completes before the signal. + pub async fn try_until_signal(self, func: F) -> Result + where + F: Future + future::FusedFuture, + { + let signals = self.future().fuse(); + + pin_mut!(func, signals); + + select! { + s = signals => Err(s), + res = func => Ok(res), + } + } } diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 3c05bdeef478..ef7a7c1b28e4 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -51,16 +51,14 @@ subxt = { workspace = true, default-features = true, features = [ tokio = { workspace = true, features = ["full"] } codec = { workspace = true, features = ["derive"] } log.workspace = true -tracing-subscriber.workspace = true pallet-revive = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } sp-weights = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } sc-rpc = { workspace = true, default-features = true } - -tower.workspace = true -tower-http = { workspace = true, features = ["full"] } -hyper.workspace = true +sc-cli = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } rlp = { workspace = true, optional = true } subxt-signer = { workspace = true, optional = true, features = [ @@ -73,7 +71,6 @@ secp256k1 = { workspace = true, optional = true, features = ["recovery"] } env_logger = { workspace = true } [features] -dev = [] example = ["hex", "hex-literal", "rlp", "secp256k1", "subxt-signer"] riscv = ["pallet-revive/riscv"] diff --git a/substrate/frame/revive/rpc/Dockerfile b/substrate/frame/revive/rpc/Dockerfile index 3ad476651d83..981d5c19a158 100644 --- a/substrate/frame/revive/rpc/Dockerfile +++ b/substrate/frame/revive/rpc/Dockerfile @@ -2,7 +2,8 @@ FROM rust AS builder RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y \ - protobuf-compiler + protobuf-compiler \ + clang libclang-dev WORKDIR /polkadot COPY . /polkadot @@ -19,5 +20,11 @@ RUN useradd -m -u 1001 -U -s /bin/sh -d /polkadot polkadot && \ /usr/local/bin/eth-rpc --help USER polkadot -EXPOSE 8545 + +# 8545 is the default port for the RPC server +# 9616 is the default port for the prometheus metrics +EXPOSE 8545 9616 ENTRYPOINT ["/usr/local/bin/eth-rpc"] + +# We call the help by default +CMD ["--help"] diff --git a/substrate/frame/revive/rpc/examples/js/src/script.ts b/substrate/frame/revive/rpc/examples/js/src/script.ts index 96414e34b7ed..999312f0fd5b 100644 --- a/substrate/frame/revive/rpc/examples/js/src/script.ts +++ b/substrate/frame/revive/rpc/examples/js/src/script.ts @@ -18,7 +18,7 @@ function str_to_bytes(str: string): Uint8Array { async function deploy() { console.log(`Deploying Contract...`); - const bytecode = readFileSync("rpc_demo.polkavm"); + const bytecode = readFileSync("../rpc_demo.polkavm"); const contractFactory = new ContractFactory( [ "constructor(bytes memory _data)", diff --git a/substrate/frame/revive/rpc/src/cli.rs b/substrate/frame/revive/rpc/src/cli.rs index 019eb624b99e..b95fa78bf3ee 100644 --- a/substrate/frame/revive/rpc/src/cli.rs +++ b/substrate/frame/revive/rpc/src/cli.rs @@ -15,117 +15,138 @@ // See the License for the specific language governing permissions and // limitations under the License. //! The Ethereum JSON-RPC server. -use crate::{client::Client, EthRpcClient, EthRpcServer, EthRpcServerImpl, LOG_TARGET}; +use crate::{client::Client, EthRpcServer, EthRpcServerImpl}; use clap::Parser; -use hyper::Method; -use jsonrpsee::{ - http_client::HttpClientBuilder, - server::{RpcModule, Server}, +use futures::{pin_mut, FutureExt}; +use jsonrpsee::server::RpcModule; +use sc_cli::{PrometheusParams, RpcParams, SharedParams, Signals}; +use sc_service::{ + config::{PrometheusConfig, RpcConfiguration}, + start_rpc_servers, TaskManager, }; -use std::net::SocketAddr; -use tower_http::cors::{Any, CorsLayer}; + +// Default port if --prometheus-port is not specified +const DEFAULT_PROMETHEUS_PORT: u16 = 9616; + +// Default port if --rpc-port is not specified +const DEFAULT_RPC_PORT: u16 = 8545; // Parsed command instructions from the command line -#[derive(Parser)] +#[derive(Parser, Debug)] #[clap(author, about, version)] pub struct CliCommand { - /// The server address to bind to - #[clap(long, default_value = "8545")] - pub rpc_port: String, - /// The node url to connect to #[clap(long, default_value = "ws://127.0.0.1:9944")] pub node_rpc_url: String, -} -/// Run the JSON-RPC server. -pub async fn run(cmd: CliCommand) -> anyhow::Result<()> { - let CliCommand { rpc_port, node_rpc_url } = cmd; - let client = Client::from_url(&node_rpc_url).await?; - let mut updates = client.updates.clone(); + #[allow(missing_docs)] + #[clap(flatten)] + pub shared_params: SharedParams, - let server_addr = run_server(client, &format!("127.0.0.1:{rpc_port}")).await?; - log::info!("Running JSON-RPC server: addr={server_addr}"); + #[allow(missing_docs)] + #[clap(flatten)] + pub rpc_params: RpcParams, - let url = format!("http://{}", server_addr); - let client = HttpClientBuilder::default().build(url)?; + #[allow(missing_docs)] + #[clap(flatten)] + pub prometheus_params: PrometheusParams, +} + +/// Initialize the logger +#[cfg(not(test))] +fn init_logger(params: &SharedParams) -> anyhow::Result<()> { + let mut logger = sc_cli::LoggerBuilder::new(params.log_filters().join(",")); + logger + .with_log_reloading(params.enable_log_reloading) + .with_detailed_output(params.detailed_log_output); + + if let Some(tracing_targets) = ¶ms.tracing_targets { + let tracing_receiver = params.tracing_receiver.into(); + logger.with_profiling(tracing_receiver, tracing_targets); + } - let block_number = client.block_number().await?; - log::info!(target: LOG_TARGET, "Client initialized - Current 📦 block: #{block_number:?}"); + if params.disable_log_color { + logger.with_colors(false); + } - // keep running server until ctrl-c or client subscription fails - let _ = updates.wait_for(|_| false).await; + logger.init()?; Ok(()) } -#[cfg(feature = "dev")] -mod dev { - use crate::LOG_TARGET; - use futures::{future::BoxFuture, FutureExt}; - use jsonrpsee::{server::middleware::rpc::RpcServiceT, types::Request, MethodResponse}; - - /// Dev Logger middleware, that logs the method and params of the request, along with the - /// success of the response. - #[derive(Clone)] - pub struct DevLogger(pub S); - - impl<'a, S> RpcServiceT<'a> for DevLogger - where - S: RpcServiceT<'a> + Send + Sync + Clone + 'static, - { - type Future = BoxFuture<'a, MethodResponse>; - - fn call(&self, req: Request<'a>) -> Self::Future { - let service = self.0.clone(); - let method = req.method.clone(); - let params = req.params.clone().unwrap_or_default(); - - async move { - log::info!(target: LOG_TARGET, "Method: {method} params: {params}"); - let resp = service.call(req).await; - if resp.is_success() { - log::info!(target: LOG_TARGET, "✅ rpc: {method}"); - } else { - log::info!(target: LOG_TARGET, "❌ rpc: {method} {}", resp.as_result()); - } - resp - } - .boxed() +/// Start the JSON-RPC server using the given command line arguments. +pub fn run(cmd: CliCommand) -> anyhow::Result<()> { + let CliCommand { rpc_params, prometheus_params, node_rpc_url, shared_params, .. } = cmd; + + #[cfg(not(test))] + init_logger(&shared_params)?; + let is_dev = shared_params.dev; + let rpc_addrs: Option> = rpc_params + .rpc_addr(is_dev, false, 8545)? + .map(|addrs| addrs.into_iter().map(Into::into).collect()); + + let rpc_config = RpcConfiguration { + addr: rpc_addrs, + methods: rpc_params.rpc_methods.into(), + max_connections: rpc_params.rpc_max_connections, + cors: rpc_params.rpc_cors(is_dev)?, + max_request_size: rpc_params.rpc_max_request_size, + max_response_size: rpc_params.rpc_max_response_size, + id_provider: None, + max_subs_per_conn: rpc_params.rpc_max_subscriptions_per_connection, + port: rpc_params.rpc_port.unwrap_or(DEFAULT_RPC_PORT), + message_buffer_capacity: rpc_params.rpc_message_buffer_capacity_per_connection, + batch_config: rpc_params.rpc_batch_config()?, + rate_limit: rpc_params.rpc_rate_limit, + rate_limit_whitelisted_ips: rpc_params.rpc_rate_limit_whitelisted_ips, + rate_limit_trust_proxy_headers: rpc_params.rpc_rate_limit_trust_proxy_headers, + }; + + let prometheus_config = + prometheus_params.prometheus_config(DEFAULT_PROMETHEUS_PORT, "eth-rpc".into()); + let prometheus_registry = prometheus_config.as_ref().map(|config| &config.registry); + + let tokio_runtime = sc_cli::build_runtime()?; + let tokio_handle = tokio_runtime.handle(); + let signals = tokio_runtime.block_on(async { Signals::capture() })?; + let mut task_manager = TaskManager::new(tokio_handle.clone(), prometheus_registry)?; + let spawn_handle = task_manager.spawn_handle(); + + let gen_rpc_module = || { + let signals = tokio_runtime.block_on(async { Signals::capture() })?; + let fut = Client::from_url(&node_rpc_url, &spawn_handle).fuse(); + pin_mut!(fut); + + match tokio_handle.block_on(signals.try_until_signal(fut)) { + Ok(Ok(client)) => rpc_module(is_dev, client), + Ok(Err(err)) => Err(sc_service::Error::Application(err.into())), + Err(_) => Err(sc_service::Error::Application("Client connection interrupted".into())), } + }; + + // Prometheus metrics. + if let Some(PrometheusConfig { port, registry }) = prometheus_config.clone() { + spawn_handle.spawn( + "prometheus-endpoint", + None, + prometheus_endpoint::init_prometheus(port, registry).map(drop), + ); } -} - -/// Starts the rpc server and returns the server address. -async fn run_server(client: Client, url: &str) -> anyhow::Result { - let cors = CorsLayer::new() - .allow_methods([Method::POST]) - .allow_origin(Any) - .allow_headers([hyper::header::CONTENT_TYPE]); - let cors_middleware = tower::ServiceBuilder::new().layer(cors); - let builder = Server::builder().set_http_middleware(cors_middleware); + let rpc_server_handle = + start_rpc_servers(&rpc_config, prometheus_registry, tokio_handle, gen_rpc_module, None)?; - #[cfg(feature = "dev")] - let builder = builder - .set_rpc_middleware(jsonrpsee::server::RpcServiceBuilder::new().layer_fn(dev::DevLogger)); - - let server = builder.build(url.parse::()?).await?; - let addr = server.local_addr()?; + task_manager.keep_alive(rpc_server_handle); + tokio_runtime.block_on(signals.run_until_signal(task_manager.future().fuse()))?; + Ok(()) +} +/// Create the JSON-RPC module. +fn rpc_module(is_dev: bool, client: Client) -> Result, sc_service::Error> { let eth_api = EthRpcServerImpl::new(client) - .with_accounts(if cfg!(feature = "dev") { - use pallet_revive::evm::Account; - vec![Account::default()] - } else { - vec![] - }) + .with_accounts(if is_dev { vec![crate::Account::default()] } else { vec![] }) .into_rpc(); let mut module = RpcModule::new(()); - module.merge(eth_api)?; - - let handle = server.start(module); - tokio::spawn(handle.stopped()); - - Ok(addr) + module.merge(eth_api).map_err(|e| sc_service::Error::Application(e.into()))?; + Ok(module) } diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index c707f298512c..64f7f2a61617 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -35,6 +35,7 @@ use pallet_revive::{ }, EthContractResult, }; +use sc_service::SpawnTaskHandle; use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_weights::Weight; use std::{ @@ -57,10 +58,7 @@ use subxt::{ }; use subxt_client::transaction_payment::events::TransactionFeePaid; use thiserror::Error; -use tokio::{ - sync::{watch::Sender, RwLock}, - task::JoinSet, -}; +use tokio::sync::{watch::Sender, RwLock}; use crate::subxt_client::{self, system::events::ExtrinsicSuccess, SrcChainConfig}; @@ -201,8 +199,6 @@ impl BlockCache { pub struct Client { /// The inner state of the client. inner: Arc, - // JoinSet to manage spawned tasks. - join_set: JoinSet>, /// A watch channel to signal cache updates. pub updates: tokio::sync::watch::Receiver<()>, } @@ -308,13 +304,6 @@ impl ClientInner { } } -/// Drop all the tasks spawned by the client on drop. -impl Drop for Client { - fn drop(&mut self) { - self.join_set.abort_all() - } -} - /// Fetch the chain ID from the substrate chain. async fn chain_id(api: &OnlineClient) -> Result { let query = subxt_client::constants().revive().chain_id(); @@ -355,18 +344,18 @@ async fn extract_block_timestamp(block: &SubstrateBlock) -> Option { impl Client { /// Create a new client instance. /// The client will subscribe to new blocks and maintain a cache of [`CACHE_SIZE`] blocks. - pub async fn from_url(url: &str) -> Result { + pub async fn from_url(url: &str, spawn_handle: &SpawnTaskHandle) -> Result { log::info!(target: LOG_TARGET, "Connecting to node at: {url} ..."); let inner: Arc = Arc::new(ClientInner::from_url(url).await?); log::info!(target: LOG_TARGET, "Connected to node at: {url}"); let (tx, mut updates) = tokio::sync::watch::channel(()); - let mut join_set = JoinSet::new(); - join_set.spawn(Self::subscribe_blocks(inner.clone(), tx)); - join_set.spawn(Self::subscribe_reconnect(inner.clone())); + + spawn_handle.spawn("subscribe-blocks", None, Self::subscribe_blocks(inner.clone(), tx)); + spawn_handle.spawn("subscribe-reconnect", None, Self::subscribe_reconnect(inner.clone())); updates.changed().await.expect("tx is not dropped"); - Ok(Self { inner, join_set, updates }) + Ok(Self { inner, updates }) } /// Expose the storage API. @@ -422,7 +411,7 @@ impl Client { } /// Subscribe and log reconnection events. - async fn subscribe_reconnect(inner: Arc) -> Result<(), ClientError> { + async fn subscribe_reconnect(inner: Arc) { let rpc = inner.as_ref().rpc_client.clone(); loop { let reconnected = rpc.reconnect_initiated().await; @@ -434,12 +423,15 @@ impl Client { } /// Subscribe to new blocks and update the cache. - async fn subscribe_blocks(inner: Arc, tx: Sender<()>) -> Result<(), ClientError> { + async fn subscribe_blocks(inner: Arc, tx: Sender<()>) { log::info!(target: LOG_TARGET, "Subscribing to new blocks"); - let mut block_stream = - inner.as_ref().api.blocks().subscribe_best().await.inspect_err(|err| { - log::error!("Failed to subscribe to blocks: {err:?}"); - })?; + let mut block_stream = match inner.as_ref().api.blocks().subscribe_best().await { + Ok(s) => s, + Err(err) => { + log::error!(target: LOG_TARGET, "Failed to subscribe to blocks: {err:?}"); + return + }, + }; while let Some(block) = block_stream.next().await { let block = match block { @@ -447,13 +439,14 @@ impl Client { Err(err) => { if err.is_disconnected_will_reconnect() { log::warn!( + target: LOG_TARGET, "The RPC connection was lost and we may have missed a few blocks" ); continue; } - log::error!("Failed to fetch block: {err:?}"); - return Err(err.into()); + log::error!(target: LOG_TARGET, "Failed to fetch block: {err:?}"); + return }, }; @@ -464,7 +457,7 @@ impl Client { .receipt_infos(&block) .await .inspect_err(|err| { - log::error!("Failed to get receipts: {err:?}"); + log::error!(target: LOG_TARGET, "Failed to get receipts: {err:?}"); }) .unwrap_or_default(); @@ -491,7 +484,6 @@ impl Client { } log::info!(target: LOG_TARGET, "Block subscription ended"); - Ok(()) } } diff --git a/substrate/frame/revive/rpc/src/main.rs b/substrate/frame/revive/rpc/src/main.rs index b1306ad096b0..3376b9b10be2 100644 --- a/substrate/frame/revive/rpc/src/main.rs +++ b/substrate/frame/revive/rpc/src/main.rs @@ -17,23 +17,8 @@ //! The Ethereum JSON-RPC server. use clap::Parser; use pallet_revive_eth_rpc::cli; -use tracing_subscriber::{util::SubscriberInitExt, EnvFilter, FmtSubscriber}; -/// Initialize tracing -fn init_tracing() { - let env_filter = - EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("eth_rpc=trace")); - - FmtSubscriber::builder() - .with_env_filter(env_filter) - .finish() - .try_init() - .expect("failed to initialize tracing"); -} - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - init_tracing(); +fn main() -> anyhow::Result<()> { let cmd = cli::CliCommand::parse(); - cli::run(cmd).await + cli::run(cmd) } diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 8b618469f25d..f745bea6a5f6 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -19,10 +19,11 @@ // We require the `riscv` feature to get access to the compiled fixtures. #![cfg(feature = "riscv")] use crate::{ - cli, + cli::{self, CliCommand}, example::{send_transaction, wait_for_receipt}, EthRpcClient, }; +use clap::Parser; use jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use pallet_revive::{ create1, @@ -50,19 +51,34 @@ async fn ws_client_with_retry(url: &str) -> WsClient { #[tokio::test] async fn test_jsonrpsee_server() -> anyhow::Result<()> { // Start the node. - let _ = thread::spawn(move || match start_node_inline(vec!["--dev", "--rpc-port=45789"]) { + let _ = thread::spawn(move || { + match start_node_inline(vec![ + "--dev", + "--rpc-port=45789", + "--no-telemetry", + "--no-prometheus", + ]) { + Ok(_) => {}, + Err(e) => { + panic!("Node exited with error: {}", e); + }, + } + }); + + // Start the rpc server. + let args = CliCommand::parse_from([ + "--dev", + "--rpc-port=45788", + "--node-rpc-url=ws://localhost:45789", + "--no-prometheus", + ]); + let _ = thread::spawn(move || match cli::run(args) { Ok(_) => {}, Err(e) => { - panic!("Node exited with error: {}", e); + panic!("eth-rpc exited with error: {}", e); }, }); - // Start the rpc server. - tokio::spawn(cli::run(cli::CliCommand { - rpc_port: "45788".to_string(), - node_rpc_url: "ws://localhost:45789".to_string(), - })); - let client = ws_client_with_retry("ws://localhost:45788").await; let account = Account::default(); From dd9924fad0cd9314f21eff621208dc2ec60e0cf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Thei=C3=9Fen?= Date: Thu, 31 Oct 2024 13:18:04 +0100 Subject: [PATCH 004/166] Remove `riscv` feature flag (#6305) Since https://github.com/paritytech/polkadot-sdk/pull/6266 we no longer require a custom toolchain to build the `pallet-revive-fixtures`. Hence we no longer have to guard the build behind a feature flag. --------- Co-authored-by: GitHub Action --- .config/zepter.yaml | 2 +- .github/scripts/cmd/test_cmd.py | 26 +- .github/workflows/runtimes-matrix.json | 2 +- .../workflows/tests-linux-stable-coverage.yml | 4 +- .github/workflows/tests-linux-stable.yml | 4 +- prdoc/pr_6305.prdoc | 17 + scripts/generate-umbrella.py | 2 - substrate/bin/node/cli/Cargo.toml | 1 - substrate/bin/node/runtime/Cargo.toml | 1 - substrate/frame/revive/Cargo.toml | 4 - substrate/frame/revive/fixtures/Cargo.toml | 4 - substrate/frame/revive/fixtures/build.rs | 348 +- substrate/frame/revive/fixtures/src/lib.rs | 7 - .../frame/revive/mock-network/Cargo.toml | 1 - .../frame/revive/mock-network/src/lib.rs | 2 +- substrate/frame/revive/rpc/Cargo.toml | 11 +- substrate/frame/revive/rpc/Dockerfile | 1 + substrate/frame/revive/rpc/examples/README.md | 3 +- substrate/frame/revive/rpc/src/tests.rs | 2 - .../frame/revive/src/benchmarking/mod.rs | 4 +- .../frame/revive/src/benchmarking_dummy.rs | 37 - substrate/frame/revive/src/evm/runtime.rs | 1 - substrate/frame/revive/src/exec.rs | 6 +- substrate/frame/revive/src/lib.rs | 1 - substrate/frame/revive/src/storage.rs | 1 - substrate/frame/revive/src/tests.rs | 7080 ++++++++--------- .../frame/revive/src/tests/test_debug.rs | 248 +- substrate/frame/revive/src/wasm/mod.rs | 2 +- umbrella/Cargo.toml | 6 - 29 files changed, 3841 insertions(+), 3987 deletions(-) create mode 100644 prdoc/pr_6305.prdoc delete mode 100644 substrate/frame/revive/src/benchmarking_dummy.rs diff --git a/.config/zepter.yaml b/.config/zepter.yaml index 7a67ba2695cf..24441e90b1a0 100644 --- a/.config/zepter.yaml +++ b/.config/zepter.yaml @@ -27,7 +27,7 @@ workflows: ] # The umbrella crate uses more features, so we to check those too: check_umbrella: - - [ $check.0, '--features=serde,experimental,riscv,runtime,with-tracing,tuples-96,with-tracing', '-p=polkadot-sdk' ] + - [ $check.0, '--features=serde,experimental,runtime,with-tracing,tuples-96,with-tracing', '-p=polkadot-sdk' ] # Same as `check_*`, but with the `--fix` flag. default: - [ $check.0, '--fix' ] diff --git a/.github/scripts/cmd/test_cmd.py b/.github/scripts/cmd/test_cmd.py index faad3f261b9a..7b29fbfe90d8 100644 --- a/.github/scripts/cmd/test_cmd.py +++ b/.github/scripts/cmd/test_cmd.py @@ -13,7 +13,7 @@ "path": "substrate/frame", "header": "substrate/HEADER-APACHE2", "template": "substrate/.maintain/frame-weight-template.hbs", - "bench_features": "runtime-benchmarks,riscv", + "bench_features": "runtime-benchmarks", "bench_flags": "--flag1 --flag2" }, { @@ -67,7 +67,7 @@ def setUp(self): self.patcher6 = patch('importlib.util.spec_from_file_location', return_value=MagicMock()) self.patcher7 = patch('importlib.util.module_from_spec', return_value=MagicMock()) self.patcher8 = patch('cmd.generate_prdoc.main', return_value=0) - + self.mock_open = self.patcher1.start() self.mock_json_load = self.patcher2.start() self.mock_parse_args = self.patcher3.start() @@ -101,7 +101,7 @@ def test_bench_command_normal_execution_all_runtimes(self): clean=False, image=None ), []) - + self.mock_popen.return_value.read.side_effect = [ "pallet_balances\npallet_staking\npallet_something\n", # Output for dev runtime "pallet_balances\npallet_staking\npallet_something\n", # Output for westend runtime @@ -109,7 +109,7 @@ def test_bench_command_normal_execution_all_runtimes(self): "pallet_balances\npallet_staking\npallet_something\n", # Output for asset-hub-westend runtime "./substrate/frame/balances/Cargo.toml\n", # Mock manifest path for dev -> pallet_balances ] - + with patch('sys.exit') as mock_exit: import cmd cmd.main() @@ -117,11 +117,11 @@ def test_bench_command_normal_execution_all_runtimes(self): expected_calls = [ # Build calls - call("forklift cargo build -p kitchensink-runtime --profile release --features=runtime-benchmarks,riscv"), + call("forklift cargo build -p kitchensink-runtime --profile release --features=runtime-benchmarks"), call("forklift cargo build -p westend-runtime --profile release --features=runtime-benchmarks"), call("forklift cargo build -p rococo-runtime --profile release --features=runtime-benchmarks"), call("forklift cargo build -p asset-hub-westend-runtime --profile release --features=runtime-benchmarks"), - + call(get_mock_bench_output( runtime='kitchensink', pallets='pallet_balances', @@ -162,7 +162,7 @@ def test_bench_command_normal_execution(self): self.mock_popen.return_value.read.side_effect = [ "pallet_balances\npallet_staking\npallet_something\n", # Output for westend runtime ] - + with patch('sys.exit') as mock_exit: import cmd cmd.main() @@ -171,7 +171,7 @@ def test_bench_command_normal_execution(self): expected_calls = [ # Build calls call("forklift cargo build -p westend-runtime --profile release --features=runtime-benchmarks"), - + # Westend runtime calls call(get_mock_bench_output( runtime='westend', @@ -205,7 +205,7 @@ def test_bench_command_normal_execution_xcm(self): self.mock_popen.return_value.read.side_effect = [ "pallet_balances\npallet_staking\npallet_something\npallet_xcm_benchmarks::generic\n", # Output for westend runtime ] - + with patch('sys.exit') as mock_exit: import cmd cmd.main() @@ -214,7 +214,7 @@ def test_bench_command_normal_execution_xcm(self): expected_calls = [ # Build calls call("forklift cargo build -p westend-runtime --profile release --features=runtime-benchmarks"), - + # Westend runtime calls call(get_mock_bench_output( runtime='westend', @@ -241,7 +241,7 @@ def test_bench_command_two_runtimes_two_pallets(self): "pallet_staking\npallet_balances\n", # Output for westend runtime "pallet_staking\npallet_balances\n", # Output for rococo runtime ] - + with patch('sys.exit') as mock_exit: import cmd cmd.main() @@ -309,7 +309,7 @@ def test_bench_command_one_dev_runtime(self): expected_calls = [ # Build calls - call("forklift cargo build -p kitchensink-runtime --profile release --features=runtime-benchmarks,riscv"), + call("forklift cargo build -p kitchensink-runtime --profile release --features=runtime-benchmarks"), # Westend runtime calls call(get_mock_bench_output( runtime='kitchensink', @@ -429,4 +429,4 @@ def test_prdoc_command(self, mock_system, mock_parse_args): self.mock_generate_prdoc_main.assert_called_with(mock_parse_args.return_value[0]) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() diff --git a/.github/workflows/runtimes-matrix.json b/.github/workflows/runtimes-matrix.json index e4e3a2dbe6d1..f991db55b86d 100644 --- a/.github/workflows/runtimes-matrix.json +++ b/.github/workflows/runtimes-matrix.json @@ -5,7 +5,7 @@ "path": "substrate/frame", "header": "substrate/HEADER-APACHE2", "template": "substrate/.maintain/frame-weight-template.hbs", - "bench_features": "runtime-benchmarks,riscv", + "bench_features": "runtime-benchmarks", "bench_flags": "--genesis-builder-policy=none --exclude-pallets=pallet_xcm,pallet_xcm_benchmarks::fungible,pallet_xcm_benchmarks::generic,pallet_nomination_pools,pallet_remark,pallet_transaction_storage", "uri": null, "is_relay": false diff --git a/.github/workflows/tests-linux-stable-coverage.yml b/.github/workflows/tests-linux-stable-coverage.yml index 90d7bc34a926..c5af6bcae77f 100644 --- a/.github/workflows/tests-linux-stable-coverage.yml +++ b/.github/workflows/tests-linux-stable-coverage.yml @@ -56,7 +56,7 @@ jobs: --no-report --release --workspace --locked --no-fail-fast - --features try-runtime,ci-only-tests,experimental,riscv + --features try-runtime,ci-only-tests,experimental --filter-expr " !test(/.*benchmark.*/) - test(/recovers_from_only_chunks_if_pov_large::case_1/) @@ -120,4 +120,4 @@ jobs: - uses: actions/checkout@v4 - uses: actions-ecosystem/action-remove-labels@v1 with: - labels: GHA-coverage \ No newline at end of file + labels: GHA-coverage diff --git a/.github/workflows/tests-linux-stable.yml b/.github/workflows/tests-linux-stable.yml index dd292d55e201..24b96219738a 100644 --- a/.github/workflows/tests-linux-stable.yml +++ b/.github/workflows/tests-linux-stable.yml @@ -91,7 +91,7 @@ jobs: --release \ --no-fail-fast \ --cargo-quiet \ - --features try-runtime,experimental,riscv,ci-only-tests \ + --features try-runtime,experimental,ci-only-tests \ --partition count:${{ matrix.partition }} # run runtime-api tests with `enable-staging-api` feature on the 1st node - name: runtime-api tests @@ -129,7 +129,7 @@ jobs: --release \ --no-fail-fast \ --cargo-quiet \ - --features experimental,riscv,ci-only-tests \ + --features experimental,ci-only-tests \ --filter-expr " !test(/all_security_features_work/) - test(/nonexistent_cache_dir/)" \ --partition count:${{ matrix.partition }} \ diff --git a/prdoc/pr_6305.prdoc b/prdoc/pr_6305.prdoc new file mode 100644 index 000000000000..bfc6f06b19ec --- /dev/null +++ b/prdoc/pr_6305.prdoc @@ -0,0 +1,17 @@ +title: Remove `riscv` feature flag +doc: +- audience: Runtime Dev + description: Since https://github.com/paritytech/polkadot-sdk/pull/6266 we no longer + require a custom toolchain to build the `pallet-revive-fixtures`. Hence we no + longer have to guard the build behind a feature flag. +crates: +- name: pallet-revive + bump: major +- name: pallet-revive-fixtures + bump: major +- name: pallet-revive-mock-network + bump: major +- name: pallet-revive-eth-rpc + bump: major +- name: polkadot-sdk + bump: major diff --git a/scripts/generate-umbrella.py b/scripts/generate-umbrella.py index e1ef6de86f9c..8326909c3449 100644 --- a/scripts/generate-umbrella.py +++ b/scripts/generate-umbrella.py @@ -111,7 +111,6 @@ def main(path, version): "runtime": list([f"{d.name}" for d, _ in runtime_crates]), "node": ["std"] + list([f"{d.name}" for d, _ in std_crates]), "tuples-96": [], - "riscv": [], } manifest = { @@ -207,4 +206,3 @@ def parse_args(): if __name__ == "__main__": args = parse_args() main(args.sdk, args.version) - diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index 933406670e5c..c179579c1885 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -183,7 +183,6 @@ try-runtime = [ "polkadot-sdk/try-runtime", "substrate-cli-test-utils/try-runtime", ] -riscv = ["kitchensink-runtime/riscv", "polkadot-sdk/riscv"] [[bench]] name = "transaction_pool" diff --git a/substrate/bin/node/runtime/Cargo.toml b/substrate/bin/node/runtime/Cargo.toml index 7acf4294c51b..3ad6315561d0 100644 --- a/substrate/bin/node/runtime/Cargo.toml +++ b/substrate/bin/node/runtime/Cargo.toml @@ -74,4 +74,3 @@ experimental = [ "pallet-example-tasks/experimental", ] metadata-hash = ["substrate-wasm-builder/metadata-hash"] -riscv = ["polkadot-sdk/riscv"] diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index c6e733477f38..67bc1809cad7 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -79,10 +79,6 @@ xcm-builder = { workspace = true, default-features = true } [features] default = ["std"] -# enabling this feature will require having a riscv toolchain installed -# if no tests are ran and runtime benchmarks will not work -# apart from this the pallet will stay functional -riscv = ["pallet-revive-fixtures/riscv"] std = [ "codec/std", "environmental/std", diff --git a/substrate/frame/revive/fixtures/Cargo.toml b/substrate/frame/revive/fixtures/Cargo.toml index 1e6c950addfd..7a5452853d65 100644 --- a/substrate/frame/revive/fixtures/Cargo.toml +++ b/substrate/frame/revive/fixtures/Cargo.toml @@ -26,9 +26,5 @@ anyhow = { workspace = true, default-features = true } [features] default = ["std"] -# only if the feature is set we are building the test fixtures -# this is because it requires a custom toolchain supporting polkavm -# we will remove this once there is an upstream toolchain -riscv = [] # only when std is enabled all fixtures are available std = ["anyhow", "frame-system", "log/std", "sp-core", "sp-io", "sp-runtime"] diff --git a/substrate/frame/revive/fixtures/build.rs b/substrate/frame/revive/fixtures/build.rs index 38d63621677d..bbd986d9d44c 100644 --- a/substrate/frame/revive/fixtures/build.rs +++ b/substrate/frame/revive/fixtures/build.rs @@ -18,218 +18,200 @@ //! Compile text fixtures to PolkaVM binaries. use anyhow::Result; -fn main() -> Result<()> { - build::run() +use anyhow::{bail, Context}; +use std::{ + cfg, env, fs, + path::{Path, PathBuf}, + process::Command, +}; + +const OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_RUSTUP_TOOLCHAIN"; +const OVERRIDE_STRIP_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_STRIP"; +const OVERRIDE_OPTIMIZE_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_OPTIMIZE"; + +/// A contract entry. +struct Entry { + /// The path to the contract source file. + path: PathBuf, } -#[cfg(feature = "riscv")] -mod build { - use super::Result; - use anyhow::{bail, Context}; - use std::{ - cfg, env, fs, - path::{Path, PathBuf}, - process::Command, - }; - - const OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_RUSTUP_TOOLCHAIN"; - const OVERRIDE_STRIP_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_STRIP"; - const OVERRIDE_OPTIMIZE_ENV_VAR: &str = "PALLET_REVIVE_FIXTURES_OPTIMIZE"; +impl Entry { + /// Create a new contract entry from the given path. + fn new(path: PathBuf) -> Self { + Self { path } + } - /// A contract entry. - struct Entry { - /// The path to the contract source file. - path: PathBuf, + /// Return the path to the contract source file. + fn path(&self) -> &str { + self.path.to_str().expect("path is valid unicode; qed") } - impl Entry { - /// Create a new contract entry from the given path. - fn new(path: PathBuf) -> Self { - Self { path } - } + /// Return the name of the contract. + fn name(&self) -> &str { + self.path + .file_stem() + .expect("file exits; qed") + .to_str() + .expect("name is valid unicode; qed") + } - /// Return the path to the contract source file. - fn path(&self) -> &str { - self.path.to_str().expect("path is valid unicode; qed") - } + /// Return the name of the polkavm file. + fn out_filename(&self) -> String { + format!("{}.polkavm", self.name()) + } +} - /// Return the name of the contract. - fn name(&self) -> &str { - self.path - .file_stem() - .expect("file exits; qed") - .to_str() - .expect("name is valid unicode; qed") - } +/// Collect all contract entries from the given source directory. +fn collect_entries(contracts_dir: &Path) -> Vec { + fs::read_dir(contracts_dir) + .expect("src dir exists; qed") + .filter_map(|file| { + let path = file.expect("file exists; qed").path(); + if path.extension().map_or(true, |ext| ext != "rs") { + return None + } - /// Return the name of the polkavm file. - fn out_filename(&self) -> String { - format!("{}.polkavm", self.name()) - } - } + Some(Entry::new(path)) + }) + .collect::>() +} - /// Collect all contract entries from the given source directory. - fn collect_entries(contracts_dir: &Path) -> Vec { - fs::read_dir(contracts_dir) - .expect("src dir exists; qed") - .filter_map(|file| { - let path = file.expect("file exists; qed").path(); - if path.extension().map_or(true, |ext| ext != "rs") { - return None - } - - Some(Entry::new(path)) +/// Create a `Cargo.toml` to compile the given contract entries. +fn create_cargo_toml<'a>( + fixtures_dir: &Path, + entries: impl Iterator, + output_dir: &Path, +) -> Result<()> { + let mut cargo_toml: toml::Value = toml::from_str(include_str!("./build/Cargo.toml"))?; + let mut set_dep = |name, path| -> Result<()> { + cargo_toml["dependencies"][name]["path"] = toml::Value::String( + fixtures_dir.join(path).canonicalize()?.to_str().unwrap().to_string(), + ); + Ok(()) + }; + set_dep("uapi", "../uapi")?; + set_dep("common", "./contracts/common")?; + + cargo_toml["bin"] = toml::Value::Array( + entries + .map(|entry| { + let name = entry.name(); + let path = entry.path(); + toml::Value::Table(toml::toml! { + name = name + path = path + }) }) - .collect::>() - } + .collect::>(), + ); - /// Create a `Cargo.toml` to compile the given contract entries. - fn create_cargo_toml<'a>( - fixtures_dir: &Path, - entries: impl Iterator, - output_dir: &Path, - ) -> Result<()> { - let mut cargo_toml: toml::Value = toml::from_str(include_str!("./build/Cargo.toml"))?; - let mut set_dep = |name, path| -> Result<()> { - cargo_toml["dependencies"][name]["path"] = toml::Value::String( - fixtures_dir.join(path).canonicalize()?.to_str().unwrap().to_string(), - ); - Ok(()) - }; - set_dep("uapi", "../uapi")?; - set_dep("common", "./contracts/common")?; - - cargo_toml["bin"] = toml::Value::Array( - entries - .map(|entry| { - let name = entry.name(); - let path = entry.path(); - toml::Value::Table(toml::toml! { - name = name - path = path - }) - }) - .collect::>(), - ); + let cargo_toml = toml::to_string_pretty(&cargo_toml)?; + fs::write(output_dir.join("Cargo.toml"), cargo_toml).map_err(Into::into) +} - let cargo_toml = toml::to_string_pretty(&cargo_toml)?; - fs::write(output_dir.join("Cargo.toml"), cargo_toml).map_err(Into::into) +fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { + let encoded_rustflags = ["-Dwarnings"].join("\x1f"); + + let mut build_command = Command::new(env::var("CARGO")?); + build_command + .current_dir(current_dir) + .env_clear() + .env("PATH", env::var("PATH").unwrap_or_default()) + .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) + .env("RUSTC_BOOTSTRAP", "1") + .env("RUSTUP_HOME", env::var("RUSTUP_HOME").unwrap_or_default()) + .args([ + "build", + "--release", + "-Zbuild-std=core", + "-Zbuild-std-features=panic_immediate_abort", + ]) + .arg("--target") + .arg(target); + + if let Ok(toolchain) = env::var(OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR) { + build_command.env("RUSTUP_TOOLCHAIN", &toolchain); } - fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { - let encoded_rustflags = ["-Dwarnings"].join("\x1f"); - - let mut build_command = Command::new(env::var("CARGO")?); - build_command - .current_dir(current_dir) - .env_clear() - .env("PATH", env::var("PATH").unwrap_or_default()) - .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) - .env("RUSTC_BOOTSTRAP", "1") - .env("RUSTUP_HOME", env::var("RUSTUP_HOME").unwrap_or_default()) - .args([ - "build", - "--release", - "-Zbuild-std=core", - "-Zbuild-std-features=panic_immediate_abort", - ]) - .arg("--target") - .arg(target); - - if let Ok(toolchain) = env::var(OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR) { - build_command.env("RUSTUP_TOOLCHAIN", &toolchain); - } + let build_res = build_command.output().expect("failed to execute process"); - let build_res = build_command.output().expect("failed to execute process"); + if build_res.status.success() { + return Ok(()) + } - if build_res.status.success() { - return Ok(()) - } + let stderr = String::from_utf8_lossy(&build_res.stderr); + eprintln!("{}", stderr); - let stderr = String::from_utf8_lossy(&build_res.stderr); - eprintln!("{}", stderr); + bail!("Failed to build contracts"); +} - bail!("Failed to build contracts"); - } +/// Post-process the compiled code. +fn post_process(input_path: &Path, output_path: &Path) -> Result<()> { + let strip = std::env::var(OVERRIDE_STRIP_ENV_VAR).map_or(false, |value| value == "1"); + let optimize = std::env::var(OVERRIDE_OPTIMIZE_ENV_VAR).map_or(true, |value| value == "1"); + + let mut config = polkavm_linker::Config::default(); + config.set_strip(strip); + config.set_optimize(optimize); + let orig = fs::read(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; + let linked = polkavm_linker::program_from_elf(config, orig.as_ref()) + .map_err(|err| anyhow::format_err!("Failed to link polkavm program: {}", err))?; + fs::write(output_path, linked).map_err(Into::into) +} - /// Post-process the compiled code. - fn post_process(input_path: &Path, output_path: &Path) -> Result<()> { - let strip = std::env::var(OVERRIDE_STRIP_ENV_VAR).map_or(false, |value| value == "1"); - let optimize = std::env::var(OVERRIDE_OPTIMIZE_ENV_VAR).map_or(true, |value| value == "1"); - - let mut config = polkavm_linker::Config::default(); - config.set_strip(strip); - config.set_optimize(optimize); - let orig = - fs::read(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; - let linked = polkavm_linker::program_from_elf(config, orig.as_ref()) - .map_err(|err| anyhow::format_err!("Failed to link polkavm program: {}", err))?; - fs::write(output_path, linked).map_err(Into::into) +/// Write the compiled contracts to the given output directory. +fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result<()> { + for entry in entries { + post_process( + &build_dir + .join("target/riscv32emac-unknown-none-polkavm/release") + .join(entry.name()), + &out_dir.join(entry.out_filename()), + )?; } - /// Write the compiled contracts to the given output directory. - fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result<()> { - for entry in entries { - post_process( - &build_dir - .join("target/riscv32emac-unknown-none-polkavm/release") - .join(entry.name()), - &out_dir.join(entry.out_filename()), - )?; - } + Ok(()) +} - Ok(()) +pub fn main() -> Result<()> { + let fixtures_dir: PathBuf = env::var("CARGO_MANIFEST_DIR")?.into(); + let contracts_dir = fixtures_dir.join("contracts"); + let out_dir: PathBuf = env::var("OUT_DIR")?.into(); + let target = fixtures_dir.join("riscv32emac-unknown-none-polkavm.json"); + + println!("cargo::rerun-if-env-changed={OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR}"); + println!("cargo::rerun-if-env-changed={OVERRIDE_STRIP_ENV_VAR}"); + println!("cargo::rerun-if-env-changed={OVERRIDE_OPTIMIZE_ENV_VAR}"); + + // the fixtures have a dependency on the uapi crate + println!("cargo::rerun-if-changed={}", fixtures_dir.display()); + let uapi_dir = fixtures_dir.parent().expect("parent dir exits; qed").join("uapi"); + if uapi_dir.exists() { + println!("cargo::rerun-if-changed={}", uapi_dir.display()); } - pub fn run() -> Result<()> { - let fixtures_dir: PathBuf = env::var("CARGO_MANIFEST_DIR")?.into(); - let contracts_dir = fixtures_dir.join("contracts"); - let out_dir: PathBuf = env::var("OUT_DIR")?.into(); - let target = fixtures_dir.join("riscv32emac-unknown-none-polkavm.json"); - - println!("cargo::rerun-if-env-changed={OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR}"); - println!("cargo::rerun-if-env-changed={OVERRIDE_STRIP_ENV_VAR}"); - println!("cargo::rerun-if-env-changed={OVERRIDE_OPTIMIZE_ENV_VAR}"); - - // the fixtures have a dependency on the uapi crate - println!("cargo::rerun-if-changed={}", fixtures_dir.display()); - let uapi_dir = fixtures_dir.parent().expect("parent dir exits; qed").join("uapi"); - if uapi_dir.exists() { - println!("cargo::rerun-if-changed={}", uapi_dir.display()); - } - - let entries = collect_entries(&contracts_dir); - if entries.is_empty() { - return Ok(()) - } + let entries = collect_entries(&contracts_dir); + if entries.is_empty() { + return Ok(()) + } - let tmp_dir = tempfile::tempdir()?; - let tmp_dir_path = tmp_dir.path(); + let tmp_dir = tempfile::tempdir()?; + let tmp_dir_path = tmp_dir.path(); - create_cargo_toml(&fixtures_dir, entries.iter(), tmp_dir.path())?; - invoke_build(&target, tmp_dir_path)?; + create_cargo_toml(&fixtures_dir, entries.iter(), tmp_dir.path())?; + invoke_build(&target, tmp_dir_path)?; - write_output(tmp_dir_path, &out_dir, entries)?; + write_output(tmp_dir_path, &out_dir, entries)?; - #[cfg(unix)] - if let Ok(symlink_dir) = env::var("CARGO_WORKSPACE_ROOT_DIR") { - let symlink_dir: PathBuf = symlink_dir.into(); - let symlink_dir: PathBuf = symlink_dir.join("target").join("pallet-revive-fixtures"); - if symlink_dir.is_symlink() { - fs::remove_file(&symlink_dir)? - } - std::os::unix::fs::symlink(&out_dir, &symlink_dir)?; + #[cfg(unix)] + if let Ok(symlink_dir) = env::var("CARGO_WORKSPACE_ROOT_DIR") { + let symlink_dir: PathBuf = symlink_dir.into(); + let symlink_dir: PathBuf = symlink_dir.join("target").join("pallet-revive-fixtures"); + if symlink_dir.is_symlink() { + fs::remove_file(&symlink_dir)? } - - Ok(()) + std::os::unix::fs::symlink(&out_dir, &symlink_dir)?; } -} - -#[cfg(not(feature = "riscv"))] -mod build { - use super::Result; - pub fn run() -> Result<()> { - Ok(()) - } + Ok(()) } diff --git a/substrate/frame/revive/fixtures/src/lib.rs b/substrate/frame/revive/fixtures/src/lib.rs index 5548dca66d07..cc84daec9b59 100644 --- a/substrate/frame/revive/fixtures/src/lib.rs +++ b/substrate/frame/revive/fixtures/src/lib.rs @@ -37,18 +37,11 @@ pub fn compile_module(fixture_name: &str) -> anyhow::Result<(Vec, sp_core::H pub mod bench { use alloc::vec::Vec; - #[cfg(feature = "riscv")] macro_rules! fixture { ($name: literal) => { include_bytes!(concat!(env!("OUT_DIR"), "/", $name, ".polkavm")) }; } - #[cfg(not(feature = "riscv"))] - macro_rules! fixture { - ($name: literal) => { - &[] - }; - } pub const DUMMY: &[u8] = fixture!("dummy"); pub const NOOP: &[u8] = fixture!("noop"); pub const INSTR: &[u8] = fixture!("instr_benchmark"); diff --git a/substrate/frame/revive/mock-network/Cargo.toml b/substrate/frame/revive/mock-network/Cargo.toml index 12de634b0b4a..c5b18b3fa290 100644 --- a/substrate/frame/revive/mock-network/Cargo.toml +++ b/substrate/frame/revive/mock-network/Cargo.toml @@ -48,7 +48,6 @@ pallet-revive-fixtures = { workspace = true } [features] default = ["std"] -riscv = ["pallet-revive-fixtures/riscv"] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/revive/mock-network/src/lib.rs b/substrate/frame/revive/mock-network/src/lib.rs index 848994653972..adfd0016b4dd 100644 --- a/substrate/frame/revive/mock-network/src/lib.rs +++ b/substrate/frame/revive/mock-network/src/lib.rs @@ -19,7 +19,7 @@ pub mod parachain; pub mod primitives; pub mod relay_chain; -#[cfg(all(test, feature = "riscv"))] +#[cfg(test)] mod tests; use crate::primitives::{AccountId, UNITS}; diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index ef7a7c1b28e4..e6d8c38c04f0 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -15,27 +15,27 @@ path = "src/main.rs" [[example]] name = "deploy" path = "examples/rust/deploy.rs" -required-features = ["example", "riscv"] +required-features = ["example"] [[example]] name = "transfer" path = "examples/rust/transfer.rs" -required-features = ["example", "riscv"] +required-features = ["example"] [[example]] name = "rpc-playground" path = "examples/rust/rpc-playground.rs" -required-features = ["example", "riscv"] +required-features = ["example"] [[example]] name = "extrinsic" path = "examples/rust/extrinsic.rs" -required-features = ["example", "riscv"] +required-features = ["example"] [[example]] name = "remark-extrinsic" path = "examples/rust/remark-extrinsic.rs" -required-features = ["example", "riscv"] +required-features = ["example"] [dependencies] clap = { workspace = true, features = ["derive"] } @@ -72,7 +72,6 @@ env_logger = { workspace = true } [features] example = ["hex", "hex-literal", "rlp", "secp256k1", "subxt-signer"] -riscv = ["pallet-revive/riscv"] [dev-dependencies] hex-literal = { workspace = true } diff --git a/substrate/frame/revive/rpc/Dockerfile b/substrate/frame/revive/rpc/Dockerfile index 981d5c19a158..fb867062a818 100644 --- a/substrate/frame/revive/rpc/Dockerfile +++ b/substrate/frame/revive/rpc/Dockerfile @@ -7,6 +7,7 @@ RUN apt-get update && \ WORKDIR /polkadot COPY . /polkadot +RUN rustup component add rust-src RUN cargo build --locked --profile production -p pallet-revive-eth-rpc --bin eth-rpc FROM docker.io/parity/base-bin:latest diff --git a/substrate/frame/revive/rpc/examples/README.md b/substrate/frame/revive/rpc/examples/README.md index 7c01dc0075ee..bf30426648ba 100644 --- a/substrate/frame/revive/rpc/examples/README.md +++ b/substrate/frame/revive/rpc/examples/README.md @@ -3,7 +3,7 @@ Build `pallet-revive-fixture`, as we need some compiled contracts to exercise the RPC server. ```bash -cargo build -p pallet-revive-fixtures --features riscv +cargo build -p pallet-revive-fixtures ``` ## Start the node @@ -96,4 +96,3 @@ See [this guide][import-account] for more info on how to import an account. [add-network]: https://support.metamask.io/networks-and-sidechains/managing-networks/how-to-add-a-custom-network-rpc/#adding-a-network-manually [import-account]: https://support.metamask.io/managing-my-wallet/accounts-and-addresses/how-to-import-an-account/ [reset-account]: https://support.metamask.io/managing-my-wallet/resetting-deleting-and-restoring/how-to-clear-your-account-activity-reset-account - diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index f745bea6a5f6..5d84e06e9e04 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -16,8 +16,6 @@ // limitations under the License. //! Test the eth-rpc cli with the kitchensink node. -// We require the `riscv` feature to get access to the compiled fixtures. -#![cfg(feature = "riscv")] use crate::{ cli::{self, CliCommand}, example::{send_transaction, wait_for_receipt}, diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index dd7e52327b66..3d1d7d2a224a 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -15,9 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Benchmarks for the contracts pallet +//! Benchmarks for the revive pallet -#![cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] +#![cfg(feature = "runtime-benchmarks")] mod call_builder; mod code; diff --git a/substrate/frame/revive/src/benchmarking_dummy.rs b/substrate/frame/revive/src/benchmarking_dummy.rs deleted file mode 100644 index 6bb467911272..000000000000 --- a/substrate/frame/revive/src/benchmarking_dummy.rs +++ /dev/null @@ -1,37 +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. -// - -//! Defines a dummy benchmarking suite so that the build doesn't fail in case -//! no RISC-V toolchain is available. - -#![cfg(feature = "runtime-benchmarks")] -#![cfg(not(feature = "riscv"))] - -use crate::{Config, *}; -use frame_benchmarking::v2::*; - -#[benchmarks] -mod benchmarks { - use super::*; - - #[benchmark(pov_mode = Ignored)] - fn enable_riscv_feature_to_unlock_benchmarks() { - #[block] - {} - } -} diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index 6db3f43857ee..3acd67b32aab 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -396,7 +396,6 @@ pub trait EthExtra { } } -#[cfg(feature = "riscv")] #[cfg(test)] mod test { use super::*; diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 4b7198d570c1..8629a21c4fda 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -819,7 +819,7 @@ where .map(|_| (address, stack.first_frame.last_frame_output)) } - #[cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] + #[cfg(feature = "runtime-benchmarks")] pub fn bench_new_call( dest: H160, origin: Origin, @@ -1330,12 +1330,12 @@ where /// Certain APIs, e.g. `{set,get}_immutable_data` behave differently depending /// on the configured entry point. Thus, we allow setting the export manually. - #[cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] + #[cfg(feature = "runtime-benchmarks")] pub(crate) fn override_export(&mut self, export: ExportedFunction) { self.top_frame_mut().entry_point = export; } - #[cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] + #[cfg(feature = "runtime-benchmarks")] pub(crate) fn set_block_number(&mut self, block_number: BlockNumberFor) { self.block_number = block_number; } diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index d50da45fc3a9..51e9a8fa3f90 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -23,7 +23,6 @@ extern crate alloc; mod address; mod benchmarking; -mod benchmarking_dummy; mod exec; mod gas; mod limits; diff --git a/substrate/frame/revive/src/storage.rs b/substrate/frame/revive/src/storage.rs index db4db3e8eac3..b7156588d44c 100644 --- a/substrate/frame/revive/src/storage.rs +++ b/substrate/frame/revive/src/storage.rs @@ -505,7 +505,6 @@ impl DeletionQueueManager { } #[cfg(test)] -#[cfg(feature = "riscv")] impl DeletionQueueManager { pub fn from_test_values(insert_counter: u32, delete_counter: u32) -> Self { Self { insert_counter, delete_counter, _phantom: Default::default() } diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 7ce2e3d9bf34..2d9cae16c441 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -15,8 +15,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![cfg_attr(not(feature = "riscv"), allow(dead_code, unused_imports, unused_macros))] - mod pallet_dummy; mod test_debug; @@ -64,6 +62,8 @@ use frame_system::{EventRecord, Phase}; use pallet_revive_fixtures::{bench::dummy_unique, compile_module}; use pallet_revive_uapi::ReturnErrorCode as RuntimeReturnCode; use pallet_transaction_payment::{ConstFeeMultiplier, Multiplier}; +use pretty_assertions::{assert_eq, assert_ne}; +use sp_core::U256; use sp_io::hashing::blake2_256; use sp_keystore::{testing::MemoryKeystore, KeystoreExt}; use sp_runtime::{ @@ -624,1300 +624,1400 @@ impl Default for Origin { } } -/// We can only run the tests if we have a riscv toolchain installed -#[cfg(feature = "riscv")] -mod run_tests { - use super::*; - use pretty_assertions::{assert_eq, assert_ne}; - use sp_core::U256; +#[test] +fn calling_plain_account_is_balance_transfer() { + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 100_000_000); + assert!(!>::contains_key(BOB_ADDR)); + assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 0); + let result = builder::bare_call(BOB_ADDR).value(42).build_and_unwrap_result(); + assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 42); + assert_eq!(result, Default::default()); + }); +} - #[test] - fn calling_plain_account_is_balance_transfer() { - ExtBuilder::default().build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 100_000_000); - assert!(!>::contains_key(BOB_ADDR)); - assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 0); - let result = builder::bare_call(BOB_ADDR).value(42).build_and_unwrap_result(); - assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 42); - assert_eq!(result, Default::default()); - }); - } +#[test] +fn instantiate_and_call_and_deposit_event() { + let (wasm, code_hash) = compile_module("event_and_return_on_deploy").unwrap(); - #[test] - fn instantiate_and_call_and_deposit_event() { - let (wasm, code_hash) = compile_module("event_and_return_on_deploy").unwrap(); + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let value = 100; - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - let value = 100; + // We determine the storage deposit limit after uploading because it depends on ALICEs + // free balance which is changed by uploading a module. + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm, + deposit_limit::(), + )); + + // Drop previous events + initialize_block(2); + + // Check at the end to get hash on error easily + let Contract { addr, account_id } = builder::bare_instantiate(Code::Existing(code_hash)) + .value(value) + .build_and_unwrap_contract(); + assert!(ContractInfoOf::::contains_key(&addr)); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: account_id.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: account_id.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id.clone(), + amount: value, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::ContractEmitted { + contract: addr, + data: vec![1, 2, 3, 4], + topics: vec![H256::repeat_byte(42)], + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE_ADDR, + contract: addr + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: addr, + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} - // We determine the storage deposit limit after uploading because it depends on ALICEs - // free balance which is changed by uploading a module. - assert_ok!(Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - wasm, - deposit_limit::(), - )); +#[test] +fn create1_address_from_extrinsic() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); - // Drop previous events - initialize_block(2); + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // Check at the end to get hash on error easily - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Existing(code_hash)) - .value(value) - .build_and_unwrap_contract(); - assert!(ContractInfoOf::::contains_key(&addr)); + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + deposit_limit::(), + )); + + assert_eq!(System::account_nonce(&ALICE), 0); + System::inc_account_nonce(&ALICE); + for nonce in 1..3 { + let Contract { addr, .. } = builder::bare_instantiate(Code::Existing(code_hash)) + .salt(None) + .build_and_unwrap_contract(); + assert!(ContractInfoOf::::contains_key(&addr)); assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::System(frame_system::Event::NewAccount { - account: account_id.clone() - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { - account: account_id.clone(), - free_balance: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id.clone(), - amount: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id.clone(), - amount: value, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::ContractEmitted { - contract: addr, - data: vec![1, 2, 3, 4], - topics: vec![H256::repeat_byte(42)], - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Instantiated { - deployer: ALICE_ADDR, - contract: addr - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: addr, - amount: test_utils::contract_info_storage_deposit(&addr), - } - ), - topics: vec![], - }, - ] + addr, + create1(&::AddressMapper::to_address(&ALICE), nonce - 1) ); - }); - } + } + assert_eq!(System::account_nonce(&ALICE), 3); - #[test] - fn create1_address_from_extrinsic() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); + for nonce in 3..6 { + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm.clone())) + .salt(None) + .build_and_unwrap_contract(); + assert!(ContractInfoOf::::contains_key(&addr)); + assert_eq!( + addr, + create1(&::AddressMapper::to_address(&ALICE), nonce - 1) + ); + } + assert_eq!(System::account_nonce(&ALICE), 6); + }); +} - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn deposit_event_max_value_limit() { + let (wasm, _code_hash) = compile_module("event_size").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_contract(); + + // Call contract with allowed storage value. + assert_ok!(builder::call(addr) + .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer, + .data(limits::PAYLOAD_BYTES.encode()) + .build()); + + // Call contract with too large a storage value. + assert_err_ignore_postinfo!( + builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(), + Error::::ValueTooLarge, + ); + }); +} - assert_ok!(Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - wasm.clone(), - deposit_limit::(), - )); +// Fail out of fuel (ref_time weight) in the engine. +#[test] +fn run_out_of_fuel_engine() { + let (wasm, _code_hash) = compile_module("run_out_of_gas").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(100 * min_balance) + .build_and_unwrap_contract(); + + // Call the contract with a fixed gas limit. It must run out of gas because it just + // loops forever. + assert_err_ignore_postinfo!( + builder::call(addr) + .gas_limit(Weight::from_parts(10_000_000_000, u64::MAX)) + .build(), + Error::::OutOfGas, + ); + }); +} - assert_eq!(System::account_nonce(&ALICE), 0); - System::inc_account_nonce(&ALICE); +// Fail out of fuel (ref_time weight) in the host. +#[test] +fn run_out_of_fuel_host() { + let (code, _hash) = compile_module("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + let gas_limit = Weight::from_parts(u32::MAX as u64, GAS_LIMIT.proof_size()); + + // Use chain extension to charge more ref_time than it is available. + let result = builder::bare_call(addr) + .gas_limit(gas_limit) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &u32::MAX.encode() }.into()) + .build() + .result; + assert_err!(result, >::OutOfGas); + }); +} - for nonce in 1..3 { - let Contract { addr, .. } = builder::bare_instantiate(Code::Existing(code_hash)) - .salt(None) - .build_and_unwrap_contract(); - assert!(ContractInfoOf::::contains_key(&addr)); - assert_eq!( - addr, - create1(&::AddressMapper::to_address(&ALICE), nonce - 1) - ); - } - assert_eq!(System::account_nonce(&ALICE), 3); +#[test] +fn gas_syncs_work() { + let (code, _code_hash) = compile_module("caller_is_origin_n").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let contract = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + + let result = builder::bare_call(contract.addr).data(0u32.encode()).build(); + assert_ok!(result.result); + let engine_consumed_noop = result.gas_consumed.ref_time(); + + let result = builder::bare_call(contract.addr).data(1u32.encode()).build(); + assert_ok!(result.result); + let gas_consumed_once = result.gas_consumed.ref_time(); + let host_consumed_once = ::WeightInfo::seal_caller_is_origin().ref_time(); + let engine_consumed_once = gas_consumed_once - host_consumed_once - engine_consumed_noop; + + let result = builder::bare_call(contract.addr).data(2u32.encode()).build(); + assert_ok!(result.result); + let gas_consumed_twice = result.gas_consumed.ref_time(); + let host_consumed_twice = host_consumed_once * 2; + let engine_consumed_twice = gas_consumed_twice - host_consumed_twice - engine_consumed_noop; + + // Second contract just repeats first contract's instructions twice. + // If runtime syncs gas with the engine properly, this should pass. + assert_eq!(engine_consumed_twice, engine_consumed_once * 2); + }); +} - for nonce in 3..6 { - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm.clone())) - .salt(None) - .build_and_unwrap_contract(); - assert!(ContractInfoOf::::contains_key(&addr)); - assert_eq!( - addr, - create1(&::AddressMapper::to_address(&ALICE), nonce - 1) - ); - } - assert_eq!(System::account_nonce(&ALICE), 6); - }); - } +/// Check that contracts with the same account id have different trie ids. +/// Check the `Nonce` storage item for more information. +#[test] +fn instantiate_unique_trie_id() { + let (wasm, code_hash) = compile_module("self_destruct").unwrap(); - #[test] - fn deposit_event_max_value_limit() { - let (wasm, _code_hash) = compile_module("event_size").unwrap(); + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, deposit_limit::()) + .unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - // Create - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(30_000) - .build_and_unwrap_contract(); + // Instantiate the contract and store its trie id for later comparison. + let Contract { addr, .. } = + builder::bare_instantiate(Code::Existing(code_hash)).build_and_unwrap_contract(); + let trie_id = get_contract(&addr).trie_id; - // Call contract with allowed storage value. - assert_ok!(builder::call(addr) - .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer, - .data(limits::PAYLOAD_BYTES.encode()) - .build()); + // Try to instantiate it again without termination should yield an error. + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).build(), + >::DuplicateContract, + ); - // Call contract with too large a storage value. - assert_err_ignore_postinfo!( - builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(), - Error::::ValueTooLarge, - ); - }); - } + // Terminate the contract. + assert_ok!(builder::call(addr).build()); - // Fail out of fuel (ref_time weight) in the engine. - #[test] - fn run_out_of_fuel_engine() { - let (wasm, _code_hash) = compile_module("run_out_of_gas").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Re-Instantiate after termination. + assert_ok!(builder::instantiate(code_hash).build()); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(100 * min_balance) - .build_and_unwrap_contract(); + // Trie ids shouldn't match or we might have a collision + assert_ne!(trie_id, get_contract(&addr).trie_id); + }); +} - // Call the contract with a fixed gas limit. It must run out of gas because it just - // loops forever. - assert_err_ignore_postinfo!( - builder::call(addr) - .gas_limit(Weight::from_parts(10_000_000_000, u64::MAX)) - .build(), - Error::::OutOfGas, - ); - }); - } +#[test] +fn storage_work() { + let (code, _code_hash) = compile_module("storage").unwrap(); - // Fail out of fuel (ref_time weight) in the host. - #[test] - fn run_out_of_fuel_host() { - let (code, _hash) = compile_module("chain_extension").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + builder::bare_call(addr).build_and_unwrap_result(); + }); +} - let gas_limit = Weight::from_parts(u32::MAX as u64, GAS_LIMIT.proof_size()); +#[test] +fn storage_max_value_limit() { + let (wasm, _code_hash) = compile_module("storage_size").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_contract(); + get_contract(&addr); + + // Call contract with allowed storage value. + assert_ok!(builder::call(addr) + .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer + .data(limits::PAYLOAD_BYTES.encode()) + .build()); + + // Call contract with too large a storage value. + assert_err_ignore_postinfo!( + builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(), + Error::::ValueTooLarge, + ); + }); +} - // Use chain extension to charge more ref_time than it is available. - let result = builder::bare_call(addr) - .gas_limit(gas_limit) - .data( - ExtensionInput { extension_id: 0, func_id: 2, extra: &u32::MAX.encode() } - .into(), - ) - .build() - .result; - assert_err!(result, >::OutOfGas); - }); - } +#[test] +fn transient_storage_work() { + let (code, _code_hash) = compile_module("transient_storage").unwrap(); - #[test] - fn gas_syncs_work() { - let (code, _code_hash) = compile_module("caller_is_origin_n").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let contract = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); - - let result = builder::bare_call(contract.addr).data(0u32.encode()).build(); - assert_ok!(result.result); - let engine_consumed_noop = result.gas_consumed.ref_time(); - - let result = builder::bare_call(contract.addr).data(1u32.encode()).build(); - assert_ok!(result.result); - let gas_consumed_once = result.gas_consumed.ref_time(); - let host_consumed_once = - ::WeightInfo::seal_caller_is_origin().ref_time(); - let engine_consumed_once = - gas_consumed_once - host_consumed_once - engine_consumed_noop; - - let result = builder::bare_call(contract.addr).data(2u32.encode()).build(); - assert_ok!(result.result); - let gas_consumed_twice = result.gas_consumed.ref_time(); - let host_consumed_twice = host_consumed_once * 2; - let engine_consumed_twice = - gas_consumed_twice - host_consumed_twice - engine_consumed_noop; - - // Second contract just repeats first contract's instructions twice. - // If runtime syncs gas with the engine properly, this should pass. - assert_eq!(engine_consumed_twice, engine_consumed_once * 2); - }); - } + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - /// Check that contracts with the same account id have different trie ids. - /// Check the `Nonce` storage item for more information. - #[test] - fn instantiate_unique_trie_id() { - let (wasm, code_hash) = compile_module("self_destruct").unwrap(); + builder::bare_call(addr).build_and_unwrap_result(); + }); +} - ExtBuilder::default().existential_deposit(500).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, deposit_limit::()) - .unwrap(); +#[test] +fn transient_storage_limit_in_call() { + let (wasm_caller, _code_hash_caller) = + compile_module("create_transient_storage_and_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("set_transient_storage").unwrap(); + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + // Call contracts with storage values within the limit. + // Caller and Callee contracts each set a transient storage value of size 100. + assert_ok!(builder::call(addr_caller) + .data((100u32, 100u32, &addr_callee).encode()) + .build(),); + + // Call a contract with a storage value that is too large. + // Limit exceeded in the caller contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((4u32 * 1024u32, 200u32, &addr_callee).encode()) + .build(), + >::OutOfTransientStorage, + ); - // Instantiate the contract and store its trie id for later comparison. - let Contract { addr, .. } = - builder::bare_instantiate(Code::Existing(code_hash)).build_and_unwrap_contract(); - let trie_id = get_contract(&addr).trie_id; + // Call a contract with a storage value that is too large. + // Limit exceeded in the callee contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((50u32, 4 * 1024u32, &addr_callee).encode()) + .build(), + >::ContractTrapped + ); + }); +} - // Try to instantiate it again without termination should yield an error. - assert_err_ignore_postinfo!( - builder::instantiate(code_hash).build(), - >::DuplicateContract, - ); +#[test] +fn deploy_and_call_other_contract() { + let (caller_wasm, _caller_code_hash) = compile_module("caller_contract").unwrap(); + let (callee_wasm, callee_code_hash) = compile_module("return_with_data").unwrap(); - // Terminate the contract. - assert_ok!(builder::call(addr).build()); + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let min_balance = Contracts::min_balance(); - // Re-Instantiate after termination. - assert_ok!(builder::instantiate(code_hash).build()); + // Create + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr: caller_addr, account_id: caller_account } = + builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(100_000) + .build_and_unwrap_contract(); - // Trie ids shouldn't match or we might have a collision - assert_ne!(trie_id, get_contract(&addr).trie_id); - }); - } + let callee_addr = create2( + &caller_addr, + &callee_wasm, + &[0, 1, 34, 51, 68, 85, 102, 119], // hard coded in wasm + &[0u8; 32], + ); + let callee_account = ::AddressMapper::to_account_id(&callee_addr); - #[test] - fn storage_work() { - let (code, _code_hash) = compile_module("storage").unwrap(); + Contracts::upload_code(RuntimeOrigin::signed(ALICE), callee_wasm, deposit_limit::()) + .unwrap(); - ExtBuilder::default().build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + // Drop previous events + initialize_block(2); - builder::bare_call(addr).build_and_unwrap_result(); - }); - } + // Call BOB contract, which attempts to instantiate and call the callee contract and + // makes various assertions on the results from those calls. + assert_ok!(builder::call(caller_addr).data(callee_code_hash.as_ref().to_vec()).build()); - #[test] - fn storage_max_value_limit() { - let (wasm, _code_hash) = compile_module("storage_size").unwrap(); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: callee_account.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: callee_account.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: callee_account.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: caller_account.clone(), + to: callee_account.clone(), + amount: 32768 // hardcoded in wasm + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: caller_addr, + contract: callee_addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: caller_account.clone(), + to: callee_account.clone(), + amount: 32768, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(caller_account.clone()), + contract: callee_addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: caller_addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: callee_addr, + amount: test_utils::contract_info_storage_deposit(&callee_addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - // Create - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(30_000) - .build_and_unwrap_contract(); - get_contract(&addr); - - // Call contract with allowed storage value. - assert_ok!(builder::call(addr) - .gas_limit(GAS_LIMIT.set_ref_time(GAS_LIMIT.ref_time() * 2)) // we are copying a huge buffer - .data(limits::PAYLOAD_BYTES.encode()) - .build()); - - // Call contract with too large a storage value. - assert_err_ignore_postinfo!( - builder::call(addr).data((limits::PAYLOAD_BYTES + 1).encode()).build(), - Error::::ValueTooLarge, - ); - }); - } +#[test] +fn delegate_call() { + let (caller_wasm, _caller_code_hash) = compile_module("delegate_call").unwrap(); + let (callee_wasm, callee_code_hash) = compile_module("delegate_call_lib").unwrap(); - #[test] - fn transient_storage_work() { - let (code, _code_hash) = compile_module("transient_storage").unwrap(); + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - ExtBuilder::default().build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) + // Instantiate the 'caller' + let Contract { addr: caller_addr, .. } = + builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(300_000) .build_and_unwrap_contract(); + // Only upload 'callee' code + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), callee_wasm, 100_000,)); + + assert_ok!(builder::call(caller_addr) + .value(1337) + .data(callee_code_hash.as_ref().to_vec()) + .build()); + }); +} - builder::bare_call(addr).build_and_unwrap_result(); - }); - } +#[test] +fn transfer_expendable_cannot_kill_account() { + let (wasm, _code_hash) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - #[test] - fn transient_storage_limit_in_call() { - let (wasm_caller, _code_hash_caller) = - compile_module("create_transient_storage_and_call").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("set_transient_storage").unwrap(); - ExtBuilder::default().build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Instantiate the BOB contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(1_000) + .build_and_unwrap_contract(); - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); - - // Call contracts with storage values within the limit. - // Caller and Callee contracts each set a transient storage value of size 100. - assert_ok!(builder::call(addr_caller) - .data((100u32, 100u32, &addr_callee).encode()) - .build(),); - - // Call a contract with a storage value that is too large. - // Limit exceeded in the caller contract. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .data((4u32 * 1024u32, 200u32, &addr_callee).encode()) - .build(), - >::OutOfTransientStorage, - ); + // Check that the BOB contract has been instantiated. + get_contract(&addr); - // Call a contract with a storage value that is too large. - // Limit exceeded in the callee contract. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .data((50u32, 4 * 1024u32, &addr_callee).encode()) - .build(), - >::ContractTrapped - ); - }); - } + let account = ::AddressMapper::to_account_id(&addr); + let total_balance = ::Currency::total_balance(&account); - #[test] - fn deploy_and_call_other_contract() { - let (caller_wasm, _caller_code_hash) = compile_module("caller_contract").unwrap(); - let (callee_wasm, callee_code_hash) = compile_module("return_with_data").unwrap(); + assert_eq!( + test_utils::get_balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account), + test_utils::contract_info_storage_deposit(&addr) + ); - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let min_balance = Contracts::min_balance(); + // Some ot the total balance is held, so it can't be transferred. + assert_err!( + <::Currency as Mutate>::transfer( + &account, + &ALICE, + total_balance, + Preservation::Expendable, + ), + TokenError::FundsUnavailable, + ); - // Create - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr: caller_addr, account_id: caller_account } = - builder::bare_instantiate(Code::Upload(caller_wasm)) - .value(100_000) - .build_and_unwrap_contract(); + assert_eq!(::Currency::total_balance(&account), total_balance); + }); +} - let callee_addr = create2( - &caller_addr, - &callee_wasm, - &[0, 1, 34, 51, 68, 85, 102, 119], // hard coded in wasm - &[0u8; 32], - ); - let callee_account = ::AddressMapper::to_account_id(&callee_addr); +#[test] +fn cannot_self_destruct_through_draining() { + let (wasm, _code_hash) = compile_module("drain").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let value = 1_000; + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_contract(); + let account = ::AddressMapper::to_account_id(&addr); + + // Check that the BOB contract has been instantiated. + get_contract(&addr); + + // Call BOB which makes it send all funds to the zero address + // The contract code asserts that the transfer fails with the correct error code + assert_ok!(builder::call(addr).build()); + + // Make sure the account wasn't remove by sending all free balance away. + assert_eq!( + ::Currency::total_balance(&account), + value + test_utils::contract_info_storage_deposit(&addr) + min_balance, + ); + }); +} - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - callee_wasm, - deposit_limit::(), - ) - .unwrap(); +#[test] +fn cannot_self_destruct_through_storage_refund_after_price_change() { + let (wasm, _code_hash) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let contract = builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + let info_deposit = test_utils::contract_info_storage_deposit(&contract.addr); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&contract.addr).total_deposit(), info_deposit); + assert_eq!(get_contract(&contract.addr).extra_deposit(), 0); + assert_eq!( + ::Currency::total_balance(&contract.account_id), + info_deposit + min_balance + ); - // Drop previous events - initialize_block(2); + // Create 100 bytes of storage with a price of per byte and a single storage item of + // price 2 + assert_ok!(builder::call(contract.addr).data(100u32.to_le_bytes().to_vec()).build()); + assert_eq!(get_contract(&contract.addr).total_deposit(), info_deposit + 102); + + // Increase the byte price and trigger a refund. This should not have any influence + // because the removal is pro rata and exactly those 100 bytes should have been + // removed. + DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 500); + assert_ok!(builder::call(contract.addr).data(0u32.to_le_bytes().to_vec()).build()); + + // Make sure the account wasn't removed by the refund + assert_eq!( + ::Currency::total_balance(&contract.account_id), + get_contract(&contract.addr).total_deposit() + min_balance, + ); + assert_eq!(get_contract(&contract.addr).extra_deposit(), 2); + }); +} - // Call BOB contract, which attempts to instantiate and call the callee contract and - // makes various assertions on the results from those calls. - assert_ok!(builder::call(caller_addr).data(callee_code_hash.as_ref().to_vec()).build()); +#[test] +fn cannot_self_destruct_while_live() { + let (wasm, _code_hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the BOB contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_contract(); + + // Check that the BOB contract has been instantiated. + get_contract(&addr); + + // Call BOB with input data, forcing it make a recursive call to itself to + // self-destruct, resulting in a trap. + assert_err_ignore_postinfo!( + builder::call(addr).data(vec![0]).build(), + Error::::ContractTrapped, + ); - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::System(frame_system::Event::NewAccount { - account: callee_account.clone() - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { - account: callee_account.clone(), - free_balance: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: callee_account.clone(), - amount: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: caller_account.clone(), - to: callee_account.clone(), - amount: 32768 // hardcoded in wasm - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Instantiated { - deployer: caller_addr, - contract: callee_addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: caller_account.clone(), - to: callee_account.clone(), - amount: 32768, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(caller_account.clone()), - contract: callee_addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: caller_addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: callee_addr, - amount: test_utils::contract_info_storage_deposit(&callee_addr), - } - ), - topics: vec![], - }, - ] - ); - }); - } + // Check that BOB is still there. + get_contract(&addr); + }); +} - #[test] - fn delegate_call() { - let (caller_wasm, _caller_code_hash) = compile_module("delegate_call").unwrap(); - let (callee_wasm, callee_code_hash) = compile_module("delegate_call_lib").unwrap(); +#[test] +fn self_destruct_works() { + let (wasm, code_hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(1_000).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&DJANGO_FALLBACK, 1_000_000); + let min_balance = Contracts::min_balance(); - ExtBuilder::default().existential_deposit(500).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Instantiate the BOB contract. + let contract = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_contract(); - // Instantiate the 'caller' - let Contract { addr: caller_addr, .. } = - builder::bare_instantiate(Code::Upload(caller_wasm)) - .value(300_000) - .build_and_unwrap_contract(); - // Only upload 'callee' code - assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), callee_wasm, 100_000,)); + // Check that the BOB contract has been instantiated. + let _ = get_contract(&contract.addr); - assert_ok!(builder::call(caller_addr) - .value(1337) - .data(callee_code_hash.as_ref().to_vec()) - .build()); - }); - } + let info_deposit = test_utils::contract_info_storage_deposit(&contract.addr); - #[test] - fn transfer_expendable_cannot_kill_account() { - let (wasm, _code_hash) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Drop all previous events + initialize_block(2); - // Instantiate the BOB contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(1_000) - .build_and_unwrap_contract(); + // Call BOB without input data which triggers termination. + assert_matches!(builder::call(contract.addr).build(), Ok(_)); - // Check that the BOB contract has been instantiated. - get_contract(&addr); + // Check that code is still there but refcount dropped to zero. + assert_refcount!(&code_hash, 0); - let account = ::AddressMapper::to_account_id(&addr); - let total_balance = ::Currency::total_balance(&account); + // Check that account is gone + assert!(get_contract_checked(&contract.addr).is_none()); + assert_eq!(::Currency::total_balance(&contract.account_id), 0); - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &account - ), - test_utils::contract_info_storage_deposit(&addr) - ); + // Check that the beneficiary (django) got remaining balance. + assert_eq!( + ::Currency::free_balance(DJANGO_FALLBACK), + 1_000_000 + 100_000 + min_balance + ); - // Some ot the total balance is held, so it can't be transferred. - assert_err!( - <::Currency as Mutate>::transfer( - &account, - &ALICE, - total_balance, - Preservation::Expendable, - ), - TokenError::FundsUnavailable, - ); + // Check that the Alice is missing Django's benefit. Within ALICE's total balance + // there's also the code upload deposit held. + assert_eq!( + ::Currency::total_balance(&ALICE), + 1_000_000 - (100_000 + min_balance) + ); - assert_eq!(::Currency::total_balance(&account), total_balance); - }); - } + pretty_assertions::assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Terminated { + contract: contract.addr, + beneficiary: DJANGO_ADDR, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: contract.addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndReleased { + from: contract.addr, + to: ALICE_ADDR, + amount: info_deposit, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::KilledAccount { + account: contract.account_id.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: contract.account_id.clone(), + to: DJANGO_FALLBACK, + amount: 100_000 + min_balance, + }), + topics: vec![], + }, + ], + ); + }); +} - #[test] - fn cannot_self_destruct_through_draining() { - let (wasm, _code_hash) = compile_module("drain").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let value = 1_000; - let min_balance = Contracts::min_balance(); +// This tests that one contract cannot prevent another from self-destructing by sending it +// additional funds after it has been drained. +#[test] +fn destroy_contract_and_transfer_funds() { + let (callee_wasm, callee_code_hash) = compile_module("self_destruct").unwrap(); + let (caller_wasm, _caller_code_hash) = compile_module("destroy_and_transfer").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + // Create code hash for bob to instantiate + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + callee_wasm.clone(), + deposit_limit::(), + ) + .unwrap(); + + // This deploys the BOB contract, which in turn deploys the CHARLIE contract during + // construction. + let Contract { addr: addr_bob, .. } = builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(200_000) + .data(callee_code_hash.as_ref().to_vec()) + .build_and_unwrap_contract(); + + // Check that the CHARLIE contract has been instantiated. + let salt = [47; 32]; // hard coded in fixture. + let addr_charlie = create2(&addr_bob, &callee_wasm, &[], &salt); + get_contract(&addr_charlie); + + // Call BOB, which calls CHARLIE, forcing CHARLIE to self-destruct. + assert_ok!(builder::call(addr_bob).data(addr_charlie.encode()).build()); + + // Check that CHARLIE has moved on to the great beyond (ie. died). + assert!(get_contract_checked(&addr_charlie).is_none()); + }); +} - // Instantiate the BOB contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(value) - .build_and_unwrap_contract(); - let account = ::AddressMapper::to_account_id(&addr); +#[test] +fn cannot_self_destruct_in_constructor() { + let (wasm, _) = compile_module("self_destructing_constructor").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // Check that the BOB contract has been instantiated. - get_contract(&addr); + // Fail to instantiate the BOB because the constructor calls seal_terminate. + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).value(100_000).build(), + Error::::TerminatedInConstructor, + ); + }); +} - // Call BOB which makes it send all funds to the zero address - // The contract code asserts that the transfer fails with the correct error code - assert_ok!(builder::call(addr).build()); +#[test] +fn crypto_hashes() { + let (wasm, _code_hash) = compile_module("crypto_hashes").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the CRYPTO_HASHES contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_contract(); + // Perform the call. + let input = b"_DEAD_BEEF"; + use sp_io::hashing::*; + // Wraps a hash function into a more dynamic form usable for testing. + macro_rules! dyn_hash_fn { + ($name:ident) => { + Box::new(|input| $name(input).as_ref().to_vec().into_boxed_slice()) + }; + } + // All hash functions and their associated output byte lengths. + let test_cases: &[(Box Box<[u8]>>, usize)] = &[ + (dyn_hash_fn!(sha2_256), 32), + (dyn_hash_fn!(keccak_256), 32), + (dyn_hash_fn!(blake2_256), 32), + (dyn_hash_fn!(blake2_128), 16), + ]; + // Test the given hash functions for the input: "_DEAD_BEEF" + for (n, (hash_fn, expected_size)) in test_cases.iter().enumerate() { + // We offset data in the contract tables by 1. + let mut params = vec![(n + 1) as u8]; + params.extend_from_slice(input); + let result = builder::bare_call(addr).data(params).build_and_unwrap_result(); + assert!(!result.did_revert()); + let expected = hash_fn(input.as_ref()); + assert_eq!(&result.data[..*expected_size], &*expected); + } + }) +} - // Make sure the account wasn't remove by sending all free balance away. - assert_eq!( - ::Currency::total_balance(&account), - value + test_utils::contract_info_storage_deposit(&addr) + min_balance, - ); - }); - } +#[test] +fn transfer_return_code() { + let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let contract = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // Contract has only the minimal balance so any transfer will fail. + ::Currency::set_balance(&contract.account_id, min_balance); + let result = builder::bare_call(contract.addr).build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + }); +} - #[test] - fn cannot_self_destruct_through_storage_refund_after_price_change() { - let (wasm, _code_hash) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); +#[test] +fn call_return_code() { + use test_utils::u256_bytes; + + let (caller_code, _caller_hash) = compile_module("call_return_code").unwrap(); + let (callee_code, _callee_hash) = compile_module("ok_trap_revert").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 bob = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // Contract calls into Django which is no valid contract + // This will be a balance transfer into a new account + // with more than the contract has which will make the transfer fail + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&DJANGO_ADDR) + .iter() + .chain(&u256_bytes(min_balance * 200)) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); - // Instantiate the BOB contract. - let contract = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - let info_deposit = test_utils::contract_info_storage_deposit(&contract.addr); + // Sending less than the minimum balance will also make the transfer fail + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&DJANGO_ADDR) + .iter() + .chain(&u256_bytes(42)) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + + // Sending at least the minimum balance should result in success but + // no code called. + assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 0); + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&DJANGO_ADDR) + .iter() + .chain(&u256_bytes(55)) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::Success); + assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 55); + + let django = builder::bare_instantiate(Code::Upload(callee_code)) + .origin(RuntimeOrigin::signed(CHARLIE)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // Sending more than the contract has will make the transfer fail. + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&django.addr) + .iter() + .chain(&u256_bytes(min_balance * 300)) + .chain(&0u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + + // Contract has enough balance but callee reverts because "1" is passed. + ::Currency::set_balance(&bob.account_id, min_balance + 1000); + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&django.addr) + .iter() + .chain(&u256_bytes(5)) + .chain(&1u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeReverted); - // Check that the contract has been instantiated and has the minimum balance - assert_eq!(get_contract(&contract.addr).total_deposit(), info_deposit); - assert_eq!(get_contract(&contract.addr).extra_deposit(), 0); - assert_eq!( - ::Currency::total_balance(&contract.account_id), - info_deposit + min_balance - ); + // Contract has enough balance but callee traps because "2" is passed. + let result = builder::bare_call(bob.addr) + .data( + AsRef::<[u8]>::as_ref(&django.addr) + .iter() + .chain(&u256_bytes(5)) + .chain(&2u32.to_le_bytes()) + .cloned() + .collect(), + ) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); + }); +} - // Create 100 bytes of storage with a price of per byte and a single storage item of - // price 2 - assert_ok!(builder::call(contract.addr).data(100u32.to_le_bytes().to_vec()).build()); - assert_eq!(get_contract(&contract.addr).total_deposit(), info_deposit + 102); - - // Increase the byte price and trigger a refund. This should not have any influence - // because the removal is pro rata and exactly those 100 bytes should have been - // removed. - DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 500); - assert_ok!(builder::call(contract.addr).data(0u32.to_le_bytes().to_vec()).build()); - - // Make sure the account wasn't removed by the refund - assert_eq!( - ::Currency::total_balance(&contract.account_id), - get_contract(&contract.addr).total_deposit() + min_balance, - ); - assert_eq!(get_contract(&contract.addr).extra_deposit(), 2); - }); - } - - #[test] - fn cannot_self_destruct_while_live() { - let (wasm, _code_hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - // Instantiate the BOB contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(100_000) - .build_and_unwrap_contract(); - - // Check that the BOB contract has been instantiated. - get_contract(&addr); - - // Call BOB with input data, forcing it make a recursive call to itself to - // self-destruct, resulting in a trap. - assert_err_ignore_postinfo!( - builder::call(addr).data(vec![0]).build(), - Error::::ContractTrapped, - ); - - // Check that BOB is still there. - get_contract(&addr); - }); - } - - #[test] - fn self_destruct_works() { - let (wasm, code_hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(1_000).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let _ = ::Currency::set_balance(&DJANGO_FALLBACK, 1_000_000); - let min_balance = Contracts::min_balance(); - - // Instantiate the BOB contract. - let contract = builder::bare_instantiate(Code::Upload(wasm)) - .value(100_000) - .build_and_unwrap_contract(); - - // Check that the BOB contract has been instantiated. - let _ = get_contract(&contract.addr); - - let info_deposit = test_utils::contract_info_storage_deposit(&contract.addr); - - // Drop all previous events - initialize_block(2); - - // Call BOB without input data which triggers termination. - assert_matches!(builder::call(contract.addr).build(), Ok(_)); - - // Check that code is still there but refcount dropped to zero. - assert_refcount!(&code_hash, 0); - - // Check that account is gone - assert!(get_contract_checked(&contract.addr).is_none()); - assert_eq!(::Currency::total_balance(&contract.account_id), 0); - - // Check that the beneficiary (django) got remaining balance. - assert_eq!( - ::Currency::free_balance(DJANGO_FALLBACK), - 1_000_000 + 100_000 + min_balance - ); +#[test] +fn instantiate_return_code() { + let (caller_code, _caller_hash) = compile_module("instantiate_return_code").unwrap(); + let (callee_code, callee_hash) = compile_module("ok_trap_revert").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 callee_hash = callee_hash.as_ref().to_vec(); + + assert_ok!(builder::instantiate_with_code(callee_code).value(min_balance * 100).build()); + + let contract = builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // Contract has only the minimal balance so any transfer will fail. + ::Currency::set_balance(&contract.account_id, min_balance); + let result = builder::bare_call(contract.addr) + .data(callee_hash.clone()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::TransferFailed); + + // Contract has enough balance but the passed code hash is invalid + ::Currency::set_balance(&contract.account_id, min_balance + 10_000); + let result = builder::bare_call(contract.addr).data(vec![0; 33]).build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CodeNotFound); + + // Contract has enough balance but callee reverts because "1" is passed. + let result = builder::bare_call(contract.addr) + .data(callee_hash.iter().chain(&1u32.to_le_bytes()).cloned().collect()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeReverted); + + // Contract has enough balance but callee traps because "2" is passed. + let result = builder::bare_call(contract.addr) + .data(callee_hash.iter().chain(&2u32.to_le_bytes()).cloned().collect()) + .build_and_unwrap_result(); + assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); + }); +} - // Check that the Alice is missing Django's benefit. Within ALICE's total balance - // there's also the code upload deposit held. - assert_eq!( - ::Currency::total_balance(&ALICE), - 1_000_000 - (100_000 + min_balance) - ); +#[test] +fn disabled_chain_extension_errors_on_call() { + let (code, _hash) = compile_module("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let contract = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + TestExtension::disable(); + assert_err_ignore_postinfo!( + builder::call(contract.addr).data(vec![7u8; 8]).build(), + Error::::NoChainExtension, + ); + }); +} - pretty_assertions::assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Terminated { - contract: contract.addr, - beneficiary: DJANGO_ADDR, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: contract.addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndReleased { - from: contract.addr, - to: ALICE_ADDR, - amount: info_deposit, - } - ), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::System(frame_system::Event::KilledAccount { - account: contract.account_id.clone() - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: contract.account_id.clone(), - to: DJANGO_FALLBACK, - amount: 100_000 + min_balance, - }), - topics: vec![], - }, - ], - ); - }); - } +#[test] +fn chain_extension_works() { + let (code, _hash) = compile_module("chain_extension").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let contract = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // 0 = read input buffer and pass it through as output + let input: Vec = ExtensionInput { extension_id: 0, func_id: 0, extra: &[99] }.into(); + let result = builder::bare_call(contract.addr).data(input.clone()).build(); + assert_eq!(TestExtension::last_seen_buffer(), input); + assert_eq!(result.result.unwrap().data, input); + + // 1 = treat inputs as integer primitives and store the supplied integers + builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 0, func_id: 1, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(TestExtension::last_seen_input_len(), 4); + + // 2 = charge some extra weight (amount supplied in the fifth byte) + let result = builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &0u32.encode() }.into()) + .build(); + assert_ok!(result.result); + let gas_consumed = result.gas_consumed; + let result = builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &42u32.encode() }.into()) + .build(); + assert_ok!(result.result); + assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 42); + let result = builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &95u32.encode() }.into()) + .build(); + assert_ok!(result.result); + assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 95); + + // 3 = diverging chain extension call that sets flags to 0x1 and returns a fixed buffer + let result = builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 0, func_id: 3, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(result.flags, ReturnFlags::REVERT); + assert_eq!(result.data, vec![42, 99]); + + // diverging to second chain extension that sets flags to 0x1 and returns a fixed buffer + // We set the MSB part to 1 (instead of 0) which routes the request into the second + // extension + let result = builder::bare_call(contract.addr) + .data(ExtensionInput { extension_id: 1, func_id: 0, extra: &[] }.into()) + .build_and_unwrap_result(); + assert_eq!(result.flags, ReturnFlags::REVERT); + assert_eq!(result.data, vec![0x4B, 0x1D]); + + // Diverging to third chain extension that is disabled + // We set the MSB part to 2 (instead of 0) which routes the request into the third + // extension + assert_err_ignore_postinfo!( + builder::call(contract.addr) + .data(ExtensionInput { extension_id: 2, func_id: 0, extra: &[] }.into()) + .build(), + Error::::NoChainExtension, + ); + }); +} - // This tests that one contract cannot prevent another from self-destructing by sending it - // additional funds after it has been drained. - #[test] - fn destroy_contract_and_transfer_funds() { - let (callee_wasm, callee_code_hash) = compile_module("self_destruct").unwrap(); - let (caller_wasm, _caller_code_hash) = compile_module("destroy_and_transfer").unwrap(); +#[test] +fn chain_extension_temp_storage_works() { + let (code, _hash) = compile_module("chain_extension_temp_storage").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let contract = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + // Call func 0 and func 1 back to back. + let stop_recursion = 0u8; + let mut input: Vec = ExtensionInput { extension_id: 3, func_id: 0, extra: &[] }.into(); + input.extend_from_slice( + ExtensionInput { extension_id: 3, func_id: 1, extra: &[stop_recursion] } + .to_vec() + .as_ref(), + ); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - // Create code hash for bob to instantiate - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - callee_wasm.clone(), - deposit_limit::(), - ) - .unwrap(); + assert_ok!(builder::bare_call(contract.addr).data(input.clone()).build().result); + }) +} - // This deploys the BOB contract, which in turn deploys the CHARLIE contract during - // construction. - let Contract { addr: addr_bob, .. } = - builder::bare_instantiate(Code::Upload(caller_wasm)) - .value(200_000) - .data(callee_code_hash.as_ref().to_vec()) - .build_and_unwrap_contract(); +#[test] +fn lazy_removal_works() { + let (code, _hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - // Check that the CHARLIE contract has been instantiated. - let salt = [47; 32]; // hard coded in fixture. - let addr_charlie = create2(&addr_bob, &callee_wasm, &[], &salt); - get_contract(&addr_charlie); + let contract = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // Call BOB, which calls CHARLIE, forcing CHARLIE to self-destruct. - assert_ok!(builder::call(addr_bob).data(addr_charlie.encode()).build()); + let info = get_contract(&contract.addr); + let trie = &info.child_trie_info(); - // Check that CHARLIE has moved on to the great beyond (ie. died). - assert!(get_contract_checked(&addr_charlie).is_none()); - }); - } + // Put value into the contracts child trie + child::put(trie, &[99], &42); - #[test] - fn cannot_self_destruct_in_constructor() { - let (wasm, _) = compile_module("self_destructing_constructor").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Terminate the contract + assert_ok!(builder::call(contract.addr).build()); - // Fail to instantiate the BOB because the constructor calls seal_terminate. - assert_err_ignore_postinfo!( - builder::instantiate_with_code(wasm).value(100_000).build(), - Error::::TerminatedInConstructor, - ); - }); - } + // Contract info should be gone + assert!(!>::contains_key(&contract.addr)); - #[test] - fn crypto_hashes() { - let (wasm, _code_hash) = compile_module("crypto_hashes").unwrap(); + // But value should be still there as the lazy removal did not run, yet. + assert_matches!(child::get(trie, &[99]), Some(42)); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Run the lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); - // Instantiate the CRYPTO_HASHES contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(100_000) - .build_and_unwrap_contract(); - // Perform the call. - let input = b"_DEAD_BEEF"; - use sp_io::hashing::*; - // Wraps a hash function into a more dynamic form usable for testing. - macro_rules! dyn_hash_fn { - ($name:ident) => { - Box::new(|input| $name(input).as_ref().to_vec().into_boxed_slice()) - }; - } - // All hash functions and their associated output byte lengths. - let test_cases: &[(Box Box<[u8]>>, usize)] = &[ - (dyn_hash_fn!(sha2_256), 32), - (dyn_hash_fn!(keccak_256), 32), - (dyn_hash_fn!(blake2_256), 32), - (dyn_hash_fn!(blake2_128), 16), - ]; - // Test the given hash functions for the input: "_DEAD_BEEF" - for (n, (hash_fn, expected_size)) in test_cases.iter().enumerate() { - // We offset data in the contract tables by 1. - let mut params = vec![(n + 1) as u8]; - params.extend_from_slice(input); - let result = builder::bare_call(addr).data(params).build_and_unwrap_result(); - assert!(!result.did_revert()); - let expected = hash_fn(input.as_ref()); - assert_eq!(&result.data[..*expected_size], &*expected); - } - }) - } + // Value should be gone now + assert_matches!(child::get::(trie, &[99]), None); + }); +} - #[test] - fn transfer_return_code() { - let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); +#[test] +fn lazy_batch_removal_works() { + let (code, _hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let mut tries: Vec = vec![]; - let contract = builder::bare_instantiate(Code::Upload(wasm)) + for i in 0..3u8 { + let contract = builder::bare_instantiate(Code::Upload(code.clone())) .value(min_balance * 100) + .salt(Some([i; 32])) .build_and_unwrap_contract(); - // Contract has only the minimal balance so any transfer will fail. - ::Currency::set_balance(&contract.account_id, min_balance); - let result = builder::bare_call(contract.addr).build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); - }); - } + let info = get_contract(&contract.addr); + let trie = &info.child_trie_info(); - #[test] - fn call_return_code() { - use test_utils::u256_bytes; + // Put value into the contracts child trie + child::put(trie, &[99], &42); - let (caller_code, _caller_hash) = compile_module("call_return_code").unwrap(); - let (callee_code, _callee_hash) = compile_module("ok_trap_revert").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); + // Terminate the contract. Contract info should be gone, but value should be still + // there as the lazy removal did not run, yet. + assert_ok!(builder::call(contract.addr).build()); - let bob = builder::bare_instantiate(Code::Upload(caller_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + assert!(!>::contains_key(&contract.addr)); + assert_matches!(child::get(trie, &[99]), Some(42)); - // Contract calls into Django which is no valid contract - // This will be a balance transfer into a new account - // with more than the contract has which will make the transfer fail - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&DJANGO_ADDR) - .iter() - .chain(&u256_bytes(min_balance * 200)) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); + tries.push(trie.clone()) + } - // Sending less than the minimum balance will also make the transfer fail - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&DJANGO_ADDR) - .iter() - .chain(&u256_bytes(42)) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); + // Run single lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); - // Sending at least the minimum balance should result in success but - // no code called. - assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 0); - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&DJANGO_ADDR) - .iter() - .chain(&u256_bytes(55)) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::Success); - assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 55); + // The single lazy removal should have removed all queued tries + for trie in tries.iter() { + assert_matches!(child::get::(trie, &[99]), None); + } + }); +} - let django = builder::bare_instantiate(Code::Upload(callee_code)) - .origin(RuntimeOrigin::signed(CHARLIE)) - .value(min_balance * 100) - .build_and_unwrap_contract(); +#[test] +fn lazy_removal_partial_remove_works() { + let (code, _hash) = compile_module("self_destruct").unwrap(); - // Sending more than the contract has will make the transfer fail. - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&django.addr) - .iter() - .chain(&u256_bytes(min_balance * 300)) - .chain(&0u32.to_le_bytes()) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); + // We create a contract with some extra keys above the weight limit + let extra_keys = 7u32; + let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); + let (weight_per_key, max_keys) = ContractInfo::::deletion_budget(&meter); + let vals: Vec<_> = (0..max_keys + extra_keys) + .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) + .collect(); - // Contract has enough balance but callee reverts because "1" is passed. - ::Currency::set_balance(&bob.account_id, min_balance + 1000); - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&django.addr) - .iter() - .chain(&u256_bytes(5)) - .chain(&1u32.to_le_bytes()) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::CalleeReverted); + let mut ext = ExtBuilder::default().existential_deposit(50).build(); - // Contract has enough balance but callee traps because "2" is passed. - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&django.addr) - .iter() - .chain(&u256_bytes(5)) - .chain(&2u32.to_le_bytes()) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); - }); - } + let trie = ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - #[test] - fn instantiate_return_code() { - let (caller_code, _caller_hash) = compile_module("instantiate_return_code").unwrap(); - let (callee_code, callee_hash) = compile_module("ok_trap_revert").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 callee_hash = callee_hash.as_ref().to_vec(); - - assert_ok!(builder::instantiate_with_code(callee_code) - .value(min_balance * 100) - .build()); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - let contract = builder::bare_instantiate(Code::Upload(caller_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + let info = get_contract(&addr); - // Contract has only the minimal balance so any transfer will fail. - ::Currency::set_balance(&contract.account_id, min_balance); - let result = builder::bare_call(contract.addr) - .data(callee_hash.clone()) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); + // Put value into the contracts child trie + for val in &vals { + info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); + } + >::insert(&addr, info.clone()); - // Contract has enough balance but the passed code hash is invalid - ::Currency::set_balance(&contract.account_id, min_balance + 10_000); - let result = - builder::bare_call(contract.addr).data(vec![0; 33]).build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::CodeNotFound); + // Terminate the contract + assert_ok!(builder::call(addr).build()); - // Contract has enough balance but callee reverts because "1" is passed. - let result = builder::bare_call(contract.addr) - .data(callee_hash.iter().chain(&1u32.to_le_bytes()).cloned().collect()) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::CalleeReverted); + // Contract info should be gone + assert!(!>::contains_key(&addr)); - // Contract has enough balance but callee traps because "2" is passed. - let result = builder::bare_call(contract.addr) - .data(callee_hash.iter().chain(&2u32.to_le_bytes()).cloned().collect()) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::CalleeTrapped); - }); - } + let trie = info.child_trie_info(); - #[test] - fn disabled_chain_extension_errors_on_call() { - let (code, _hash) = compile_module("chain_extension").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let contract = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); - TestExtension::disable(); - assert_err_ignore_postinfo!( - builder::call(contract.addr).data(vec![7u8; 8]).build(), - Error::::NoChainExtension, - ); - }); - } + // But value should be still there as the lazy removal did not run, yet. + for val in &vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); + } - #[test] - fn chain_extension_works() { - let (code, _hash) = compile_module("chain_extension").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let contract = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + trie.clone() + }); - // 0 = read input buffer and pass it through as output - let input: Vec = - ExtensionInput { extension_id: 0, func_id: 0, extra: &[99] }.into(); - let result = builder::bare_call(contract.addr).data(input.clone()).build(); - assert_eq!(TestExtension::last_seen_buffer(), input); - assert_eq!(result.result.unwrap().data, input); + // The lazy removal limit only applies to the backend but not to the overlay. + // This commits all keys from the overlay to the backend. + ext.commit_all().unwrap(); - // 1 = treat inputs as integer primitives and store the supplied integers - builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 0, func_id: 1, extra: &[] }.into()) - .build_and_unwrap_result(); - assert_eq!(TestExtension::last_seen_input_len(), 4); - - // 2 = charge some extra weight (amount supplied in the fifth byte) - let result = builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &0u32.encode() }.into()) - .build(); - assert_ok!(result.result); - let gas_consumed = result.gas_consumed; - let result = builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &42u32.encode() }.into()) - .build(); - assert_ok!(result.result); - assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 42); - let result = builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 0, func_id: 2, extra: &95u32.encode() }.into()) - .build(); - assert_ok!(result.result); - assert_eq!(result.gas_consumed.ref_time(), gas_consumed.ref_time() + 95); - - // 3 = diverging chain extension call that sets flags to 0x1 and returns a fixed buffer - let result = builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 0, func_id: 3, extra: &[] }.into()) - .build_and_unwrap_result(); - assert_eq!(result.flags, ReturnFlags::REVERT); - assert_eq!(result.data, vec![42, 99]); - - // diverging to second chain extension that sets flags to 0x1 and returns a fixed buffer - // We set the MSB part to 1 (instead of 0) which routes the request into the second - // extension - let result = builder::bare_call(contract.addr) - .data(ExtensionInput { extension_id: 1, func_id: 0, extra: &[] }.into()) - .build_and_unwrap_result(); - assert_eq!(result.flags, ReturnFlags::REVERT); - assert_eq!(result.data, vec![0x4B, 0x1D]); - - // Diverging to third chain extension that is disabled - // We set the MSB part to 2 (instead of 0) which routes the request into the third - // extension - assert_err_ignore_postinfo!( - builder::call(contract.addr) - .data(ExtensionInput { extension_id: 2, func_id: 0, extra: &[] }.into()) - .build(), - Error::::NoChainExtension, - ); - }); - } + ext.execute_with(|| { + // Run the lazy removal + ContractInfo::::process_deletion_queue_batch(&mut meter); - #[test] - fn chain_extension_temp_storage_works() { - let (code, _hash) = compile_module("chain_extension_temp_storage").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let contract = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + // Weight should be exhausted because we could not even delete all keys + assert!(!meter.can_consume(weight_per_key)); - // Call func 0 and func 1 back to back. - let stop_recursion = 0u8; - let mut input: Vec = - ExtensionInput { extension_id: 3, func_id: 0, extra: &[] }.into(); - input.extend_from_slice( - ExtensionInput { extension_id: 3, func_id: 1, extra: &[stop_recursion] } - .to_vec() - .as_ref(), - ); + let mut num_deleted = 0u32; + let mut num_remaining = 0u32; - assert_ok!(builder::bare_call(contract.addr).data(input.clone()).build().result); - }) - } + for val in &vals { + match child::get::(&trie, &blake2_256(&val.0)) { + None => num_deleted += 1, + Some(x) if x == val.1 => num_remaining += 1, + Some(_) => panic!("Unexpected value in contract storage"), + } + } - #[test] - fn lazy_removal_works() { - let (code, _hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + // All but one key is removed + assert_eq!(num_deleted + num_remaining, vals.len() as u32); + assert_eq!(num_deleted, max_keys); + assert_eq!(num_remaining, extra_keys); + }); +} - let contract = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); +#[test] +fn lazy_removal_does_no_run_on_low_remaining_weight() { + let (code, _hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let info = get_contract(&contract.addr); - let trie = &info.child_trie_info(); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // Put value into the contracts child trie - child::put(trie, &[99], &42); + let info = get_contract(&addr); + let trie = &info.child_trie_info(); - // Terminate the contract - assert_ok!(builder::call(contract.addr).build()); + // Put value into the contracts child trie + child::put(trie, &[99], &42); - // Contract info should be gone - assert!(!>::contains_key(&contract.addr)); + // Terminate the contract + assert_ok!(builder::call(addr).build()); - // But value should be still there as the lazy removal did not run, yet. - assert_matches!(child::get(trie, &[99]), Some(42)); + // Contract info should be gone + assert!(!>::contains_key(&addr)); - // Run the lazy removal - Contracts::on_idle(System::block_number(), Weight::MAX); + // But value should be still there as the lazy removal did not run, yet. + assert_matches!(child::get(trie, &[99]), Some(42)); - // Value should be gone now - assert_matches!(child::get::(trie, &[99]), None); - }); - } + // Assign a remaining weight which is too low for a successful deletion of the contract + let low_remaining_weight = + <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); - #[test] - fn lazy_batch_removal_works() { - let (code, _hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let mut tries: Vec = vec![]; - - for i in 0..3u8 { - let contract = builder::bare_instantiate(Code::Upload(code.clone())) - .value(min_balance * 100) - .salt(Some([i; 32])) - .build_and_unwrap_contract(); + // Run the lazy removal + Contracts::on_idle(System::block_number(), low_remaining_weight); - let info = get_contract(&contract.addr); - let trie = &info.child_trie_info(); + // Value should still be there, since remaining weight was too low for removal + assert_matches!(child::get::(trie, &[99]), Some(42)); - // Put value into the contracts child trie - child::put(trie, &[99], &42); + // Run the lazy removal while deletion_queue is not full + Contracts::on_initialize(System::block_number()); - // Terminate the contract. Contract info should be gone, but value should be still - // there as the lazy removal did not run, yet. - assert_ok!(builder::call(contract.addr).build()); + // Value should still be there, since deletion_queue was not full + assert_matches!(child::get::(trie, &[99]), Some(42)); - assert!(!>::contains_key(&contract.addr)); - assert_matches!(child::get(trie, &[99]), Some(42)); + // Run on_idle with max remaining weight, this should remove the value + Contracts::on_idle(System::block_number(), Weight::MAX); - tries.push(trie.clone()) - } + // Value should be gone + assert_matches!(child::get::(trie, &[99]), None); + }); +} - // Run single lazy removal - Contracts::on_idle(System::block_number(), Weight::MAX); +#[test] +fn lazy_removal_does_not_use_all_weight() { + let (code, _hash) = compile_module("self_destruct").unwrap(); - // The single lazy removal should have removed all queued tries - for trie in tries.iter() { - assert_matches!(child::get::(trie, &[99]), None); - } - }); - } + let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); + let mut ext = ExtBuilder::default().existential_deposit(50).build(); - #[test] - fn lazy_removal_partial_remove_works() { - let (code, _hash) = compile_module("self_destruct").unwrap(); + let (trie, vals, weight_per_key) = ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - // We create a contract with some extra keys above the weight limit - let extra_keys = 7u32; - let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); + + let info = get_contract(&addr); let (weight_per_key, max_keys) = ContractInfo::::deletion_budget(&meter); - let vals: Vec<_> = (0..max_keys + extra_keys) + assert!(max_keys > 0); + + // We create a contract with one less storage item than we can remove within the limit + let vals: Vec<_> = (0..max_keys - 1) .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) .collect(); - let mut ext = ExtBuilder::default().existential_deposit(50).build(); - - let trie = ext.execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); - - let info = get_contract(&addr); - - // Put value into the contracts child trie - for val in &vals { - info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); - } - >::insert(&addr, info.clone()); + // Put value into the contracts child trie + for val in &vals { + info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); + } + >::insert(&addr, info.clone()); - // Terminate the contract - assert_ok!(builder::call(addr).build()); + // Terminate the contract + assert_ok!(builder::call(addr).build()); - // Contract info should be gone - assert!(!>::contains_key(&addr)); + // Contract info should be gone + assert!(!>::contains_key(&addr)); - let trie = info.child_trie_info(); + let trie = info.child_trie_info(); - // But value should be still there as the lazy removal did not run, yet. - for val in &vals { - assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); - } + // But value should be still there as the lazy removal did not run, yet. + for val in &vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); + } - trie.clone() - }); + (trie, vals, weight_per_key) + }); - // The lazy removal limit only applies to the backend but not to the overlay. - // This commits all keys from the overlay to the backend. - ext.commit_all().unwrap(); + // The lazy removal limit only applies to the backend but not to the overlay. + // This commits all keys from the overlay to the backend. + ext.commit_all().unwrap(); - ext.execute_with(|| { - // Run the lazy removal - ContractInfo::::process_deletion_queue_batch(&mut meter); + ext.execute_with(|| { + // Run the lazy removal + ContractInfo::::process_deletion_queue_batch(&mut meter); + let base_weight = + <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); + assert_eq!(meter.consumed(), weight_per_key.mul(vals.len() as _) + base_weight); - // Weight should be exhausted because we could not even delete all keys - assert!(!meter.can_consume(weight_per_key)); + // All the keys are removed + for val in vals { + assert_eq!(child::get::(&trie, &blake2_256(&val.0)), None); + } + }); +} - let mut num_deleted = 0u32; - let mut num_remaining = 0u32; +#[test] +fn deletion_queue_ring_buffer_overflow() { + let (code, _hash) = compile_module("self_destruct").unwrap(); + let mut ext = ExtBuilder::default().existential_deposit(50).build(); - for val in &vals { - match child::get::(&trie, &blake2_256(&val.0)) { - None => num_deleted += 1, - Some(x) if x == val.1 => num_remaining += 1, - Some(_) => panic!("Unexpected value in contract storage"), - } - } + // setup the deletion queue with custom counters + ext.execute_with(|| { + let queue = DeletionQueueManager::from_test_values(u32::MAX - 1, u32::MAX - 1); + >::set(queue); + }); - // All but one key is removed - assert_eq!(num_deleted + num_remaining, vals.len() as u32); - assert_eq!(num_deleted, max_keys); - assert_eq!(num_remaining, extra_keys); - }); - } + // commit the changes to the storage + ext.commit_all().unwrap(); - #[test] - fn lazy_removal_does_no_run_on_low_remaining_weight() { - let (code, _hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + ext.execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + let mut tries: Vec = vec![]; - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + // add 3 contracts to the deletion queue + for i in 0..3u8 { + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code.clone())) .value(min_balance * 100) + .salt(Some([i; 32])) .build_and_unwrap_contract(); let info = get_contract(&addr); @@ -1926,669 +2026,816 @@ mod run_tests { // Put value into the contracts child trie child::put(trie, &[99], &42); - // Terminate the contract + // Terminate the contract. Contract info should be gone, but value should be still + // there as the lazy removal did not run, yet. assert_ok!(builder::call(addr).build()); - // Contract info should be gone assert!(!>::contains_key(&addr)); - - // But value should be still there as the lazy removal did not run, yet. assert_matches!(child::get(trie, &[99]), Some(42)); - // Assign a remaining weight which is too low for a successful deletion of the contract - let low_remaining_weight = - <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); - - // Run the lazy removal - Contracts::on_idle(System::block_number(), low_remaining_weight); + tries.push(trie.clone()) + } - // Value should still be there, since remaining weight was too low for removal - assert_matches!(child::get::(trie, &[99]), Some(42)); + // Run single lazy removal + Contracts::on_idle(System::block_number(), Weight::MAX); - // Run the lazy removal while deletion_queue is not full - Contracts::on_initialize(System::block_number()); + // The single lazy removal should have removed all queued tries + for trie in tries.iter() { + assert_matches!(child::get::(trie, &[99]), None); + } - // Value should still be there, since deletion_queue was not full - assert_matches!(child::get::(trie, &[99]), Some(42)); + // insert and delete counter values should go from u32::MAX - 1 to 1 + assert_eq!(>::get().as_test_tuple(), (1, 1)); + }) +} +#[test] +fn refcounter() { + let (wasm, code_hash) = compile_module("self_destruct").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create two contracts with the same code and check that they do in fact share it. + let Contract { addr: addr0, .. } = builder::bare_instantiate(Code::Upload(wasm.clone())) + .value(min_balance * 100) + .salt(Some([0; 32])) + .build_and_unwrap_contract(); + let Contract { addr: addr1, .. } = builder::bare_instantiate(Code::Upload(wasm.clone())) + .value(min_balance * 100) + .salt(Some([1; 32])) + .build_and_unwrap_contract(); + assert_refcount!(code_hash, 2); + + // Sharing should also work with the usual instantiate call + let Contract { addr: addr2, .. } = builder::bare_instantiate(Code::Existing(code_hash)) + .value(min_balance * 100) + .salt(Some([2; 32])) + .build_and_unwrap_contract(); + assert_refcount!(code_hash, 3); + + // Terminating one contract should decrement the refcount + assert_ok!(builder::call(addr0).build()); + assert_refcount!(code_hash, 2); + + // remove another one + assert_ok!(builder::call(addr1).build()); + assert_refcount!(code_hash, 1); + + // Pristine code should still be there + PristineCode::::get(code_hash).unwrap(); + + // remove the last contract + assert_ok!(builder::call(addr2).build()); + assert_refcount!(code_hash, 0); + + // refcount is `0` but code should still exists because it needs to be removed manually + assert!(crate::PristineCode::::contains_key(&code_hash)); + }); +} - // Run on_idle with max remaining weight, this should remove the value - Contracts::on_idle(System::block_number(), Weight::MAX); +#[test] +fn debug_message_works() { + let (wasm, _code_hash) = compile_module("debug_message_works").unwrap(); - // Value should be gone - assert_matches!(child::get::(trie, &[99]), None); - }); - } + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_contract(); + let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); - #[test] - fn lazy_removal_does_not_use_all_weight() { - let (code, _hash) = compile_module("self_destruct").unwrap(); + assert_matches!(result.result, Ok(_)); + assert_eq!(std::str::from_utf8(&result.debug_message).unwrap(), "Hello World!"); + }); +} - let mut meter = WeightMeter::with_limit(Weight::from_parts(5_000_000_000, 100 * 1024)); - let mut ext = ExtBuilder::default().existential_deposit(50).build(); +#[test] +fn debug_message_logging_disabled() { + let (wasm, _code_hash) = compile_module("debug_message_logging_disabled").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_contract(); + // the dispatchables always run without debugging + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr, + 0, + GAS_LIMIT, + deposit_limit::(), + vec![] + )); + }); +} - let (trie, vals, weight_per_key) = ext.execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); +#[test] +fn debug_message_invalid_utf8() { + let (wasm, _code_hash) = compile_module("debug_message_invalid_utf8").unwrap(); + + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(30_000) + .build_and_unwrap_contract(); + let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); + assert_ok!(result.result); + assert!(result.debug_message.is_empty()); + }); +} - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) +#[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(); + let _ = ::Currency::set_balance(&ALICE, 2_000 * min_balance); + + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(caller_code)) .value(min_balance * 100) .build_and_unwrap_contract(); - let info = get_contract(&addr); - let (weight_per_key, max_keys) = ContractInfo::::deletion_budget(&meter); - assert!(max_keys > 0); + let Contract { addr: addr_dummy, .. } = builder::bare_instantiate(Code::Upload(dummy_code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // We create a contract with one less storage item than we can remove within the limit - let vals: Vec<_> = (0..max_keys - 1) - .map(|i| (blake2_256(&i.encode()), (i as u32), (i as u32).encode())) - .collect(); + let Contract { addr: addr_call_runtime, .. } = + builder::bare_instantiate(Code::Upload(call_runtime_code)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // Put value into the contracts child trie - for val in &vals { - info.write(&Key::Fix(val.0), Some(val.2.clone()), None, false).unwrap(); - } - >::insert(&addr, info.clone()); + // Run the test for all of those weight limits for the subcall + let weights = [ + Weight::zero(), + GAS_LIMIT, + GAS_LIMIT * 2, + GAS_LIMIT / 5, + Weight::from_parts(0, GAS_LIMIT.proof_size()), + Weight::from_parts(GAS_LIMIT.ref_time(), 0), + ]; - // Terminate the contract - assert_ok!(builder::call(addr).build()); + // 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(); - // Contract info should be gone - assert!(!>::contains_key(&addr)); + // 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 trie = info.child_trie_info(); + 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() + }; - // But value should be still there as the lazy removal did not run, yet. - for val in &vals { - assert_eq!(child::get::(&trie, &blake2_256(&val.0)), Some(val.1)); + // 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()) + .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()) + .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()) + .data(input.clone()) + .build(); + assert_err!(result.result, error); } + } + }); +} - (trie, vals, weight_per_key) - }); +#[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); - // The lazy removal limit only applies to the backend but not to the overlay. - // This commits all keys from the overlay to the backend. - ext.commit_all().unwrap(); + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(caller_code)) + .value(min_balance * 100) + .salt(Some([0; 32])) + .build_and_unwrap_contract(); - ext.execute_with(|| { - // Run the lazy removal - ContractInfo::::process_deletion_queue_batch(&mut meter); - let base_weight = - <::WeightInfo as WeightInfo>::on_process_deletion_queue_batch(); - assert_eq!(meter.consumed(), weight_per_key.mul(vals.len() as _) + base_weight); - - // All the keys are removed - for val in vals { - assert_eq!(child::get::(&trie, &blake2_256(&val.0)), None); - } + // 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 + ); + }); +} - #[test] - fn deletion_queue_ring_buffer_overflow() { - let (code, _hash) = compile_module("self_destruct").unwrap(); - let mut ext = ExtBuilder::default().existential_deposit(50).build(); +#[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(); - // setup the deletion queue with custom counters - ext.execute_with(|| { - let queue = DeletionQueueManager::from_test_values(u32::MAX - 1, u32::MAX - 1); - >::set(queue); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(callee_code)) + .value(min_balance * 100) + .salt(Some([1; 32])) + .build_and_unwrap_contract(); + + // Call pallet_revive call() dispatchable + let call = RuntimeCall::Contracts(crate::Call::call { + dest: addr_callee, + value: 0, + gas_limit: GAS_LIMIT / 3, + storage_deposit_limit: deposit_limit::(), + data: vec![], }); - // commit the changes to the storage - ext.commit_all().unwrap(); + // 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(); + // Call to runtime should fail because of the re-entrancy guard + assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); + }); +} - ext.execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let mut tries: Vec = vec![]; - - // add 3 contracts to the deletion queue - for i in 0..3u8 { - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code.clone())) - .value(min_balance * 100) - .salt(Some([i; 32])) - .build_and_unwrap_contract(); +#[test] +fn ecdsa_recover() { + let (wasm, _code_hash) = compile_module("ecdsa_recover").unwrap(); - let info = get_contract(&addr); - let trie = &info.child_trie_info(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // Put value into the contracts child trie - child::put(trie, &[99], &42); + // Instantiate the ecdsa_recover contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_contract(); - // Terminate the contract. Contract info should be gone, but value should be still - // there as the lazy removal did not run, yet. - assert_ok!(builder::call(addr).build()); + #[rustfmt::skip] + let signature: [u8; 65] = [ + 161, 234, 203, 74, 147, 96, 51, 212, 5, 174, 231, 9, 142, 48, 137, 201, + 162, 118, 192, 67, 239, 16, 71, 216, 125, 86, 167, 139, 70, 7, 86, 241, + 33, 87, 154, 251, 81, 29, 160, 4, 176, 239, 88, 211, 244, 232, 232, 52, + 211, 234, 100, 115, 230, 47, 80, 44, 152, 166, 62, 50, 8, 13, 86, 175, + 28, + ]; + #[rustfmt::skip] + let message_hash: [u8; 32] = [ + 162, 28, 244, 179, 96, 76, 244, 178, 188, 83, 230, 248, 143, 106, 77, 117, + 239, 95, 244, 171, 65, 95, 62, 153, 174, 166, 182, 28, 130, 73, 196, 208 + ]; + #[rustfmt::skip] + const EXPECTED_COMPRESSED_PUBLIC_KEY: [u8; 33] = [ + 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, + 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, + 152, + ]; + let mut params = vec![]; + params.extend_from_slice(&signature); + params.extend_from_slice(&message_hash); + assert!(params.len() == 65 + 32); + let result = builder::bare_call(addr).data(params).build_and_unwrap_result(); + assert!(!result.did_revert()); + assert_eq!(result.data, EXPECTED_COMPRESSED_PUBLIC_KEY); + }) +} - assert!(!>::contains_key(&addr)); - assert_matches!(child::get(trie, &[99]), Some(42)); +#[test] +fn bare_instantiate_returns_events() { + let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + + let result = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .collect_events(CollectEvents::UnsafeCollect) + .build(); + + let events = result.events.unwrap(); + assert!(!events.is_empty()); + assert_eq!(events, System::events()); + }); +} - tries.push(trie.clone()) - } +#[test] +fn bare_instantiate_does_not_return_events() { + let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - // Run single lazy removal - Contracts::on_idle(System::block_number(), Weight::MAX); + let result = builder::bare_instantiate(Code::Upload(wasm)).value(min_balance * 100).build(); - // The single lazy removal should have removed all queued tries - for trie in tries.iter() { - assert_matches!(child::get::(trie, &[99]), None); - } + let events = result.events; + assert!(!System::events().is_empty()); + assert!(events.is_none()); + }); +} - // insert and delete counter values should go from u32::MAX - 1 to 1 - assert_eq!(>::get().as_test_tuple(), (1, 1)); - }) - } - #[test] - fn refcounter() { - let (wasm, code_hash) = compile_module("self_destruct").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); +#[test] +fn bare_call_returns_events() { + let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - // Create two contracts with the same code and check that they do in fact share it. - let Contract { addr: addr0, .. } = - builder::bare_instantiate(Code::Upload(wasm.clone())) - .value(min_balance * 100) - .salt(Some([0; 32])) - .build_and_unwrap_contract(); - let Contract { addr: addr1, .. } = - builder::bare_instantiate(Code::Upload(wasm.clone())) - .value(min_balance * 100) - .salt(Some([1; 32])) - .build_and_unwrap_contract(); - assert_refcount!(code_hash, 2); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // Sharing should also work with the usual instantiate call - let Contract { addr: addr2, .. } = builder::bare_instantiate(Code::Existing(code_hash)) - .value(min_balance * 100) - .salt(Some([2; 32])) - .build_and_unwrap_contract(); - assert_refcount!(code_hash, 3); + let result = builder::bare_call(addr).collect_events(CollectEvents::UnsafeCollect).build(); - // Terminating one contract should decrement the refcount - assert_ok!(builder::call(addr0).build()); - assert_refcount!(code_hash, 2); + let events = result.events.unwrap(); + assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); + assert!(!events.is_empty()); + assert_eq!(events, System::events()); + }); +} - // remove another one - assert_ok!(builder::call(addr1).build()); - assert_refcount!(code_hash, 1); +#[test] +fn bare_call_does_not_return_events() { + let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let min_balance = Contracts::min_balance(); + let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - // Pristine code should still be there - PristineCode::::get(code_hash).unwrap(); + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(min_balance * 100) + .build_and_unwrap_contract(); - // remove the last contract - assert_ok!(builder::call(addr2).build()); - assert_refcount!(code_hash, 0); + let result = builder::bare_call(addr).build(); - // refcount is `0` but code should still exists because it needs to be removed manually - assert!(crate::PristineCode::::contains_key(&code_hash)); - }); - } + let events = result.events; + assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); + assert!(!System::events().is_empty()); + assert!(events.is_none()); + }); +} - #[test] - fn debug_message_works() { - let (wasm, _code_hash) = compile_module("debug_message_works").unwrap(); +#[test] +fn sr25519_verify() { + let (wasm, _code_hash) = compile_module("sr25519_verify").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(30_000) - .build_and_unwrap_contract(); - let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); + ExtBuilder::default().existential_deposit(50).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - assert_matches!(result.result, Ok(_)); - assert_eq!(std::str::from_utf8(&result.debug_message).unwrap(), "Hello World!"); - }); - } - - #[test] - fn debug_message_logging_disabled() { - let (wasm, _code_hash) = compile_module("debug_message_logging_disabled").unwrap(); - - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(30_000) - .build_and_unwrap_contract(); - // the dispatchables always run without debugging - assert_ok!(Contracts::call( - RuntimeOrigin::signed(ALICE), - addr, - 0, - GAS_LIMIT, - deposit_limit::(), - vec![] - )); - }); - } + // Instantiate the sr25519_verify contract. + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(100_000) + .build_and_unwrap_contract(); - #[test] - fn debug_message_invalid_utf8() { - let (wasm, _code_hash) = compile_module("debug_message_invalid_utf8").unwrap(); + let call_with = |message: &[u8; 11]| { + // Alice's signature for "hello world" + #[rustfmt::skip] + let signature: [u8; 64] = [ + 184, 49, 74, 238, 78, 165, 102, 252, 22, 92, 156, 176, 124, 118, 168, 116, 247, + 99, 0, 94, 2, 45, 9, 170, 73, 222, 182, 74, 60, 32, 75, 64, 98, 174, 69, 55, 83, + 85, 180, 98, 208, 75, 231, 57, 205, 62, 4, 105, 26, 136, 172, 17, 123, 99, 90, 255, + 228, 54, 115, 63, 30, 207, 205, 131, + ]; - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(30_000) - .build_and_unwrap_contract(); - let result = builder::bare_call(addr).debug(DebugInfo::UnsafeDebug).build(); - assert_ok!(result.result); - assert!(result.debug_message.is_empty()); - }); - } + // Alice's public key + #[rustfmt::skip] + let public_key: [u8; 32] = [ + 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, + 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, + ]; - #[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(); - let _ = ::Currency::set_balance(&ALICE, 2_000 * min_balance); - - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(caller_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + let mut params = vec![]; + params.extend_from_slice(&signature); + params.extend_from_slice(&public_key); + params.extend_from_slice(message); - let Contract { addr: addr_dummy, .. } = - builder::bare_instantiate(Code::Upload(dummy_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + builder::bare_call(addr).data(params).build_and_unwrap_result() + }; - let Contract { addr: addr_call_runtime, .. } = - builder::bare_instantiate(Code::Upload(call_runtime_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + // verification should succeed for "hello world" + assert_return_code!(call_with(&b"hello world"), RuntimeReturnCode::Success); - // Run the test for all of those weight limits for the subcall - let weights = [ - Weight::zero(), - GAS_LIMIT, - GAS_LIMIT * 2, - GAS_LIMIT / 5, - Weight::from_parts(0, GAS_LIMIT.proof_size()), - Weight::from_parts(GAS_LIMIT.ref_time(), 0), - ]; + // verification should fail for other messages + assert_return_code!(call_with(&b"hello worlD"), RuntimeReturnCode::Sr25519VerifyFailed); + }); +} - // 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), - ]; +#[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; - 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()) - .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()) - .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()) - .data(input.clone()) - .build(); - assert_err!(result.result, error); - } - } - }); - } + let execute = || { + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - #[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])) + // 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(); - // 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), + // 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, + })); + + // 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 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 data = ( + (ED - DepositPerItem::get()) as u32, // storage length + addr_callee, + transfer_proxy_call, ); - }); - } - #[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(); + builder::call(caller.addr).data(data.encode()).build() + }) + }; - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(callee_code)) - .value(min_balance * 100) - .salt(Some([1; 32])) - .build_and_unwrap_contract(); + // With a low enough deposit per byte, the call should succeed. + let result = execute().unwrap(); - // Call pallet_revive call() dispatchable - let call = RuntimeCall::Contracts(crate::Call::call { - dest: addr_callee, - value: 0, - gas_limit: GAS_LIMIT / 3, - storage_deposit_limit: deposit_limit::(), - data: vec![], - }); + // Bump the deposit per byte to a high value to trigger a FundsUnavailable error. + DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 20); + assert_err_with_weight!(execute(), TokenError::FundsUnavailable, result.actual_weight); +} - // 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(); - // Call to runtime should fail because of the re-entrancy guard - assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); - }); - } +#[test] +fn upload_code_works() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Drop previous events + initialize_block(2); + + assert!(!PristineCode::::contains_key(&code_hash)); + + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + + assert_eq!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE_ADDR + }), + topics: vec![], + },] + ); + }); +} - #[test] - fn ecdsa_recover() { - let (wasm, _code_hash) = compile_module("ecdsa_recover").unwrap(); +#[test] +fn upload_code_limit_too_low() { + let (wasm, _code_hash) = compile_module("dummy").unwrap(); + let deposit_expected = expected_deposit(wasm.len()); + let deposit_insufficient = deposit_expected.saturating_sub(1); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // Instantiate the ecdsa_recover contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(100_000) - .build_and_unwrap_contract(); + // Drop previous events + initialize_block(2); - #[rustfmt::skip] - let signature: [u8; 65] = [ - 161, 234, 203, 74, 147, 96, 51, 212, 5, 174, 231, 9, 142, 48, 137, 201, - 162, 118, 192, 67, 239, 16, 71, 216, 125, 86, 167, 139, 70, 7, 86, 241, - 33, 87, 154, 251, 81, 29, 160, 4, 176, 239, 88, 211, 244, 232, 232, 52, - 211, 234, 100, 115, 230, 47, 80, 44, 152, 166, 62, 50, 8, 13, 86, 175, - 28, - ]; - #[rustfmt::skip] - let message_hash: [u8; 32] = [ - 162, 28, 244, 179, 96, 76, 244, 178, 188, 83, 230, 248, 143, 106, 77, 117, - 239, 95, 244, 171, 65, 95, 62, 153, 174, 166, 182, 28, 130, 73, 196, 208 - ]; - #[rustfmt::skip] - const EXPECTED_COMPRESSED_PUBLIC_KEY: [u8; 33] = [ - 2, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, - 7, 2, 155, 252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, - 152, - ]; - let mut params = vec![]; - params.extend_from_slice(&signature); - params.extend_from_slice(&message_hash); - assert!(params.len() == 65 + 32); - let result = builder::bare_call(addr).data(params).build_and_unwrap_result(); - assert!(!result.did_revert()); - assert_eq!(result.data, EXPECTED_COMPRESSED_PUBLIC_KEY); - }) - } + assert_noop!( + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, deposit_insufficient,), + >::StorageDepositLimitExhausted, + ); - #[test] - fn bare_instantiate_returns_events() { - let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + assert_eq!(System::events(), vec![]); + }); +} - let result = builder::bare_instantiate(Code::Upload(wasm)) - .value(min_balance * 100) - .collect_events(CollectEvents::UnsafeCollect) - .build(); +#[test] +fn upload_code_not_enough_balance() { + let (wasm, _code_hash) = compile_module("dummy").unwrap(); + let deposit_expected = expected_deposit(wasm.len()); + let deposit_insufficient = deposit_expected.saturating_sub(1); - let events = result.events.unwrap(); - assert!(!events.is_empty()); - assert_eq!(events, System::events()); - }); - } + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, deposit_insufficient); - #[test] - fn bare_instantiate_does_not_return_events() { - let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + // Drop previous events + initialize_block(2); - let result = - builder::bare_instantiate(Code::Upload(wasm)).value(min_balance * 100).build(); + assert_noop!( + Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,), + >::StorageDepositNotEnoughFunds, + ); - let events = result.events; - assert!(!System::events().is_empty()); - assert!(events.is_none()); - }); - } + assert_eq!(System::events(), vec![]); + }); +} - #[test] - fn bare_call_returns_events() { - let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); +#[test] +fn remove_code_works() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(min_balance * 100) - .build_and_unwrap_contract(); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let result = - builder::bare_call(addr).collect_events(CollectEvents::UnsafeCollect).build(); + // Drop previous events + initialize_block(2); - let events = result.events.unwrap(); - assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); - assert!(!events.is_empty()); - assert_eq!(events, System::events()); - }); - } + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); - #[test] - fn bare_call_does_not_return_events() { - let (wasm, _code_hash) = compile_module("transfer_return_code").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE_ADDR + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeRemoved { + code_hash, + deposit_released: deposit_expected, + remover: ALICE_ADDR + }), + topics: vec![], + }, + ] + ); + }); +} - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(min_balance * 100) - .build_and_unwrap_contract(); +#[test] +fn remove_code_wrong_origin() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); - let result = builder::bare_call(addr).build(); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let events = result.events; - assert_return_code!(&result.result.unwrap(), RuntimeReturnCode::Success); - assert!(!System::events().is_empty()); - assert!(events.is_none()); - }); - } + // Drop previous events + initialize_block(2); - #[test] - fn sr25519_verify() { - let (wasm, _code_hash) = compile_module("sr25519_verify").unwrap(); + assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(BOB), code_hash), + sp_runtime::traits::BadOrigin, + ); - // Instantiate the sr25519_verify contract. - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) - .value(100_000) - .build_and_unwrap_contract(); + assert_eq!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE_ADDR + }), + topics: vec![], + },] + ); + }); +} - let call_with = |message: &[u8; 11]| { - // Alice's signature for "hello world" - #[rustfmt::skip] - let signature: [u8; 64] = [ - 184, 49, 74, 238, 78, 165, 102, 252, 22, 92, 156, 176, 124, 118, 168, 116, 247, - 99, 0, 94, 2, 45, 9, 170, 73, 222, 182, 74, 60, 32, 75, 64, 98, 174, 69, 55, 83, - 85, 180, 98, 208, 75, 231, 57, 205, 62, 4, 105, 26, 136, 172, 17, 123, 99, 90, 255, - 228, 54, 115, 63, 30, 207, 205, 131, - ]; +#[test] +fn remove_code_in_use() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); - // Alice's public key - #[rustfmt::skip] - let public_key: [u8; 32] = [ - 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, - 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125, - ]; + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let mut params = vec![]; - params.extend_from_slice(&signature); - params.extend_from_slice(&public_key); - params.extend_from_slice(message); + assert_ok!(builder::instantiate_with_code(wasm).build()); - builder::bare_call(addr).data(params).build_and_unwrap_result() - }; + // Drop previous events + initialize_block(2); + + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + >::CodeInUse, + ); - // verification should succeed for "hello world" - assert_return_code!(call_with(&b"hello world"), RuntimeReturnCode::Success); + assert_eq!(System::events(), vec![]); + }); +} - // verification should fail for other messages - assert_return_code!(call_with(&b"hello worlD"), RuntimeReturnCode::Sr25519VerifyFailed); - }); - } +#[test] +fn remove_code_not_found() { + let (_wasm, code_hash) = compile_module("dummy").unwrap(); - #[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; + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let execute = || { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Drop previous events + initialize_block(2); - // 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, - })); - - // 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 = ( - (ED - DepositPerItem::get()) as u32, // storage length - addr_callee, - transfer_proxy_call, - ); + assert_noop!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), + >::CodeNotFound, + ); - builder::call(caller.addr).data(data.encode()).build() - }) - }; + assert_eq!(System::events(), vec![]); + }); +} - // With a low enough deposit per byte, the call should succeed. - let result = execute().unwrap(); +#[test] +fn instantiate_with_zero_balance_works() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); - // Bump the deposit per byte to a high value to trigger a FundsUnavailable error. - DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 20); - assert_err_with_weight!(execute(), TokenError::FundsUnavailable, result.actual_weight); - } + // Drop previous events + initialize_block(2); - #[test] - fn upload_code_works() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); + // Instantiate the BOB contract. + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); - // Drop previous events - initialize_block(2); + // Make sure the account exists even though no free balance was send + assert_eq!(::Currency::free_balance(&account_id), min_balance); + assert_eq!( + ::Currency::total_balance(&account_id), + min_balance + test_utils::contract_info_storage_deposit(&addr) + ); - assert!(!PristineCode::::contains_key(&code_hash)); + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::CodeStored { + code_hash, + deposit_held: deposit_expected, + uploader: ALICE_ADDR + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: account_id.clone(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: account_id.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id, + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE_ADDR, + contract: addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: addr, + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} - assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); - // Ensure the contract was stored and get expected deposit amount to be reserved. - let deposit_expected = expected_deposit(ensure_stored(code_hash)); +#[test] +fn instantiate_with_below_existential_deposit_works() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let value = 50; + + // Drop previous events + initialize_block(2); + + // Instantiate the BOB contract. + let Contract { addr, account_id } = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_contract(); + + // Ensure the contract was stored and get expected deposit amount to be reserved. + let deposit_expected = expected_deposit(ensure_stored(code_hash)); + // Make sure the account exists even though not enough free balance was send + assert_eq!(::Currency::free_balance(&account_id), min_balance + value); + assert_eq!( + ::Currency::total_balance(&account_id), + min_balance + value + test_utils::contract_info_storage_deposit(&addr) + ); - assert_eq!( - System::events(), - vec![EventRecord { + assert_eq!( + System::events(), + vec![ + EventRecord { phase: Phase::Initialization, event: RuntimeEvent::Contracts(crate::Event::CodeStored { code_hash, @@ -2596,2057 +2843,1740 @@ mod run_tests { uploader: ALICE_ADDR }), topics: vec![], - },] - ); - }); - } + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::System(frame_system::Event::NewAccount { + account: account_id.clone() + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { + account: account_id.clone(), + free_balance: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id.clone(), + amount: min_balance, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id.clone(), + amount: 50, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Instantiated { + deployer: ALICE_ADDR, + contract: addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: addr, + amount: test_utils::contract_info_storage_deposit(&addr), + } + ), + topics: vec![], + }, + ] + ); + }); +} - #[test] - fn upload_code_limit_too_low() { - let (wasm, _code_hash) = compile_module("dummy").unwrap(); - let deposit_expected = expected_deposit(wasm.len()); - let deposit_insufficient = deposit_expected.saturating_sub(1); +#[test] +fn storage_deposit_works() { + let (wasm, _code_hash) = compile_module("multi_store").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + + let mut deposit = test_utils::contract_info_storage_deposit(&addr); + + // Drop previous events + initialize_block(2); + + // Create storage + assert_ok!(builder::call(addr).value(42).data((50u32, 20u32).encode()).build()); + // 4 is for creating 2 storage items + let charged0 = 4 + 50 + 20; + deposit += charged0; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + // Add more storage (but also remove some) + assert_ok!(builder::call(addr).data((100u32, 10u32).encode()).build()); + let charged1 = 50 - 10; + deposit += charged1; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + // Remove more storage (but also add some) + assert_ok!(builder::call(addr).data((10u32, 20u32).encode()).build()); + // -1 for numeric instability + let refunded0 = 90 - 10 - 1; + deposit -= refunded0; + assert_eq!(get_contract(&addr).total_deposit(), deposit); + + assert_eq!( + System::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { + from: ALICE, + to: account_id.clone(), + amount: 42, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: addr, + amount: charged0, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndHeld { + from: ALICE_ADDR, + to: addr, + amount: charged1, + } + ), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts( + pallet_revive::Event::StorageDepositTransferredAndReleased { + from: addr, + to: ALICE_ADDR, + amount: refunded0, + } + ), + topics: vec![], + }, + ] + ); + }); +} - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn storage_deposit_callee_works() { + let (wasm_caller, _code_hash_caller) = compile_module("call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, account_id } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + assert_ok!(builder::call(addr_caller).data((100u32, &addr_callee).encode()).build()); + + let callee = get_contract(&addr_callee); + let deposit = DepositPerByte::get() * 100 + DepositPerItem::get() * 1; + + assert_eq!(test_utils::get_balance(&account_id), min_balance); + assert_eq!( + callee.total_deposit(), + deposit + test_utils::contract_info_storage_deposit(&addr_callee) + ); + }); +} - // Drop previous events - initialize_block(2); +#[test] +fn set_code_extrinsic() { + let (wasm, code_hash) = compile_module("dummy").unwrap(); + let (new_wasm, new_code_hash) = compile_module("crypto_hashes").unwrap(); - assert_noop!( - Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, deposit_insufficient,), - >::StorageDepositLimitExhausted, - ); + assert_ne!(code_hash, new_code_hash); - assert_eq!(System::events(), vec![]); - }); - } + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - #[test] - fn upload_code_not_enough_balance() { - let (wasm, _code_hash) = compile_module("dummy").unwrap(); - let deposit_expected = expected_deposit(wasm.len()); - let deposit_insufficient = deposit_expected.saturating_sub(1); + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, deposit_insufficient); + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + new_wasm, + deposit_limit::(), + )); - // Drop previous events - initialize_block(2); + // Drop previous events + initialize_block(2); - assert_noop!( - Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,), - >::StorageDepositNotEnoughFunds, - ); + assert_eq!(get_contract(&addr).code_hash, code_hash); + assert_refcount!(&code_hash, 1); + assert_refcount!(&new_code_hash, 0); - assert_eq!(System::events(), vec![]); - }); - } + // only root can execute this extrinsic + assert_noop!( + Contracts::set_code(RuntimeOrigin::signed(ALICE), addr, new_code_hash), + sp_runtime::traits::BadOrigin, + ); + assert_eq!(get_contract(&addr).code_hash, code_hash); + assert_refcount!(&code_hash, 1); + assert_refcount!(&new_code_hash, 0); + assert_eq!(System::events(), vec![]); + + // contract must exist + assert_noop!( + Contracts::set_code(RuntimeOrigin::root(), BOB_ADDR, new_code_hash), + >::ContractNotFound, + ); + assert_eq!(get_contract(&addr).code_hash, code_hash); + assert_refcount!(&code_hash, 1); + assert_refcount!(&new_code_hash, 0); + assert_eq!(System::events(), vec![]); + + // new code hash must exist + assert_noop!( + Contracts::set_code(RuntimeOrigin::root(), addr, Default::default()), + >::CodeNotFound, + ); + assert_eq!(get_contract(&addr).code_hash, code_hash); + assert_refcount!(&code_hash, 1); + assert_refcount!(&new_code_hash, 0); + assert_eq!(System::events(), vec![]); + + // successful call + assert_ok!(Contracts::set_code(RuntimeOrigin::root(), addr, new_code_hash)); + assert_eq!(get_contract(&addr).code_hash, new_code_hash); + assert_refcount!(&code_hash, 0); + assert_refcount!(&new_code_hash, 1); + assert_eq!( + System::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(pallet_revive::Event::ContractCodeUpdated { + contract: addr, + new_code_hash, + old_code_hash: code_hash, + }), + topics: vec![], + },] + ); + }); +} - #[test] - fn remove_code_works() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); +#[test] +fn slash_cannot_kill_account() { + let (wasm, _code_hash) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let value = 700; + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let Contract { addr, account_id } = builder::bare_instantiate(Code::Upload(wasm)) + .value(value) + .build_and_unwrap_contract(); - // Drop previous events - initialize_block(2); + // Drop previous events + initialize_block(2); - assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); - // Ensure the contract was stored and get expected deposit amount to be reserved. - let deposit_expected = expected_deposit(ensure_stored(code_hash)); + let info_deposit = test_utils::contract_info_storage_deposit(&addr); - assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash)); - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { - code_hash, - deposit_held: deposit_expected, - uploader: ALICE_ADDR - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeRemoved { - code_hash, - deposit_released: deposit_expected, - remover: ALICE_ADDR - }), - topics: vec![], - }, - ] - ); - }); - } + assert_eq!( + test_utils::get_balance_on_hold(&HoldReason::StorageDepositReserve.into(), &account_id), + info_deposit + ); - #[test] - fn remove_code_wrong_origin() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); + assert_eq!( + ::Currency::total_balance(&account_id), + info_deposit + value + min_balance + ); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Try to destroy the account of the contract by slashing the total balance. + // The account does not get destroyed because slashing only affects the balance held + // under certain `reason`. Slashing can for example happen if the contract takes part + // in staking. + let _ = ::Currency::slash( + &HoldReason::StorageDepositReserve.into(), + &account_id, + ::Currency::total_balance(&account_id), + ); - // Drop previous events - initialize_block(2); + // Slashing only removed the balance held. + assert_eq!(::Currency::total_balance(&account_id), value + min_balance); + }); +} - assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), wasm, 1_000,)); - // Ensure the contract was stored and get expected deposit amount to be reserved. - let deposit_expected = expected_deposit(ensure_stored(code_hash)); +#[test] +fn contract_reverted() { + let (wasm, code_hash) = compile_module("return_with_data").unwrap(); - assert_noop!( - Contracts::remove_code(RuntimeOrigin::signed(BOB), code_hash), - sp_runtime::traits::BadOrigin, - ); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let flags = ReturnFlags::REVERT; + let buffer = [4u8, 8, 15, 16, 23, 42]; + let input = (flags.bits(), buffer).encode(); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { - code_hash, - deposit_held: deposit_expected, - uploader: ALICE_ADDR - }), - topics: vec![], - },] - ); - }); - } - - #[test] - fn remove_code_in_use() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); - - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - assert_ok!(builder::instantiate_with_code(wasm).build()); - - // Drop previous events - initialize_block(2); - - assert_noop!( - Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), - >::CodeInUse, - ); - - assert_eq!(System::events(), vec![]); - }); - } - - #[test] - fn remove_code_not_found() { - let (_wasm, code_hash) = compile_module("dummy").unwrap(); - - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - // Drop previous events - initialize_block(2); - - assert_noop!( - Contracts::remove_code(RuntimeOrigin::signed(ALICE), code_hash), - >::CodeNotFound, - ); - - assert_eq!(System::events(), vec![]); - }); - } - - #[test] - fn instantiate_with_zero_balance_works() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - - // Drop previous events - initialize_block(2); - - // Instantiate the BOB contract. - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - - // Ensure the contract was stored and get expected deposit amount to be reserved. - let deposit_expected = expected_deposit(ensure_stored(code_hash)); - - // Make sure the account exists even though no free balance was send - assert_eq!(::Currency::free_balance(&account_id), min_balance); - assert_eq!( - ::Currency::total_balance(&account_id), - min_balance + test_utils::contract_info_storage_deposit(&addr) - ); - - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { - code_hash, - deposit_held: deposit_expected, - uploader: ALICE_ADDR - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::System(frame_system::Event::NewAccount { - account: account_id.clone(), - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { - account: account_id.clone(), - free_balance: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id, - amount: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Instantiated { - deployer: ALICE_ADDR, - contract: addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: addr, - amount: test_utils::contract_info_storage_deposit(&addr), - } - ), - topics: vec![], - }, - ] - ); - }); - } - - #[test] - fn instantiate_with_below_existential_deposit_works() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - let value = 50; - - // Drop previous events - initialize_block(2); - - // Instantiate the BOB contract. - let Contract { addr, account_id } = builder::bare_instantiate(Code::Upload(wasm)) - .value(value) - .build_and_unwrap_contract(); - - // Ensure the contract was stored and get expected deposit amount to be reserved. - let deposit_expected = expected_deposit(ensure_stored(code_hash)); - // Make sure the account exists even though not enough free balance was send - assert_eq!(::Currency::free_balance(&account_id), min_balance + value); - assert_eq!( - ::Currency::total_balance(&account_id), - min_balance + value + test_utils::contract_info_storage_deposit(&addr) - ); - - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::CodeStored { - code_hash, - deposit_held: deposit_expected, - uploader: ALICE_ADDR - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::System(frame_system::Event::NewAccount { - account: account_id.clone() - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Endowed { - account: account_id.clone(), - free_balance: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id.clone(), - amount: min_balance, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id.clone(), - amount: 50, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Instantiated { - deployer: ALICE_ADDR, - contract: addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: addr, - amount: test_utils::contract_info_storage_deposit(&addr), - } - ), - topics: vec![], - }, - ] - ); - }); - } - - #[test] - fn storage_deposit_works() { - let (wasm, _code_hash) = compile_module("multi_store").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - - let mut deposit = test_utils::contract_info_storage_deposit(&addr); - - // Drop previous events - initialize_block(2); - - // Create storage - assert_ok!(builder::call(addr).value(42).data((50u32, 20u32).encode()).build()); - // 4 is for creating 2 storage items - let charged0 = 4 + 50 + 20; - deposit += charged0; - assert_eq!(get_contract(&addr).total_deposit(), deposit); - - // Add more storage (but also remove some) - assert_ok!(builder::call(addr).data((100u32, 10u32).encode()).build()); - let charged1 = 50 - 10; - deposit += charged1; - assert_eq!(get_contract(&addr).total_deposit(), deposit); - - // Remove more storage (but also add some) - assert_ok!(builder::call(addr).data((10u32, 20u32).encode()).build()); - // -1 for numeric instability - let refunded0 = 90 - 10 - 1; - deposit -= refunded0; - assert_eq!(get_contract(&addr).total_deposit(), deposit); - - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Balances(pallet_balances::Event::Transfer { - from: ALICE, - to: account_id.clone(), - amount: 42, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: addr, - amount: charged0, - } - ), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndHeld { - from: ALICE_ADDR, - to: addr, - amount: charged1, - } - ), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts( - pallet_revive::Event::StorageDepositTransferredAndReleased { - from: addr, - to: ALICE_ADDR, - amount: refunded0, - } - ), - topics: vec![], - }, - ] - ); - }); - } - - #[test] - fn storage_deposit_callee_works() { - let (wasm_caller, _code_hash_caller) = compile_module("call").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, account_id } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); - - assert_ok!(builder::call(addr_caller).data((100u32, &addr_callee).encode()).build()); - - let callee = get_contract(&addr_callee); - let deposit = DepositPerByte::get() * 100 + DepositPerItem::get() * 1; - - assert_eq!(test_utils::get_balance(&account_id), min_balance); - assert_eq!( - callee.total_deposit(), - deposit + test_utils::contract_info_storage_deposit(&addr_callee) - ); - }); - } - - #[test] - fn set_code_extrinsic() { - let (wasm, code_hash) = compile_module("dummy").unwrap(); - let (new_wasm, new_code_hash) = compile_module("crypto_hashes").unwrap(); - - assert_ne!(code_hash, new_code_hash); + // We just upload the code for later use + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + deposit_limit::(), + )); + + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).data(input.clone()).build(), + >::ContractReverted, + ); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).data(input.clone()).build(), + >::ContractReverted, + ); - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + // Calling directly: revert leads to success but the flags indicate the error + // This is just a different way of transporting the error that allows the read out + // the `data` which is only there on success. Obviously, the contract isn't + // instantiated. + let result = builder::bare_instantiate(Code::Existing(code_hash)) + .data(input.clone()) + .build_and_unwrap_result(); + assert_eq!(result.result.flags, flags); + assert_eq!(result.result.data, buffer); + assert!(!>::contains_key(result.addr)); + + // Pass empty flags and therefore successfully instantiate the contract for later use. + let Contract { addr, .. } = builder::bare_instantiate(Code::Existing(code_hash)) + .data(ReturnFlags::empty().bits().encode()) + .build_and_unwrap_contract(); + + // Calling extrinsic: revert leads to an error + assert_err_ignore_postinfo!( + builder::call(addr).data(input.clone()).build(), + >::ContractReverted, + ); - assert_ok!(Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - new_wasm, - deposit_limit::(), - )); + // Calling directly: revert leads to success but the flags indicate the error + let result = builder::bare_call(addr).data(input).build_and_unwrap_result(); + assert_eq!(result.flags, flags); + assert_eq!(result.data, buffer); + }); +} - // Drop previous events - initialize_block(2); +#[test] +fn set_code_hash() { + let (wasm, code_hash) = compile_module("set_code_hash").unwrap(); + let (new_wasm, new_code_hash) = compile_module("new_set_code_hash_contract").unwrap(); - assert_eq!(get_contract(&addr).code_hash, code_hash); - assert_refcount!(&code_hash, 1); - assert_refcount!(&new_code_hash, 0); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // only root can execute this extrinsic - assert_noop!( - Contracts::set_code(RuntimeOrigin::signed(ALICE), addr, new_code_hash), - sp_runtime::traits::BadOrigin, - ); - assert_eq!(get_contract(&addr).code_hash, code_hash); - assert_refcount!(&code_hash, 1); - assert_refcount!(&new_code_hash, 0); - assert_eq!(System::events(), vec![]); - - // contract must exist - assert_noop!( - Contracts::set_code(RuntimeOrigin::root(), BOB_ADDR, new_code_hash), - >::ContractNotFound, - ); - assert_eq!(get_contract(&addr).code_hash, code_hash); - assert_refcount!(&code_hash, 1); - assert_refcount!(&new_code_hash, 0); - assert_eq!(System::events(), vec![]); - - // new code hash must exist - assert_noop!( - Contracts::set_code(RuntimeOrigin::root(), addr, Default::default()), - >::CodeNotFound, - ); - assert_eq!(get_contract(&addr).code_hash, code_hash); - assert_refcount!(&code_hash, 1); - assert_refcount!(&new_code_hash, 0); - assert_eq!(System::events(), vec![]); - - // successful call - assert_ok!(Contracts::set_code(RuntimeOrigin::root(), addr, new_code_hash)); - assert_eq!(get_contract(&addr).code_hash, new_code_hash); - assert_refcount!(&code_hash, 0); - assert_refcount!(&new_code_hash, 1); - assert_eq!( - System::events(), - vec![EventRecord { + // Instantiate the 'caller' + let Contract { addr: contract_addr, .. } = builder::bare_instantiate(Code::Upload(wasm)) + .value(300_000) + .build_and_unwrap_contract(); + // upload new code + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + new_wasm.clone(), + deposit_limit::(), + )); + + System::reset_events(); + + // First call sets new code_hash and returns 1 + let result = builder::bare_call(contract_addr) + .data(new_code_hash.as_ref().to_vec()) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + assert_return_code!(result, 1); + + // Second calls new contract code that returns 2 + let result = builder::bare_call(contract_addr) + .debug(DebugInfo::UnsafeDebug) + .build_and_unwrap_result(); + assert_return_code!(result, 2); + + // Checking for the last event only + assert_eq!( + &System::events(), + &[ + EventRecord { phase: Phase::Initialization, - event: RuntimeEvent::Contracts(pallet_revive::Event::ContractCodeUpdated { - contract: addr, + event: RuntimeEvent::Contracts(crate::Event::ContractCodeUpdated { + contract: contract_addr, new_code_hash, old_code_hash: code_hash, }), topics: vec![], - },] - ); - }); - } - - #[test] - fn slash_cannot_kill_account() { - let (wasm, _code_hash) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let value = 700; - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - - let Contract { addr, account_id } = builder::bare_instantiate(Code::Upload(wasm)) - .value(value) - .build_and_unwrap_contract(); - - // Drop previous events - initialize_block(2); - - let info_deposit = test_utils::contract_info_storage_deposit(&addr); - - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &account_id - ), - info_deposit - ); - - assert_eq!( - ::Currency::total_balance(&account_id), - info_deposit + value + min_balance - ); - - // Try to destroy the account of the contract by slashing the total balance. - // The account does not get destroyed because slashing only affects the balance held - // under certain `reason`. Slashing can for example happen if the contract takes part - // in staking. - let _ = ::Currency::slash( - &HoldReason::StorageDepositReserve.into(), - &account_id, - ::Currency::total_balance(&account_id), - ); - - // Slashing only removed the balance held. - assert_eq!(::Currency::total_balance(&account_id), value + min_balance); - }); - } - - #[test] - fn contract_reverted() { - let (wasm, code_hash) = compile_module("return_with_data").unwrap(); - - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let flags = ReturnFlags::REVERT; - let buffer = [4u8, 8, 15, 16, 23, 42]; - let input = (flags.bits(), buffer).encode(); - - // We just upload the code for later use - assert_ok!(Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - wasm.clone(), - deposit_limit::(), - )); - - // Calling extrinsic: revert leads to an error - assert_err_ignore_postinfo!( - builder::instantiate(code_hash).data(input.clone()).build(), - >::ContractReverted, - ); - - // Calling extrinsic: revert leads to an error - assert_err_ignore_postinfo!( - builder::instantiate_with_code(wasm).data(input.clone()).build(), - >::ContractReverted, - ); - - // Calling directly: revert leads to success but the flags indicate the error - // This is just a different way of transporting the error that allows the read out - // the `data` which is only there on success. Obviously, the contract isn't - // instantiated. - let result = builder::bare_instantiate(Code::Existing(code_hash)) - .data(input.clone()) - .build_and_unwrap_result(); - assert_eq!(result.result.flags, flags); - assert_eq!(result.result.data, buffer); - assert!(!>::contains_key(result.addr)); - - // Pass empty flags and therefore successfully instantiate the contract for later use. - let Contract { addr, .. } = builder::bare_instantiate(Code::Existing(code_hash)) - .data(ReturnFlags::empty().bits().encode()) - .build_and_unwrap_contract(); - - // Calling extrinsic: revert leads to an error - assert_err_ignore_postinfo!( - builder::call(addr).data(input.clone()).build(), - >::ContractReverted, - ); - - // Calling directly: revert leads to success but the flags indicate the error - let result = builder::bare_call(addr).data(input).build_and_unwrap_result(); - assert_eq!(result.flags, flags); - assert_eq!(result.data, buffer); - }); - } - - #[test] - fn set_code_hash() { - let (wasm, code_hash) = compile_module("set_code_hash").unwrap(); - let (new_wasm, new_code_hash) = compile_module("new_set_code_hash_contract").unwrap(); - - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - // Instantiate the 'caller' - let Contract { addr: contract_addr, .. } = - builder::bare_instantiate(Code::Upload(wasm)) - .value(300_000) - .build_and_unwrap_contract(); - // upload new code - assert_ok!(Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - new_wasm.clone(), - deposit_limit::(), - )); - - System::reset_events(); - - // First call sets new code_hash and returns 1 - let result = builder::bare_call(contract_addr) - .data(new_code_hash.as_ref().to_vec()) - .debug(DebugInfo::UnsafeDebug) - .build_and_unwrap_result(); - assert_return_code!(result, 1); - - // Second calls new contract code that returns 2 - let result = builder::bare_call(contract_addr) - .debug(DebugInfo::UnsafeDebug) - .build_and_unwrap_result(); - assert_return_code!(result, 2); - - // Checking for the last event only - assert_eq!( - &System::events(), - &[ - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::ContractCodeUpdated { - contract: contract_addr, - new_code_hash, - old_code_hash: code_hash, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: contract_addr, - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: RuntimeEvent::Contracts(crate::Event::Called { - caller: Origin::from_account_id(ALICE), - contract: contract_addr, - }), - topics: vec![], - }, - ], - ); - }); - } - - #[test] - fn storage_deposit_limit_is_enforced() { - let (wasm, _code_hash) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let min_balance = Contracts::min_balance(); - - // Setting insufficient storage_deposit should fail. - assert_err!( - builder::bare_instantiate(Code::Upload(wasm.clone())) - // expected deposit is 2 * ed + 3 for the call - .storage_deposit_limit((2 * min_balance + 3 - 1).into()) - .build() - .result, - >::StorageDepositLimitExhausted, - ); + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: contract_addr, + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: RuntimeEvent::Contracts(crate::Event::Called { + caller: Origin::from_account_id(ALICE), + contract: contract_addr, + }), + topics: vec![], + }, + ], + ); + }); +} - // Instantiate the BOB contract. - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); +#[test] +fn storage_deposit_limit_is_enforced() { + let (wasm, _code_hash) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Setting insufficient storage_deposit should fail. + assert_err!( + builder::bare_instantiate(Code::Upload(wasm.clone())) + // expected deposit is 2 * ed + 3 for the call + .storage_deposit_limit((2 * min_balance + 3 - 1).into()) + .build() + .result, + >::StorageDepositLimitExhausted, + ); - let info_deposit = test_utils::contract_info_storage_deposit(&addr); - // Check that the BOB contract has been instantiated and has the minimum balance - assert_eq!(get_contract(&addr).total_deposit(), info_deposit); - assert_eq!( - ::Currency::total_balance(&account_id), - info_deposit + min_balance - ); + // Instantiate the BOB contract. + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - // Create 1 byte of storage with a price of per byte, - // setting insufficient deposit limit, as it requires 3 Balance: - // 2 for the item added + 1 for the new storage item. - assert_err_ignore_postinfo!( - builder::call(addr) - .storage_deposit_limit(2) - .data(1u32.to_le_bytes().to_vec()) - .build(), - >::StorageDepositLimitExhausted, - ); + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + // Check that the BOB contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!( + ::Currency::total_balance(&account_id), + info_deposit + min_balance + ); - // Create 1 byte of storage, should cost 3 Balance: - // 2 for the item added + 1 for the new storage item. - // Should pass as it fallbacks to DefaultDepositLimit. - assert_ok!(builder::call(addr) - .storage_deposit_limit(3) + // Create 1 byte of storage with a price of per byte, + // setting insufficient deposit limit, as it requires 3 Balance: + // 2 for the item added + 1 for the new storage item. + assert_err_ignore_postinfo!( + builder::call(addr) + .storage_deposit_limit(2) .data(1u32.to_le_bytes().to_vec()) - .build()); - - // Use 4 more bytes of the storage for the same item, which requires 4 Balance. - // Should fail as DefaultDepositLimit is 3 and hence isn't enough. - assert_err_ignore_postinfo!( - builder::call(addr) - .storage_deposit_limit(3) - .data(5u32.to_le_bytes().to_vec()) - .build(), - >::StorageDepositLimitExhausted, - ); - }); - } - - #[test] - fn deposit_limit_in_nested_calls() { - let (wasm_caller, _code_hash_caller) = compile_module("create_storage_and_call").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + .build(), + >::StorageDepositLimitExhausted, + ); - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + // Create 1 byte of storage, should cost 3 Balance: + // 2 for the item added + 1 for the new storage item. + // Should pass as it fallbacks to DefaultDepositLimit. + assert_ok!(builder::call(addr) + .storage_deposit_limit(3) + .data(1u32.to_le_bytes().to_vec()) + .build()); + + // Use 4 more bytes of the storage for the same item, which requires 4 Balance. + // Should fail as DefaultDepositLimit is 3 and hence isn't enough. + assert_err_ignore_postinfo!( + builder::call(addr) + .storage_deposit_limit(3) + .data(5u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositLimitExhausted, + ); + }); +} - // Create 100 bytes of storage with a price of per byte - // This is 100 Balance + 2 Balance for the item - assert_ok!(builder::call(addr_callee) - .storage_deposit_limit(102) - .data(100u32.to_le_bytes().to_vec()) - .build()); - - // We do not remove any storage but add a storage item of 12 bytes in the caller - // contract. This would cost 12 + 2 = 14 Balance. - // The nested call doesn't get a special limit, which is set by passing 0 to it. - // This should fail as the specified parent's limit is less than the cost: 13 < - // 14. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .storage_deposit_limit(13) - .data((100u32, &addr_callee, U256::from(0u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); +#[test] +fn deposit_limit_in_nested_calls() { + let (wasm_caller, _code_hash_caller) = compile_module("create_storage_and_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + // Create 100 bytes of storage with a price of per byte + // This is 100 Balance + 2 Balance for the item + assert_ok!(builder::call(addr_callee) + .storage_deposit_limit(102) + .data(100u32.to_le_bytes().to_vec()) + .build()); + + // We do not remove any storage but add a storage item of 12 bytes in the caller + // contract. This would cost 12 + 2 = 14 Balance. + // The nested call doesn't get a special limit, which is set by passing 0 to it. + // This should fail as the specified parent's limit is less than the cost: 13 < + // 14. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .storage_deposit_limit(13) + .data((100u32, &addr_callee, U256::from(0u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); - // Now we specify the parent's limit high enough to cover the caller's storage - // additions. However, we use a single byte more in the callee, hence the storage - // deposit should be 15 Balance. - // The nested call doesn't get a special limit, which is set by passing 0 to it. - // This should fail as the specified parent's limit is less than the cost: 14 - // < 15. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .storage_deposit_limit(14) - .data((101u32, &addr_callee, U256::from(0u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); + // Now we specify the parent's limit high enough to cover the caller's storage + // additions. However, we use a single byte more in the callee, hence the storage + // deposit should be 15 Balance. + // The nested call doesn't get a special limit, which is set by passing 0 to it. + // This should fail as the specified parent's limit is less than the cost: 14 + // < 15. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .storage_deposit_limit(14) + .data((101u32, &addr_callee, U256::from(0u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); - // Now we specify the parent's limit high enough to cover both the caller's and callee's - // storage additions. However, we set a special deposit limit of 1 Balance for the - // nested call. This should fail as callee adds up 2 bytes to the storage, meaning - // that the nested call should have a deposit limit of at least 2 Balance. The - // sub-call should be rolled back, which is covered by the next test case. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .storage_deposit_limit(16) - .data((102u32, &addr_callee, U256::from(1u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); + // Now we specify the parent's limit high enough to cover both the caller's and callee's + // storage additions. However, we set a special deposit limit of 1 Balance for the + // nested call. This should fail as callee adds up 2 bytes to the storage, meaning + // that the nested call should have a deposit limit of at least 2 Balance. The + // sub-call should be rolled back, which is covered by the next test case. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .storage_deposit_limit(16) + .data((102u32, &addr_callee, U256::from(1u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); - // Refund in the callee contract but not enough to cover the 14 Balance required by the - // caller. Note that if previous sub-call wouldn't roll back, this call would pass - // making the test case fail. We don't set a special limit for the nested call here. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .storage_deposit_limit(0) - .data((87u32, &addr_callee, U256::from(0u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); + // Refund in the callee contract but not enough to cover the 14 Balance required by the + // caller. Note that if previous sub-call wouldn't roll back, this call would pass + // making the test case fail. We don't set a special limit for the nested call here. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .storage_deposit_limit(0) + .data((87u32, &addr_callee, U256::from(0u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); - let _ = ::Currency::set_balance(&ALICE, 511); + let _ = ::Currency::set_balance(&ALICE, 511); - // Require more than the sender's balance. - // We don't set a special limit for the nested call. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .data((512u32, &addr_callee, U256::from(1u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); + // Require more than the sender's balance. + // We don't set a special limit for the nested call. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((512u32, &addr_callee, U256::from(1u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); - // Same as above but allow for the additional deposit of 1 Balance in parent. - // We set the special deposit limit of 1 Balance for the nested call, which isn't - // enforced as callee frees up storage. This should pass. - assert_ok!(builder::call(addr_caller) - .storage_deposit_limit(1) - .data((87u32, &addr_callee, U256::from(1u64)).encode()) - .build()); - }); - } + // Same as above but allow for the additional deposit of 1 Balance in parent. + // We set the special deposit limit of 1 Balance for the nested call, which isn't + // enforced as callee frees up storage. This should pass. + assert_ok!(builder::call(addr_caller) + .storage_deposit_limit(1) + .data((87u32, &addr_callee, U256::from(1u64)).encode()) + .build()); + }); +} - #[test] - fn deposit_limit_in_nested_instantiate() { - let (wasm_caller, _code_hash_caller) = - compile_module("create_storage_and_instantiate").unwrap(); - let (wasm_callee, code_hash_callee) = compile_module("store_deploy").unwrap(); - const ED: u64 = 5; - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let _ = ::Currency::set_balance(&BOB, 1_000_000); - // Create caller contract - let Contract { addr: addr_caller, account_id: caller_id } = - builder::bare_instantiate(Code::Upload(wasm_caller)) - .value(10_000u64) // this balance is later passed to the deployed contract - .build_and_unwrap_contract(); - // Deploy a contract to get its occupied storage size - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm_callee)) - .data(vec![0, 0, 0, 0]) +#[test] +fn deposit_limit_in_nested_instantiate() { + let (wasm_caller, _code_hash_caller) = + compile_module("create_storage_and_instantiate").unwrap(); + let (wasm_callee, code_hash_callee) = compile_module("store_deploy").unwrap(); + const ED: u64 = 5; + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 1_000_000); + // Create caller contract + let Contract { addr: addr_caller, account_id: caller_id } = + builder::bare_instantiate(Code::Upload(wasm_caller)) + .value(10_000u64) // this balance is later passed to the deployed contract .build_and_unwrap_contract(); - - let callee_info_len = ContractInfoOf::::get(&addr).unwrap().encoded_size() as u64; - - // We don't set a special deposit limit for the nested instantiation. - // - // The deposit limit set for the parent is insufficient for the instantiation, which - // requires: - // - callee_info_len + 2 for storing the new contract info, - // - ED for deployed contract account, - // - 2 for the storage item of 0 bytes being created in the callee constructor - // or (callee_info_len + 2 + ED + 2) Balance in total. - // - // Provided the limit is set to be 1 Balance less, - // this call should fail on the return from the caller contract. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 1) - .data((0u32, &code_hash_callee, U256::from(0u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); - // The charges made on instantiation should be rolled back. - assert_eq!(::Currency::free_balance(&BOB), 1_000_000); - - // Now we give enough limit for the instantiation itself, but require for 1 more storage - // byte in the constructor. Hence +1 Balance to the limit is needed. This should fail on - // the return from constructor. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 2) - .data((1u32, &code_hash_callee, U256::from(0u64)).encode()) - .build(), - >::StorageDepositLimitExhausted, - ); - // The charges made on the instantiation should be rolled back. - assert_eq!(::Currency::free_balance(&BOB), 1_000_000); - - // Now we set enough limit in parent call, but an insufficient limit for child - // instantiate. This should fail during the charging for the instantiation in - // `RawMeter::charge_instantiate()` - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 2) - .data( - (0u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 1)) - .encode() - ) - .build(), - >::StorageDepositLimitExhausted, - ); - // The charges made on the instantiation should be rolled back. - assert_eq!(::Currency::free_balance(&BOB), 1_000_000); - - // Same as above but requires for single added storage - // item of 1 byte to be covered by the limit, which implies 3 more Balance. - // Now we set enough limit for the parent call, but insufficient limit for child - // instantiate. This should fail right after the constructor execution. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 3) // enough parent limit - .data( - (1u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 2)) - .encode() - ) - .build(), - >::StorageDepositLimitExhausted, - ); - // The charges made on the instantiation should be rolled back. - assert_eq!(::Currency::free_balance(&BOB), 1_000_000); - - // Set enough deposit limit for the child instantiate. This should succeed. - let result = builder::bare_call(addr_caller) + // Deploy a contract to get its occupied storage size + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(wasm_callee)) + .data(vec![0, 0, 0, 0]) + .build_and_unwrap_contract(); + + let callee_info_len = ContractInfoOf::::get(&addr).unwrap().encoded_size() as u64; + + // We don't set a special deposit limit for the nested instantiation. + // + // The deposit limit set for the parent is insufficient for the instantiation, which + // requires: + // - callee_info_len + 2 for storing the new contract info, + // - ED for deployed contract account, + // - 2 for the storage item of 0 bytes being created in the callee constructor + // or (callee_info_len + 2 + ED + 2) Balance in total. + // + // Provided the limit is set to be 1 Balance less, + // this call should fail on the return from the caller contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller) .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 4 + 2) - .data( - (1u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 3 + 2)) - .encode(), - ) - .build(); - - let returned = result.result.unwrap(); - // All balance of the caller except ED has been transferred to the callee. - // No deposit has been taken from it. - assert_eq!(::Currency::free_balance(&caller_id), ED); - // Get address of the deployed contract. - let addr_callee = H160::from_slice(&returned.data[0..20]); - let callee_account_id = ::AddressMapper::to_account_id(&addr_callee); - // 10_000 should be sent to callee from the caller contract, plus ED to be sent from the - // origin. - assert_eq!(::Currency::free_balance(&callee_account_id), 10_000 + ED); - // The origin should be charged with: - // - callee instantiation deposit = (callee_info_len + 2) - // - callee account ED - // - for writing an item of 1 byte to storage = 3 Balance - // - Immutable data storage item deposit - assert_eq!( - ::Currency::free_balance(&BOB), - 1_000_000 - (callee_info_len + 2 + ED + 3) - ); - // Check that deposit due to be charged still includes these 3 Balance - assert_eq!(result.storage_deposit.charge_or_zero(), (callee_info_len + 2 + ED + 3)) - }); - } - - #[test] - fn deposit_limit_honors_liquidity_restrictions() { - let (wasm, _code_hash) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let bobs_balance = 1_000; - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let _ = ::Currency::set_balance(&BOB, bobs_balance); - let min_balance = Contracts::min_balance(); - - // Instantiate the BOB contract. - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - - let info_deposit = test_utils::contract_info_storage_deposit(&addr); - // Check that the contract has been instantiated and has the minimum balance - assert_eq!(get_contract(&addr).total_deposit(), info_deposit); - assert_eq!( - ::Currency::total_balance(&account_id), - info_deposit + min_balance - ); - - // check that the hold is honored - ::Currency::hold( - &HoldReason::CodeUploadDepositReserve.into(), - &BOB, - bobs_balance - min_balance, - ) - .unwrap(); - assert_err_ignore_postinfo!( - builder::call(addr) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(10_000) - .data(100u32.to_le_bytes().to_vec()) - .build(), - >::StorageDepositLimitExhausted, - ); - assert_eq!(::Currency::free_balance(&BOB), min_balance); - }); - } - - #[test] - fn deposit_limit_honors_existential_deposit() { - let (wasm, _code_hash) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let _ = ::Currency::set_balance(&BOB, 300); - let min_balance = Contracts::min_balance(); - - // Instantiate the BOB contract. - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - - let info_deposit = test_utils::contract_info_storage_deposit(&addr); - - // Check that the contract has been instantiated and has the minimum balance - assert_eq!(get_contract(&addr).total_deposit(), info_deposit); - assert_eq!( - ::Currency::total_balance(&account_id), - min_balance + info_deposit - ); - - // check that the deposit can't bring the account below the existential deposit - assert_err_ignore_postinfo!( - builder::call(addr) - .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(10_000) - .data(100u32.to_le_bytes().to_vec()) - .build(), - >::StorageDepositLimitExhausted, - ); - assert_eq!(::Currency::free_balance(&BOB), 300); - }); - } - - #[test] - fn deposit_limit_honors_min_leftover() { - let (wasm, _code_hash) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let _ = ::Currency::set_balance(&BOB, 1_000); - let min_balance = Contracts::min_balance(); - - // Instantiate the BOB contract. - let Contract { addr, account_id } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - - let info_deposit = test_utils::contract_info_storage_deposit(&addr); - - // Check that the contract has been instantiated and has the minimum balance and the - // storage deposit - assert_eq!(get_contract(&addr).total_deposit(), info_deposit); - assert_eq!( - ::Currency::total_balance(&account_id), - info_deposit + min_balance - ); - - // check that the minimum leftover (value send) is considered - // given the minimum deposit of 200 sending 750 will only leave - // 50 for the storage deposit. Which is not enough to store the 50 bytes - // as we also need 2 bytes for the item - assert_err_ignore_postinfo!( - builder::call(addr) - .origin(RuntimeOrigin::signed(BOB)) - .value(750) - .storage_deposit_limit(10_000) - .data(50u32.to_le_bytes().to_vec()) - .build(), - >::StorageDepositLimitExhausted, - ); - assert_eq!(::Currency::free_balance(&BOB), 1_000); - }); - } - - #[test] - fn locking_delegate_dependency_works() { - // set hash lock up deposit to 30%, to test deposit calculation. - CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); - - let (wasm_caller, self_code_hash) = compile_module("locking_delegate_dependency").unwrap(); - let callee_codes: Vec<_> = - (0..limits::DELEGATE_DEPENDENCIES + 1).map(|idx| dummy_unique(idx)).collect(); - let callee_hashes: Vec<_> = callee_codes - .iter() - .map(|c| sp_core::H256(sp_io::hashing::keccak_256(c))) - .collect(); - - // Define inputs with various actions to test locking / unlocking delegate_dependencies. - // See the contract for more details. - let noop_input = (0u32, callee_hashes[0]); - let lock_delegate_dependency_input = (1u32, callee_hashes[0]); - let unlock_delegate_dependency_input = (2u32, callee_hashes[0]); - let terminate_input = (3u32, callee_hashes[0]); - - // Instantiate the caller contract with the given input. - let instantiate = |input: &(u32, H256)| { - builder::bare_instantiate(Code::Upload(wasm_caller.clone())) - .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) - .data(input.encode()) - .build() - }; - - // Call contract with the given input. - let call = |addr_caller: &H160, input: &(u32, H256)| { - builder::bare_call(*addr_caller) - .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) - .data(input.encode()) - .build() - }; - const ED: u64 = 2000; - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let _ = Balances::set_balance(&ALICE_FALLBACK, 1_000_000); - - // Instantiate with lock_delegate_dependency should fail since the code is not yet on - // chain. - assert_err!( - instantiate(&lock_delegate_dependency_input).result, - Error::::CodeNotFound - ); - - // Upload all the delegated codes (they all have the same size) - let mut deposit = Default::default(); - for code in callee_codes.iter() { - let CodeUploadReturnValue { deposit: deposit_per_code, .. } = - Contracts::bare_upload_code( - RuntimeOrigin::signed(ALICE_FALLBACK), - code.clone(), - deposit_limit::(), - ) - .unwrap(); - deposit = deposit_per_code; - } - - // Instantiate should now work. - let addr_caller = instantiate(&lock_delegate_dependency_input).result.unwrap().addr; - let caller_account_id = ::AddressMapper::to_account_id(&addr_caller); - - // There should be a dependency and a deposit. - let contract = test_utils::get_contract(&addr_caller); - - let dependency_deposit = &CodeHashLockupDepositPercent::get().mul_ceil(deposit); - assert_eq!( - contract.delegate_dependencies().get(&callee_hashes[0]), - Some(dependency_deposit) - ); - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &caller_account_id - ), - dependency_deposit + contract.storage_base_deposit() - ); - - // Removing the code should fail, since we have added a dependency. - assert_err!( - Contracts::remove_code(RuntimeOrigin::signed(ALICE_FALLBACK), callee_hashes[0]), - >::CodeInUse - ); - - // Locking an already existing dependency should fail. - assert_err!( - call(&addr_caller, &lock_delegate_dependency_input).result, - Error::::DelegateDependencyAlreadyExists - ); - - // Locking self should fail. - assert_err!( - call(&addr_caller, &(1u32, self_code_hash)).result, - Error::::CannotAddSelfAsDelegateDependency - ); - - // Locking more than the maximum allowed delegate_dependencies should fail. - for hash in &callee_hashes[1..callee_hashes.len() - 1] { - call(&addr_caller, &(1u32, *hash)).result.unwrap(); - } - assert_err!( - call(&addr_caller, &(1u32, *callee_hashes.last().unwrap())).result, - Error::::MaxDelegateDependenciesReached - ); - - // Unlocking all dependency should work. - for hash in &callee_hashes[..callee_hashes.len() - 1] { - call(&addr_caller, &(2u32, *hash)).result.unwrap(); - } - - // Dependency should be removed, and deposit should be returned. - let contract = test_utils::get_contract(&addr_caller); - assert!(contract.delegate_dependencies().is_empty()); - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &caller_account_id - ), - contract.storage_base_deposit() - ); - - // Removing a nonexistent dependency should fail. - assert_err!( - call(&addr_caller, &unlock_delegate_dependency_input).result, - Error::::DelegateDependencyNotFound - ); - - // Locking a dependency with a storage limit too low should fail. - assert_err!( - builder::bare_call(addr_caller) - .storage_deposit_limit(dependency_deposit - 1) - .data(lock_delegate_dependency_input.encode()) - .build() - .result, - Error::::StorageDepositLimitExhausted - ); + .storage_deposit_limit(callee_info_len + 2 + ED + 1) + .data((0u32, &code_hash_callee, U256::from(0u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Now we give enough limit for the instantiation itself, but require for 1 more storage + // byte in the constructor. Hence +1 Balance to the limit is needed. This should fail on + // the return from constructor. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(callee_info_len + 2 + ED + 2) + .data((1u32, &code_hash_callee, U256::from(0u64)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Now we set enough limit in parent call, but an insufficient limit for child + // instantiate. This should fail during the charging for the instantiation in + // `RawMeter::charge_instantiate()` + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(callee_info_len + 2 + ED + 2) + .data((0u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 1)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Same as above but requires for single added storage + // item of 1 byte to be covered by the limit, which implies 3 more Balance. + // Now we set enough limit for the parent call, but insufficient limit for child + // instantiate. This should fail right after the constructor execution. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(callee_info_len + 2 + ED + 3) // enough parent limit + .data((1u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 2)).encode()) + .build(), + >::StorageDepositLimitExhausted, + ); + // The charges made on the instantiation should be rolled back. + assert_eq!(::Currency::free_balance(&BOB), 1_000_000); + + // Set enough deposit limit for the child instantiate. This should succeed. + let result = builder::bare_call(addr_caller) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(callee_info_len + 2 + ED + 4 + 2) + .data((1u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 3 + 2)).encode()) + .build(); + + let returned = result.result.unwrap(); + // All balance of the caller except ED has been transferred to the callee. + // No deposit has been taken from it. + assert_eq!(::Currency::free_balance(&caller_id), ED); + // Get address of the deployed contract. + let addr_callee = H160::from_slice(&returned.data[0..20]); + let callee_account_id = ::AddressMapper::to_account_id(&addr_callee); + // 10_000 should be sent to callee from the caller contract, plus ED to be sent from the + // origin. + assert_eq!(::Currency::free_balance(&callee_account_id), 10_000 + ED); + // The origin should be charged with: + // - callee instantiation deposit = (callee_info_len + 2) + // - callee account ED + // - for writing an item of 1 byte to storage = 3 Balance + // - Immutable data storage item deposit + assert_eq!( + ::Currency::free_balance(&BOB), + 1_000_000 - (callee_info_len + 2 + ED + 3) + ); + // Check that deposit due to be charged still includes these 3 Balance + assert_eq!(result.storage_deposit.charge_or_zero(), (callee_info_len + 2 + ED + 3)) + }); +} - // Since we unlocked the dependency we should now be able to remove the code. - assert_ok!(Contracts::remove_code( - RuntimeOrigin::signed(ALICE_FALLBACK), - callee_hashes[0] - )); +#[test] +fn deposit_limit_honors_liquidity_restrictions() { + let (wasm, _code_hash) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let bobs_balance = 1_000; + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, bobs_balance); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!( + ::Currency::total_balance(&account_id), + info_deposit + min_balance + ); - // Calling should fail since the delegated contract is not on chain anymore. - assert_err!(call(&addr_caller, &noop_input).result, Error::::ContractTrapped); + // check that the hold is honored + ::Currency::hold( + &HoldReason::CodeUploadDepositReserve.into(), + &BOB, + bobs_balance - min_balance, + ) + .unwrap(); + assert_err_ignore_postinfo!( + builder::call(addr) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(10_000) + .data(100u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositLimitExhausted, + ); + assert_eq!(::Currency::free_balance(&BOB), min_balance); + }); +} - // Add the dependency back. - Contracts::upload_code( - RuntimeOrigin::signed(ALICE_FALLBACK), - callee_codes[0].clone(), - deposit_limit::(), - ) - .unwrap(); - call(&addr_caller, &lock_delegate_dependency_input).result.unwrap(); +#[test] +fn deposit_limit_honors_existential_deposit() { + let (wasm, _code_hash) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 300); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Check that the contract has been instantiated and has the minimum balance + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!( + ::Currency::total_balance(&account_id), + min_balance + info_deposit + ); - // Call terminate should work, and return the deposit. - let balance_before = test_utils::get_balance(&ALICE_FALLBACK); - assert_ok!(call(&addr_caller, &terminate_input).result); - assert_eq!( - test_utils::get_balance(&ALICE_FALLBACK), - ED + balance_before + contract.storage_base_deposit() + dependency_deposit - ); + // check that the deposit can't bring the account below the existential deposit + assert_err_ignore_postinfo!( + builder::call(addr) + .origin(RuntimeOrigin::signed(BOB)) + .storage_deposit_limit(10_000) + .data(100u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositLimitExhausted, + ); + assert_eq!(::Currency::free_balance(&BOB), 300); + }); +} - // Terminate should also remove the dependency, so we can remove the code. - assert_ok!(Contracts::remove_code( - RuntimeOrigin::signed(ALICE_FALLBACK), - callee_hashes[0] - )); - }); - } +#[test] +fn deposit_limit_honors_min_leftover() { + let (wasm, _code_hash) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let _ = ::Currency::set_balance(&BOB, 1_000); + let min_balance = Contracts::min_balance(); + + // Instantiate the BOB contract. + let Contract { addr, account_id } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + + let info_deposit = test_utils::contract_info_storage_deposit(&addr); + + // Check that the contract has been instantiated and has the minimum balance and the + // storage deposit + assert_eq!(get_contract(&addr).total_deposit(), info_deposit); + assert_eq!( + ::Currency::total_balance(&account_id), + info_deposit + min_balance + ); - #[test] - fn native_dependency_deposit_works() { - let (wasm, code_hash) = compile_module("set_code_hash").unwrap(); - let (dummy_wasm, dummy_code_hash) = compile_module("dummy").unwrap(); + // check that the minimum leftover (value send) is considered + // given the minimum deposit of 200 sending 750 will only leave + // 50 for the storage deposit. Which is not enough to store the 50 bytes + // as we also need 2 bytes for the item + assert_err_ignore_postinfo!( + builder::call(addr) + .origin(RuntimeOrigin::signed(BOB)) + .value(750) + .storage_deposit_limit(10_000) + .data(50u32.to_le_bytes().to_vec()) + .build(), + >::StorageDepositLimitExhausted, + ); + assert_eq!(::Currency::free_balance(&BOB), 1_000); + }); +} - // Set hash lock up deposit to 30%, to test deposit calculation. - CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); +#[test] +fn locking_delegate_dependency_works() { + // set hash lock up deposit to 30%, to test deposit calculation. + CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); + + let (wasm_caller, self_code_hash) = compile_module("locking_delegate_dependency").unwrap(); + let callee_codes: Vec<_> = + (0..limits::DELEGATE_DEPENDENCIES + 1).map(|idx| dummy_unique(idx)).collect(); + let callee_hashes: Vec<_> = callee_codes + .iter() + .map(|c| sp_core::H256(sp_io::hashing::keccak_256(c))) + .collect(); + + // Define inputs with various actions to test locking / unlocking delegate_dependencies. + // See the contract for more details. + let noop_input = (0u32, callee_hashes[0]); + let lock_delegate_dependency_input = (1u32, callee_hashes[0]); + let unlock_delegate_dependency_input = (2u32, callee_hashes[0]); + let terminate_input = (3u32, callee_hashes[0]); + + // Instantiate the caller contract with the given input. + let instantiate = |input: &(u32, H256)| { + builder::bare_instantiate(Code::Upload(wasm_caller.clone())) + .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) + .data(input.encode()) + .build() + }; - // Test with both existing and uploaded code - for code in [Code::Upload(wasm.clone()), Code::Existing(code_hash)] { - ExtBuilder::default().build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); - let lockup_deposit_percent = CodeHashLockupDepositPercent::get(); + // Call contract with the given input. + let call = |addr_caller: &H160, input: &(u32, H256)| { + builder::bare_call(*addr_caller) + .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) + .data(input.encode()) + .build() + }; + const ED: u64 = 2000; + ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { + let _ = Balances::set_balance(&ALICE_FALLBACK, 1_000_000); + + // Instantiate with lock_delegate_dependency should fail since the code is not yet on + // chain. + assert_err!( + instantiate(&lock_delegate_dependency_input).result, + Error::::CodeNotFound + ); - // Upload the dummy contract, - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - dummy_wasm.clone(), + // Upload all the delegated codes (they all have the same size) + let mut deposit = Default::default(); + for code in callee_codes.iter() { + let CodeUploadReturnValue { deposit: deposit_per_code, .. } = + Contracts::bare_upload_code( + RuntimeOrigin::signed(ALICE_FALLBACK), + code.clone(), deposit_limit::(), ) .unwrap(); + deposit = deposit_per_code; + } - // Upload `set_code_hash` contracts if using Code::Existing. - let add_upload_deposit = match code { - Code::Existing(_) => { - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - wasm.clone(), - deposit_limit::(), - ) - .unwrap(); - false - }, - Code::Upload(_) => true, - }; - - // Instantiate the set_code_hash contract. - let res = builder::bare_instantiate(code).build(); + // Instantiate should now work. + let addr_caller = instantiate(&lock_delegate_dependency_input).result.unwrap().addr; + let caller_account_id = ::AddressMapper::to_account_id(&addr_caller); - let addr = res.result.unwrap().addr; - let account_id = ::AddressMapper::to_account_id(&addr); - let base_deposit = test_utils::contract_info_storage_deposit(&addr); - let upload_deposit = test_utils::get_code_deposit(&code_hash); - let extra_deposit = add_upload_deposit.then(|| upload_deposit).unwrap_or_default(); + // There should be a dependency and a deposit. + let contract = test_utils::get_contract(&addr_caller); - // Check initial storage_deposit - // The base deposit should be: contract_info_storage_deposit + 30% * deposit - let deposit = - extra_deposit + base_deposit + lockup_deposit_percent.mul_ceil(upload_deposit); + let dependency_deposit = &CodeHashLockupDepositPercent::get().mul_ceil(deposit); + assert_eq!( + contract.delegate_dependencies().get(&callee_hashes[0]), + Some(dependency_deposit) + ); + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &caller_account_id + ), + dependency_deposit + contract.storage_base_deposit() + ); - assert_eq!( - res.storage_deposit.charge_or_zero(), - deposit + Contracts::min_balance() - ); + // Removing the code should fail, since we have added a dependency. + assert_err!( + Contracts::remove_code(RuntimeOrigin::signed(ALICE_FALLBACK), callee_hashes[0]), + >::CodeInUse + ); - // call set_code_hash - builder::bare_call(addr) - .data(dummy_code_hash.encode()) - .build_and_unwrap_result(); + // Locking an already existing dependency should fail. + assert_err!( + call(&addr_caller, &lock_delegate_dependency_input).result, + Error::::DelegateDependencyAlreadyExists + ); - // Check updated storage_deposit - let code_deposit = test_utils::get_code_deposit(&dummy_code_hash); - let deposit = base_deposit + lockup_deposit_percent.mul_ceil(code_deposit); - assert_eq!(test_utils::get_contract(&addr).storage_base_deposit(), deposit); + // Locking self should fail. + assert_err!( + call(&addr_caller, &(1u32, self_code_hash)).result, + Error::::CannotAddSelfAsDelegateDependency + ); - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &account_id - ), - deposit - ); - }); + // Locking more than the maximum allowed delegate_dependencies should fail. + for hash in &callee_hashes[1..callee_hashes.len() - 1] { + call(&addr_caller, &(1u32, *hash)).result.unwrap(); } - } - - #[test] - fn root_cannot_upload_code() { - let (wasm, _) = compile_module("dummy").unwrap(); - - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - Contracts::upload_code(RuntimeOrigin::root(), wasm, deposit_limit::()), - DispatchError::BadOrigin, - ); - }); - } - - #[test] - fn root_cannot_remove_code() { - let (_, code_hash) = compile_module("dummy").unwrap(); - - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - Contracts::remove_code(RuntimeOrigin::root(), code_hash), - DispatchError::BadOrigin, - ); - }); - } - - #[test] - fn signed_cannot_set_code() { - let (_, code_hash) = compile_module("dummy").unwrap(); + assert_err!( + call(&addr_caller, &(1u32, *callee_hashes.last().unwrap())).result, + Error::::MaxDelegateDependenciesReached + ); - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - Contracts::set_code(RuntimeOrigin::signed(ALICE), BOB_ADDR, code_hash), - DispatchError::BadOrigin, - ); - }); - } + // Unlocking all dependency should work. + for hash in &callee_hashes[..callee_hashes.len() - 1] { + call(&addr_caller, &(2u32, *hash)).result.unwrap(); + } - #[test] - fn none_cannot_call_code() { - ExtBuilder::default().build().execute_with(|| { - assert_err_ignore_postinfo!( - builder::call(BOB_ADDR).origin(RuntimeOrigin::none()).build(), - DispatchError::BadOrigin, - ); - }); - } + // Dependency should be removed, and deposit should be returned. + let contract = test_utils::get_contract(&addr_caller); + assert!(contract.delegate_dependencies().is_empty()); + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &caller_account_id + ), + contract.storage_base_deposit() + ); - #[test] - fn root_can_call() { - let (wasm, _) = compile_module("dummy").unwrap(); + // Removing a nonexistent dependency should fail. + assert_err!( + call(&addr_caller, &unlock_delegate_dependency_input).result, + Error::::DelegateDependencyNotFound + ); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Locking a dependency with a storage limit too low should fail. + assert_err!( + builder::bare_call(addr_caller) + .storage_deposit_limit(dependency_deposit - 1) + .data(lock_delegate_dependency_input.encode()) + .build() + .result, + Error::::StorageDepositLimitExhausted + ); - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); + // Since we unlocked the dependency we should now be able to remove the code. + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE_FALLBACK), callee_hashes[0])); - // Call the contract. - assert_ok!(builder::call(addr).origin(RuntimeOrigin::root()).build()); - }); - } + // Calling should fail since the delegated contract is not on chain anymore. + assert_err!(call(&addr_caller, &noop_input).result, Error::::ContractTrapped); - #[test] - fn root_cannot_instantiate_with_code() { - let (wasm, _) = compile_module("dummy").unwrap(); + // Add the dependency back. + Contracts::upload_code( + RuntimeOrigin::signed(ALICE_FALLBACK), + callee_codes[0].clone(), + deposit_limit::(), + ) + .unwrap(); + call(&addr_caller, &lock_delegate_dependency_input).result.unwrap(); + + // Call terminate should work, and return the deposit. + let balance_before = test_utils::get_balance(&ALICE_FALLBACK); + assert_ok!(call(&addr_caller, &terminate_input).result); + assert_eq!( + test_utils::get_balance(&ALICE_FALLBACK), + ED + balance_before + contract.storage_base_deposit() + dependency_deposit + ); - ExtBuilder::default().build().execute_with(|| { - assert_err_ignore_postinfo!( - builder::instantiate_with_code(wasm).origin(RuntimeOrigin::root()).build(), - DispatchError::BadOrigin - ); - }); - } + // Terminate should also remove the dependency, so we can remove the code. + assert_ok!(Contracts::remove_code(RuntimeOrigin::signed(ALICE_FALLBACK), callee_hashes[0])); + }); +} - #[test] - fn root_cannot_instantiate() { - let (_, code_hash) = compile_module("dummy").unwrap(); +#[test] +fn native_dependency_deposit_works() { + let (wasm, code_hash) = compile_module("set_code_hash").unwrap(); + let (dummy_wasm, dummy_code_hash) = compile_module("dummy").unwrap(); - ExtBuilder::default().build().execute_with(|| { - assert_err_ignore_postinfo!( - builder::instantiate(code_hash).origin(RuntimeOrigin::root()).build(), - DispatchError::BadOrigin - ); - }); - } + // Set hash lock up deposit to 30%, to test deposit calculation. + CODE_HASH_LOCKUP_DEPOSIT_PERCENT.with(|c| *c.borrow_mut() = Perbill::from_percent(30)); - #[test] - fn only_upload_origin_can_upload() { - let (wasm, _) = compile_module("dummy").unwrap(); - UploadAccount::set(Some(ALICE)); + // Test with both existing and uploaded code + for code in [Code::Upload(wasm.clone()), Code::Existing(code_hash)] { ExtBuilder::default().build().execute_with(|| { let _ = Balances::set_balance(&ALICE, 1_000_000); - let _ = Balances::set_balance(&BOB, 1_000_000); - - assert_err!( - Contracts::upload_code( - RuntimeOrigin::root(), - wasm.clone(), - deposit_limit::(), - ), - DispatchError::BadOrigin - ); - - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(BOB), - wasm.clone(), - deposit_limit::(), - ), - DispatchError::BadOrigin - ); + let lockup_deposit_percent = CodeHashLockupDepositPercent::get(); - // Only alice is allowed to upload contract code. - assert_ok!(Contracts::upload_code( + // Upload the dummy contract, + Contracts::upload_code( RuntimeOrigin::signed(ALICE), - wasm.clone(), + dummy_wasm.clone(), deposit_limit::(), - )); - }); - } + ) + .unwrap(); - #[test] - fn only_instantiation_origin_can_instantiate() { - let (code, code_hash) = compile_module("dummy").unwrap(); - InstantiateAccount::set(Some(ALICE)); - ExtBuilder::default().build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); - let _ = Balances::set_balance(&BOB, 1_000_000); + // Upload `set_code_hash` contracts if using Code::Existing. + let add_upload_deposit = match code { + Code::Existing(_) => { + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + deposit_limit::(), + ) + .unwrap(); + false + }, + Code::Upload(_) => true, + }; - assert_err_ignore_postinfo!( - builder::instantiate_with_code(code.clone()) - .origin(RuntimeOrigin::root()) - .build(), - DispatchError::BadOrigin - ); + // Instantiate the set_code_hash contract. + let res = builder::bare_instantiate(code).build(); - assert_err_ignore_postinfo!( - builder::instantiate_with_code(code.clone()) - .origin(RuntimeOrigin::signed(BOB)) - .build(), - DispatchError::BadOrigin - ); + let addr = res.result.unwrap().addr; + let account_id = ::AddressMapper::to_account_id(&addr); + let base_deposit = test_utils::contract_info_storage_deposit(&addr); + let upload_deposit = test_utils::get_code_deposit(&code_hash); + let extra_deposit = add_upload_deposit.then(|| upload_deposit).unwrap_or_default(); - // Only Alice can instantiate - assert_ok!(builder::instantiate_with_code(code).build()); + // Check initial storage_deposit + // The base deposit should be: contract_info_storage_deposit + 30% * deposit + let deposit = + extra_deposit + base_deposit + lockup_deposit_percent.mul_ceil(upload_deposit); - // Bob cannot instantiate with either `instantiate_with_code` or `instantiate`. - assert_err_ignore_postinfo!( - builder::instantiate(code_hash).origin(RuntimeOrigin::signed(BOB)).build(), - DispatchError::BadOrigin - ); - }); - } + assert_eq!(res.storage_deposit.charge_or_zero(), deposit + Contracts::min_balance()); - #[test] - fn balance_of_api() { - let (wasm, _code_hash) = compile_module("balance_of").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); - let _ = Balances::set_balance(&ALICE_FALLBACK, 1_000_000); - - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_contract(); - - // The fixture asserts a non-zero returned free balance of the account; - // The ALICE_FALLBACK account is endowed; - // Hence we should not revert - assert_ok!(builder::call(addr).data(ALICE_ADDR.0.to_vec()).build()); - - // The fixture asserts a non-zero returned free balance of the account; - // The ETH_BOB account is not endowed; - // Hence we should revert - assert_err_ignore_postinfo!( - builder::call(addr).data(BOB_ADDR.0.to_vec()).build(), - >::ContractTrapped + // call set_code_hash + builder::bare_call(addr) + .data(dummy_code_hash.encode()) + .build_and_unwrap_result(); + + // Check updated storage_deposit + let code_deposit = test_utils::get_code_deposit(&dummy_code_hash); + let deposit = base_deposit + lockup_deposit_percent.mul_ceil(code_deposit); + assert_eq!(test_utils::get_contract(&addr).storage_base_deposit(), deposit); + + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &account_id + ), + deposit ); }); } +} - #[test] - fn balance_api_returns_free_balance() { - let (wasm, _code_hash) = compile_module("balance").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn block_hash_works() { + let (code, _) = compile_module("block_hash").unwrap(); - // Instantiate the BOB contract without any extra balance. - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_contract(); + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let value = 0; - // Call BOB which makes it call the balance runtime API. - // The contract code asserts that the returned balance is 0. - assert_ok!(builder::call(addr).value(value).build()); + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); - let value = 1; - // Calling with value will trap the contract. - assert_err_ignore_postinfo!( - builder::call(addr).value(value).build(), - >::ContractTrapped - ); - }); - } + // The genesis config sets to the block number to 1 + let block_hash = [1; 32]; + frame_system::BlockHash::::insert( + &crate::BlockNumberFor::::from(0u32), + ::Hash::from(&block_hash), + ); + assert_ok!(builder::call(addr) + .data((U256::zero(), H256::from(block_hash)).encode()) + .build()); - #[test] - fn gas_consumed_is_linear_for_nested_calls() { - let (code, _code_hash) = compile_module("recurse").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // A block number out of range returns the zero value + assert_ok!(builder::call(addr).data((U256::from(1), H256::zero()).encode()).build()); + }); +} - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); +#[test] +fn root_cannot_upload_code() { + let (wasm, _) = compile_module("dummy").unwrap(); - let [gas_0, gas_1, gas_2, gas_max] = { - [0u32, 1u32, 2u32, limits::CALL_STACK_DEPTH] - .iter() - .map(|i| { - let result = builder::bare_call(addr).data(i.encode()).build(); - assert_ok!(result.result); - result.gas_consumed - }) - .collect::>() - .try_into() - .unwrap() - }; + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::upload_code(RuntimeOrigin::root(), wasm, deposit_limit::()), + DispatchError::BadOrigin, + ); + }); +} - let gas_per_recursion = gas_2.checked_sub(&gas_1).unwrap(); - assert_eq!(gas_max, gas_0 + gas_per_recursion * limits::CALL_STACK_DEPTH as u64); - }); - } +#[test] +fn root_cannot_remove_code() { + let (_, code_hash) = compile_module("dummy").unwrap(); - #[test] - fn read_only_call_cannot_store() { - let (wasm_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::remove_code(RuntimeOrigin::root(), code_hash), + DispatchError::BadOrigin, + ); + }); +} - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); +#[test] +fn signed_cannot_set_code() { + let (_, code_hash) = compile_module("dummy").unwrap(); - // Read-only call fails when modifying storage. - assert_err_ignore_postinfo!( - builder::call(addr_caller).data((&addr_callee, 100u32).encode()).build(), - >::ContractTrapped - ); - }); - } + ExtBuilder::default().build().execute_with(|| { + assert_noop!( + Contracts::set_code(RuntimeOrigin::signed(ALICE), BOB_ADDR, code_hash), + DispatchError::BadOrigin, + ); + }); +} - #[test] - fn read_only_call_cannot_transfer() { - let (wasm_caller, _code_hash_caller) = compile_module("call_with_flags_and_value").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn none_cannot_call_code() { + ExtBuilder::default().build().execute_with(|| { + assert_err_ignore_postinfo!( + builder::call(BOB_ADDR).origin(RuntimeOrigin::none()).build(), + DispatchError::BadOrigin, + ); + }); +} - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); - - // Read-only call fails when a non-zero value is set. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .data( - (addr_callee, pallet_revive_uapi::CallFlags::READ_ONLY.bits(), 100u64) - .encode() - ) - .build(), - >::StateChangeDenied - ); - }); - } +#[test] +fn root_can_call() { + let (wasm, _) = compile_module("dummy").unwrap(); - #[test] - fn read_only_subsequent_call_cannot_store() { - let (wasm_read_only_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); - let (wasm_caller, _code_hash_caller) = compile_module("call_with_flags_and_value").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // Create contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_read_only_caller)) - .build_and_unwrap_contract(); - let Contract { addr: addr_subsequent_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(wasm)).build_and_unwrap_contract(); - // Subsequent call input. - let input = (&addr_callee, pallet_revive_uapi::CallFlags::empty().bits(), 0u64, 100u32); + // Call the contract. + assert_ok!(builder::call(addr).origin(RuntimeOrigin::root()).build()); + }); +} - // Read-only call fails when modifying storage. - assert_err_ignore_postinfo!( - builder::call(addr_caller) - .data((&addr_subsequent_caller, input).encode()) - .build(), - >::ContractTrapped - ); - }); - } +#[test] +fn root_cannot_instantiate_with_code() { + let (wasm, _) = compile_module("dummy").unwrap(); - #[test] - fn read_only_call_works() { - let (wasm_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); - let (wasm_callee, _code_hash_callee) = compile_module("dummy").unwrap(); - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().build().execute_with(|| { + assert_err_ignore_postinfo!( + builder::instantiate_with_code(wasm).origin(RuntimeOrigin::root()).build(), + DispatchError::BadOrigin + ); + }); +} - // Create both contracts: Constructors do nothing. - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); +#[test] +fn root_cannot_instantiate() { + let (_, code_hash) = compile_module("dummy").unwrap(); - assert_ok!(builder::call(addr_caller).data(addr_callee.encode()).build()); - }); - } + ExtBuilder::default().build().execute_with(|| { + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).origin(RuntimeOrigin::root()).build(), + DispatchError::BadOrigin + ); + }); +} - #[test] - fn create1_with_value_works() { - let (code, code_hash) = compile_module("create1_with_value").unwrap(); - let value = 42; - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn only_upload_origin_can_upload() { + let (wasm, _) = compile_module("dummy").unwrap(); + UploadAccount::set(Some(ALICE)); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let _ = Balances::set_balance(&BOB, 1_000_000); + + assert_err!( + Contracts::upload_code(RuntimeOrigin::root(), wasm.clone(), deposit_limit::(),), + DispatchError::BadOrigin + ); - // Create the contract: Constructor does nothing. - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(BOB), + wasm.clone(), + deposit_limit::(), + ), + DispatchError::BadOrigin + ); - // Call the contract: Deploys itself using create1 and the expected value - assert_ok!(builder::call(addr).value(value).data(code_hash.encode()).build()); + // Only alice is allowed to upload contract code. + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + wasm.clone(), + deposit_limit::(), + )); + }); +} - // We should see the expected balance at the expected account - let address = crate::address::create1(&addr, 0); - let account_id = ::AddressMapper::to_account_id(&address); - let usable_balance = ::Currency::usable_balance(&account_id); - assert_eq!(usable_balance, value); - }); - } +#[test] +fn only_instantiation_origin_can_instantiate() { + let (code, code_hash) = compile_module("dummy").unwrap(); + InstantiateAccount::set(Some(ALICE)); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let _ = Balances::set_balance(&BOB, 1_000_000); + + assert_err_ignore_postinfo!( + builder::instantiate_with_code(code.clone()) + .origin(RuntimeOrigin::root()) + .build(), + DispatchError::BadOrigin + ); - #[test] - fn static_data_limit_is_enforced() { - let (oom_rw_trailing, _) = compile_module("oom_rw_trailing").unwrap(); - let (oom_rw_included, _) = compile_module("oom_rw_included").unwrap(); - let (oom_ro, _) = compile_module("oom_ro").unwrap(); + assert_err_ignore_postinfo!( + builder::instantiate_with_code(code.clone()) + .origin(RuntimeOrigin::signed(BOB)) + .build(), + DispatchError::BadOrigin + ); - ExtBuilder::default().build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); + // Only Alice can instantiate + assert_ok!(builder::instantiate_with_code(code).build()); - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - oom_rw_trailing, - deposit_limit::(), - ), - >::StaticMemoryTooLarge - ); + // Bob cannot instantiate with either `instantiate_with_code` or `instantiate`. + assert_err_ignore_postinfo!( + builder::instantiate(code_hash).origin(RuntimeOrigin::signed(BOB)).build(), + DispatchError::BadOrigin + ); + }); +} - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - oom_rw_included, - deposit_limit::(), - ), - >::BlobTooLarge - ); +#[test] +fn balance_of_api() { + let (wasm, _code_hash) = compile_module("balance_of").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + let _ = Balances::set_balance(&ALICE_FALLBACK, 1_000_000); + + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_contract(); + + // The fixture asserts a non-zero returned free balance of the account; + // The ALICE_FALLBACK account is endowed; + // Hence we should not revert + assert_ok!(builder::call(addr).data(ALICE_ADDR.0.to_vec()).build()); + + // The fixture asserts a non-zero returned free balance of the account; + // The ETH_BOB account is not endowed; + // Hence we should revert + assert_err_ignore_postinfo!( + builder::call(addr).data(BOB_ADDR.0.to_vec()).build(), + >::ContractTrapped + ); + }); +} - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - oom_ro, - deposit_limit::(), - ), - >::BlobTooLarge - ); - }); - } +#[test] +fn balance_api_returns_free_balance() { + let (wasm, _code_hash) = compile_module("balance").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the BOB contract without any extra balance. + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_contract(); + + let value = 0; + // Call BOB which makes it call the balance runtime API. + // The contract code asserts that the returned balance is 0. + assert_ok!(builder::call(addr).value(value).build()); + + let value = 1; + // Calling with value will trap the contract. + assert_err_ignore_postinfo!( + builder::call(addr).value(value).build(), + >::ContractTrapped + ); + }); +} - #[test] - fn call_diverging_out_len_works() { - let (code, _) = compile_module("call_diverging_out_len").unwrap(); +#[test] +fn gas_consumed_is_linear_for_nested_calls() { + let (code, _code_hash) = compile_module("recurse").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + + let [gas_0, gas_1, gas_2, gas_max] = { + [0u32, 1u32, 2u32, limits::CALL_STACK_DEPTH] + .iter() + .map(|i| { + let result = builder::bare_call(addr).data(i.encode()).build(); + assert_ok!(result.result); + result.gas_consumed + }) + .collect::>() + .try_into() + .unwrap() + }; - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let gas_per_recursion = gas_2.checked_sub(&gas_1).unwrap(); + assert_eq!(gas_max, gas_0 + gas_per_recursion * limits::CALL_STACK_DEPTH as u64); + }); +} - // Create the contract: Constructor does nothing - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); +#[test] +fn read_only_call_cannot_store() { + let (wasm_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + // Read-only call fails when modifying storage. + assert_err_ignore_postinfo!( + builder::call(addr_caller).data((&addr_callee, 100u32).encode()).build(), + >::ContractTrapped + ); + }); +} - // Call the contract: It will issue calls and deploys, asserting on - // correct output if the supplied output length was smaller than - // than what the callee returned. - assert_ok!(builder::call(addr).build()); - }); - } +#[test] +fn read_only_call_cannot_transfer() { + let (wasm_caller, _code_hash_caller) = compile_module("call_with_flags_and_value").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + // Read-only call fails when a non-zero value is set. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data( + (addr_callee, pallet_revive_uapi::CallFlags::READ_ONLY.bits(), 100u64).encode() + ) + .build(), + >::StateChangeDenied + ); + }); +} - #[test] - fn chain_id_works() { - let (code, _) = compile_module("chain_id").unwrap(); +#[test] +fn read_only_subsequent_call_cannot_store() { + let (wasm_read_only_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); + let (wasm_caller, _code_hash_caller) = compile_module("call_with_flags_and_value").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("store_call").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_read_only_caller)) + .build_and_unwrap_contract(); + let Contract { addr: addr_subsequent_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + // Subsequent call input. + let input = (&addr_callee, pallet_revive_uapi::CallFlags::empty().bits(), 0u64, 100u32); + + // Read-only call fails when modifying storage. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((&addr_subsequent_caller, input).encode()) + .build(), + >::ContractTrapped + ); + }); +} - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn read_only_call_works() { + let (wasm_caller, _code_hash_caller) = compile_module("read_only_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module("dummy").unwrap(); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create both contracts: Constructors do nothing. + let Contract { addr: addr_caller, .. } = + builder::bare_instantiate(Code::Upload(wasm_caller)).build_and_unwrap_contract(); + let Contract { addr: addr_callee, .. } = + builder::bare_instantiate(Code::Upload(wasm_callee)).build_and_unwrap_contract(); + + assert_ok!(builder::call(addr_caller).data(addr_callee.encode()).build()); + }); +} - let chain_id = U256::from(::ChainId::get()); - let received = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_result(); - assert_eq!(received.result.data, chain_id.encode()); - }); - } +#[test] +fn create1_with_value_works() { + let (code, code_hash) = compile_module("create1_with_value").unwrap(); + let value = 42; + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Create the contract: Constructor does nothing. + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + + // Call the contract: Deploys itself using create1 and the expected value + assert_ok!(builder::call(addr).value(value).data(code_hash.encode()).build()); + + // We should see the expected balance at the expected account + let address = crate::address::create1(&addr, 0); + let account_id = ::AddressMapper::to_account_id(&address); + let usable_balance = ::Currency::usable_balance(&account_id); + assert_eq!(usable_balance, value); + }); +} - #[test] - fn return_data_api_works() { - let (code_return_data_api, _) = compile_module("return_data_api").unwrap(); - let (code_return_with_data, hash_return_with_data) = - compile_module("return_with_data").unwrap(); +#[test] +fn static_data_limit_is_enforced() { + let (oom_rw_trailing, _) = compile_module("oom_rw_trailing").unwrap(); + let (oom_rw_included, _) = compile_module("oom_rw_included").unwrap(); + let (oom_ro, _) = compile_module("oom_ro").unwrap(); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); - // Upload the io echoing fixture for later use - assert_ok!(Contracts::upload_code( + assert_err!( + Contracts::upload_code( RuntimeOrigin::signed(ALICE), - code_return_with_data, + oom_rw_trailing, deposit_limit::(), - )); + ), + >::StaticMemoryTooLarge + ); - // Create fixture: Constructor does nothing - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code_return_data_api)) - .build_and_unwrap_contract(); + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + oom_rw_included, + deposit_limit::(), + ), + >::BlobTooLarge + ); - // Call the contract: It will issue calls and deploys, asserting on - assert_ok!(builder::call(addr) - .value(10 * 1024) - .data(hash_return_with_data.encode()) - .build()); - }); - } + assert_err!( + Contracts::upload_code(RuntimeOrigin::signed(ALICE), oom_ro, deposit_limit::(),), + >::BlobTooLarge + ); + }); +} - #[test] - fn immutable_data_works() { - let (code, _) = compile_module("immutable_data").unwrap(); +#[test] +fn call_diverging_out_len_works() { + let (code, _) = compile_module("call_diverging_out_len").unwrap(); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - let data = [0xfe; 8]; + // Create the contract: Constructor does nothing + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); - // Create fixture: Constructor sets the immtuable data - let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) - .data(data.to_vec()) - .build_and_unwrap_contract(); + // Call the contract: It will issue calls and deploys, asserting on + // correct output if the supplied output length was smaller than + // than what the callee returned. + assert_ok!(builder::call(addr).build()); + }); +} - // Storing immmutable data charges storage deposit; verify it explicitly. - assert_eq!( - test_utils::get_balance_on_hold( - &HoldReason::StorageDepositReserve.into(), - &::AddressMapper::to_account_id(&addr) - ), - test_utils::contract_info_storage_deposit(&addr) - ); - assert_eq!(test_utils::get_contract(&addr).immutable_data_len(), data.len() as u32); +#[test] +fn chain_id_works() { + let (code, _) = compile_module("chain_id").unwrap(); - // Call the contract: Asserts the input to equal the immutable data - assert_ok!(builder::call(addr).data(data.to_vec()).build()); - }); - } + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - #[test] - fn sbrk_cannot_be_deployed() { - let (code, _) = compile_module("sbrk").unwrap(); + let chain_id = U256::from(::ChainId::get()); + let received = builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_result(); + assert_eq!(received.result.data, chain_id.encode()); + }); +} - ExtBuilder::default().build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); +#[test] +fn return_data_api_works() { + let (code_return_data_api, _) = compile_module("return_data_api").unwrap(); + let (code_return_with_data, hash_return_with_data) = + compile_module("return_with_data").unwrap(); - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - code.clone(), - deposit_limit::(), - ), - >::InvalidInstruction - ); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - assert_err!( - builder::bare_instantiate(Code::Upload(code)).build().result, - >::InvalidInstruction - ); - }); - } + // Upload the io echoing fixture for later use + assert_ok!(Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + code_return_with_data, + deposit_limit::(), + )); + + // Create fixture: Constructor does nothing + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code_return_data_api)) + .build_and_unwrap_contract(); + + // Call the contract: It will issue calls and deploys, asserting on + assert_ok!(builder::call(addr) + .value(10 * 1024) + .data(hash_return_with_data.encode()) + .build()); + }); +} - #[test] - fn overweight_basic_block_cannot_be_deployed() { - let (code, _) = compile_module("basic_block").unwrap(); +#[test] +fn immutable_data_works() { + let (code, _) = compile_module("immutable_data").unwrap(); - ExtBuilder::default().build().execute_with(|| { - let _ = Balances::set_balance(&ALICE, 1_000_000); + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - assert_err!( - Contracts::upload_code( - RuntimeOrigin::signed(ALICE), - code.clone(), - deposit_limit::(), - ), - >::BasicBlockTooLarge - ); + let data = [0xfe; 8]; - assert_err!( - builder::bare_instantiate(Code::Upload(code)).build().result, - >::BasicBlockTooLarge - ); - }); - } + // Create fixture: Constructor sets the immtuable data + let Contract { addr, .. } = builder::bare_instantiate(Code::Upload(code)) + .data(data.to_vec()) + .build_and_unwrap_contract(); - #[test] - fn origin_api_works() { - let (code, _) = compile_module("origin").unwrap(); + // Storing immmutable data charges storage deposit; verify it explicitly. + assert_eq!( + test_utils::get_balance_on_hold( + &HoldReason::StorageDepositReserve.into(), + &::AddressMapper::to_account_id(&addr) + ), + test_utils::contract_info_storage_deposit(&addr) + ); + assert_eq!(test_utils::get_contract(&addr).immutable_data_len(), data.len() as u32); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Call the contract: Asserts the input to equal the immutable data + assert_ok!(builder::call(addr).data(data.to_vec()).build()); + }); +} - // Create fixture: Constructor does nothing - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); +#[test] +fn sbrk_cannot_be_deployed() { + let (code, _) = compile_module("sbrk").unwrap(); - // Call the contract: Asserts the origin API to work as expected - assert_ok!(builder::call(addr).build()); - }); - } + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); + + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + code.clone(), + deposit_limit::(), + ), + >::InvalidInstruction + ); - #[test] - fn code_hash_works() { - let (code_hash_code, self_code_hash) = compile_module("code_hash").unwrap(); - let (dummy_code, code_hash) = compile_module("dummy").unwrap(); + assert_err!( + builder::bare_instantiate(Code::Upload(code)).build().result, + >::InvalidInstruction + ); + }); +} - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); +#[test] +fn overweight_basic_block_cannot_be_deployed() { + let (code, _) = compile_module("basic_block").unwrap(); - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code_hash_code)).build_and_unwrap_contract(); - let Contract { addr: dummy_addr, .. } = - builder::bare_instantiate(Code::Upload(dummy_code)).build_and_unwrap_contract(); - - // code hash of dummy contract - assert_ok!(builder::call(addr).data((dummy_addr, code_hash).encode()).build()); - // code has of itself - assert_ok!(builder::call(addr).data((addr, self_code_hash).encode()).build()); - - // EOA doesn't exists - assert_err!( - builder::bare_call(addr) - .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) - .build() - .result, - Error::::ContractTrapped - ); - // non-existing will return zero - assert_ok!(builder::call(addr).data((BOB_ADDR, H256::zero()).encode()).build()); + ExtBuilder::default().build().execute_with(|| { + let _ = Balances::set_balance(&ALICE, 1_000_000); - // create EOA - let _ = ::Currency::set_balance( - &::AddressMapper::to_account_id(&BOB_ADDR), - 1_000_000, - ); + assert_err!( + Contracts::upload_code( + RuntimeOrigin::signed(ALICE), + code.clone(), + deposit_limit::(), + ), + >::BasicBlockTooLarge + ); - // EOA returns empty code hash - assert_ok!(builder::call(addr) - .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) - .build()); - }); - } + assert_err!( + builder::bare_instantiate(Code::Upload(code)).build().result, + >::BasicBlockTooLarge + ); + }); +} - #[test] - fn code_size_works() { - let (tester_code, _) = compile_module("extcodesize").unwrap(); - let tester_code_len = tester_code.len() as u64; +#[test] +fn origin_api_works() { + let (code, _) = compile_module("origin").unwrap(); - let (dummy_code, _) = compile_module("dummy").unwrap(); - let dummy_code_len = dummy_code.len() as u64; + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // Create fixture: Constructor does nothing + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); - let Contract { addr: tester_addr, .. } = - builder::bare_instantiate(Code::Upload(tester_code)).build_and_unwrap_contract(); - let Contract { addr: dummy_addr, .. } = - builder::bare_instantiate(Code::Upload(dummy_code)).build_and_unwrap_contract(); + // Call the contract: Asserts the origin API to work as expected + assert_ok!(builder::call(addr).build()); + }); +} - // code size of another contract address - assert_ok!(builder::call(tester_addr) - .data((dummy_addr, dummy_code_len).encode()) - .build()); +#[test] +fn code_hash_works() { + let (code_hash_code, self_code_hash) = compile_module("code_hash").unwrap(); + let (dummy_code, code_hash) = compile_module("dummy").unwrap(); - // code size of own contract address - assert_ok!(builder::call(tester_addr) - .data((tester_addr, tester_code_len).encode()) - .build()); + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - // code size of non contract accounts - assert_ok!(builder::call(tester_addr).data(([8u8; 20], 0u64).encode()).build()); - }); - } + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code_hash_code)).build_and_unwrap_contract(); + let Contract { addr: dummy_addr, .. } = + builder::bare_instantiate(Code::Upload(dummy_code)).build_and_unwrap_contract(); - #[test] - fn origin_must_be_mapped() { - let (code, hash) = compile_module("dummy").unwrap(); + // code hash of dummy contract + assert_ok!(builder::call(addr).data((dummy_addr, code_hash).encode()).build()); + // code has of itself + assert_ok!(builder::call(addr).data((addr, self_code_hash).encode()).build()); - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - ::Currency::set_balance(&ALICE, 1_000_000); - ::Currency::set_balance(&EVE, 1_000_000); + // EOA doesn't exists + assert_err!( + builder::bare_call(addr) + .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) + .build() + .result, + Error::::ContractTrapped + ); + // non-existing will return zero + assert_ok!(builder::call(addr).data((BOB_ADDR, H256::zero()).encode()).build()); - let eve = RuntimeOrigin::signed(EVE); + // create EOA + let _ = ::Currency::set_balance( + &::AddressMapper::to_account_id(&BOB_ADDR), + 1_000_000, + ); - // alice can instantiate as she doesn't need a mapping - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + // EOA returns empty code hash + assert_ok!(builder::call(addr) + .data((BOB_ADDR, crate::exec::EMPTY_CODE_HASH).encode()) + .build()); + }); +} - // without a mapping eve can neither call nor instantiate - assert_err!( - builder::bare_call(addr).origin(eve.clone()).build().result, - >::AccountUnmapped - ); - assert_err!( - builder::bare_instantiate(Code::Existing(hash)) - .origin(eve.clone()) - .build() - .result, - >::AccountUnmapped - ); +#[test] +fn code_size_works() { + let (tester_code, _) = compile_module("extcodesize").unwrap(); + let tester_code_len = tester_code.len() as u64; - // after mapping eve is usable as an origin - >::map_account(eve.clone()).unwrap(); - assert_ok!(builder::bare_call(addr).origin(eve.clone()).build().result); - assert_ok!(builder::bare_instantiate(Code::Existing(hash)).origin(eve).build().result); - }); - } + let (dummy_code, _) = compile_module("dummy").unwrap(); + let dummy_code_len = dummy_code.len() as u64; - #[test] - fn mapped_address_works() { - let (code, _) = compile_module("terminate_and_send_to_eve").unwrap(); - - ExtBuilder::default().existential_deposit(100).build().execute_with(|| { - ::Currency::set_balance(&ALICE, 1_000_000); - - // without a mapping everything will be send to the fallback account - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code.clone())).build_and_unwrap_contract(); - assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 0); - builder::bare_call(addr).build_and_unwrap_result(); - assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 100); - - // after mapping it will be sent to the real eve account - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); - // need some balance to pay for the map deposit - ::Currency::set_balance(&EVE, 1_000); - >::map_account(RuntimeOrigin::signed(EVE)).unwrap(); - builder::bare_call(addr).build_and_unwrap_result(); - assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 100); - assert_eq!(::Currency::total_balance(&EVE), 1_100); - }); - } + ExtBuilder::default().existential_deposit(1).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); - #[test] - fn block_hash_works() { - let (code, _) = compile_module("block_hash").unwrap(); + let Contract { addr: tester_addr, .. } = + builder::bare_instantiate(Code::Upload(tester_code)).build_and_unwrap_contract(); + let Contract { addr: dummy_addr, .. } = + builder::bare_instantiate(Code::Upload(dummy_code)).build_and_unwrap_contract(); - ExtBuilder::default().existential_deposit(1).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); + // code size of another contract address + assert_ok!(builder::call(tester_addr).data((dummy_addr, dummy_code_len).encode()).build()); - let Contract { addr, .. } = - builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + // code size of own contract address + assert_ok!(builder::call(tester_addr) + .data((tester_addr, tester_code_len).encode()) + .build()); - // The genesis config sets to the block number to 1 - let block_hash = [1; 32]; - frame_system::BlockHash::::insert( - &crate::BlockNumberFor::::from(0u32), - ::Hash::from(&block_hash), - ); - assert_ok!(builder::call(addr) - .data((U256::zero(), H256::from(block_hash)).encode()) - .build()); + // code size of non contract accounts + assert_ok!(builder::call(tester_addr).data(([8u8; 20], 0u64).encode()).build()); + }); +} - // A block number out of range returns the zero value - assert_ok!(builder::call(addr).data((U256::from(1), H256::zero()).encode()).build()); - }); - } +#[test] +fn origin_must_be_mapped() { + let (code, hash) = compile_module("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + ::Currency::set_balance(&ALICE, 1_000_000); + ::Currency::set_balance(&EVE, 1_000_000); + + let eve = RuntimeOrigin::signed(EVE); + + // alice can instantiate as she doesn't need a mapping + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + + // without a mapping eve can neither call nor instantiate + assert_err!( + builder::bare_call(addr).origin(eve.clone()).build().result, + >::AccountUnmapped + ); + assert_err!( + builder::bare_instantiate(Code::Existing(hash)) + .origin(eve.clone()) + .build() + .result, + >::AccountUnmapped + ); + + // after mapping eve is usable as an origin + >::map_account(eve.clone()).unwrap(); + assert_ok!(builder::bare_call(addr).origin(eve.clone()).build().result); + assert_ok!(builder::bare_instantiate(Code::Existing(hash)).origin(eve).build().result); + }); +} + +#[test] +fn mapped_address_works() { + let (code, _) = compile_module("terminate_and_send_to_eve").unwrap(); + + ExtBuilder::default().existential_deposit(100).build().execute_with(|| { + ::Currency::set_balance(&ALICE, 1_000_000); + + // without a mapping everything will be send to the fallback account + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code.clone())).build_and_unwrap_contract(); + assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 0); + builder::bare_call(addr).build_and_unwrap_result(); + assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 100); + + // after mapping it will be sent to the real eve account + let Contract { addr, .. } = + builder::bare_instantiate(Code::Upload(code)).build_and_unwrap_contract(); + // need some balance to pay for the map deposit + ::Currency::set_balance(&EVE, 1_000); + >::map_account(RuntimeOrigin::signed(EVE)).unwrap(); + builder::bare_call(addr).build_and_unwrap_result(); + assert_eq!(::Currency::total_balance(&EVE_FALLBACK), 100); + assert_eq!(::Currency::total_balance(&EVE), 1_100); + }); } diff --git a/substrate/frame/revive/src/tests/test_debug.rs b/substrate/frame/revive/src/tests/test_debug.rs index 1e94d5cafb81..7c4fbba71f65 100644 --- a/substrate/frame/revive/src/tests/test_debug.rs +++ b/substrate/frame/revive/src/tests/test_debug.rs @@ -23,6 +23,7 @@ use crate::{ test_utils::*, }; use frame_support::traits::Currency; +use pretty_assertions::assert_eq; use sp_core::H160; use std::cell::RefCell; @@ -99,146 +100,139 @@ impl CallSpan for TestCallSpan { } } -/// We can only run the tests if we have a riscv toolchain installed -#[cfg(feature = "riscv")] -mod run_tests { - use super::*; - use pretty_assertions::assert_eq; +#[test] +fn debugging_works() { + let (wasm_caller, _) = compile_module("call").unwrap(); + let (wasm_callee, _) = compile_module("store_call").unwrap(); - #[test] - fn debugging_works() { - let (wasm_caller, _) = compile_module("call").unwrap(); - let (wasm_callee, _) = compile_module("store_call").unwrap(); - - fn current_stack() -> Vec { - DEBUG_EXECUTION_TRACE.with(|stack| stack.borrow().clone()) - } + fn current_stack() -> Vec { + DEBUG_EXECUTION_TRACE.with(|stack| stack.borrow().clone()) + } - fn deploy(wasm: Vec) -> H160 { - Contracts::bare_instantiate( - RuntimeOrigin::signed(ALICE), - 0, - GAS_LIMIT, - deposit_limit::(), - Code::Upload(wasm), - vec![], - Some([0u8; 32]), - DebugInfo::Skip, - CollectEvents::Skip, - ) - .result - .unwrap() - .addr - } + fn deploy(wasm: Vec) -> H160 { + Contracts::bare_instantiate( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + deposit_limit::(), + Code::Upload(wasm), + vec![], + Some([0u8; 32]), + DebugInfo::Skip, + CollectEvents::Skip, + ) + .result + .unwrap() + .addr + } - fn constructor_frame(contract_address: &H160, after: bool) -> DebugFrame { - DebugFrame { - contract_address: *contract_address, - call: ExportedFunction::Constructor, - input: vec![], - result: if after { Some(vec![]) } else { None }, - } + fn constructor_frame(contract_address: &H160, after: bool) -> DebugFrame { + DebugFrame { + contract_address: *contract_address, + call: ExportedFunction::Constructor, + input: vec![], + result: if after { Some(vec![]) } else { None }, } + } - fn call_frame(contract_address: &H160, args: Vec, after: bool) -> DebugFrame { - DebugFrame { - contract_address: *contract_address, - call: ExportedFunction::Call, - input: args, - result: if after { Some(vec![]) } else { None }, - } + fn call_frame(contract_address: &H160, args: Vec, after: bool) -> DebugFrame { + DebugFrame { + contract_address: *contract_address, + call: ExportedFunction::Call, + input: args, + result: if after { Some(vec![]) } else { None }, } - - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = Balances::deposit_creating(&ALICE, 1_000_000); - - assert_eq!(current_stack(), vec![]); - - let addr_caller = deploy(wasm_caller); - let addr_callee = deploy(wasm_callee); - - assert_eq!( - current_stack(), - vec![ - constructor_frame(&addr_caller, false), - constructor_frame(&addr_caller, true), - constructor_frame(&addr_callee, false), - constructor_frame(&addr_callee, true), - ] - ); - - let main_args = (100u32, &addr_callee.clone()).encode(); - let inner_args = (100u32).encode(); - - assert_ok!(Contracts::call( - RuntimeOrigin::signed(ALICE), - addr_caller, - 0, - GAS_LIMIT, - deposit_limit::(), - main_args.clone() - )); - - let stack_top = current_stack()[4..].to_vec(); - assert_eq!( - stack_top, - vec![ - call_frame(&addr_caller, main_args.clone(), false), - call_frame(&addr_callee, inner_args.clone(), false), - call_frame(&addr_callee, inner_args, true), - call_frame(&addr_caller, main_args, true), - ] - ); - }); } - #[test] - fn call_interception_works() { - let (wasm, _) = compile_module("dummy").unwrap(); - - ExtBuilder::default().existential_deposit(200).build().execute_with(|| { - let _ = Balances::deposit_creating(&ALICE, 1_000_000); + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + assert_eq!(current_stack(), vec![]); + + let addr_caller = deploy(wasm_caller); + let addr_callee = deploy(wasm_callee); + + assert_eq!( + current_stack(), + vec![ + constructor_frame(&addr_caller, false), + constructor_frame(&addr_caller, true), + constructor_frame(&addr_callee, false), + constructor_frame(&addr_callee, true), + ] + ); + + let main_args = (100u32, &addr_callee.clone()).encode(); + let inner_args = (100u32).encode(); + + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + addr_caller, + 0, + GAS_LIMIT, + deposit_limit::(), + main_args.clone() + )); + + let stack_top = current_stack()[4..].to_vec(); + assert_eq!( + stack_top, + vec![ + call_frame(&addr_caller, main_args.clone(), false), + call_frame(&addr_callee, inner_args.clone(), false), + call_frame(&addr_callee, inner_args, true), + call_frame(&addr_caller, main_args, true), + ] + ); + }); +} - let account_id = Contracts::bare_instantiate( - RuntimeOrigin::signed(ALICE), - 0, - GAS_LIMIT, - deposit_limit::(), - Code::Upload(wasm), - vec![], - // some salt to ensure that the address of this contract is unique among all tests - Some([0x41; 32]), - DebugInfo::Skip, - CollectEvents::Skip, - ) - .result - .unwrap() - .addr; - - // no interception yet - assert_ok!(Contracts::call( +#[test] +fn call_interception_works() { + let (wasm, _) = compile_module("dummy").unwrap(); + + ExtBuilder::default().existential_deposit(200).build().execute_with(|| { + let _ = Balances::deposit_creating(&ALICE, 1_000_000); + + let account_id = Contracts::bare_instantiate( + RuntimeOrigin::signed(ALICE), + 0, + GAS_LIMIT, + deposit_limit::(), + Code::Upload(wasm), + vec![], + // some salt to ensure that the address of this contract is unique among all tests + Some([0x41; 32]), + DebugInfo::Skip, + CollectEvents::Skip, + ) + .result + .unwrap() + .addr; + + // no interception yet + assert_ok!(Contracts::call( + RuntimeOrigin::signed(ALICE), + account_id, + 0, + GAS_LIMIT, + deposit_limit::(), + vec![], + )); + + // intercept calls to this contract + INTERCEPTED_ADDRESS.with(|i| *i.borrow_mut() = Some(account_id)); + + assert_err_ignore_postinfo!( + Contracts::call( RuntimeOrigin::signed(ALICE), account_id, 0, GAS_LIMIT, deposit_limit::(), vec![], - )); - - // intercept calls to this contract - INTERCEPTED_ADDRESS.with(|i| *i.borrow_mut() = Some(account_id)); - - assert_err_ignore_postinfo!( - Contracts::call( - RuntimeOrigin::signed(ALICE), - account_id, - 0, - GAS_LIMIT, - deposit_limit::(), - vec![], - ), - >::ContractReverted, - ); - }); - } + ), + >::ContractReverted, + ); + }); } diff --git a/substrate/frame/revive/src/wasm/mod.rs b/substrate/frame/revive/src/wasm/mod.rs index 6779f551113c..f10c4f5fddf8 100644 --- a/substrate/frame/revive/src/wasm/mod.rs +++ b/substrate/frame/revive/src/wasm/mod.rs @@ -26,7 +26,7 @@ pub use crate::wasm::runtime::SyscallDoc; #[cfg(test)] pub use runtime::HIGHEST_API_VERSION; -#[cfg(all(feature = "runtime-benchmarks", feature = "riscv"))] +#[cfg(feature = "runtime-benchmarks")] pub use crate::wasm::runtime::{ReturnData, TrapReason}; pub use crate::wasm::runtime::{ApiVersion, Memory, Runtime, RuntimeCosts}; diff --git a/umbrella/Cargo.toml b/umbrella/Cargo.toml index 28d6a2c3fb01..7f50658c4e16 100644 --- a/umbrella/Cargo.toml +++ b/umbrella/Cargo.toml @@ -610,12 +610,6 @@ tuples-96 = [ "frame-support-procedural?/tuples-96", "frame-support?/tuples-96", ] -riscv = [ - "pallet-revive-eth-rpc?/riscv", - "pallet-revive-fixtures?/riscv", - "pallet-revive-mock-network?/riscv", - "pallet-revive?/riscv", -] [package.edition] workspace = true From 2700dbf2dda8b7f593447c939e1a26dacdb8ce45 Mon Sep 17 00:00:00 2001 From: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Date: Thu, 31 Oct 2024 18:22:12 +0200 Subject: [PATCH 005/166] `candidate-validation`: RFC103 implementation (#5847) Part of https://github.com/paritytech/polkadot-sdk/issues/5047 On top of https://github.com/paritytech/polkadot-sdk/pull/5679 --------- Signed-off-by: Andrei Sandu Co-authored-by: GitHub Action --- Cargo.lock | 1 + .../node/core/candidate-validation/Cargo.toml | 2 + .../node/core/candidate-validation/src/lib.rs | 166 +++++-- .../core/candidate-validation/src/tests.rs | 407 +++++++++++++++++- polkadot/node/primitives/src/lib.rs | 4 + polkadot/primitives/src/vstaging/mod.rs | 12 + prdoc/pr_5847.prdoc | 19 + 7 files changed, 571 insertions(+), 40 deletions(-) create mode 100644 prdoc/pr_5847.prdoc diff --git a/Cargo.lock b/Cargo.lock index a6c2bc1fd318..1f171ad756c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14485,6 +14485,7 @@ dependencies = [ "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-primitives-test-helpers", + "rstest", "sp-application-crypto 30.0.0", "sp-core 28.0.0", "sp-keyring", diff --git a/polkadot/node/core/candidate-validation/Cargo.toml b/polkadot/node/core/candidate-validation/Cargo.toml index fcacc38cae65..87855dbce415 100644 --- a/polkadot/node/core/candidate-validation/Cargo.toml +++ b/polkadot/node/core/candidate-validation/Cargo.toml @@ -38,3 +38,5 @@ polkadot-node-subsystem-test-helpers = { workspace = true } sp-maybe-compressed-blob = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } polkadot-primitives-test-helpers = { workspace = true } +rstest = { workspace = true } +polkadot-primitives = { workspace = true, features = ["test"] } diff --git a/polkadot/node/core/candidate-validation/src/lib.rs b/polkadot/node/core/candidate-validation/src/lib.rs index a48669c24825..1e732e2f1f03 100644 --- a/polkadot/node/core/candidate-validation/src/lib.rs +++ b/polkadot/node/core/candidate-validation/src/lib.rs @@ -37,7 +37,7 @@ use polkadot_node_subsystem::{ overseer, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError, SubsystemResult, SubsystemSender, }; -use polkadot_node_subsystem_util as util; +use polkadot_node_subsystem_util::{self as util, runtime::ClaimQueueSnapshot}; use polkadot_overseer::ActiveLeavesUpdate; use polkadot_parachain_primitives::primitives::ValidationResult as WasmValidationResult; use polkadot_primitives::{ @@ -46,8 +46,9 @@ use polkadot_primitives::{ DEFAULT_LENIENT_PREPARATION_TIMEOUT, DEFAULT_PRECHECK_PREPARATION_TIMEOUT, }, vstaging::{ - CandidateDescriptorV2 as CandidateDescriptor, CandidateEvent, + transpose_claim_queue, CandidateDescriptorV2 as CandidateDescriptor, CandidateEvent, CandidateReceiptV2 as CandidateReceipt, + CommittedCandidateReceiptV2 as CommittedCandidateReceipt, }, AuthorityDiscoveryId, CandidateCommitments, ExecutorParams, Hash, PersistedValidationData, PvfExecKind as RuntimePvfExecKind, PvfPrepKind, SessionIndex, ValidationCode, @@ -148,6 +149,25 @@ impl CandidateValidationSubsystem { } } +// Returns the claim queue at relay parent and logs a warning if it is not available. +async fn claim_queue(relay_parent: Hash, sender: &mut Sender) -> Option +where + Sender: SubsystemSender, +{ + match util::runtime::fetch_claim_queue(sender, relay_parent).await { + Ok(maybe_cq) => maybe_cq, + Err(err) => { + gum::warn!( + target: LOG_TARGET, + ?relay_parent, + ?err, + "Claim queue not available" + ); + None + }, + } +} + fn handle_validation_message( mut sender: S, validation_host: ValidationHost, @@ -167,24 +187,40 @@ where exec_kind, response_sender, .. - } => async move { - let _timer = metrics.time_validate_from_exhaustive(); - let res = validate_candidate_exhaustive( - validation_host, - validation_data, - validation_code, - candidate_receipt, - pov, - executor_params, - exec_kind, - &metrics, - ) - .await; + } => + async move { + let _timer = metrics.time_validate_from_exhaustive(); + let relay_parent = candidate_receipt.descriptor.relay_parent(); + + let maybe_claim_queue = claim_queue(relay_parent, &mut sender).await; + + let maybe_expected_session_index = + match util::request_session_index_for_child(relay_parent, &mut sender) + .await + .await + { + Ok(Ok(expected_session_index)) => Some(expected_session_index), + _ => None, + }; + + let res = validate_candidate_exhaustive( + maybe_expected_session_index, + validation_host, + validation_data, + validation_code, + candidate_receipt, + pov, + executor_params, + exec_kind, + &metrics, + maybe_claim_queue, + ) + .await; - metrics.on_validation_event(&res); - let _ = response_sender.send(res); - } - .boxed(), + metrics.on_validation_event(&res); + let _ = response_sender.send(res); + } + .boxed(), CandidateValidationMessage::PreCheck { relay_parent, validation_code_hash, @@ -637,6 +673,7 @@ where } async fn validate_candidate_exhaustive( + maybe_expected_session_index: Option, mut validation_backend: impl ValidationBackend + Send, persisted_validation_data: PersistedValidationData, validation_code: ValidationCode, @@ -645,11 +682,13 @@ async fn validate_candidate_exhaustive( executor_params: ExecutorParams, exec_kind: PvfExecKind, metrics: &Metrics, + maybe_claim_queue: Option, ) -> Result { let _timer = metrics.time_validate_candidate_exhaustive(); - let validation_code_hash = validation_code.hash(); + let relay_parent = candidate_receipt.descriptor.relay_parent(); let para_id = candidate_receipt.descriptor.para_id(); + gum::debug!( target: LOG_TARGET, ?validation_code_hash, @@ -657,6 +696,27 @@ async fn validate_candidate_exhaustive( "About to validate a candidate.", ); + // We only check the session index for backing. + match (exec_kind, candidate_receipt.descriptor.session_index()) { + (PvfExecKind::Backing | PvfExecKind::BackingSystemParas, Some(session_index)) => { + let Some(expected_session_index) = maybe_expected_session_index else { + let error = "cannot fetch session index from the runtime"; + gum::warn!( + target: LOG_TARGET, + ?relay_parent, + error, + ); + + return Err(ValidationFailed(error.into())) + }; + + if session_index != expected_session_index { + return Ok(ValidationResult::Invalid(InvalidCandidate::InvalidSessionIndex)) + } + }, + (_, _) => {}, + }; + if let Err(e) = perform_basic_checks( &candidate_receipt.descriptor, persisted_validation_data.max_pov_size, @@ -754,15 +814,21 @@ async fn validate_candidate_exhaustive( gum::info!(target: LOG_TARGET, ?para_id, "Invalid candidate (para_head)"); Ok(ValidationResult::Invalid(InvalidCandidate::ParaHeadHashMismatch)) } else { - let outputs = CandidateCommitments { - head_data: res.head_data, - upward_messages: res.upward_messages, - horizontal_messages: res.horizontal_messages, - new_validation_code: res.new_validation_code, - processed_downward_messages: res.processed_downward_messages, - hrmp_watermark: res.hrmp_watermark, + let committed_candidate_receipt = CommittedCandidateReceipt { + descriptor: candidate_receipt.descriptor.clone(), + commitments: CandidateCommitments { + head_data: res.head_data, + upward_messages: res.upward_messages, + horizontal_messages: res.horizontal_messages, + new_validation_code: res.new_validation_code, + processed_downward_messages: res.processed_downward_messages, + hrmp_watermark: res.hrmp_watermark, + }, }; - if candidate_receipt.commitments_hash != outputs.hash() { + + if candidate_receipt.commitments_hash != + committed_candidate_receipt.commitments.hash() + { gum::info!( target: LOG_TARGET, ?para_id, @@ -773,7 +839,48 @@ async fn validate_candidate_exhaustive( // invalid. Ok(ValidationResult::Invalid(InvalidCandidate::CommitmentsHashMismatch)) } else { - Ok(ValidationResult::Valid(outputs, (*persisted_validation_data).clone())) + let core_index = candidate_receipt.descriptor.core_index(); + + match (core_index, exec_kind) { + // Core selectors are optional for V2 descriptors, but we still check the + // descriptor core index. + ( + Some(_core_index), + PvfExecKind::Backing | PvfExecKind::BackingSystemParas, + ) => { + let Some(claim_queue) = maybe_claim_queue else { + let error = "cannot fetch the claim queue from the runtime"; + gum::warn!( + target: LOG_TARGET, + ?relay_parent, + error + ); + + return Err(ValidationFailed(error.into())) + }; + + if let Err(err) = committed_candidate_receipt + .check_core_index(&transpose_claim_queue(claim_queue.0)) + { + gum::warn!( + target: LOG_TARGET, + ?err, + candidate_hash = ?candidate_receipt.hash(), + "Candidate core index is invalid", + ); + return Ok(ValidationResult::Invalid( + InvalidCandidate::InvalidCoreIndex, + )) + } + }, + // No checks for approvals and disputes + (_, _) => {}, + } + + Ok(ValidationResult::Valid( + committed_candidate_receipt.commitments, + (*persisted_validation_data).clone(), + )) } }, } @@ -1003,6 +1110,7 @@ fn perform_basic_checks( return Err(InvalidCandidate::CodeHashMismatch) } + // No-op for `v2` receipts. if let Err(()) = candidate.check_collator_signature() { return Err(InvalidCandidate::BadSignature) } diff --git a/polkadot/node/core/candidate-validation/src/tests.rs b/polkadot/node/core/candidate-validation/src/tests.rs index 997a347631a0..391247858ed6 100644 --- a/polkadot/node/core/candidate-validation/src/tests.rs +++ b/polkadot/node/core/candidate-validation/src/tests.rs @@ -14,7 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::{ + collections::BTreeMap, + sync::atomic::{AtomicUsize, Ordering}, +}; use super::*; use crate::PvfExecKind; @@ -26,12 +29,18 @@ use polkadot_node_subsystem::messages::AllMessages; use polkadot_node_subsystem_util::reexports::SubsystemContext; use polkadot_overseer::ActivatedLeaf; use polkadot_primitives::{ - vstaging::CandidateDescriptorV2, CandidateDescriptor, CoreIndex, GroupIndex, HeadData, - Id as ParaId, OccupiedCoreAssumption, SessionInfo, UpwardMessage, ValidatorId, + vstaging::{ + CandidateDescriptorV2, ClaimQueueOffset, CoreSelector, MutateDescriptorV2, UMPSignal, + UMP_SEPARATOR, + }, + CandidateDescriptor, CoreIndex, GroupIndex, HeadData, Id as ParaId, OccupiedCoreAssumption, + SessionInfo, UpwardMessage, ValidatorId, }; use polkadot_primitives_test_helpers::{ dummy_collator, dummy_collator_signature, dummy_hash, make_valid_candidate_descriptor, + make_valid_candidate_descriptor_v2, }; +use rstest::rstest; use sp_core::{sr25519::Public, testing::TaskExecutor}; use sp_keyring::Sr25519Keyring; use sp_keystore::{testing::MemoryKeystore, Keystore}; @@ -467,25 +476,24 @@ impl ValidationBackend for MockValidateCandidateBackend { } #[test] -fn candidate_validation_ok_is_ok() { +fn session_index_checked_only_in_backing() { let validation_data = PersistedValidationData { max_pov_size: 1024, ..Default::default() }; let pov = PoV { block_data: BlockData(vec![1; 32]) }; let head_data = HeadData(vec![1, 1, 1]); let validation_code = ValidationCode(vec![2; 16]); - let descriptor = make_valid_candidate_descriptor( + let descriptor = make_valid_candidate_descriptor_v2( ParaId::from(1_u32), dummy_hash(), - validation_data.hash(), + CoreIndex(0), + 100, + dummy_hash(), pov.hash(), validation_code.hash(), head_data.hash(), dummy_hash(), - Sr25519Keyring::Alice, - ) - .into(); - + ); let check = perform_basic_checks( &descriptor, validation_data.max_pov_size, @@ -514,15 +522,59 @@ fn candidate_validation_ok_is_ok() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: commitments.hash() }; + // The session index is invalid + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Backing, + &Default::default(), + Default::default(), + )) + .unwrap(); + + assert_matches!(v, ValidationResult::Invalid(InvalidCandidate::InvalidSessionIndex)); + + // Approval doesn't fail since the check is ommited. let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Approval, + &Default::default(), + Default::default(), + )) + .unwrap(); + + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, Vec::::new()); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); + + // Approval doesn't fail since the check is ommited. + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result)), validation_data.clone(), validation_code, candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Dispute, &Default::default(), + Default::default(), )) .unwrap(); @@ -536,6 +588,323 @@ fn candidate_validation_ok_is_ok() { }); } +#[rstest] +#[case(true)] +#[case(false)] +fn candidate_validation_ok_is_ok(#[case] v2_descriptor: bool) { + let validation_data = PersistedValidationData { max_pov_size: 1024, ..Default::default() }; + + let pov = PoV { block_data: BlockData(vec![1; 32]) }; + let head_data = HeadData(vec![1, 1, 1]); + let validation_code = ValidationCode(vec![2; 16]); + + let descriptor = if v2_descriptor { + make_valid_candidate_descriptor_v2( + ParaId::from(1_u32), + dummy_hash(), + CoreIndex(1), + 1, + dummy_hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + ) + } else { + make_valid_candidate_descriptor( + ParaId::from(1_u32), + dummy_hash(), + validation_data.hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + Sr25519Keyring::Alice, + ) + .into() + }; + + let check = perform_basic_checks( + &descriptor, + validation_data.max_pov_size, + &pov, + &validation_code.hash(), + ); + assert!(check.is_ok()); + + let mut validation_result = WasmValidationResult { + head_data, + new_validation_code: Some(vec![2, 2, 2].into()), + upward_messages: Default::default(), + horizontal_messages: Default::default(), + processed_downward_messages: 0, + hrmp_watermark: 0, + }; + + if v2_descriptor { + validation_result.upward_messages.force_push(UMP_SEPARATOR); + validation_result + .upward_messages + .force_push(UMPSignal::SelectCore(CoreSelector(0), ClaimQueueOffset(1)).encode()); + } + + let commitments = CandidateCommitments { + head_data: validation_result.head_data.clone(), + upward_messages: validation_result.upward_messages.clone(), + horizontal_messages: validation_result.horizontal_messages.clone(), + new_validation_code: validation_result.new_validation_code.clone(), + processed_downward_messages: validation_result.processed_downward_messages, + hrmp_watermark: validation_result.hrmp_watermark, + }; + + let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: commitments.hash() }; + let mut cq = BTreeMap::new(); + let _ = cq.insert(CoreIndex(0), vec![1.into(), 2.into()].into()); + let _ = cq.insert(CoreIndex(1), vec![1.into(), 1.into()].into()); + + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result)), + validation_data.clone(), + validation_code, + candidate_receipt, + Arc::new(pov), + ExecutorParams::default(), + PvfExecKind::Backing, + &Default::default(), + Some(ClaimQueueSnapshot(cq)), + )) + .unwrap(); + + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, commitments.upward_messages); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); +} + +#[test] +fn invalid_session_or_core_index() { + let validation_data = PersistedValidationData { max_pov_size: 1024, ..Default::default() }; + + let pov = PoV { block_data: BlockData(vec![1; 32]) }; + let head_data = HeadData(vec![1, 1, 1]); + let validation_code = ValidationCode(vec![2; 16]); + + let descriptor = make_valid_candidate_descriptor_v2( + ParaId::from(1_u32), + dummy_hash(), + CoreIndex(1), + 100, + dummy_hash(), + pov.hash(), + validation_code.hash(), + head_data.hash(), + dummy_hash(), + ); + + let check = perform_basic_checks( + &descriptor, + validation_data.max_pov_size, + &pov, + &validation_code.hash(), + ); + assert!(check.is_ok()); + + let mut validation_result = WasmValidationResult { + head_data, + new_validation_code: Some(vec![2, 2, 2].into()), + upward_messages: Default::default(), + horizontal_messages: Default::default(), + processed_downward_messages: 0, + hrmp_watermark: 0, + }; + + validation_result.upward_messages.force_push(UMP_SEPARATOR); + validation_result + .upward_messages + .force_push(UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(0)).encode()); + + let commitments = CandidateCommitments { + head_data: validation_result.head_data.clone(), + upward_messages: validation_result.upward_messages.clone(), + horizontal_messages: validation_result.horizontal_messages.clone(), + new_validation_code: validation_result.new_validation_code.clone(), + processed_downward_messages: validation_result.processed_downward_messages, + hrmp_watermark: validation_result.hrmp_watermark, + }; + + let mut candidate_receipt = + CandidateReceipt { descriptor, commitments_hash: commitments.hash() }; + + let err = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Backing, + &Default::default(), + Default::default(), + )) + .unwrap(); + + assert_matches!(err, ValidationResult::Invalid(InvalidCandidate::InvalidSessionIndex)); + + let err = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::BackingSystemParas, + &Default::default(), + Default::default(), + )) + .unwrap(); + + assert_matches!(err, ValidationResult::Invalid(InvalidCandidate::InvalidSessionIndex)); + + candidate_receipt.descriptor.set_session_index(1); + + let result = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Backing, + &Default::default(), + Some(Default::default()), + )) + .unwrap(); + assert_matches!(result, ValidationResult::Invalid(InvalidCandidate::InvalidCoreIndex)); + + let result = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::BackingSystemParas, + &Default::default(), + Some(Default::default()), + )) + .unwrap(); + assert_matches!(result, ValidationResult::Invalid(InvalidCandidate::InvalidCoreIndex)); + + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Approval, + &Default::default(), + Default::default(), + )) + .unwrap(); + + // Validation doesn't fail for approvals, core/session index is not checked. + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, commitments.upward_messages); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); + + // Dispute check passes because we don't check core or session index + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Dispute, + &Default::default(), + Default::default(), + )) + .unwrap(); + + // Validation doesn't fail for approvals, core/session index is not checked. + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, commitments.upward_messages); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); + + // Populate claim queue. + let mut cq = BTreeMap::new(); + let _ = cq.insert(CoreIndex(0), vec![1.into(), 2.into()].into()); + let _ = cq.insert(CoreIndex(1), vec![1.into(), 2.into()].into()); + + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::Backing, + &Default::default(), + Some(ClaimQueueSnapshot(cq.clone())), + )) + .unwrap(); + + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, commitments.upward_messages); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); + + let v = executor::block_on(validate_candidate_exhaustive( + Some(1), + MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result.clone())), + validation_data.clone(), + validation_code.clone(), + candidate_receipt.clone(), + Arc::new(pov.clone()), + ExecutorParams::default(), + PvfExecKind::BackingSystemParas, + &Default::default(), + Some(ClaimQueueSnapshot(cq)), + )) + .unwrap(); + + assert_matches!(v, ValidationResult::Valid(outputs, used_validation_data) => { + assert_eq!(outputs.head_data, HeadData(vec![1, 1, 1])); + assert_eq!(outputs.upward_messages, commitments.upward_messages); + assert_eq!(outputs.horizontal_messages, Vec::new()); + assert_eq!(outputs.new_validation_code, Some(vec![2, 2, 2].into())); + assert_eq!(outputs.hrmp_watermark, 0); + assert_eq!(used_validation_data, validation_data); + }); +} + #[test] fn candidate_validation_bad_return_is_invalid() { let validation_data = PersistedValidationData { max_pov_size: 1024, ..Default::default() }; @@ -566,6 +935,7 @@ fn candidate_validation_bad_return_is_invalid() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: Hash::zero() }; let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Err(ValidationError::Invalid( WasmInvalidCandidate::HardTimeout, ))), @@ -576,6 +946,7 @@ fn candidate_validation_bad_return_is_invalid() { ExecutorParams::default(), PvfExecKind::Backing, &Default::default(), + Default::default(), )) .unwrap(); @@ -647,6 +1018,7 @@ fn candidate_validation_one_ambiguous_error_is_valid() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: commitments.hash() }; let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result_list(vec![ Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousWorkerDeath)), Ok(validation_result), @@ -658,6 +1030,7 @@ fn candidate_validation_one_ambiguous_error_is_valid() { ExecutorParams::default(), PvfExecKind::Approval, &Default::default(), + Default::default(), )) .unwrap(); @@ -688,6 +1061,7 @@ fn candidate_validation_multiple_ambiguous_errors_is_invalid() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: Hash::zero() }; let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result_list(vec![ Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousWorkerDeath)), Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::AmbiguousWorkerDeath)), @@ -699,6 +1073,7 @@ fn candidate_validation_multiple_ambiguous_errors_is_invalid() { ExecutorParams::default(), PvfExecKind::Approval, &Default::default(), + Default::default(), )) .unwrap(); @@ -806,6 +1181,7 @@ fn candidate_validation_retry_on_error_helper( let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: Hash::zero() }; return executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result_list(mock_errors), validation_data, validation_code, @@ -814,6 +1190,7 @@ fn candidate_validation_retry_on_error_helper( ExecutorParams::default(), exec_kind, &Default::default(), + Default::default(), )) } @@ -847,6 +1224,7 @@ fn candidate_validation_timeout_is_internal_error() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: Hash::zero() }; let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Err(ValidationError::Invalid( WasmInvalidCandidate::HardTimeout, ))), @@ -857,6 +1235,7 @@ fn candidate_validation_timeout_is_internal_error() { ExecutorParams::default(), PvfExecKind::Backing, &Default::default(), + Default::default(), )); assert_matches!(v, Ok(ValidationResult::Invalid(InvalidCandidate::Timeout))); @@ -896,6 +1275,7 @@ fn candidate_validation_commitment_hash_mismatch_is_invalid() { }; let result = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result)), validation_data, validation_code, @@ -904,6 +1284,7 @@ fn candidate_validation_commitment_hash_mismatch_is_invalid() { ExecutorParams::default(), PvfExecKind::Backing, &Default::default(), + Default::default(), )) .unwrap(); @@ -947,6 +1328,7 @@ fn candidate_validation_code_mismatch_is_invalid() { >(pool.clone()); let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Err(ValidationError::Invalid( WasmInvalidCandidate::HardTimeout, ))), @@ -957,6 +1339,7 @@ fn candidate_validation_code_mismatch_is_invalid() { ExecutorParams::default(), PvfExecKind::Backing, &Default::default(), + Default::default(), )) .unwrap(); @@ -1007,6 +1390,7 @@ fn compressed_code_works() { let candidate_receipt = CandidateReceipt { descriptor, commitments_hash: commitments.hash() }; let v = executor::block_on(validate_candidate_exhaustive( + Some(1), MockValidateCandidateBackend::with_hardcoded_result(Ok(validation_result)), validation_data, validation_code, @@ -1015,6 +1399,7 @@ fn compressed_code_works() { ExecutorParams::default(), PvfExecKind::Backing, &Default::default(), + Default::default(), )); assert_matches!(v, Ok(ValidationResult::Valid(_, _))); diff --git a/polkadot/node/primitives/src/lib.rs b/polkadot/node/primitives/src/lib.rs index e2e7aa92b11c..6985e86098b0 100644 --- a/polkadot/node/primitives/src/lib.rs +++ b/polkadot/node/primitives/src/lib.rs @@ -348,6 +348,10 @@ pub enum InvalidCandidate { CodeHashMismatch, /// Validation has generated different candidate commitments. CommitmentsHashMismatch, + /// The candidate receipt contains an invalid session index. + InvalidSessionIndex, + /// The candidate receipt contains an invalid core index. + InvalidCoreIndex, } /// Result of the validation of the candidate. diff --git a/polkadot/primitives/src/vstaging/mod.rs b/polkadot/primitives/src/vstaging/mod.rs index 265fcd899d74..21aab41902be 100644 --- a/polkadot/primitives/src/vstaging/mod.rs +++ b/polkadot/primitives/src/vstaging/mod.rs @@ -208,6 +208,10 @@ pub trait MutateDescriptorV2 { fn set_erasure_root(&mut self, erasure_root: Hash); /// Set the para head of the descriptor. fn set_para_head(&mut self, para_head: Hash); + /// Set the core index of the descriptor. + fn set_core_index(&mut self, core_index: CoreIndex); + /// Set the session index of the descriptor. + fn set_session_index(&mut self, session_index: SessionIndex); } #[cfg(feature = "test")] @@ -228,6 +232,14 @@ impl MutateDescriptorV2 for CandidateDescriptorV2 { self.version = version; } + fn set_core_index(&mut self, core_index: CoreIndex) { + self.core_index = core_index.0 as u16; + } + + fn set_session_index(&mut self, session_index: SessionIndex) { + self.session_index = session_index; + } + fn set_persisted_validation_data_hash(&mut self, persisted_validation_data_hash: Hash) { self.persisted_validation_data_hash = persisted_validation_data_hash; } diff --git a/prdoc/pr_5847.prdoc b/prdoc/pr_5847.prdoc new file mode 100644 index 000000000000..fdbf6423da60 --- /dev/null +++ b/prdoc/pr_5847.prdoc @@ -0,0 +1,19 @@ +title: '`candidate-validation`: RFC103 implementation' +doc: +- audience: Node Dev + description: | + Introduces support for new v2 descriptor `core_index` and `session_index` fields. + The subsystem will check the values of the new fields only during backing validations. +crates: +- name: polkadot-node-primitives + bump: major +- name: polkadot-primitives + bump: major +- name: cumulus-relay-chain-inprocess-interface + bump: minor +- name: cumulus-relay-chain-interface + bump: minor +- name: cumulus-client-consensus-aura + bump: minor +- name: polkadot-node-core-candidate-validation + bump: major From fa52407856c11ee138a32f2ba744f774fac984d5 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Fri, 1 Nov 2024 06:30:26 -0700 Subject: [PATCH 006/166] Update Treasury to Support Relay Chain Block Number Provider (#3970) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The goal of this PR is to have the treasury pallet work on a parachain which does not produce blocks on a regular schedule, thus can use the relay chain as a block provider. Because blocks are not produced regularly, we cannot make the assumption that block number increases monotonically, and thus have new logic to handle multiple spend periods passing between blocks. --------- Co-authored-by: Bastian Köcher Co-authored-by: Muharem --- .../collectives-westend/src/fellowship/mod.rs | 1 + polkadot/runtime/common/src/impls.rs | 1 + polkadot/runtime/rococo/src/lib.rs | 1 + polkadot/runtime/westend/src/lib.rs | 1 + prdoc/pr_3970.prdoc | 17 +++ substrate/bin/node/runtime/src/lib.rs | 1 + substrate/frame/bounties/src/benchmarking.rs | 29 ++-- substrate/frame/bounties/src/lib.rs | 26 ++-- substrate/frame/bounties/src/tests.rs | 120 ++++++--------- .../frame/child-bounties/src/benchmarking.rs | 16 +- substrate/frame/child-bounties/src/lib.rs | 18 ++- substrate/frame/child-bounties/src/tests.rs | 139 +++++++----------- substrate/frame/tips/src/tests.rs | 2 + substrate/frame/treasury/src/lib.rs | 84 +++++++++-- substrate/frame/treasury/src/tests.rs | 66 +++++++-- 15 files changed, 302 insertions(+), 220 deletions(-) create mode 100644 prdoc/pr_3970.prdoc diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs index 942e0c294dd0..1e8212cf6ac2 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -333,4 +333,5 @@ impl pallet_treasury::Config for Runtime { sp_core::ConstU8<1>, ConstU32<1000>, >; + type BlockNumberProvider = crate::System; } diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index b6a93cf53685..2f79d223d3c0 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -366,6 +366,7 @@ mod tests { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<0>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 5bcde612cf1b..e02a28353d29 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -543,6 +543,7 @@ impl pallet_treasury::Config for Runtime { AssetRate, >; type PayoutPeriod = PayoutSpendPeriod; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments; } diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 970ef5318994..251d92b03bbb 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -823,6 +823,7 @@ impl pallet_treasury::Config for Runtime { AssetRate, >; type PayoutPeriod = PayoutSpendPeriod; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments; } diff --git a/prdoc/pr_3970.prdoc b/prdoc/pr_3970.prdoc new file mode 100644 index 000000000000..5c20e7444782 --- /dev/null +++ b/prdoc/pr_3970.prdoc @@ -0,0 +1,17 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Update Treasury to Support Block Number Provider + +doc: + - audience: Runtime Dev + description: | + The goal of this PR is to have the treasury pallet work on a parachain which does not produce blocks on a regular schedule, thus can use the relay chain as a block provider. Because blocks are not produced regularly, we cannot make the assumption that block number increases monotonically, and thus have new logic to handle multiple spend periods passing between blocks. To migrate existing treasury implementations, simply add `type BlockNumberProvider = System` to have the same behavior as before. + +crates: +- name: pallet-treasury + bump: major +- name: pallet-bounties + bump: minor +- name: pallet-child-bounties + bump: minor diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 12e8dc3e5077..7712d8ba9540 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -1266,6 +1266,7 @@ impl pallet_treasury::Config for Runtime { type Paymaster = PayAssetFromAccount; type BalanceConverter = AssetRate; type PayoutPeriod = SpendPayoutPeriod; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index de93ba5c4ce7..6fa60e6938b6 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -26,13 +26,17 @@ use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; -use sp_runtime::traits::Bounded; +use sp_runtime::traits::{BlockNumberProvider, Bounded}; use crate::Pallet as Bounties; use pallet_treasury::Pallet as Treasury; const SEED: u32 = 0; +fn set_block_number, I: 'static>(n: BlockNumberFor) { + >::BlockNumberProvider::set_block_number(n); +} + // Create bounties that are approved for use in `on_initialize`. fn create_approved_bounties, I: 'static>(n: u32) -> Result<(), BenchmarkError> { for i in 0..n { @@ -78,7 +82,8 @@ fn create_bounty, I: 'static>( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + set_block_number::(T::SpendPeriod::get()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup.clone(), fee)?; Bounties::::accept_curator(RawOrigin::Signed(curator).into(), bounty_id)?; Ok((curator_lookup, bounty_id)) @@ -116,16 +121,17 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + set_block_number::(T::SpendPeriod::get()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); }: _(approve_origin, bounty_id, curator_lookup, fee) // Worst case when curator is inactive and any sender unassigns the curator. unassign_curator { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); let bounty_id = BountyCount::::get() - 1; - frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 2u32.into()); + set_block_number::(T::SpendPeriod::get() + T::BountyUpdatePeriod::get() + 2u32.into()); let caller = whitelisted_caller(); }: _(RawOrigin::Signed(caller), bounty_id) @@ -137,14 +143,15 @@ benchmarks_instance_pallet! { let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin.clone(), bounty_id)?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + set_block_number::(T::SpendPeriod::get()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); Bounties::::propose_curator(approve_origin, bounty_id, curator_lookup, fee)?; }: _(RawOrigin::Signed(curator), bounty_id) award_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -155,7 +162,7 @@ benchmarks_instance_pallet! { claim_bounty { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; @@ -164,7 +171,7 @@ benchmarks_instance_pallet! { let beneficiary = T::Lookup::unlookup(beneficiary_account.clone()); Bounties::::award_bounty(RawOrigin::Signed(curator.clone()).into(), bounty_id, beneficiary)?; - frame_system::Pallet::::set_block_number(T::BountyDepositPayoutDelay::get() + 1u32.into()); + set_block_number::(T::SpendPeriod::get() + T::BountyDepositPayoutDelay::get() + 1u32.into()); ensure!(T::Currency::free_balance(&beneficiary_account).is_zero(), "Beneficiary already has balance"); }: _(RawOrigin::Signed(curator), bounty_id) @@ -184,7 +191,7 @@ benchmarks_instance_pallet! { close_bounty_active { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); let bounty_id = BountyCount::::get() - 1; let approve_origin = T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; @@ -196,7 +203,7 @@ benchmarks_instance_pallet! { extend_bounty_expiry { setup_pot_account::(); let (curator_lookup, bounty_id) = create_bounty::()?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); let bounty_id = BountyCount::::get() - 1; let curator = T::Lookup::lookup(curator_lookup).map_err(<&str>::from)?; diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index e30d6fa2d143..9d5931f4a608 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -96,7 +96,7 @@ use frame_support::traits::{ }; use sp_runtime::{ - traits::{AccountIdConversion, BadOrigin, Saturating, StaticLookup, Zero}, + traits::{AccountIdConversion, BadOrigin, BlockNumberProvider, Saturating, StaticLookup, Zero}, DispatchResult, Permill, RuntimeDebug, }; @@ -488,7 +488,7 @@ pub mod pallet { // If the sender is not the curator, and the curator is inactive, // slash the curator. if sender != *curator { - let block_number = frame_system::Pallet::::block_number(); + let block_number = Self::treasury_block_number(); if *update_due < block_number { slash_curator(curator, &mut bounty.curator_deposit); // Continue to change bounty status below... @@ -552,8 +552,8 @@ pub mod pallet { T::Currency::reserve(curator, deposit)?; bounty.curator_deposit = deposit; - let update_due = frame_system::Pallet::::block_number() + - T::BountyUpdatePeriod::get(); + let update_due = + Self::treasury_block_number() + T::BountyUpdatePeriod::get(); bounty.status = BountyStatus::Active { curator: curator.clone(), update_due }; @@ -607,8 +607,7 @@ pub mod pallet { bounty.status = BountyStatus::PendingPayout { curator: signer, beneficiary: beneficiary.clone(), - unlock_at: frame_system::Pallet::::block_number() + - T::BountyDepositPayoutDelay::get(), + unlock_at: Self::treasury_block_number() + T::BountyDepositPayoutDelay::get(), }; Ok(()) @@ -639,10 +638,7 @@ pub mod pallet { if let BountyStatus::PendingPayout { curator, beneficiary, unlock_at } = bounty.status { - ensure!( - frame_system::Pallet::::block_number() >= unlock_at, - Error::::Premature - ); + ensure!(Self::treasury_block_number() >= unlock_at, Error::::Premature); let bounty_account = Self::bounty_account_id(bounty_id); let balance = T::Currency::free_balance(&bounty_account); let fee = bounty.fee.min(balance); // just to be safe @@ -795,7 +791,7 @@ pub mod pallet { match bounty.status { BountyStatus::Active { ref curator, ref mut update_due } => { ensure!(*curator == signer, Error::::RequireCurator); - *update_due = (frame_system::Pallet::::block_number() + + *update_due = (Self::treasury_block_number() + T::BountyUpdatePeriod::get()) .max(*update_due); }, @@ -860,6 +856,14 @@ impl, I: 'static> Pallet { } impl, I: 'static> Pallet { + /// Get the block number used in the treasury pallet. + /// + /// It may be configured to use the relay chain block number on a parachain. + pub fn treasury_block_number() -> BlockNumberFor { + >::BlockNumberProvider::current_block_number() + } + + /// Calculate the deposit required for a curator. pub fn calculate_curator_deposit(fee: &BalanceOf) -> BalanceOf { let mut deposit = T::CuratorDepositMultiplier::get() * *fee; diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index c152391d807a..37bcadddae5b 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -40,6 +40,12 @@ use super::Event as BountiesEvent; type Block = frame_system::mocking::MockBlock; +// This function directly jumps to a block number, and calls `on_initialize`. +fn go_to_block(n: u64) { + ::BlockNumberProvider::set_block_number(n); + >::on_initialize(n); +} + frame_support::construct_runtime!( pub enum Test { @@ -98,6 +104,7 @@ impl pallet_treasury::Config for Test { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<10>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } @@ -120,6 +127,7 @@ impl pallet_treasury::Config for Test { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<10>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } @@ -186,7 +194,9 @@ impl ExtBuilder { .build_storage() .unwrap() .into(); - ext.execute_with(|| System::set_block_number(1)); + ext.execute_with(|| { + ::BlockNumberProvider::set_block_number(1) + }); ext } @@ -232,7 +242,7 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); - >::on_initialize(1); + go_to_block(1); assert_eq!(Balances::free_balance(3), 0); assert_eq!(Treasury::pot(), 100); }); @@ -245,7 +255,7 @@ fn unused_pot_should_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(pallet_balances::TotalIssuance::::get(), init_total_issuance + 100); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 50); assert_eq!(pallet_balances::TotalIssuance::::get(), init_total_issuance + 50); }); @@ -259,7 +269,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); - >::on_initialize(2); + go_to_block(2); assert_eq!(Balances::free_balance(3), 100); assert_eq!(Treasury::pot(), 0); }); @@ -273,11 +283,11 @@ fn pot_underflow_should_not_diminish() { assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 150, 3) }); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed assert_ok!(Balances::deposit_into_existing(&Treasury::account_id(), 100)); - >::on_initialize(4); + go_to_block(4); assert_eq!(Balances::free_balance(3), 150); // Fund has been spent assert_eq!(Treasury::pot(), 25); // Pot has finally changed }); @@ -294,12 +304,12 @@ fn treasury_account_doesnt_get_deleted() { assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), treasury_balance, 3) }); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), Treasury::pot(), 3) }); - >::on_initialize(4); + go_to_block(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied assert_eq!(Balances::free_balance(Treasury::account_id()), 1); // but the account is still there }); @@ -322,7 +332,8 @@ fn inexistent_account_works() { assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 99, 3) }); assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 1, 3) }); - >::on_initialize(2); + go_to_block(2); + assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -330,7 +341,7 @@ fn inexistent_account_works() { assert_eq!(Treasury::pot(), 99); // Pot now contains funds assert_eq!(Balances::free_balance(Treasury::account_id()), 100); // Account does exist - >::on_initialize(4); + go_to_block(4); assert_eq!(Treasury::pot(), 0); // Pot has changed assert_eq!(Balances::free_balance(3), 99); // Balance of `3` has changed @@ -340,8 +351,6 @@ fn inexistent_account_works() { #[test] fn propose_bounty_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); - Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -377,8 +386,6 @@ fn propose_bounty_works() { #[test] fn propose_bounty_validation_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); - Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -406,7 +413,6 @@ fn propose_bounty_validation_works() { #[test] fn close_bounty_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!(Bounties::close_bounty(RuntimeOrigin::root(), 0), Error::::InvalidIndex); @@ -431,7 +437,6 @@ fn close_bounty_works() { #[test] fn approve_bounty_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!( Bounties::approve_bounty(RuntimeOrigin::root(), 0), @@ -466,7 +471,7 @@ fn approve_bounty_works() { assert_eq!(Balances::reserved_balance(0), deposit); assert_eq!(Balances::free_balance(0), 100 - deposit); - >::on_initialize(2); + go_to_block(2); // return deposit assert_eq!(Balances::reserved_balance(0), 0); @@ -492,7 +497,6 @@ fn approve_bounty_works() { #[test] fn assign_curator_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!( @@ -504,8 +508,7 @@ fn assign_curator_works() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_noop!( Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 50), @@ -562,14 +565,12 @@ fn assign_curator_works() { #[test] fn unassign_curator_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); let fee = 4; @@ -615,15 +616,13 @@ fn unassign_curator_works() { #[test] fn award_and_claim_bounty_works() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); let fee = 4; assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); @@ -653,8 +652,7 @@ fn award_and_claim_bounty_works() { assert_noop!(Bounties::claim_bounty(RuntimeOrigin::signed(1), 0), Error::::Premature); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); assert_ok!(Balances::transfer_allow_death( RuntimeOrigin::signed(0), @@ -682,23 +680,20 @@ fn award_and_claim_bounty_works() { #[test] fn claim_handles_high_fee() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 30); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 49)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 3)); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); // make fee > balance let res = Balances::slash(&Bounties::bounty_account_id(0), 10); @@ -723,16 +718,13 @@ fn claim_handles_high_fee() { #[test] fn cancel_and_refund() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); - Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Balances::transfer_allow_death( RuntimeOrigin::signed(0), @@ -766,14 +758,12 @@ fn cancel_and_refund() { #[test] fn award_and_cancel() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 0, 10)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(0), 0)); @@ -809,14 +799,12 @@ fn award_and_cancel() { #[test] fn expire_and_unassign() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 1, 10)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(1), 0)); @@ -824,16 +812,14 @@ fn expire_and_unassign() { assert_eq!(Balances::free_balance(1), 93); assert_eq!(Balances::reserved_balance(1), 5); - System::set_block_number(22); - >::on_initialize(22); + go_to_block(22); assert_noop!( Bounties::unassign_curator(RuntimeOrigin::signed(0), 0), Error::::Premature ); - System::set_block_number(23); - >::on_initialize(23); + go_to_block(23); assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(0), 0)); @@ -857,7 +843,6 @@ fn expire_and_unassign() { #[test] fn extend_expiry() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); @@ -869,8 +854,7 @@ fn extend_expiry() { Error::::UnexpectedStatus ); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 10)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -878,8 +862,7 @@ fn extend_expiry() { assert_eq!(Balances::free_balance(4), 5); assert_eq!(Balances::reserved_balance(4), 5); - System::set_block_number(10); - >::on_initialize(10); + go_to_block(10); assert_noop!( Bounties::extend_bounty_expiry(RuntimeOrigin::signed(0), 0, Vec::new()), @@ -913,8 +896,7 @@ fn extend_expiry() { } ); - System::set_block_number(25); - >::on_initialize(25); + go_to_block(25); assert_noop!( Bounties::unassign_curator(RuntimeOrigin::signed(0), 0), @@ -993,13 +975,11 @@ fn genesis_funding_works() { #[test] fn unassign_curator_self() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 1, 10)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(1), 0)); @@ -1007,8 +987,7 @@ fn unassign_curator_self() { assert_eq!(Balances::free_balance(1), 93); assert_eq!(Balances::reserved_balance(1), 5); - System::set_block_number(8); - >::on_initialize(8); + go_to_block(8); assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(1), 0)); @@ -1040,7 +1019,6 @@ fn accept_curator_handles_different_deposit_calculations() { let value = 88; let fee = 42; - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&user, 100); // Allow for a larger spend limit: @@ -1048,8 +1026,7 @@ fn accept_curator_handles_different_deposit_calculations() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); @@ -1070,8 +1047,7 @@ fn accept_curator_handles_different_deposit_calculations() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); @@ -1096,8 +1072,7 @@ fn accept_curator_handles_different_deposit_calculations() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), value, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), bounty_index)); - System::set_block_number(6); - >::on_initialize(6); + go_to_block(6); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), bounty_index, user, fee)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(user), bounty_index)); @@ -1114,7 +1089,6 @@ fn approve_bounty_works_second_instance() { // Set burn to 0 to make tracking funds easier. Burn::set(Permill::from_percent(0)); - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&Treasury1::account_id(), 201); assert_eq!(Balances::free_balance(&Treasury::account_id()), 101); @@ -1122,7 +1096,7 @@ fn approve_bounty_works_second_instance() { assert_ok!(Bounties1::propose_bounty(RuntimeOrigin::signed(0), 10, b"12345".to_vec())); assert_ok!(Bounties1::approve_bounty(RuntimeOrigin::root(), 0)); - >::on_initialize(2); + go_to_block(2); >::on_initialize(2); // Bounties 1 is funded... but from where? @@ -1137,8 +1111,6 @@ fn approve_bounty_works_second_instance() { #[test] fn approve_bounty_insufficient_spend_limit_errors() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); - Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -1155,8 +1127,6 @@ fn approve_bounty_insufficient_spend_limit_errors() { #[test] fn approve_bounty_instance1_insufficient_spend_limit_errors() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); - Balances::make_free_balance_be(&Treasury1::account_id(), 101); assert_eq!(Treasury1::pot(), 100); @@ -1173,7 +1143,6 @@ fn approve_bounty_instance1_insufficient_spend_limit_errors() { #[test] fn propose_curator_insufficient_spend_limit_errors() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); // Temporarily set a larger spend limit; @@ -1181,8 +1150,7 @@ fn propose_curator_insufficient_spend_limit_errors() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 51, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); SpendLimit::set(50); // 51 will not work since the limit is 50. @@ -1196,7 +1164,6 @@ fn propose_curator_insufficient_spend_limit_errors() { #[test] fn propose_curator_instance1_insufficient_spend_limit_errors() { ExtBuilder::default().build_and_execute(|| { - System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); // Temporarily set a larger spend limit; @@ -1204,7 +1171,6 @@ fn propose_curator_instance1_insufficient_spend_limit_errors() { assert_ok!(Bounties1::propose_bounty(RuntimeOrigin::signed(0), 11, b"12345".to_vec())); assert_ok!(Bounties1::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); >::on_initialize(2); SpendLimit1::set(10); diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index b1f6370f3340..68e99e21a456 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -25,6 +25,7 @@ use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use sp_runtime::traits::BlockNumberProvider; use crate::Pallet as ChildBounties; use pallet_bounties::Pallet as Bounties; @@ -56,6 +57,10 @@ struct BenchmarkChildBounty { reason: Vec, } +fn set_block_number(n: BlockNumberFor) { + ::BlockNumberProvider::set_block_number(n); +} + fn setup_bounty( user: u32, description: u32, @@ -116,7 +121,8 @@ fn activate_bounty( let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; Bounties::::approve_bounty(approve_origin, child_bounty_setup.bounty_id)?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + set_block_number::(T::SpendPeriod::get()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); Bounties::::propose_curator( RawOrigin::Root.into(), child_bounty_setup.bounty_id, @@ -231,8 +237,8 @@ benchmarks! { unassign_curator { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(BlockNumberFor::::zero()); - frame_system::Pallet::::set_block_number(T::BountyUpdatePeriod::get() + 1u32.into()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); + set_block_number::(T::SpendPeriod::get() + T::BountyUpdatePeriod::get() + 1u32.into()); let caller = whitelisted_caller(); }: _(RawOrigin::Signed(caller), bounty_setup.bounty_id, bounty_setup.child_bounty_id) @@ -268,7 +274,7 @@ benchmarks! { let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED); let beneficiary = T::Lookup::unlookup(beneficiary_account.clone()); - frame_system::Pallet::::set_block_number(T::BountyDepositPayoutDelay::get()); + set_block_number::(T::SpendPeriod::get() + T::BountyDepositPayoutDelay::get()); ensure!(T::Currency::free_balance(&beneficiary_account).is_zero(), "Beneficiary already has balance."); @@ -305,7 +311,7 @@ benchmarks! { close_child_bounty_active { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(frame_system::Pallet::::block_number()); }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id) verify { assert_last_event::(Event::Canceled { diff --git a/substrate/frame/child-bounties/src/lib.rs b/substrate/frame/child-bounties/src/lib.rs index 660a30ca5d26..1e970b6ae67c 100644 --- a/substrate/frame/child-bounties/src/lib.rs +++ b/substrate/frame/child-bounties/src/lib.rs @@ -67,7 +67,10 @@ use frame_support::traits::{ }; use sp_runtime::{ - traits::{AccountIdConversion, BadOrigin, CheckedSub, Saturating, StaticLookup, Zero}, + traits::{ + AccountIdConversion, BadOrigin, BlockNumberProvider, CheckedSub, Saturating, StaticLookup, + Zero, + }, DispatchResult, RuntimeDebug, }; @@ -523,7 +526,7 @@ pub mod pallet { let (parent_curator, update_due) = Self::ensure_bounty_active(parent_bounty_id)?; if sender == parent_curator || - update_due < frame_system::Pallet::::block_number() + update_due < Self::treasury_block_number() { // Slash the child-bounty curator if // + the call is made by the parent bounty curator. @@ -602,7 +605,7 @@ pub mod pallet { child_bounty.status = ChildBountyStatus::PendingPayout { curator: signer, beneficiary: beneficiary.clone(), - unlock_at: frame_system::Pallet::::block_number() + + unlock_at: Self::treasury_block_number() + T::BountyDepositPayoutDelay::get(), }; Ok(()) @@ -664,7 +667,7 @@ pub mod pallet { // Ensure block number is elapsed for processing the // claim. ensure!( - frame_system::Pallet::::block_number() >= *unlock_at, + Self::treasury_block_number() >= *unlock_at, BountiesError::::Premature, ); @@ -772,6 +775,13 @@ pub mod pallet { } impl Pallet { + /// Get the block number used in the treasury pallet. + /// + /// It may be configured to use the relay chain block number on a parachain. + pub fn treasury_block_number() -> BlockNumberFor { + ::BlockNumberProvider::current_block_number() + } + // This function will calculate the deposit of a curator. fn calculate_curator_deposit( parent_curator: &T::AccountId, diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 125844fa70e2..96d01b03560d 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -42,6 +42,12 @@ use super::Event as ChildBountiesEvent; type Block = frame_system::mocking::MockBlock; type BountiesError = pallet_bounties::Error; +// This function directly jumps to a block number, and calls `on_initialize`. +fn go_to_block(n: u64) { + ::BlockNumberProvider::set_block_number(n); + >::on_initialize(n); +} + frame_support::construct_runtime!( pub enum Test { @@ -98,6 +104,7 @@ impl pallet_treasury::Config for Test { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<10>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } @@ -184,15 +191,14 @@ fn add_child_bounty() { // Curator, child-bounty curator & beneficiary. // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); let fee = 8; assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); @@ -278,7 +284,7 @@ fn child_bounty_assign_curator() { // 3, Test for DB state of `ChildBounties`. // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 101); Balances::make_free_balance_be(&8, 101); @@ -287,8 +293,7 @@ fn child_bounty_assign_curator() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); let fee = 4; assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); @@ -383,7 +388,7 @@ fn child_bounty_assign_curator() { fn award_claim_child_bounty() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -396,8 +401,7 @@ fn award_claim_child_bounty() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -449,7 +453,7 @@ fn award_claim_child_bounty() { BountiesError::Premature ); - System::set_block_number(9); + go_to_block(9); assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); @@ -474,7 +478,7 @@ fn award_claim_child_bounty() { fn close_child_bounty_added() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -487,8 +491,7 @@ fn close_child_bounty_added() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); @@ -504,7 +507,7 @@ fn close_child_bounty_added() { assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - System::set_block_number(4); + go_to_block(4); // Close child-bounty. // Wrong origin. @@ -531,7 +534,7 @@ fn close_child_bounty_added() { fn close_child_bounty_active() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -544,8 +547,7 @@ fn close_child_bounty_active() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); @@ -589,7 +591,7 @@ fn close_child_bounty_active() { fn close_child_bounty_pending() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -602,8 +604,7 @@ fn close_child_bounty_pending() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); let parent_fee = 6; assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, parent_fee)); @@ -650,7 +651,7 @@ fn close_child_bounty_pending() { fn child_bounty_added_unassign_curator() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -663,8 +664,7 @@ fn child_bounty_added_unassign_curator() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); @@ -692,7 +692,7 @@ fn child_bounty_added_unassign_curator() { fn child_bounty_curator_proposed_unassign_curator() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -705,8 +705,7 @@ fn child_bounty_curator_proposed_unassign_curator() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); @@ -767,7 +766,7 @@ fn child_bounty_active_unassign_curator() { // bounty. Unassign from random account. Should slash. new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -782,8 +781,7 @@ fn child_bounty_active_unassign_curator() { assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -797,8 +795,7 @@ fn child_bounty_active_unassign_curator() { )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - System::set_block_number(3); - >::on_initialize(3); + go_to_block(3); // Propose and accept curator for child-bounty. let fee = 6; @@ -817,8 +814,7 @@ fn child_bounty_active_unassign_curator() { } ); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); // Unassign curator - from reject origin. assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::root(), 0, 0)); @@ -856,8 +852,7 @@ fn child_bounty_active_unassign_curator() { } ); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); // Unassign curator again - from parent curator. assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0)); @@ -893,8 +888,7 @@ fn child_bounty_active_unassign_curator() { } ); - System::set_block_number(6); - >::on_initialize(6); + go_to_block(6); // Unassign curator again - from child-bounty curator. assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(6), 0, 0)); @@ -932,8 +926,7 @@ fn child_bounty_active_unassign_curator() { } ); - System::set_block_number(7); - >::on_initialize(7); + go_to_block(7); // Unassign curator again - from non curator; non reject origin; some random guy. // Bounty update period is not yet complete. @@ -942,8 +935,7 @@ fn child_bounty_active_unassign_curator() { BountiesError::Premature ); - System::set_block_number(20); - >::on_initialize(20); + go_to_block(20); // Unassign child curator from random account after inactivity. assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0)); @@ -972,7 +964,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // This can happen when the curator of parent bounty has been unassigned. new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -987,8 +979,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -1002,8 +993,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - System::set_block_number(3); - >::on_initialize(3); + go_to_block(3); // Propose and accept curator for child-bounty. let fee = 8; @@ -1022,14 +1012,12 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { } ); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); // Unassign parent bounty curator. assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); // Try unassign child-bounty curator - from non curator; non reject // origin; some random guy. Bounty update period is not yet complete. @@ -1057,15 +1045,13 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { assert_eq!(Balances::free_balance(8), 101 - expected_child_deposit); assert_eq!(Balances::reserved_balance(8), 0); // slashed - System::set_block_number(6); - >::on_initialize(6); + go_to_block(6); // Propose and accept curator for parent-bounty again. assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 5, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(5), 0)); - System::set_block_number(7); - >::on_initialize(7); + go_to_block(7); // Propose and accept curator for child-bounty again. let fee = 2; @@ -1084,8 +1070,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { } ); - System::set_block_number(8); - >::on_initialize(8); + go_to_block(8); assert_noop!( ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), @@ -1095,8 +1080,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Unassign parent bounty curator again. assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(5), 0)); - System::set_block_number(9); - >::on_initialize(9); + go_to_block(9); // Unassign curator again - from parent curator. assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(7), 0, 0)); @@ -1123,7 +1107,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { fn close_parent_with_child_bounty() { new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -1142,8 +1126,7 @@ fn close_parent_with_child_bounty() { Error::::ParentBountyNotActive ); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -1157,8 +1140,7 @@ fn close_parent_with_child_bounty() { )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); // Try close parent-bounty. // Child bounty active, can't close parent. @@ -1167,8 +1149,6 @@ fn close_parent_with_child_bounty() { BountiesError::HasActiveChildBounty ); - System::set_block_number(2); - // Close child-bounty. assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::root(), 0, 0)); @@ -1187,7 +1167,7 @@ fn children_curator_fee_calculation_test() { // from parent bounty fee when claiming bounties. new_test_ext().execute_with(|| { // Make the parent bounty. - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::free_balance(Treasury::account_id()), 101); assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); @@ -1199,8 +1179,7 @@ fn children_curator_fee_calculation_test() { assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); @@ -1214,8 +1193,7 @@ fn children_curator_fee_calculation_test() { )); assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); let fee = 6; @@ -1245,7 +1223,7 @@ fn children_curator_fee_calculation_test() { } ); - System::set_block_number(9); + go_to_block(9); // Claim child-bounty. assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); @@ -1256,7 +1234,7 @@ fn children_curator_fee_calculation_test() { // Award the parent bounty. assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 9)); - System::set_block_number(15); + go_to_block(15); // Claim the parent bounty. assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(9), 0)); @@ -1282,7 +1260,7 @@ fn accept_curator_handles_different_deposit_calculations() { let parent_value = 1_000_000; let parent_fee = 10_000; - System::set_block_number(1); + go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), parent_value * 3); Balances::make_free_balance_be(&parent_curator, parent_fee * 100); assert_ok!(Bounties::propose_bounty( @@ -1292,8 +1270,7 @@ fn accept_curator_handles_different_deposit_calculations() { )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), parent_index)); - System::set_block_number(2); - >::on_initialize(2); + go_to_block(2); assert_ok!(Bounties::propose_curator( RuntimeOrigin::root(), @@ -1319,8 +1296,7 @@ fn accept_curator_handles_different_deposit_calculations() { child_value, b"12345-p1".to_vec() )); - System::set_block_number(3); - >::on_initialize(3); + go_to_block(3); assert_ok!(ChildBounties::propose_curator( RuntimeOrigin::signed(parent_curator), parent_index, @@ -1354,8 +1330,7 @@ fn accept_curator_handles_different_deposit_calculations() { child_value, b"12345-p1".to_vec() )); - System::set_block_number(4); - >::on_initialize(4); + go_to_block(4); assert_ok!(ChildBounties::propose_curator( RuntimeOrigin::signed(parent_curator), parent_index, @@ -1387,8 +1362,7 @@ fn accept_curator_handles_different_deposit_calculations() { child_value, b"12345-p1".to_vec() )); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); assert_ok!(ChildBounties::propose_curator( RuntimeOrigin::signed(parent_curator), parent_index, @@ -1423,8 +1397,7 @@ fn accept_curator_handles_different_deposit_calculations() { child_value, b"12345-p1".to_vec() )); - System::set_block_number(5); - >::on_initialize(5); + go_to_block(5); assert_ok!(ChildBounties::propose_curator( RuntimeOrigin::signed(parent_curator), parent_index, diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index 7e4a9368ad0c..f6f130b7e261 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -119,6 +119,7 @@ impl pallet_treasury::Config for Test { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<10>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } @@ -141,6 +142,7 @@ impl pallet_treasury::Config for Test { type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU64<10>; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index ad74495ce090..b21a36949357 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -89,8 +89,11 @@ use scale_info::TypeInfo; use alloc::{boxed::Box, collections::btree_map::BTreeMap}; use sp_runtime::{ - traits::{AccountIdConversion, CheckedAdd, Saturating, StaticLookup, Zero}, - Permill, RuntimeDebug, + traits::{ + AccountIdConversion, BlockNumberProvider, CheckedAdd, One, Saturating, StaticLookup, + UniqueSaturatedInto, Zero, + }, + PerThing, Permill, RuntimeDebug, }; use frame_support::{ @@ -103,6 +106,7 @@ use frame_support::{ weights::Weight, BoundedVec, PalletId, }; +use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; pub use weights::WeightInfo; @@ -275,6 +279,9 @@ pub mod pallet { /// Helper type for benchmarks. #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper: ArgumentsFactory; + + /// Provider for the block number. Normally this is the `frame_system` pallet. + type BlockNumberProvider: BlockNumberProvider>; } /// Number of proposals that have been made. @@ -322,6 +329,10 @@ pub mod pallet { OptionQuery, >; + /// The blocknumber for the last triggered spend period. + #[pallet::storage] + pub(crate) type LastSpendPeriod = StorageValue<_, BlockNumberFor, OptionQuery>; + #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { @@ -414,7 +425,8 @@ pub mod pallet { impl, I: 'static> Hooks> for Pallet { /// ## Complexity /// - `O(A)` where `A` is the number of approvals - fn on_initialize(n: frame_system::pallet_prelude::BlockNumberFor) -> Weight { + fn on_initialize(_do_not_use_local_block_number: BlockNumberFor) -> Weight { + let block_number = T::BlockNumberProvider::current_block_number(); let pot = Self::pot(); let deactivated = Deactivated::::get(); if pot != deactivated { @@ -428,17 +440,29 @@ pub mod pallet { } // Check to see if we should spend some funds! - if (n % T::SpendPeriod::get()).is_zero() { - Self::spend_funds() + let last_spend_period = LastSpendPeriod::::get() + // This unwrap should only occur one time on any blockchain. + // `update_last_spend_period` will populate the `LastSpendPeriod` storage if it is + // empty. + .unwrap_or_else(|| Self::update_last_spend_period()); + let blocks_since_last_spend_period = block_number.saturating_sub(last_spend_period); + let safe_spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); + + // Safe because of `max(1)` above. + let (spend_periods_passed, extra_blocks) = ( + blocks_since_last_spend_period / safe_spend_period, + blocks_since_last_spend_period % safe_spend_period, + ); + let new_last_spend_period = block_number.saturating_sub(extra_blocks); + if spend_periods_passed > BlockNumberFor::::zero() { + Self::spend_funds(spend_periods_passed, new_last_spend_period) } else { Weight::zero() } } #[cfg(feature = "try-runtime")] - fn try_state( - _: frame_system::pallet_prelude::BlockNumberFor, - ) -> Result<(), sp_runtime::TryRuntimeError> { + fn try_state(_: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { Self::do_try_state()?; Ok(()) } @@ -594,7 +618,7 @@ pub mod pallet { let max_amount = T::SpendOrigin::ensure_origin(origin)?; let beneficiary = T::BeneficiaryLookup::lookup(*beneficiary)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let valid_from = valid_from.unwrap_or(now); let expire_at = valid_from.saturating_add(T::PayoutPeriod::get()); ensure!(expire_at > now, Error::::SpendExpired); @@ -672,7 +696,7 @@ pub mod pallet { pub fn payout(origin: OriginFor, index: SpendIndex) -> DispatchResult { ensure_signed(origin)?; let mut spend = Spends::::get(index).ok_or(Error::::InvalidIndex)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); ensure!(now >= spend.valid_from, Error::::EarlyPayout); ensure!(spend.expire_at > now, Error::::SpendExpired); ensure!( @@ -718,7 +742,7 @@ pub mod pallet { ensure_signed(origin)?; let mut spend = Spends::::get(index).ok_or(Error::::InvalidIndex)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if now > spend.expire_at && !matches!(spend.status, State::Attempted { .. }) { // spend has expired and no further status update is expected. @@ -792,6 +816,25 @@ impl, I: 'static> Pallet { T::PalletId::get().into_account_truncating() } + // Backfill the `LastSpendPeriod` storage, assuming that no configuration has changed + // since introducing this code. Used specifically for a migration-less switch to populate + // `LastSpendPeriod`. + fn update_last_spend_period() -> BlockNumberFor { + let block_number = T::BlockNumberProvider::current_block_number(); + let spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); + let time_since_last_spend = block_number % spend_period; + // If it happens that this logic runs directly on a spend period block, we need to backdate + // to the last spend period so a spend still occurs this block. + let last_spend_period = if time_since_last_spend.is_zero() { + block_number.saturating_sub(spend_period) + } else { + // Otherwise, this is the last time we had a spend period. + block_number.saturating_sub(time_since_last_spend) + }; + LastSpendPeriod::::put(last_spend_period); + last_spend_period + } + /// Public function to proposal_count storage. pub fn proposal_count() -> ProposalIndex { ProposalCount::::get() @@ -808,7 +851,11 @@ impl, I: 'static> Pallet { } /// Spend some money! returns number of approvals before spend. - pub fn spend_funds() -> Weight { + pub fn spend_funds( + spend_periods_passed: BlockNumberFor, + new_last_spend_period: BlockNumberFor, + ) -> Weight { + LastSpendPeriod::::put(new_last_spend_period); let mut total_weight = Weight::zero(); let mut budget_remaining = Self::pot(); @@ -860,10 +907,15 @@ impl, I: 'static> Pallet { &mut missed_any, ); - if !missed_any { - // burn some proportion of the remaining budget if we run a surplus. - let burn = (T::Burn::get() * budget_remaining).min(budget_remaining); - budget_remaining -= burn; + if !missed_any && !T::Burn::get().is_zero() { + // Get the amount of treasury that should be left after potentially multiple spend + // periods have passed. + let one_minus_burn = T::Burn::get().left_from_one(); + let percent_left = + one_minus_burn.saturating_pow(spend_periods_passed.unique_saturated_into()); + let new_budget_remaining = percent_left * budget_remaining; + let burn = budget_remaining.saturating_sub(new_budget_remaining); + budget_remaining = new_budget_remaining; let (debit, credit) = T::Currency::pair(burn); imbalance.subsume(debit); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 106bfb530a88..a99dd0dd4449 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -97,6 +97,12 @@ fn set_status(id: u64, s: PaymentStatus) { STATUS.with(|m| m.borrow_mut().insert(id, s)); } +// This function directly jumps to a block number, and calls `on_initialize`. +fn go_to_block(n: u64) { + ::BlockNumberProvider::set_block_number(n); + >::on_initialize(n); +} + pub struct TestPay; impl Pay for TestPay { type Beneficiary = u128; @@ -187,6 +193,7 @@ impl Config for Test { type Paymaster = TestPay; type BalanceConverter = MulBy>; type PayoutPeriod = SpendPayoutPeriod; + type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } @@ -268,7 +275,7 @@ fn spend_local_origin_permissioning_works() { fn spend_local_origin_works() { ExtBuilder::default().build().execute_with(|| { // Check that accumulate works when we have Some value in Dummy already. - Balances::make_free_balance_be(&Treasury::account_id(), 101); + Balances::make_free_balance_be(&Treasury::account_id(), 102); // approve spend of some amount to beneficiary `6`. assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); @@ -278,12 +285,12 @@ fn spend_local_origin_works() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(12), 20, 6)); assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(13), 50, 6)); // free balance of `6` is zero, spend period has not passed. - >::on_initialize(1); + go_to_block(1); assert_eq!(Balances::free_balance(6), 0); // free balance of `6` is `100`, spend period has passed. - >::on_initialize(2); + go_to_block(2); assert_eq!(Balances::free_balance(6), 100); - // `100` spent, `1` burned. + // `100` spent, `1` burned, `1` in ED. assert_eq!(Treasury::pot(), 0); }); } @@ -304,7 +311,7 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); - >::on_initialize(1); + go_to_block(1); assert_eq!(Balances::free_balance(3), 0); assert_eq!(Treasury::pot(), 100); }); @@ -317,7 +324,7 @@ fn unused_pot_should_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(pallet_balances::TotalIssuance::::get(), init_total_issuance + 100); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 50); assert_eq!(pallet_balances::TotalIssuance::::get(), init_total_issuance + 50); }); @@ -331,7 +338,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); - >::on_initialize(2); + go_to_block(2); assert_eq!(Balances::free_balance(3), 100); assert_eq!(Treasury::pot(), 0); }); @@ -345,11 +352,11 @@ fn pot_underflow_should_not_diminish() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 150, 3)); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed let _ = Balances::deposit_into_existing(&Treasury::account_id(), 100).unwrap(); - >::on_initialize(4); + go_to_block(4); assert_eq!(Balances::free_balance(3), 150); // Fund has been spent assert_eq!(Treasury::pot(), 25); // Pot has finally changed }); @@ -366,12 +373,12 @@ fn treasury_account_doesnt_get_deleted() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); - >::on_initialize(2); + go_to_block(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), Treasury::pot(), 3)); - >::on_initialize(4); + go_to_block(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied assert_eq!(Balances::free_balance(Treasury::account_id()), 1); // but the account is still there }); @@ -395,7 +402,8 @@ fn inexistent_account_works() { assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 99, 3)); assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); - >::on_initialize(2); + go_to_block(2); + assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -403,7 +411,7 @@ fn inexistent_account_works() { assert_eq!(Treasury::pot(), 99); // Pot now contains funds assert_eq!(Balances::free_balance(Treasury::account_id()), 100); // Account does exist - >::on_initialize(4); + go_to_block(4); assert_eq!(Treasury::pot(), 0); // Pot has changed assert_eq!(Balances::free_balance(3), 99); // Balance of `3` has changed @@ -936,3 +944,35 @@ fn try_state_spends_invariant_3_works() { ); }); } + +#[test] +fn multiple_spend_periods_work() { + ExtBuilder::default().build().execute_with(|| { + // Check that accumulate works when we have Some value in Dummy already. + // 100 will be spent, 1024 will be the burn amount, 1 for ED + Balances::make_free_balance_be(&Treasury::account_id(), 100 + 1024 + 1); + // approve spend of total amount 100 to beneficiary `6`. + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(11), 10, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(12), 20, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(13), 50, 6)); + // free balance of `6` is zero, spend period has not passed. + go_to_block(1); + assert_eq!(Balances::free_balance(6), 0); + // free balance of `6` is `100`, spend period has passed. + go_to_block(2); + assert_eq!(Balances::free_balance(6), 100); + // `100` spent, 50% burned + assert_eq!(Treasury::pot(), 512); + + // 3 more spends periods pass at once, and an extra block. + go_to_block(2 + (3 * 2) + 1); + // Pot should be reduced by 50% 3 times, so 1/8th the amount. + assert_eq!(Treasury::pot(), 64); + // Even though we are on block 9, the last spend period was block 8. + assert_eq!(LastSpendPeriod::::get(), Some(8)); + }); +} From 68e05636877448d1d9d4944706af63a2f7677a46 Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Mon, 4 Nov 2024 09:39:13 +0200 Subject: [PATCH 007/166] collation-generation: use v2 receipts (#5908) Part of https://github.com/paritytech/polkadot-sdk/issues/5047 Plus some cleanups --------- Signed-off-by: Andrei Sandu Co-authored-by: Andrei Sandu Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Co-authored-by: GitHub Action --- Cargo.lock | 2 + polkadot/node/collation-generation/Cargo.toml | 1 + .../node/collation-generation/src/error.rs | 9 +- polkadot/node/collation-generation/src/lib.rs | 576 ++++----- .../node/collation-generation/src/metrics.rs | 68 +- .../node/collation-generation/src/tests.rs | 1078 ++++------------- polkadot/primitives/Cargo.toml | 2 + polkadot/primitives/src/vstaging/mod.rs | 13 + prdoc/pr_5908.prdoc | 14 + 9 files changed, 529 insertions(+), 1234 deletions(-) create mode 100644 prdoc/pr_5908.prdoc diff --git a/Cargo.lock b/Cargo.lock index 1f171ad756c0..520b088f913c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14299,6 +14299,7 @@ dependencies = [ "polkadot-primitives", "polkadot-primitives-test-helpers", "rstest", + "schnellru", "sp-core 28.0.0", "sp-keyring", "sp-maybe-compressed-blob 11.0.0", @@ -15139,6 +15140,7 @@ dependencies = [ "sp-runtime 31.0.1", "sp-staking", "sp-std 14.0.0", + "thiserror", ] [[package]] diff --git a/polkadot/node/collation-generation/Cargo.toml b/polkadot/node/collation-generation/Cargo.toml index 855b6b0e86eb..777458673f5b 100644 --- a/polkadot/node/collation-generation/Cargo.toml +++ b/polkadot/node/collation-generation/Cargo.toml @@ -21,6 +21,7 @@ sp-core = { workspace = true, default-features = true } sp-maybe-compressed-blob = { workspace = true, default-features = true } thiserror = { workspace = true } codec = { features = ["bit-vec", "derive"], workspace = true } +schnellru = { workspace = true } [dev-dependencies] polkadot-node-subsystem-test-helpers = { workspace = true } diff --git a/polkadot/node/collation-generation/src/error.rs b/polkadot/node/collation-generation/src/error.rs index f04e3c4f20b4..68902f58579a 100644 --- a/polkadot/node/collation-generation/src/error.rs +++ b/polkadot/node/collation-generation/src/error.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use polkadot_primitives::vstaging::CandidateReceiptError; use thiserror::Error; #[derive(Debug, Error)] @@ -30,8 +31,12 @@ pub enum Error { UtilRuntime(#[from] polkadot_node_subsystem_util::runtime::Error), #[error(transparent)] Erasure(#[from] polkadot_erasure_coding::Error), - #[error("Parachain backing state not available in runtime.")] - MissingParaBackingState, + #[error("Collation submitted before initialization")] + SubmittedBeforeInit, + #[error("V2 core index check failed: {0}")] + CandidateReceiptCheck(CandidateReceiptError), + #[error("PoV size {0} exceeded maximum size of {1}")] + POVSizeExceeded(usize, usize), } pub type Result = std::result::Result; diff --git a/polkadot/node/collation-generation/src/lib.rs b/polkadot/node/collation-generation/src/lib.rs index f04f69cbd380..9e975acf10b8 100644 --- a/polkadot/node/collation-generation/src/lib.rs +++ b/polkadot/node/collation-generation/src/lib.rs @@ -32,27 +32,34 @@ #![deny(missing_docs)] use codec::Encode; -use futures::{channel::oneshot, future::FutureExt, join, select}; +use error::{Error, Result}; +use futures::{channel::oneshot, future::FutureExt, select}; use polkadot_node_primitives::{ AvailableData, Collation, CollationGenerationConfig, CollationSecondedSignal, PoV, SubmitCollationParams, }; use polkadot_node_subsystem::{ - messages::{CollationGenerationMessage, CollatorProtocolMessage}, - overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, RuntimeApiError, SpawnedSubsystem, - SubsystemContext, SubsystemError, SubsystemResult, + messages::{CollationGenerationMessage, CollatorProtocolMessage, RuntimeApiMessage}, + overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, SpawnedSubsystem, + SubsystemContext, SubsystemError, SubsystemResult, SubsystemSender, }; use polkadot_node_subsystem_util::{ - request_async_backing_params, request_availability_cores, request_para_backing_state, - request_persisted_validation_data, request_validation_code, request_validation_code_hash, - request_validators, runtime::fetch_claim_queue, + request_claim_queue, request_persisted_validation_data, request_session_index_for_child, + request_validation_code_hash, request_validators, + runtime::{request_node_features, ClaimQueueSnapshot}, }; use polkadot_primitives::{ collator_signature_payload, - vstaging::{CandidateReceiptV2 as CandidateReceipt, CoreState}, + node_features::FeatureIndex, + vstaging::{ + transpose_claim_queue, CandidateDescriptorV2, CandidateReceiptV2 as CandidateReceipt, + CommittedCandidateReceiptV2, TransposedClaimQueue, + }, CandidateCommitments, CandidateDescriptor, CollatorPair, CoreIndex, Hash, Id as ParaId, - OccupiedCoreAssumption, PersistedValidationData, ScheduledCore, ValidationCodeHash, + NodeFeatures, OccupiedCoreAssumption, PersistedValidationData, SessionIndex, + ValidationCodeHash, }; +use schnellru::{ByLength, LruMap}; use sp_core::crypto::Pair; use std::sync::Arc; @@ -69,6 +76,7 @@ const LOG_TARGET: &'static str = "parachain::collation-generation"; /// Collation Generation Subsystem pub struct CollationGenerationSubsystem { config: Option>, + session_info_cache: SessionInfoCache, metrics: Metrics, } @@ -76,7 +84,7 @@ pub struct CollationGenerationSubsystem { impl CollationGenerationSubsystem { /// Create a new instance of the `CollationGenerationSubsystem`. pub fn new(metrics: Metrics) -> Self { - Self { config: None, metrics } + Self { config: None, metrics, session_info_cache: SessionInfoCache::new() } } /// Run this subsystem @@ -117,19 +125,8 @@ impl CollationGenerationSubsystem { activated, .. }))) => { - // follow the procedure from the guide - if let Some(config) = &self.config { - let metrics = self.metrics.clone(); - if let Err(err) = handle_new_activations( - config.clone(), - activated.into_iter().map(|v| v.hash), - ctx, - metrics, - ) - .await - { - gum::warn!(target: LOG_TARGET, err = ?err, "failed to handle new activations"); - } + if let Err(err) = self.handle_new_activation(activated.map(|v| v.hash), ctx).await { + gum::warn!(target: LOG_TARGET, err = ?err, "failed to handle new activation"); } false @@ -154,14 +151,8 @@ impl CollationGenerationSubsystem { Ok(FromOrchestra::Communication { msg: CollationGenerationMessage::SubmitCollation(params), }) => { - if let Some(config) = &self.config { - if let Err(err) = - handle_submit_collation(params, config, ctx, &self.metrics).await - { - gum::error!(target: LOG_TARGET, ?err, "Failed to submit collation"); - } - } else { - gum::error!(target: LOG_TARGET, "Collation submitted before initialization"); + if let Err(err) = self.handle_submit_collation(params, ctx).await { + gum::error!(target: LOG_TARGET, ?err, "Failed to submit collation"); } false @@ -178,175 +169,132 @@ impl CollationGenerationSubsystem { }, } } -} - -#[overseer::subsystem(CollationGeneration, error=SubsystemError, prefix=self::overseer)] -impl CollationGenerationSubsystem { - fn start(self, ctx: Context) -> SpawnedSubsystem { - let future = async move { - self.run(ctx).await; - Ok(()) - } - .boxed(); - - SpawnedSubsystem { name: "collation-generation-subsystem", future } - } -} -#[overseer::contextbounds(CollationGeneration, prefix = self::overseer)] -async fn handle_new_activations( - config: Arc, - activated: impl IntoIterator, - ctx: &mut Context, - metrics: Metrics, -) -> crate::error::Result<()> { - // follow the procedure from the guide: - // https://paritytech.github.io/polkadot-sdk/book/node/collators/collation-generation.html - - // If there is no collation function provided, bail out early. - // Important: Lookahead collator and slot based collator do not use `CollatorFn`. - if config.collator.is_none() { - return Ok(()) - } - - let para_id = config.para_id; - - let _overall_timer = metrics.time_new_activations(); - - for relay_parent in activated { - let _relay_parent_timer = metrics.time_new_activations_relay_parent(); - - let (availability_cores, validators, async_backing_params) = join!( - request_availability_cores(relay_parent, ctx.sender()).await, - request_validators(relay_parent, ctx.sender()).await, - request_async_backing_params(relay_parent, ctx.sender()).await, - ); - - let availability_cores = availability_cores??; - let async_backing_params = async_backing_params?.ok(); - let n_validators = validators??.len(); - let maybe_claim_queue = fetch_claim_queue(ctx.sender(), relay_parent) - .await - .map_err(crate::error::Error::UtilRuntime)?; - - // The loop bellow will fill in cores that the para is allowed to build on. - let mut cores_to_build_on = Vec::new(); - - // This assumption refers to all cores of the parachain, taking elastic scaling - // into account. - let mut para_assumption = None; - for (core_idx, core) in availability_cores.into_iter().enumerate() { - // This nested assumption refers only to the core being iterated. - let (core_assumption, scheduled_core) = match core { - CoreState::Scheduled(scheduled_core) => - (OccupiedCoreAssumption::Free, scheduled_core), - CoreState::Occupied(occupied_core) => match async_backing_params { - Some(params) if params.max_candidate_depth >= 1 => { - // maximum candidate depth when building on top of a block - // pending availability is necessarily 1 - the depth of the - // pending block is 0 so the child has depth 1. - - // Use claim queue if available, or fallback to `next_up_on_available` - let res = match maybe_claim_queue { - Some(ref claim_queue) => { - // read what's in the claim queue for this core at depth 0. - claim_queue - .get_claim_for(CoreIndex(core_idx as u32), 0) - .map(|para_id| ScheduledCore { para_id, collator: None }) - }, - None => { - // Runtime doesn't support claim queue runtime api. Fallback to - // `next_up_on_available` - occupied_core.next_up_on_available - }, - }; + async fn handle_submit_collation( + &mut self, + params: SubmitCollationParams, + ctx: &mut Context, + ) -> Result<()> { + let Some(config) = &self.config else { + return Err(Error::SubmittedBeforeInit); + }; + let _timer = self.metrics.time_submit_collation(); - match res { - Some(res) => (OccupiedCoreAssumption::Included, res), - None => continue, - } - }, - _ => { - gum::trace!( - target: LOG_TARGET, - core_idx = %core_idx, - relay_parent = ?relay_parent, - "core is occupied. Keep going.", - ); - continue - }, - }, - CoreState::Free => { - gum::trace!( - target: LOG_TARGET, - core_idx = %core_idx, - "core is not assigned to any para. Keep going.", - ); - continue - }, - }; + let SubmitCollationParams { + relay_parent, + collation, + parent_head, + validation_code_hash, + result_sender, + core_index, + } = params; - if scheduled_core.para_id != config.para_id { - gum::trace!( + let mut validation_data = match request_persisted_validation_data( + relay_parent, + config.para_id, + OccupiedCoreAssumption::TimedOut, + ctx.sender(), + ) + .await + .await?? + { + Some(v) => v, + None => { + gum::debug!( target: LOG_TARGET, - core_idx = %core_idx, relay_parent = ?relay_parent, our_para = %config.para_id, - their_para = %scheduled_core.para_id, - "core is not assigned to our para. Keep going.", + "No validation data for para - does it exist at this relay-parent?", ); - } else { - // This does not work for elastic scaling, but it should be enough for single - // core parachains. If async backing runtime is available we later override - // the assumption based on the `para_backing_state` API response. - para_assumption = Some(core_assumption); - // Accumulate cores for building collation(s) outside the loop. - cores_to_build_on.push(CoreIndex(core_idx as u32)); - } - } + return Ok(()) + }, + }; - // Skip to next relay parent if there is no core assigned to us. - if cores_to_build_on.is_empty() { - continue + // We need to swap the parent-head data, but all other fields here will be correct. + validation_data.parent_head = parent_head; + + let claim_queue = request_claim_queue(relay_parent, ctx.sender()).await.await??; + + let session_index = + request_session_index_for_child(relay_parent, ctx.sender()).await.await??; + + let session_info = + self.session_info_cache.get(relay_parent, session_index, ctx.sender()).await?; + let collation = PreparedCollation { + collation, + relay_parent, + para_id: config.para_id, + validation_data, + validation_code_hash, + n_validators: session_info.n_validators, + core_index, + session_index, + }; + + construct_and_distribute_receipt( + collation, + config.key.clone(), + ctx.sender(), + result_sender, + &mut self.metrics, + session_info.v2_receipts, + &transpose_claim_queue(claim_queue), + ) + .await?; + + Ok(()) + } + + async fn handle_new_activation( + &mut self, + maybe_activated: Option, + ctx: &mut Context, + ) -> Result<()> { + let Some(config) = &self.config else { + return Ok(()); + }; + + let Some(relay_parent) = maybe_activated else { return Ok(()) }; + + // If there is no collation function provided, bail out early. + // Important: Lookahead collator and slot based collator do not use `CollatorFn`. + if config.collator.is_none() { + return Ok(()) } - // If at least one core is assigned to us, `para_assumption` is `Some`. - let Some(mut para_assumption) = para_assumption else { continue }; - - // If it is none it means that neither async backing or elastic scaling (which - // depends on it) are supported. We'll use the `para_assumption` we got from - // iterating cores. - if async_backing_params.is_some() { - // We are being very optimistic here, but one of the cores could pend availability some - // more block, ore even time out. - // For timeout assumption the collator can't really know because it doesn't receive - // bitfield gossip. - let para_backing_state = - request_para_backing_state(relay_parent, config.para_id, ctx.sender()) - .await - .await?? - .ok_or(crate::error::Error::MissingParaBackingState)?; - - // Override the assumption about the para's assigned cores. - para_assumption = if para_backing_state.pending_availability.is_empty() { - OccupiedCoreAssumption::Free - } else { - OccupiedCoreAssumption::Included - } + let para_id = config.para_id; + + let _timer = self.metrics.time_new_activation(); + + let session_index = + request_session_index_for_child(relay_parent, ctx.sender()).await.await??; + + let session_info = + self.session_info_cache.get(relay_parent, session_index, ctx.sender()).await?; + let n_validators = session_info.n_validators; + + let claim_queue = + ClaimQueueSnapshot::from(request_claim_queue(relay_parent, ctx.sender()).await.await??); + + let cores_to_build_on = claim_queue + .iter_claims_at_depth(0) + .filter_map(|(core_idx, para_id)| (para_id == config.para_id).then_some(core_idx)) + .collect::>(); + + // Nothing to do if no core assigned to us. + if cores_to_build_on.is_empty() { + return Ok(()) } - gum::debug!( - target: LOG_TARGET, - relay_parent = ?relay_parent, - our_para = %para_id, - ?para_assumption, - "Occupied core(s) assumption", - ); + // We are being very optimistic here, but one of the cores could be pending availability + // for some more blocks, or even time out. We assume all cores are being freed. let mut validation_data = match request_persisted_validation_data( relay_parent, para_id, - para_assumption, + // Just use included assumption always. If there are no pending candidates it's a + // no-op. + OccupiedCoreAssumption::Included, ctx.sender(), ) .await @@ -360,17 +308,20 @@ async fn handle_new_activations( our_para = %para_id, "validation data is not available", ); - continue + return Ok(()) }, }; - let validation_code_hash = match obtain_validation_code_hash_with_assumption( + let validation_code_hash = match request_validation_code_hash( relay_parent, para_id, - para_assumption, + // Just use included assumption always. If there are no pending candidates it's a + // no-op. + OccupiedCoreAssumption::Included, ctx.sender(), ) - .await? + .await + .await?? { Some(v) => v, None => { @@ -380,17 +331,19 @@ async fn handle_new_activations( our_para = %para_id, "validation code hash is not found.", ); - continue + return Ok(()) }, }; let task_config = config.clone(); - let metrics = metrics.clone(); + let metrics = self.metrics.clone(); let mut task_sender = ctx.sender().clone(); ctx.spawn( "chained-collation-builder", Box::pin(async move { + let transposed_claim_queue = transpose_claim_queue(claim_queue.0); + for core_index in cores_to_build_on { let collator_fn = match task_config.collator.as_ref() { Some(x) => x, @@ -411,7 +364,7 @@ async fn handle_new_activations( }; let parent_head = collation.head_data.clone(); - construct_and_distribute_receipt( + if let Err(err) = construct_and_distribute_receipt( PreparedCollation { collation, para_id, @@ -420,13 +373,24 @@ async fn handle_new_activations( validation_code_hash, n_validators, core_index, + session_index, }, task_config.key.clone(), &mut task_sender, result_sender, &metrics, + session_info.v2_receipts, + &transposed_claim_queue, ) - .await; + .await + { + gum::error!( + target: LOG_TARGET, + "Failed to construct and distribute collation: {}", + err + ); + return + } // Chain the collations. All else stays the same as we build the chained // collation on same relay parent. @@ -434,76 +398,64 @@ async fn handle_new_activations( } }), )?; - } - Ok(()) + Ok(()) + } } -#[overseer::contextbounds(CollationGeneration, prefix = self::overseer)] -async fn handle_submit_collation( - params: SubmitCollationParams, - config: &CollationGenerationConfig, - ctx: &mut Context, - metrics: &Metrics, -) -> crate::error::Result<()> { - let _timer = metrics.time_submit_collation(); +#[overseer::subsystem(CollationGeneration, error=SubsystemError, prefix=self::overseer)] +impl CollationGenerationSubsystem { + fn start(self, ctx: Context) -> SpawnedSubsystem { + let future = async move { + self.run(ctx).await; + Ok(()) + } + .boxed(); - let SubmitCollationParams { - relay_parent, - collation, - parent_head, - validation_code_hash, - result_sender, - core_index, - } = params; + SpawnedSubsystem { name: "collation-generation-subsystem", future } + } +} - let validators = request_validators(relay_parent, ctx.sender()).await.await??; - let n_validators = validators.len(); +#[derive(Clone)] +struct PerSessionInfo { + v2_receipts: bool, + n_validators: usize, +} - // We need to swap the parent-head data, but all other fields here will be correct. - let mut validation_data = match request_persisted_validation_data( - relay_parent, - config.para_id, - OccupiedCoreAssumption::TimedOut, - ctx.sender(), - ) - .await - .await?? - { - Some(v) => v, - None => { - gum::debug!( - target: LOG_TARGET, - relay_parent = ?relay_parent, - our_para = %config.para_id, - "No validation data for para - does it exist at this relay-parent?", - ); - return Ok(()) - }, - }; +struct SessionInfoCache(LruMap); - validation_data.parent_head = parent_head; +impl SessionInfoCache { + fn new() -> Self { + Self(LruMap::new(ByLength::new(2))) + } - let collation = PreparedCollation { - collation, - relay_parent, - para_id: config.para_id, - validation_data, - validation_code_hash, - n_validators, - core_index, - }; + async fn get>( + &mut self, + relay_parent: Hash, + session_index: SessionIndex, + sender: &mut Sender, + ) -> Result { + if let Some(info) = self.0.get(&session_index) { + return Ok(info.clone()) + } - construct_and_distribute_receipt( - collation, - config.key.clone(), - ctx.sender(), - result_sender, - metrics, - ) - .await; + let n_validators = + request_validators(relay_parent, &mut sender.clone()).await.await??.len(); - Ok(()) + let node_features = request_node_features(relay_parent, session_index, sender) + .await? + .unwrap_or(NodeFeatures::EMPTY); + + let info = PerSessionInfo { + v2_receipts: node_features + .get(FeatureIndex::CandidateReceiptV2 as usize) + .map(|b| *b) + .unwrap_or(false), + n_validators, + }; + self.0.insert(session_index, info); + Ok(self.0.get(&session_index).expect("Just inserted").clone()) + } } struct PreparedCollation { @@ -514,6 +466,7 @@ struct PreparedCollation { validation_code_hash: ValidationCodeHash, n_validators: usize, core_index: CoreIndex, + session_index: SessionIndex, } /// Takes a prepared collation, along with its context, and produces a candidate receipt @@ -524,7 +477,9 @@ async fn construct_and_distribute_receipt( sender: &mut impl overseer::CollationGenerationSenderTrait, result_sender: Option>, metrics: &Metrics, -) { + v2_receipts: bool, + transposed_claim_queue: &TransposedClaimQueue, +) -> Result<()> { let PreparedCollation { collation, para_id, @@ -533,6 +488,7 @@ async fn construct_and_distribute_receipt( validation_code_hash, n_validators, core_index, + session_index, } = collation; let persisted_validation_data_hash = validation_data.hash(); @@ -550,15 +506,7 @@ async fn construct_and_distribute_receipt( // As such, honest collators never produce an uncompressed PoV which starts with // a compression magic number, which would lead validators to reject the collation. if encoded_size > validation_data.max_pov_size as usize { - gum::debug!( - target: LOG_TARGET, - para_id = %para_id, - size = encoded_size, - max_size = validation_data.max_pov_size, - "PoV exceeded maximum size" - ); - - return + return Err(Error::POVSizeExceeded(encoded_size, validation_data.max_pov_size as usize)) } pov @@ -574,18 +522,7 @@ async fn construct_and_distribute_receipt( &validation_code_hash, ); - let erasure_root = match erasure_root(n_validators, validation_data, pov.clone()) { - Ok(erasure_root) => erasure_root, - Err(err) => { - gum::error!( - target: LOG_TARGET, - para_id = %para_id, - err = ?err, - "failed to calculate erasure root", - ); - return - }, - }; + let erasure_root = erasure_root(n_validators, validation_data, pov.clone())?; let commitments = CandidateCommitments { upward_messages: collation.upward_messages, @@ -596,35 +533,67 @@ async fn construct_and_distribute_receipt( hrmp_watermark: collation.hrmp_watermark, }; - let ccr = CandidateReceipt { - commitments_hash: commitments.hash(), - descriptor: CandidateDescriptor { - signature: key.sign(&signature_payload), - para_id, - relay_parent, - collator: key.public(), - persisted_validation_data_hash, - pov_hash, - erasure_root, - para_head: commitments.head_data.hash(), - validation_code_hash, + let receipt = if v2_receipts { + let ccr = CommittedCandidateReceiptV2 { + descriptor: CandidateDescriptorV2::new( + para_id, + relay_parent, + core_index, + session_index, + persisted_validation_data_hash, + pov_hash, + erasure_root, + commitments.head_data.hash(), + validation_code_hash, + ), + commitments, + }; + + ccr.check_core_index(&transposed_claim_queue) + .map_err(Error::CandidateReceiptCheck)?; + + ccr.to_plain() + } else { + if commitments.selected_core().is_some() { + gum::warn!( + target: LOG_TARGET, + ?pov_hash, + ?relay_parent, + para_id = %para_id, + "Candidate commitments contain UMP signal without v2 receipts being enabled.", + ); + } + CandidateReceipt { + commitments_hash: commitments.hash(), + descriptor: CandidateDescriptor { + signature: key.sign(&signature_payload), + para_id, + relay_parent, + collator: key.public(), + persisted_validation_data_hash, + pov_hash, + erasure_root, + para_head: commitments.head_data.hash(), + validation_code_hash, + } + .into(), } - .into(), }; gum::debug!( target: LOG_TARGET, - candidate_hash = ?ccr.hash(), + candidate_hash = ?receipt.hash(), ?pov_hash, ?relay_parent, para_id = %para_id, + ?core_index, "candidate is generated", ); metrics.on_collation_generated(); sender .send_message(CollatorProtocolMessage::DistributeCollation { - candidate_receipt: ccr, + candidate_receipt: receipt, parent_head_data_hash, pov, parent_head_data, @@ -632,40 +601,15 @@ async fn construct_and_distribute_receipt( core_index, }) .await; -} -async fn obtain_validation_code_hash_with_assumption( - relay_parent: Hash, - para_id: ParaId, - assumption: OccupiedCoreAssumption, - sender: &mut impl overseer::CollationGenerationSenderTrait, -) -> crate::error::Result> { - match request_validation_code_hash(relay_parent, para_id, assumption, sender) - .await - .await? - { - Ok(Some(v)) => Ok(Some(v)), - Ok(None) => Ok(None), - Err(RuntimeApiError::NotSupported { .. }) => { - match request_validation_code(relay_parent, para_id, assumption, sender).await.await? { - Ok(Some(v)) => Ok(Some(v.hash())), - Ok(None) => Ok(None), - Err(e) => { - // We assume that the `validation_code` API is always available, so any error - // is unexpected. - Err(e.into()) - }, - } - }, - Err(e @ RuntimeApiError::Execution { .. }) => Err(e.into()), - } + Ok(()) } fn erasure_root( n_validators: usize, persisted_validation: PersistedValidationData, pov: PoV, -) -> crate::error::Result { +) -> Result { let available_data = AvailableData { validation_data: persisted_validation, pov: Arc::new(pov) }; diff --git a/polkadot/node/collation-generation/src/metrics.rs b/polkadot/node/collation-generation/src/metrics.rs index c7690ec82c4f..80566dcd6fa1 100644 --- a/polkadot/node/collation-generation/src/metrics.rs +++ b/polkadot/node/collation-generation/src/metrics.rs @@ -19,9 +19,7 @@ use polkadot_node_subsystem_util::metrics::{self, prometheus}; #[derive(Clone)] pub(crate) struct MetricsInner { pub(crate) collations_generated_total: prometheus::Counter, - pub(crate) new_activations_overall: prometheus::Histogram, - pub(crate) new_activations_per_relay_parent: prometheus::Histogram, - pub(crate) new_activations_per_availability_core: prometheus::Histogram, + pub(crate) new_activation: prometheus::Histogram, pub(crate) submit_collation: prometheus::Histogram, } @@ -37,26 +35,8 @@ impl Metrics { } /// Provide a timer for new activations which updates on drop. - pub fn time_new_activations(&self) -> Option { - self.0.as_ref().map(|metrics| metrics.new_activations_overall.start_timer()) - } - - /// Provide a timer per relay parents which updates on drop. - pub fn time_new_activations_relay_parent( - &self, - ) -> Option { - self.0 - .as_ref() - .map(|metrics| metrics.new_activations_per_relay_parent.start_timer()) - } - - /// Provide a timer per availability core which updates on drop. - pub fn time_new_activations_availability_core( - &self, - ) -> Option { - self.0 - .as_ref() - .map(|metrics| metrics.new_activations_per_availability_core.start_timer()) + pub fn time_new_activation(&self) -> Option { + self.0.as_ref().map(|metrics| metrics.new_activation.start_timer()) } /// Provide a timer for submitting a collation which updates on drop. @@ -71,44 +51,22 @@ impl metrics::Metrics for Metrics { collations_generated_total: prometheus::register( prometheus::Counter::new( "polkadot_parachain_collations_generated_total", - "Number of collations generated." - )?, - registry, - )?, - new_activations_overall: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_collation_generation_new_activations", - "Time spent within fn handle_new_activations", - ) - )?, - registry, - )?, - new_activations_per_relay_parent: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_collation_generation_per_relay_parent", - "Time spent handling a particular relay parent within fn handle_new_activations" - ) + "Number of collations generated.", )?, registry, )?, - new_activations_per_availability_core: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_collation_generation_per_availability_core", - "Time spent handling a particular availability core for a relay parent in fn handle_new_activations", - ) - )?, + new_activation: prometheus::register( + prometheus::Histogram::with_opts(prometheus::HistogramOpts::new( + "polkadot_parachain_collation_generation_new_activations", + "Time spent within fn handle_new_activation", + ))?, registry, )?, submit_collation: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_collation_generation_submit_collation", - "Time spent preparing and submitting a collation to the network protocol", - ) - )?, + prometheus::Histogram::with_opts(prometheus::HistogramOpts::new( + "polkadot_parachain_collation_generation_submit_collation", + "Time spent preparing and submitting a collation to the network protocol", + ))?, registry, )?, }; diff --git a/polkadot/node/collation-generation/src/tests.rs b/polkadot/node/collation-generation/src/tests.rs index 78b35fde0ea2..f81c14cdf8f9 100644 --- a/polkadot/node/collation-generation/src/tests.rs +++ b/polkadot/node/collation-generation/src/tests.rs @@ -17,26 +17,20 @@ use super::*; use assert_matches::assert_matches; use futures::{ - lock::Mutex, task::{Context as FuturesContext, Poll}, - Future, + Future, StreamExt, }; use polkadot_node_primitives::{BlockData, Collation, CollationResult, MaybeCompressedPoV, PoV}; use polkadot_node_subsystem::{ - errors::RuntimeApiError, messages::{AllMessages, RuntimeApiMessage, RuntimeApiRequest}, ActivatedLeaf, }; -use polkadot_node_subsystem_test_helpers::{subsystem_test_harness, TestSubsystemContextHandle}; +use polkadot_node_subsystem_test_helpers::TestSubsystemContextHandle; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::{ - vstaging::async_backing::{BackingState, CandidatePendingAvailability}, - AsyncBackingParams, BlockNumber, CollatorPair, HeadData, PersistedValidationData, - ScheduledCore, ValidationCode, -}; -use polkadot_primitives_test_helpers::{ - dummy_candidate_descriptor_v2, dummy_hash, dummy_head_data, dummy_validator, make_candidate, + node_features, vstaging::CandidateDescriptorVersion, CollatorPair, PersistedValidationData, }; +use polkadot_primitives_test_helpers::dummy_head_data; use rstest::rstest; use sp_keyring::sr25519::Keyring as Sr25519Keyring; use std::{ @@ -63,7 +57,7 @@ fn test_harness>(test: impl FnOnce(VirtualOv async move { let mut virtual_overseer = test_fut.await; // Ensure we have handled all responses. - if let Ok(Some(msg)) = virtual_overseer.rx.try_next() { + if let Some(msg) = virtual_overseer.rx.next().timeout(TIMEOUT).await { panic!("Did not handle all responses: {:?}", msg); } // Conclude. @@ -85,20 +79,6 @@ fn test_collation() -> Collation { } } -fn test_collation_compressed() -> Collation { - let mut collation = test_collation(); - let compressed = collation.proof_of_validity.clone().into_compressed(); - collation.proof_of_validity = MaybeCompressedPoV::Compressed(compressed); - collation -} - -fn test_validation_data() -> PersistedValidationData { - let mut persisted_validation_data = PersistedValidationData::default(); - persisted_validation_data.max_pov_size = 1024; - persisted_validation_data -} - -// Box + Unpin + Send struct TestCollator; impl Future for TestCollator { @@ -137,531 +117,11 @@ fn test_config_no_collator>(para_id: Id) -> CollationGeneration } } -fn scheduled_core_for>(para_id: Id) -> ScheduledCore { - ScheduledCore { para_id: para_id.into(), collator: None } -} - -fn dummy_candidate_pending_availability( - para_id: ParaId, - candidate_relay_parent: Hash, - relay_parent_number: BlockNumber, -) -> CandidatePendingAvailability { - let (candidate, _pvd) = make_candidate( - candidate_relay_parent, - relay_parent_number, - para_id, - dummy_head_data(), - HeadData(vec![1]), - ValidationCode(vec![1, 2, 3]).hash(), - ); - let candidate_hash = candidate.hash(); - - CandidatePendingAvailability { - candidate_hash, - descriptor: candidate.descriptor, - commitments: candidate.commitments, - relay_parent_number, - max_pov_size: 5 * 1024 * 1024, - } -} - -fn dummy_backing_state(pending_availability: Vec) -> BackingState { - let constraints = helpers::dummy_constraints( - 0, - vec![0], - dummy_head_data(), - ValidationCodeHash::from(Hash::repeat_byte(42)), - ); - - BackingState { constraints, pending_availability } -} - -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn requests_availability_per_relay_parent(#[case] runtime_version: u32) { - let activated_hashes: Vec = - vec![[1; 32].into(), [4; 32].into(), [9; 32].into(), [16; 32].into()]; - - let requested_availability_cores = Arc::new(Mutex::new(Vec::new())); - - let overseer_requested_availability_cores = requested_availability_cores.clone(); - let overseer = |mut handle: TestSubsystemContextHandle| async move { - loop { - match handle.try_recv().await { - None => break, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::AvailabilityCores(tx)))) => { - overseer_requested_availability_cores.lock().await.push(hash); - tx.send(Ok(vec![])).unwrap(); - } - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request(_hash, RuntimeApiRequest::Validators(tx)))) => { - tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); - } - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::AsyncBackingParams( - tx, - ), - ))) => { - tx.send(Err(RuntimeApiError::NotSupported { runtime_api_name: "doesnt_matter" })).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Version(tx), - ))) => { - tx.send(Ok(runtime_version)).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ClaimQueue(tx), - ))) if runtime_version >= RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT => { - tx.send(Ok(BTreeMap::new())).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ParaBackingState(_para_id, tx), - ))) => { - tx.send(Ok(Some(dummy_backing_state(vec![])))).unwrap(); - }, - Some(msg) => panic!("didn't expect any other overseer requests given no availability cores; got {:?}", msg), - } - } - }; - - let subsystem_activated_hashes = activated_hashes.clone(); - subsystem_test_harness(overseer, |mut ctx| async move { - handle_new_activations( - Arc::new(test_config(123u32)), - subsystem_activated_hashes, - &mut ctx, - Metrics(None), - ) - .await - .unwrap(); - }); - - let mut requested_availability_cores = Arc::try_unwrap(requested_availability_cores) - .expect("overseer should have shut down by now") - .into_inner(); - requested_availability_cores.sort(); - - assert_eq!(requested_availability_cores, activated_hashes); -} - -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn requests_validation_data_for_scheduled_matches(#[case] runtime_version: u32) { - let activated_hashes: Vec = vec![ - Hash::repeat_byte(1), - Hash::repeat_byte(4), - Hash::repeat_byte(9), - Hash::repeat_byte(16), - ]; - - let requested_validation_data = Arc::new(Mutex::new(Vec::new())); - - let overseer_requested_validation_data = requested_validation_data.clone(); - let overseer = |mut handle: TestSubsystemContextHandle| async move { - loop { - match handle.try_recv().await { - None => break, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::AvailabilityCores(tx), - ))) => { - tx.send(Ok(vec![ - CoreState::Free, - // this is weird, see explanation below - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 4) as u32, - )), - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 5) as u32, - )), - ])) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::PersistedValidationData( - _para_id, - _occupied_core_assumption, - tx, - ), - ))) => { - overseer_requested_validation_data.lock().await.push(hash); - tx.send(Ok(None)).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Validators(tx), - ))) => { - tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::AsyncBackingParams(tx), - ))) => { - tx.send(Err(RuntimeApiError::NotSupported { - runtime_api_name: "doesnt_matter", - })) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Version(tx), - ))) => { - tx.send(Ok(runtime_version)).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ClaimQueue(tx), - ))) if runtime_version >= RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT => { - tx.send(Ok(BTreeMap::new())).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ParaBackingState(_para_id, tx), - ))) => { - tx.send(Ok(Some(dummy_backing_state(vec![])))).unwrap(); - }, - Some(msg) => { - panic!("didn't expect any other overseer requests; got {:?}", msg) - }, - } - } - }; - - subsystem_test_harness(overseer, |mut ctx| async move { - handle_new_activations( - Arc::new(test_config(16)), - activated_hashes, - &mut ctx, - Metrics(None), - ) - .await - .unwrap(); - }); - - let requested_validation_data = Arc::try_unwrap(requested_validation_data) - .expect("overseer should have shut down by now") - .into_inner(); - - // the only activated hash should be from the 4 hash: - // each activated hash generates two scheduled cores: one with its value * 4, one with its value - // * 5 given that the test configuration has a `para_id` of 16, there's only one way to get that - // value: with the 4 hash. - assert_eq!(requested_validation_data, vec![[4; 32].into()]); -} - -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn sends_distribute_collation_message(#[case] runtime_version: u32) { - let activated_hashes: Vec = vec![ - Hash::repeat_byte(1), - Hash::repeat_byte(4), - Hash::repeat_byte(9), - Hash::repeat_byte(16), - ]; - - // empty vec doesn't allocate on the heap, so it's ok we throw it away - let to_collator_protocol = Arc::new(Mutex::new(Vec::new())); - let inner_to_collator_protocol = to_collator_protocol.clone(); - - let overseer = |mut handle: TestSubsystemContextHandle| async move { - loop { - match handle.try_recv().await { - None => break, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::AvailabilityCores(tx), - ))) => { - tx.send(Ok(vec![ - CoreState::Free, - // this is weird, see explanation below - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 4) as u32, - )), - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 5) as u32, - )), - ])) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::PersistedValidationData( - _para_id, - _occupied_core_assumption, - tx, - ), - ))) => { - tx.send(Ok(Some(test_validation_data()))).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Validators(tx), - ))) => { - tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ValidationCodeHash( - _para_id, - OccupiedCoreAssumption::Free, - tx, - ), - ))) => { - tx.send(Ok(Some(ValidationCode(vec![1, 2, 3]).hash()))).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::AsyncBackingParams(tx), - ))) => { - tx.send(Err(RuntimeApiError::NotSupported { - runtime_api_name: "doesnt_matter", - })) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Version(tx), - ))) => { - tx.send(Ok(runtime_version)).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ClaimQueue(tx), - ))) if runtime_version >= RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT => { - tx.send(Ok(BTreeMap::new())).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ParaBackingState(_para_id, tx), - ))) => { - tx.send(Ok(Some(dummy_backing_state(vec![])))).unwrap(); - }, - Some(msg @ AllMessages::CollatorProtocol(_)) => { - inner_to_collator_protocol.lock().await.push(msg); - }, - Some(msg) => { - panic!("didn't expect any other overseer requests; got {:?}", msg) - }, - } - } - }; - - let config = Arc::new(test_config(16)); - let subsystem_config = config.clone(); - - subsystem_test_harness(overseer, |mut ctx| async move { - handle_new_activations(subsystem_config, activated_hashes, &mut ctx, Metrics(None)) - .await - .unwrap(); - }); - - let mut to_collator_protocol = Arc::try_unwrap(to_collator_protocol) - .expect("subsystem should have shut down by now") - .into_inner(); - - // we expect a single message to be sent, containing a candidate receipt. - // we don't care too much about the `commitments_hash` right now, but let's ensure that we've - // calculated the correct descriptor - let expect_pov_hash = test_collation_compressed().proof_of_validity.into_compressed().hash(); - let expect_validation_data_hash = test_validation_data().hash(); - let expect_relay_parent = Hash::repeat_byte(4); - let expect_validation_code_hash = ValidationCode(vec![1, 2, 3]).hash(); - let expect_payload = collator_signature_payload( - &expect_relay_parent, - &config.para_id, - &expect_validation_data_hash, - &expect_pov_hash, - &expect_validation_code_hash, - ); - let expect_descriptor = CandidateDescriptor { - signature: config.key.sign(&expect_payload), - para_id: config.para_id, - relay_parent: expect_relay_parent, - collator: config.key.public(), - persisted_validation_data_hash: expect_validation_data_hash, - pov_hash: expect_pov_hash, - erasure_root: dummy_hash(), // this isn't something we're checking right now - para_head: test_collation().head_data.hash(), - validation_code_hash: expect_validation_code_hash, - }; - - assert_eq!(to_collator_protocol.len(), 1); - match AllMessages::from(to_collator_protocol.pop().unwrap()) { - AllMessages::CollatorProtocol(CollatorProtocolMessage::DistributeCollation { - candidate_receipt, - .. - }) => { - let CandidateReceipt { descriptor, .. } = candidate_receipt; - // signature generation is non-deterministic, so we can't just assert that the - // expected descriptor is correct. What we can do is validate that the produced - // descriptor has a valid signature, then just copy in the generated signature - // and check the rest of the fields for equality. - assert!(CollatorPair::verify( - &descriptor.signature().unwrap(), - &collator_signature_payload( - &descriptor.relay_parent(), - &descriptor.para_id(), - &descriptor.persisted_validation_data_hash(), - &descriptor.pov_hash(), - &descriptor.validation_code_hash(), - ) - .as_ref(), - &descriptor.collator().unwrap(), - )); - let expect_descriptor = { - let mut expect_descriptor = expect_descriptor; - expect_descriptor.signature = descriptor.signature().clone().unwrap(); - expect_descriptor.erasure_root = descriptor.erasure_root(); - expect_descriptor.into() - }; - assert_eq!(descriptor, expect_descriptor); - }, - _ => panic!("received wrong message type"), - } -} - -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn fallback_when_no_validation_code_hash_api(#[case] runtime_version: u32) { - // This is a variant of the above test, but with the validation code hash API disabled. - - let activated_hashes: Vec = vec![ - Hash::repeat_byte(1), - Hash::repeat_byte(4), - Hash::repeat_byte(9), - Hash::repeat_byte(16), - ]; - - // empty vec doesn't allocate on the heap, so it's ok we throw it away - let to_collator_protocol = Arc::new(Mutex::new(Vec::new())); - let inner_to_collator_protocol = to_collator_protocol.clone(); - - let overseer = |mut handle: TestSubsystemContextHandle| async move { - loop { - match handle.try_recv().await { - None => break, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::AvailabilityCores(tx), - ))) => { - tx.send(Ok(vec![ - CoreState::Free, - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 4) as u32, - )), - CoreState::Scheduled(scheduled_core_for( - (hash.as_fixed_bytes()[0] * 5) as u32, - )), - ])) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::PersistedValidationData( - _para_id, - _occupied_core_assumption, - tx, - ), - ))) => { - tx.send(Ok(Some(test_validation_data()))).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Validators(tx), - ))) => { - tx.send(Ok(vec![dummy_validator(); 3])).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ValidationCodeHash( - _para_id, - OccupiedCoreAssumption::Free, - tx, - ), - ))) => { - tx.send(Err(RuntimeApiError::NotSupported { - runtime_api_name: "validation_code_hash", - })) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ValidationCode(_para_id, OccupiedCoreAssumption::Free, tx), - ))) => { - tx.send(Ok(Some(ValidationCode(vec![1, 2, 3])))).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::AsyncBackingParams(tx), - ))) => { - tx.send(Err(RuntimeApiError::NotSupported { - runtime_api_name: "doesnt_matter", - })) - .unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::Version(tx), - ))) => { - tx.send(Ok(runtime_version)).unwrap(); - }, - Some(msg @ AllMessages::CollatorProtocol(_)) => { - inner_to_collator_protocol.lock().await.push(msg); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ClaimQueue(tx), - ))) if runtime_version >= RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT => { - tx.send(Ok(Default::default())).unwrap(); - }, - Some(AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _hash, - RuntimeApiRequest::ParaBackingState(_para_id, tx), - ))) => { - tx.send(Ok(Some(dummy_backing_state(vec![])))).unwrap(); - }, - Some(msg) => { - panic!("didn't expect any other overseer requests; got {:?}", msg) - }, - } - } - }; - - let config = Arc::new(test_config(16u32)); - let subsystem_config = config.clone(); - - // empty vec doesn't allocate on the heap, so it's ok we throw it away - subsystem_test_harness(overseer, |mut ctx| async move { - handle_new_activations(subsystem_config, activated_hashes, &mut ctx, Metrics(None)) - .await - .unwrap(); - }); - - let to_collator_protocol = Arc::try_unwrap(to_collator_protocol) - .expect("subsystem should have shut down by now") - .into_inner(); - - let expect_validation_code_hash = ValidationCode(vec![1, 2, 3]).hash(); - - assert_eq!(to_collator_protocol.len(), 1); - match &to_collator_protocol[0] { - AllMessages::CollatorProtocol(CollatorProtocolMessage::DistributeCollation { - candidate_receipt, - .. - }) => { - let CandidateReceipt { descriptor, .. } = candidate_receipt; - assert_eq!(expect_validation_code_hash, descriptor.validation_code_hash()); - }, - _ => panic!("received wrong message type"), - } +fn node_features_with_v2_enabled() -> NodeFeatures { + let mut node_features = NodeFeatures::new(); + node_features.resize(node_features::FeatureIndex::CandidateReceiptV2 as usize + 1, false); + node_features.set(node_features::FeatureIndex::CandidateReceiptV2 as u8 as usize, true); + node_features } #[test] @@ -717,31 +177,15 @@ fn submit_collation_leads_to_distribution() { }) .await; - assert_matches!( - overseer_recv(&mut virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(rp, RuntimeApiRequest::Validators(tx))) => { - assert_eq!(rp, relay_parent); - let _ = tx.send(Ok(vec![ - Sr25519Keyring::Alice.public().into(), - Sr25519Keyring::Bob.public().into(), - Sr25519Keyring::Charlie.public().into(), - ])); - } - ); - - assert_matches!( - overseer_recv(&mut virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(rp, RuntimeApiRequest::PersistedValidationData(id, a, tx))) => { - assert_eq!(rp, relay_parent); - assert_eq!(id, para_id); - assert_eq!(a, OccupiedCoreAssumption::TimedOut); - - // Candidate receipt should be constructed with the real parent head. - let mut pvd = expected_pvd.clone(); - pvd.parent_head = vec![4, 5, 6].into(); - let _ = tx.send(Ok(Some(pvd))); - } - ); + helpers::handle_runtime_calls_on_submit_collation( + &mut virtual_overseer, + relay_parent, + para_id, + expected_pvd.clone(), + NodeFeatures::EMPTY, + Default::default(), + ) + .await; assert_matches!( overseer_recv(&mut virtual_overseer).await, @@ -762,78 +206,16 @@ fn submit_collation_leads_to_distribution() { }); } -// There is one core in `Occupied` state and async backing is enabled. On new head activation -// `CollationGeneration` should produce and distribute a new collation. -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn distribute_collation_for_occupied_core_with_async_backing_enabled(#[case] runtime_version: u32) { - let activated_hash: Hash = [1; 32].into(); - let para_id = ParaId::from(5); - - // One core, in occupied state. The data in `CoreState` and `ClaimQueue` should match. - let cores: Vec = - vec![CoreState::Occupied(polkadot_primitives::vstaging::OccupiedCore { - next_up_on_available: Some(ScheduledCore { para_id, collator: None }), - occupied_since: 1, - time_out_at: 10, - next_up_on_time_out: Some(ScheduledCore { para_id, collator: None }), - availability: Default::default(), // doesn't matter - group_responsible: polkadot_primitives::GroupIndex(0), - candidate_hash: Default::default(), - candidate_descriptor: dummy_candidate_descriptor_v2(dummy_hash()), - })]; - let claim_queue = BTreeMap::from([(CoreIndex::from(0), VecDeque::from([para_id]))]).into(); - - test_harness(|mut virtual_overseer| async move { - helpers::initialize_collator(&mut virtual_overseer, para_id).await; - helpers::activate_new_head(&mut virtual_overseer, activated_hash).await; - - let pending_availability = - vec![dummy_candidate_pending_availability(para_id, activated_hash, 1)]; - helpers::handle_runtime_calls_on_new_head_activation( - &mut virtual_overseer, - activated_hash, - AsyncBackingParams { max_candidate_depth: 1, allowed_ancestry_len: 1 }, - cores, - runtime_version, - claim_queue, - ) - .await; - helpers::handle_cores_processing_for_a_leaf( - &mut virtual_overseer, - activated_hash, - para_id, - // `CoreState` is `Occupied` => `OccupiedCoreAssumption` is `Included` - OccupiedCoreAssumption::Included, - 1, - pending_availability, - runtime_version, - ) - .await; - - virtual_overseer - }); -} - #[test] -fn distribute_collation_for_occupied_core_pre_async_backing() { +fn distribute_collation_only_for_assigned_para_id_at_offset_0() { let activated_hash: Hash = [1; 32].into(); let para_id = ParaId::from(5); - let total_cores = 3; - - // Use runtime version before async backing - let runtime_version = RuntimeApiRequest::ASYNC_BACKING_STATE_RUNTIME_REQUIREMENT - 1; - let cores = (0..total_cores) + let claim_queue = (0..=5) .into_iter() - .map(|_idx| CoreState::Scheduled(ScheduledCore { para_id, collator: None })) - .collect::>(); - - let claim_queue = cores - .iter() - .enumerate() - .map(|(idx, _core)| (CoreIndex::from(idx as u32), VecDeque::from([para_id]))) + // Set all cores assigned to para_id 5 at the second and third depths. This shouldn't + // matter. + .map(|idx| (CoreIndex(idx), VecDeque::from([ParaId::from(idx), para_id, para_id]))) .collect::>(); test_harness(|mut virtual_overseer| async move { @@ -842,10 +224,8 @@ fn distribute_collation_for_occupied_core_pre_async_backing() { helpers::handle_runtime_calls_on_new_head_activation( &mut virtual_overseer, activated_hash, - AsyncBackingParams { max_candidate_depth: 1, allowed_ancestry_len: 1 }, - cores, - runtime_version, claim_queue, + NodeFeatures::EMPTY, ) .await; @@ -853,11 +233,7 @@ fn distribute_collation_for_occupied_core_pre_async_backing() { &mut virtual_overseer, activated_hash, para_id, - // `CoreState` is `Free` => `OccupiedCoreAssumption` is `Free` - OccupiedCoreAssumption::Free, - total_cores, - vec![], - runtime_version, + vec![5], // Only core 5 is assigned to paraid 5. ) .await; @@ -865,48 +241,22 @@ fn distribute_collation_for_occupied_core_pre_async_backing() { }); } -// There are variable number of cores of cores in `Occupied` state and async backing is enabled. -// On new head activation `CollationGeneration` should produce and distribute a new collation -// with proper assumption about the para candidate chain availability at next block. +// There are variable number of cores assigned to the paraid. +// On new head activation `CollationGeneration` should produce and distribute the right number of +// new collations with proper assumption about the para candidate chain availability at next block. #[rstest] #[case(0)] #[case(1)] #[case(2)] -fn distribute_collation_for_occupied_cores_with_async_backing_enabled_and_elastic_scaling( - #[case] candidates_pending_avail: u32, -) { +#[case(3)] +fn distribute_collation_with_elastic_scaling(#[case] total_cores: u32) { let activated_hash: Hash = [1; 32].into(); let para_id = ParaId::from(5); - // Using latest runtime with the fancy claim queue exposed. - let runtime_version = RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT; - let cores = (0..3) + let claim_queue = (0..total_cores) .into_iter() - .map(|idx| { - CoreState::Occupied(polkadot_primitives::vstaging::OccupiedCore { - next_up_on_available: Some(ScheduledCore { para_id, collator: None }), - occupied_since: 0, - time_out_at: 10, - next_up_on_time_out: Some(ScheduledCore { para_id, collator: None }), - availability: Default::default(), // doesn't matter - group_responsible: polkadot_primitives::GroupIndex(idx as u32), - candidate_hash: Default::default(), - candidate_descriptor: dummy_candidate_descriptor_v2(dummy_hash()), - }) - }) - .collect::>(); - - let pending_availability = (0..candidates_pending_avail) - .into_iter() - .map(|_idx| dummy_candidate_pending_availability(para_id, activated_hash, 0)) - .collect::>(); - - let claim_queue = cores - .iter() - .enumerate() - .map(|(idx, _core)| (CoreIndex::from(idx as u32), VecDeque::from([para_id]))) + .map(|idx| (CoreIndex(idx), VecDeque::from([para_id]))) .collect::>(); - let total_cores = cores.len(); test_harness(|mut virtual_overseer| async move { helpers::initialize_collator(&mut virtual_overseer, para_id).await; @@ -914,10 +264,8 @@ fn distribute_collation_for_occupied_cores_with_async_backing_enabled_and_elasti helpers::handle_runtime_calls_on_new_head_activation( &mut virtual_overseer, activated_hash, - AsyncBackingParams { max_candidate_depth: 1, allowed_ancestry_len: 1 }, - cores, - runtime_version, claim_queue, + NodeFeatures::EMPTY, ) .await; @@ -925,16 +273,7 @@ fn distribute_collation_for_occupied_cores_with_async_backing_enabled_and_elasti &mut virtual_overseer, activated_hash, para_id, - // if at least 1 cores is occupied => `OccupiedCoreAssumption` is `Included` - // else assumption is `Free`. - if candidates_pending_avail > 0 { - OccupiedCoreAssumption::Included - } else { - OccupiedCoreAssumption::Free - }, - total_cores, - pending_availability, - runtime_version, + (0..total_cores).collect(), ) .await; @@ -942,136 +281,128 @@ fn distribute_collation_for_occupied_cores_with_async_backing_enabled_and_elasti }); } -// There are variable number of cores of cores in `Free` state and async backing is enabled. -// On new head activation `CollationGeneration` should produce and distribute a new collation -// with proper assumption about the para candidate chain availability at next block. #[rstest] -#[case(0)] -#[case(1)] -#[case(2)] -fn distribute_collation_for_free_cores_with_async_backing_enabled_and_elastic_scaling( - #[case] total_cores: usize, -) { - let activated_hash: Hash = [1; 32].into(); +#[case(true)] +#[case(false)] +fn test_candidate_receipt_versioning(#[case] v2_receipts: bool) { + let relay_parent = Hash::repeat_byte(0); + let validation_code_hash = ValidationCodeHash::from(Hash::repeat_byte(42)); + let parent_head = dummy_head_data(); let para_id = ParaId::from(5); - // Using latest runtime with the fancy claim queue exposed. - let runtime_version = RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT; - - let cores = (0..total_cores) - .into_iter() - .map(|_idx| CoreState::Scheduled(ScheduledCore { para_id, collator: None })) - .collect::>(); - - let claim_queue = cores - .iter() - .enumerate() - .map(|(idx, _core)| (CoreIndex::from(idx as u32), VecDeque::from([para_id]))) - .collect::>(); + let expected_pvd = PersistedValidationData { + parent_head: parent_head.clone(), + relay_parent_number: 10, + relay_parent_storage_root: Hash::repeat_byte(1), + max_pov_size: 1024, + }; + let node_features = + if v2_receipts { node_features_with_v2_enabled() } else { NodeFeatures::EMPTY }; + let expected_descriptor_version = + if v2_receipts { CandidateDescriptorVersion::V2 } else { CandidateDescriptorVersion::V1 }; test_harness(|mut virtual_overseer| async move { - helpers::initialize_collator(&mut virtual_overseer, para_id).await; - helpers::activate_new_head(&mut virtual_overseer, activated_hash).await; - helpers::handle_runtime_calls_on_new_head_activation( - &mut virtual_overseer, - activated_hash, - AsyncBackingParams { max_candidate_depth: 1, allowed_ancestry_len: 1 }, - cores, - runtime_version, - claim_queue, - ) - .await; + virtual_overseer + .send(FromOrchestra::Communication { + msg: CollationGenerationMessage::Initialize(test_config_no_collator(para_id)), + }) + .await; - helpers::handle_cores_processing_for_a_leaf( + virtual_overseer + .send(FromOrchestra::Communication { + msg: CollationGenerationMessage::SubmitCollation(SubmitCollationParams { + relay_parent, + collation: test_collation(), + parent_head: dummy_head_data(), + validation_code_hash, + result_sender: None, + core_index: CoreIndex(0), + }), + }) + .await; + + helpers::handle_runtime_calls_on_submit_collation( &mut virtual_overseer, - activated_hash, + relay_parent, para_id, - // `CoreState` is `Free` => `OccupiedCoreAssumption` is `Free` - OccupiedCoreAssumption::Free, - total_cores, - vec![], - runtime_version, + expected_pvd.clone(), + node_features, + [(CoreIndex(0), [para_id].into_iter().collect())].into_iter().collect(), ) .await; + assert_matches!( + overseer_recv(&mut virtual_overseer).await, + AllMessages::CollatorProtocol(CollatorProtocolMessage::DistributeCollation { + candidate_receipt, + parent_head_data_hash, + .. + }) => { + let CandidateReceipt { descriptor, .. } = candidate_receipt; + assert_eq!(parent_head_data_hash, parent_head.hash()); + assert_eq!(descriptor.persisted_validation_data_hash(), expected_pvd.hash()); + assert_eq!(descriptor.para_head(), dummy_head_data().hash()); + assert_eq!(descriptor.validation_code_hash(), validation_code_hash); + // Check that the right version was indeed used. + assert_eq!(descriptor.version(), expected_descriptor_version); + } + ); + virtual_overseer }); } -// There is one core in `Occupied` state and async backing is disabled. On new head activation -// no new collation should be generated. -#[rstest] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT - 1)] -#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] -fn no_collation_is_distributed_for_occupied_core_with_async_backing_disabled( - #[case] runtime_version: u32, -) { - let activated_hash: Hash = [1; 32].into(); +#[test] +fn v2_receipts_failed_core_index_check() { + let relay_parent = Hash::repeat_byte(0); + let validation_code_hash = ValidationCodeHash::from(Hash::repeat_byte(42)); + let parent_head = dummy_head_data(); let para_id = ParaId::from(5); - - // One core, in occupied state. The data in `CoreState` and `ClaimQueue` should match. - let cores: Vec = - vec![CoreState::Occupied(polkadot_primitives::vstaging::OccupiedCore { - next_up_on_available: Some(ScheduledCore { para_id, collator: None }), - occupied_since: 1, - time_out_at: 10, - next_up_on_time_out: Some(ScheduledCore { para_id, collator: None }), - availability: Default::default(), // doesn't matter - group_responsible: polkadot_primitives::GroupIndex(0), - candidate_hash: Default::default(), - candidate_descriptor: dummy_candidate_descriptor_v2(dummy_hash()), - })]; - let claim_queue = BTreeMap::from([(CoreIndex::from(0), VecDeque::from([para_id]))]).into(); + let expected_pvd = PersistedValidationData { + parent_head: parent_head.clone(), + relay_parent_number: 10, + relay_parent_storage_root: Hash::repeat_byte(1), + max_pov_size: 1024, + }; test_harness(|mut virtual_overseer| async move { - helpers::initialize_collator(&mut virtual_overseer, para_id).await; - helpers::activate_new_head(&mut virtual_overseer, activated_hash).await; + virtual_overseer + .send(FromOrchestra::Communication { + msg: CollationGenerationMessage::Initialize(test_config_no_collator(para_id)), + }) + .await; - helpers::handle_runtime_calls_on_new_head_activation( + virtual_overseer + .send(FromOrchestra::Communication { + msg: CollationGenerationMessage::SubmitCollation(SubmitCollationParams { + relay_parent, + collation: test_collation(), + parent_head: dummy_head_data(), + validation_code_hash, + result_sender: None, + core_index: CoreIndex(0), + }), + }) + .await; + + helpers::handle_runtime_calls_on_submit_collation( &mut virtual_overseer, - activated_hash, - AsyncBackingParams { max_candidate_depth: 0, allowed_ancestry_len: 0 }, - cores, - runtime_version, - claim_queue, + relay_parent, + para_id, + expected_pvd.clone(), + node_features_with_v2_enabled(), + // Core index commitment is on core 0 but don't add any assignment for core 0. + [(CoreIndex(1), [para_id].into_iter().collect())].into_iter().collect(), ) .await; + // No collation is distributed. + virtual_overseer }); } - mod helpers { - use polkadot_primitives::{ - async_backing::{Constraints, InboundHrmpLimitations}, - BlockNumber, - }; - use super::*; - - // A set for dummy constraints for `ParaBackingState`` - pub(crate) fn dummy_constraints( - min_relay_parent_number: BlockNumber, - valid_watermarks: Vec, - required_parent: HeadData, - validation_code_hash: ValidationCodeHash, - ) -> Constraints { - Constraints { - min_relay_parent_number, - max_pov_size: 5 * 1024 * 1024, - max_code_size: 1_000_000, - ump_remaining: 10, - ump_remaining_bytes: 1_000, - max_ump_num_per_candidate: 10, - dmp_remaining_messages: vec![], - hrmp_inbound: InboundHrmpLimitations { valid_watermarks }, - hrmp_channels_out: vec![], - max_hrmp_num_per_candidate: 0, - required_parent, - validation_code_hash, - upgrade_restriction: None, - future_validation_code: None, - } - } + use std::collections::{BTreeMap, VecDeque}; // Sends `Initialize` with a collator config pub async fn initialize_collator(virtual_overseer: &mut VirtualOverseer, para_id: ParaId) { @@ -1098,22 +429,18 @@ mod helpers { .await; } - // Handle all runtime calls performed in `handle_new_activations`. Conditionally expects a - // `CLAIM_QUEUE_RUNTIME_REQUIREMENT` call if the passed `runtime_version` is greater or equal to - // `CLAIM_QUEUE_RUNTIME_REQUIREMENT` + // Handle all runtime calls performed in `handle_new_activation`. pub async fn handle_runtime_calls_on_new_head_activation( virtual_overseer: &mut VirtualOverseer, activated_hash: Hash, - async_backing_params: AsyncBackingParams, - cores: Vec, - runtime_version: u32, claim_queue: BTreeMap>, + node_features: NodeFeatures, ) { assert_matches!( overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::AvailabilityCores(tx))) => { + AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::SessionIndexForChild(tx))) => { assert_eq!(hash, activated_hash); - let _ = tx.send(Ok(cores)); + tx.send(Ok(1)).unwrap(); } ); @@ -1121,73 +448,46 @@ mod helpers { overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::Validators(tx))) => { assert_eq!(hash, activated_hash); - let _ = tx.send(Ok(vec![ + tx.send(Ok(vec![ Sr25519Keyring::Alice.public().into(), Sr25519Keyring::Bob.public().into(), Sr25519Keyring::Charlie.public().into(), - ])); + ])).unwrap(); } ); - let async_backing_response = - if runtime_version >= RuntimeApiRequest::ASYNC_BACKING_STATE_RUNTIME_REQUIREMENT { - Ok(async_backing_params) - } else { - Err(RuntimeApiError::NotSupported { runtime_api_name: "async_backing_params" }) - }; - assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::AsyncBackingParams( - tx, - ), - )) => { + hash, + RuntimeApiRequest::NodeFeatures(session_index, tx), + )) => { + assert_eq!(1, session_index); assert_eq!(hash, activated_hash); - let _ = tx.send(async_backing_response); + + tx.send(Ok(node_features)).unwrap(); } ); assert_matches!( overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::Version(tx), - )) => { + AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::ClaimQueue(tx))) => { assert_eq!(hash, activated_hash); - let _ = tx.send(Ok(runtime_version)); + tx.send(Ok(claim_queue)).unwrap(); } ); - - if runtime_version == RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - hash, - RuntimeApiRequest::ClaimQueue(tx), - )) => { - assert_eq!(hash, activated_hash); - let _ = tx.send(Ok(claim_queue.into())); - } - ); - } } - // Handles all runtime requests performed in `handle_new_activations` for the case when a + // Handles all runtime requests performed in `handle_new_activation` for the case when a // collation should be prepared for the new leaf pub async fn handle_cores_processing_for_a_leaf( virtual_overseer: &mut VirtualOverseer, activated_hash: Hash, para_id: ParaId, - expected_occupied_core_assumption: OccupiedCoreAssumption, - cores_assigned: usize, - pending_availability: Vec, - runtime_version: u32, + cores_assigned: Vec, ) { // Expect no messages if no cores is assigned to the para - if cores_assigned == 0 { - assert!(overseer_recv(virtual_overseer).timeout(TIMEOUT / 2).await.is_none()); + if cores_assigned.is_empty() { return } @@ -1201,23 +501,12 @@ mod helpers { max_pov_size: 1024, }; - if runtime_version >= RuntimeApiRequest::ASYNC_BACKING_STATE_RUNTIME_REQUIREMENT { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::ParaBackingState(p_id, tx)) - ) if parent == activated_hash && p_id == para_id => { - tx.send(Ok(Some(dummy_backing_state(pending_availability)))).unwrap(); - } - ); - } - assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request(hash, RuntimeApiRequest::PersistedValidationData(id, a, tx))) => { assert_eq!(hash, activated_hash); assert_eq!(id, para_id); - assert_eq!(a, expected_occupied_core_assumption); + assert_eq!(a, OccupiedCoreAssumption::Included); let _ = tx.send(Ok(Some(pvd.clone()))); } @@ -1235,20 +524,22 @@ mod helpers { )) => { assert_eq!(hash, activated_hash); assert_eq!(id, para_id); - assert_eq!(assumption, expected_occupied_core_assumption); + assert_eq!(assumption, OccupiedCoreAssumption::Included); let _ = tx.send(Ok(Some(validation_code_hash))); } ); - for _ in 0..cores_assigned { + for core in cores_assigned { assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::CollatorProtocol(CollatorProtocolMessage::DistributeCollation{ candidate_receipt, parent_head_data_hash, + core_index, .. }) => { + assert_eq!(CoreIndex(core), core_index); assert_eq!(parent_head_data_hash, parent_head.hash()); assert_eq!(candidate_receipt.descriptor().persisted_validation_data_hash(), pvd.hash()); assert_eq!(candidate_receipt.descriptor().para_head(), dummy_head_data().hash()); @@ -1257,4 +548,69 @@ mod helpers { ); } } + + // Handles all runtime requests performed in `handle_submit_collation` + pub async fn handle_runtime_calls_on_submit_collation( + virtual_overseer: &mut VirtualOverseer, + relay_parent: Hash, + para_id: ParaId, + expected_pvd: PersistedValidationData, + node_features: NodeFeatures, + claim_queue: BTreeMap>, + ) { + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request(rp, RuntimeApiRequest::PersistedValidationData(id, a, tx))) => { + assert_eq!(rp, relay_parent); + assert_eq!(id, para_id); + assert_eq!(a, OccupiedCoreAssumption::TimedOut); + + tx.send(Ok(Some(expected_pvd))).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + rp, + RuntimeApiRequest::ClaimQueue(tx), + )) => { + assert_eq!(rp, relay_parent); + tx.send(Ok(claim_queue)).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request(rp, RuntimeApiRequest::SessionIndexForChild(tx))) => { + assert_eq!(rp, relay_parent); + tx.send(Ok(1)).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request(rp, RuntimeApiRequest::Validators(tx))) => { + assert_eq!(rp, relay_parent); + tx.send(Ok(vec![ + Sr25519Keyring::Alice.public().into(), + Sr25519Keyring::Bob.public().into(), + Sr25519Keyring::Charlie.public().into(), + ])).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + rp, + RuntimeApiRequest::NodeFeatures(session_index, tx), + )) => { + assert_eq!(1, session_index); + assert_eq!(rp, relay_parent); + + tx.send(Ok(node_features.clone())).unwrap(); + } + ); + } } diff --git a/polkadot/primitives/Cargo.toml b/polkadot/primitives/Cargo.toml index a8cd6cb5f4e0..dd269caa2d60 100644 --- a/polkadot/primitives/Cargo.toml +++ b/polkadot/primitives/Cargo.toml @@ -16,6 +16,7 @@ codec = { features = ["bit-vec", "derive"], workspace = true } scale-info = { features = ["bit-vec", "derive", "serde"], workspace = true } log = { workspace = true } serde = { features = ["alloc", "derive"], workspace = true } +thiserror = { workspace = true, optional = true } sp-application-crypto = { features = ["serde"], workspace = true } sp-inherents = { workspace = true } @@ -59,6 +60,7 @@ std = [ "sp-runtime/std", "sp-staking/std", "sp-std/std", + "thiserror", ] runtime-benchmarks = [ "polkadot-parachain-primitives/runtime-benchmarks", diff --git a/polkadot/primitives/src/vstaging/mod.rs b/polkadot/primitives/src/vstaging/mod.rs index 21aab41902be..94b7b200e68f 100644 --- a/polkadot/primitives/src/vstaging/mod.rs +++ b/polkadot/primitives/src/vstaging/mod.rs @@ -465,19 +465,32 @@ impl CandidateCommitments { /// CandidateReceipt construction errors. #[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] +#[cfg_attr(feature = "std", derive(thiserror::Error))] pub enum CandidateReceiptError { /// The specified core index is invalid. + #[cfg_attr(feature = "std", error("The specified core index is invalid"))] InvalidCoreIndex, /// The core index in commitments doesn't match the one in descriptor + #[cfg_attr( + feature = "std", + error("The core index in commitments doesn't match the one in descriptor") + )] CoreIndexMismatch, /// The core selector or claim queue offset is invalid. + #[cfg_attr(feature = "std", error("The core selector or claim queue offset is invalid"))] InvalidSelectedCore, /// The parachain is not assigned to any core at specified claim queue offset. + #[cfg_attr( + feature = "std", + error("The parachain is not assigned to any core at specified claim queue offset") + )] NoAssignment, /// No core was selected. The `SelectCore` commitment is mandatory for /// v2 receipts if parachains has multiple cores assigned. + #[cfg_attr(feature = "std", error("Core selector not present"))] NoCoreSelected, /// Unknown version. + #[cfg_attr(feature = "std", error("Unknown internal version"))] UnknownVersion(InternalVersion), } diff --git a/prdoc/pr_5908.prdoc b/prdoc/pr_5908.prdoc new file mode 100644 index 000000000000..8f05819451a0 --- /dev/null +++ b/prdoc/pr_5908.prdoc @@ -0,0 +1,14 @@ +title: "collation-generation: use v2 receipts" + +doc: + - audience: Node Dev + description: | + Implementation of [RFC 103](https://github.com/polkadot-fellows/RFCs/pull/103) for the collation-generation subsystem. + Also removes the usage of AsyncBackingParams. + +crates: + - name: polkadot-node-collation-generation + bump: major + validate: false + - name: polkadot-primitives + bump: minor From 7f80f45217793bde96d0a2a068eae09514d2b671 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Mon, 4 Nov 2024 10:27:02 +0100 Subject: [PATCH 008/166] [eth-rpc] Fixes (#6317) Various fixes for the release of eth-rpc & ah-westend-runtime - Bump asset-hub westend spec version - Fix the status of the Receipt to properly report failed transactions - Fix value conversion between native and eth decimal representation --------- Co-authored-by: GitHub Action --- .../assets/asset-hub-westend/src/lib.rs | 3 +- prdoc/pr_6317.prdoc | 12 +++++ substrate/bin/node/runtime/src/lib.rs | 1 + substrate/client/service/src/lib.rs | 4 +- substrate/frame/revive/rpc/Cargo.toml | 1 + .../revive/rpc/examples/rust/transfer.rs | 15 +++--- .../frame/revive/rpc/revive_chain.metadata | Bin 342591 -> 655430 bytes substrate/frame/revive/rpc/src/cli.rs | 6 +-- substrate/frame/revive/rpc/src/client.rs | 41 ++++++++--------- substrate/frame/revive/rpc/src/tests.rs | 43 ++++++++++++------ substrate/frame/revive/src/evm/runtime.rs | 14 ++++-- substrate/frame/revive/src/exec.rs | 6 ++- substrate/frame/revive/src/lib.rs | 16 +++++-- 13 files changed, 102 insertions(+), 60 deletions(-) create mode 100644 prdoc/pr_6317.prdoc 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 0ed24db97df8..bbd686b5cf50 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -124,7 +124,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("westmint"), impl_name: create_runtime_str!("westmint"), authoring_version: 1, - spec_version: 1_016_002, + spec_version: 1_016_004, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, @@ -968,6 +968,7 @@ impl pallet_revive::Config for Runtime { type Debug = (); 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. } impl TryFrom for pallet_revive::Call { diff --git a/prdoc/pr_6317.prdoc b/prdoc/pr_6317.prdoc new file mode 100644 index 000000000000..4034ab3f3012 --- /dev/null +++ b/prdoc/pr_6317.prdoc @@ -0,0 +1,12 @@ +title: eth-rpc fixes +doc: +- audience: Runtime Dev + description: | + Various fixes for the release of eth-rpc & ah-westend-runtime: + - Bump asset-hub westend spec version + - Fix the status of the Receipt to properly report failed transactions + - Fix value conversion between native and eth decimal representation + +crates: +- name: asset-hub-westend-runtime + bump: patch diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 7712d8ba9540..d407aafb452b 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -1427,6 +1427,7 @@ impl pallet_revive::Config for Runtime { type Debug = (); 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. } impl pallet_sudo::Config for Runtime { diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 54e847791cff..3df9020b0418 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -98,7 +98,9 @@ pub use sc_transaction_pool::TransactionPoolOptions; pub use sc_transaction_pool_api::{error::IntoPoolError, InPoolTransaction, TransactionPool}; #[doc(hidden)] pub use std::{ops::Deref, result::Result, sync::Arc}; -pub use task_manager::{SpawnTaskHandle, Task, TaskManager, TaskRegistry, DEFAULT_GROUP_NAME}; +pub use task_manager::{ + SpawnEssentialTaskHandle, SpawnTaskHandle, Task, TaskManager, TaskRegistry, DEFAULT_GROUP_NAME, +}; use tokio::runtime::Handle; const DEFAULT_PROTOCOL_ID: &str = "sup"; diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index e6d8c38c04f0..56db91f920fa 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -77,3 +77,4 @@ example = ["hex", "hex-literal", "rlp", "secp256k1", "subxt-signer"] hex-literal = { workspace = true } pallet-revive-fixtures = { workspace = true } substrate-cli-test-utils = { workspace = true } +subxt-signer = { workspace = true, features = ["unstable-eth"] } diff --git a/substrate/frame/revive/rpc/examples/rust/transfer.rs b/substrate/frame/revive/rpc/examples/rust/transfer.rs index 185ad808e787..b99d48a2f78e 100644 --- a/substrate/frame/revive/rpc/examples/rust/transfer.rs +++ b/substrate/frame/revive/rpc/examples/rust/transfer.rs @@ -26,14 +26,14 @@ async fn main() -> anyhow::Result<()> { let alith = Account::default(); let client = HttpClientBuilder::default().build("http://localhost:8545")?; - let baltathar = Account::from(subxt_signer::eth::dev::baltathar()); - let value = 1_000_000_000_000_000_000u128.into(); // 1 ETH + let ethan = Account::from(subxt_signer::eth::dev::ethan()); + let value = 1_000_000_000_000_000_000_000u128.into(); let print_balance = || async { let balance = client.get_balance(alith.address(), BlockTag::Latest.into()).await?; println!("Alith {:?} balance: {balance:?}", alith.address()); - let balance = client.get_balance(baltathar.address(), BlockTag::Latest.into()).await?; - println!("Baltathar {:?} balance: {balance:?}", baltathar.address()); + let balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; + println!("ethan {:?} balance: {balance:?}", ethan.address()); anyhow::Result::<()>::Ok(()) }; @@ -41,14 +41,15 @@ async fn main() -> anyhow::Result<()> { println!("\n\n=== Transferring ===\n\n"); let hash = - send_transaction(&alith, &client, value, Bytes::default(), Some(baltathar.address())) - .await?; + send_transaction(&alith, &client, value, Bytes::default(), Some(ethan.address())).await?; println!("Transaction hash: {hash:?}"); - let ReceiptInfo { block_number, gas_used, .. } = wait_for_receipt(&client, hash).await?; + let ReceiptInfo { block_number, gas_used, status, .. } = + wait_for_receipt(&client, hash).await?; println!("Receipt: "); println!("- Block number: {block_number}"); println!("- Gas used: {gas_used}"); + println!("- Success: {status:?}"); print_balance().await?; Ok(()) diff --git a/substrate/frame/revive/rpc/revive_chain.metadata b/substrate/frame/revive/rpc/revive_chain.metadata index eef6dd2a0aeaa5b55ef9519aafb2301bd8cd51dc..305d079f9bd86786d1cd00fadac152eb856b26ee 100644 GIT binary patch literal 655430 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�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%0A1e~t}_Qk8dIj$=EL>@d+qeaky*Y_87kl!ZIWR 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%0Aj(4&mO+3j*eJ>XBDj%#06)nLaL4DbBAH?7r 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 literal 342591 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 XtqGG|`D)@FGI!*k7+yGXOYQ#ynerH6 diff --git a/substrate/frame/revive/rpc/src/cli.rs b/substrate/frame/revive/rpc/src/cli.rs index b95fa78bf3ee..fcb84e6b54b0 100644 --- a/substrate/frame/revive/rpc/src/cli.rs +++ b/substrate/frame/revive/rpc/src/cli.rs @@ -109,11 +109,11 @@ pub fn run(cmd: CliCommand) -> anyhow::Result<()> { let tokio_handle = tokio_runtime.handle(); let signals = tokio_runtime.block_on(async { Signals::capture() })?; let mut task_manager = TaskManager::new(tokio_handle.clone(), prometheus_registry)?; - let spawn_handle = task_manager.spawn_handle(); + let essential_spawn_handle = task_manager.spawn_essential_handle(); let gen_rpc_module = || { let signals = tokio_runtime.block_on(async { Signals::capture() })?; - let fut = Client::from_url(&node_rpc_url, &spawn_handle).fuse(); + let fut = Client::from_url(&node_rpc_url, &essential_spawn_handle).fuse(); pin_mut!(fut); match tokio_handle.block_on(signals.try_until_signal(fut)) { @@ -125,7 +125,7 @@ pub fn run(cmd: CliCommand) -> anyhow::Result<()> { // Prometheus metrics. if let Some(PrometheusConfig { port, registry }) = prometheus_config.clone() { - spawn_handle.spawn( + task_manager.spawn_handle().spawn( "prometheus-endpoint", None, prometheus_endpoint::init_prometheus(port, registry).map(drop), diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index 64f7f2a61617..ba93d0af62ac 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -35,7 +35,6 @@ use pallet_revive::{ }, EthContractResult, }; -use sc_service::SpawnTaskHandle; use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_weights::Weight; use std::{ @@ -145,9 +144,6 @@ pub enum ClientError { /// The transaction fee could not be found #[error("TransactionFeePaid event not found")] TxFeeNotFound, - /// The token decimals property was not found - #[error("tokenDecimals not found in properties")] - TokenDecimalsNotFound, /// The cache is empty. #[error("Cache is empty")] CacheEmpty, @@ -165,7 +161,7 @@ impl From for ErrorObjectOwned { /// The number of recent blocks maintained by the cache. /// For each block in the cache, we also store the EVM transaction receipts. -pub const CACHE_SIZE: usize = 10; +pub const CACHE_SIZE: usize = 256; impl BlockCache { fn latest_block(&self) -> Option<&Arc> { @@ -228,7 +224,7 @@ impl ClientInner { let rpc = LegacyRpcMethods::::new(RpcClient::new(rpc_client.clone())); let (native_to_evm_ratio, chain_id, max_block_weight) = - tokio::try_join!(native_to_evm_ratio(&rpc), chain_id(&api), max_block_weight(&api))?; + tokio::try_join!(native_to_evm_ratio(&api), chain_id(&api), max_block_weight(&api))?; Ok(Self { api, rpc_client, rpc, cache, chain_id, max_block_weight, native_to_evm_ratio }) } @@ -238,6 +234,11 @@ impl ClientInner { value.saturating_mul(self.native_to_evm_ratio) } + /// Convert an evm balance to a native balance. + fn evm_to_native_decimals(&self, value: U256) -> U256 { + value / self.native_to_evm_ratio + } + /// Get the receipt infos from the extrinsics in a block. async fn receipt_infos( &self, @@ -274,7 +275,7 @@ impl ClientInner { .checked_div(gas_price.as_u128()) .unwrap_or_default(); - let success = events.find_first::().is_ok(); + let success = events.has::()?; let transaction_index = ext.index(); let transaction_hash = BlakeTwo256::hash(&Vec::from(ext.bytes()).encode()); let block_hash = block.hash(); @@ -319,16 +320,10 @@ async fn max_block_weight(api: &OnlineClient) -> Result) -> Result { - let props = rpc.system_properties().await?; - let eth_decimals = U256::from(18u32); - let native_decimals: U256 = props - .get("tokenDecimals") - .and_then(|v| v.as_number()?.as_u64()) - .ok_or(ClientError::TokenDecimalsNotFound)? - .into(); - - Ok(U256::from(10u32).pow(eth_decimals - native_decimals)) +async fn native_to_evm_ratio(api: &OnlineClient) -> Result { + let query = subxt_client::constants().revive().native_to_eth_ratio(); + let ratio = api.constants().at(&query)?; + Ok(U256::from(ratio)) } /// Extract the block timestamp. @@ -344,7 +339,10 @@ async fn extract_block_timestamp(block: &SubstrateBlock) -> Option { impl Client { /// Create a new client instance. /// The client will subscribe to new blocks and maintain a cache of [`CACHE_SIZE`] blocks. - pub async fn from_url(url: &str, spawn_handle: &SpawnTaskHandle) -> Result { + pub async fn from_url( + url: &str, + spawn_handle: &sc_service::SpawnEssentialTaskHandle, + ) -> Result { log::info!(target: LOG_TARGET, "Connecting to node at: {url} ..."); let inner: Arc = Arc::new(ClientInner::from_url(url).await?); log::info!(target: LOG_TARGET, "Connected to node at: {url}"); @@ -619,9 +617,10 @@ impl Client { block: BlockNumberOrTagOrHash, ) -> Result, ClientError> { let runtime_api = self.runtime_api(&block).await?; - let value = tx - .value - .unwrap_or_default() + + let value = self + .inner + .evm_to_native_decimals(tx.value.unwrap_or_default()) .try_into() .map_err(|_| ClientError::ConversionFailed)?; diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 5d84e06e9e04..01fcb6ae3bd2 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -50,16 +50,14 @@ async fn ws_client_with_retry(url: &str) -> WsClient { async fn test_jsonrpsee_server() -> anyhow::Result<()> { // Start the node. let _ = thread::spawn(move || { - match start_node_inline(vec![ + if let Err(e) = start_node_inline(vec![ "--dev", "--rpc-port=45789", "--no-telemetry", "--no-prometheus", + "-lerror,evm=debug,sc_rpc_server=info,runtime::revive=debug", ]) { - Ok(_) => {}, - Err(e) => { - panic!("Node exited with error: {}", e); - }, + panic!("Node exited with error: {e:?}"); } }); @@ -69,17 +67,36 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { "--rpc-port=45788", "--node-rpc-url=ws://localhost:45789", "--no-prometheus", + "-linfo,eth-rpc=debug", ]); - let _ = thread::spawn(move || match cli::run(args) { - Ok(_) => {}, - Err(e) => { - panic!("eth-rpc exited with error: {}", e); - }, + let _ = thread::spawn(move || { + if let Err(e) = cli::run(args) { + panic!("eth-rpc exited with error: {e:?}"); + } }); let client = ws_client_with_retry("ws://localhost:45788").await; let account = Account::default(); + // Balance transfer + let ethan = Account::from(subxt_signer::eth::dev::ethan()); + let ethan_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; + assert_eq!(U256::zero(), ethan_balance); + + let value = 1_000_000_000_000_000_000_000u128.into(); + let hash = + send_transaction(&account, &client, value, Bytes::default(), Some(ethan.address())).await?; + + let receipt = wait_for_receipt(&client, hash).await?; + assert_eq!( + Some(ethan.address()), + receipt.to, + "Receipt should have the correct contract address." + ); + + let ethan_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; + assert_eq!(value, ethan_balance, "ethan's balance should be the same as the value sent."); + // Deploy contract let data = b"hello world".to_vec(); let value = U256::from(5_000_000_000_000u128); @@ -96,11 +113,7 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { ); let balance = client.get_balance(contract_address, BlockTag::Latest.into()).await?; - assert_eq!( - value * 1_000_000, - balance, - "Contract balance should be the same as the value sent." - ); + assert_eq!(value, balance, "Contract balance should be the same as the value sent."); // Call contract let hash = diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index 3acd67b32aab..9b360c7de712 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -313,10 +313,14 @@ pub trait EthExtra { return Err(InvalidTransaction::Call); } + let value = (value / U256::from(::NativeToEthRatio::get())) + .try_into() + .map_err(|_| InvalidTransaction::Call)?; + let call = if let Some(dest) = to { crate::Call::call:: { dest, - value: value.try_into().map_err(|_| InvalidTransaction::Call)?, + value, gas_limit, storage_deposit_limit, data: input.0, @@ -336,7 +340,7 @@ pub trait EthExtra { }; crate::Call::instantiate_with_code:: { - value: value.try_into().map_err(|_| InvalidTransaction::Call)?, + value, gas_limit, storage_deposit_limit, code: code.to_vec(), @@ -370,7 +374,7 @@ pub trait EthExtra { Default::default(), ) .into(); - log::debug!(target: LOG_TARGET, "try_into_checked_extrinsic: encoded_len: {encoded_len:?} actual_fee: {actual_fee:?} eth_fee: {eth_fee:?}"); + log::trace!(target: LOG_TARGET, "try_into_checked_extrinsic: encoded_len: {encoded_len:?} actual_fee: {actual_fee:?} eth_fee: {eth_fee:?}"); if eth_fee < actual_fee { log::debug!(target: LOG_TARGET, "fees {eth_fee:?} too low for the extrinsic {actual_fee:?}"); @@ -381,10 +385,10 @@ pub trait EthExtra { let max = actual_fee.max(eth_fee_no_tip); let diff = Percent::from_rational(max - min, min); if diff > Percent::from_percent(10) { - log::debug!(target: LOG_TARGET, "Difference between the extrinsic fees {actual_fee:?} and the Ethereum gas fees {eth_fee_no_tip:?} should be no more than 10% got {diff:?}"); + log::trace!(target: LOG_TARGET, "Difference between the extrinsic fees {actual_fee:?} and the Ethereum gas fees {eth_fee_no_tip:?} should be no more than 10% got {diff:?}"); return Err(InvalidTransaction::Call.into()) } else { - log::debug!(target: LOG_TARGET, "Difference between the extrinsic fees {actual_fee:?} and the Ethereum gas fees {eth_fee_no_tip:?}: {diff:?}"); + log::trace!(target: LOG_TARGET, "Difference between the extrinsic fees {actual_fee:?} and the Ethereum gas fees {eth_fee_no_tip:?}: {diff:?}"); } let tip = eth_fee.saturating_sub(eth_fee_no_tip); diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 8629a21c4fda..943c377e504d 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -1268,8 +1268,10 @@ where fn transfer(from: &T::AccountId, to: &T::AccountId, value: BalanceOf) -> ExecResult { // this avoids events to be emitted for zero balance transfers if !value.is_zero() { - T::Currency::transfer(from, to, value, Preservation::Preserve) - .map_err(|_| Error::::TransferFailed)?; + T::Currency::transfer(from, to, value, Preservation::Preserve).map_err(|err| { + log::debug!(target: LOG_TARGET, "Transfer of {value:?} from {from:?} to {to:?} failed: {err:?}"); + Error::::TransferFailed + })?; } Ok(Default::default()) } diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index 51e9a8fa3f90..5038ae44afad 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -303,6 +303,10 @@ pub mod pallet { /// preventing replay attacks. #[pallet::constant] type ChainId: Get; + + /// The ratio between the decimal representation of the native token and the ETH token. + #[pallet::constant] + type NativeToEthRatio: Get; } /// Container for different types that implement [`DefaultConfig`]` of this pallet. @@ -374,7 +378,8 @@ pub mod pallet { type Xcm = (); type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>; type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>; - type ChainId = ConstU64<{ 0 }>; + type ChainId = ConstU64<0>; + type NativeToEthRatio = ConstU32<1_000_000>; } } @@ -1239,6 +1244,7 @@ where T::Nonce: Into, T::Hash: frame_support::traits::IsType, { + log::debug!(target: LOG_TARGET, "bare_eth_transact: dest: {dest:?} value: {value:?} gas_limit: {gas_limit:?} storage_deposit_limit: {storage_deposit_limit:?}"); // Get the nonce to encode in the tx. let nonce: T::Nonce = >::account_nonce(&origin); @@ -1264,7 +1270,7 @@ where // Get the encoded size of the transaction. let tx = TransactionLegacyUnsigned { - value: value.into(), + value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), input: input.into(), nonce: nonce.into(), chain_id: Some(T::ChainId::get().into()), @@ -1300,7 +1306,7 @@ where ) .into(); - log::debug!(target: LOG_TARGET, "bare_eth_call: len: {encoded_len:?} fee: {fee:?}"); + log::trace!(target: LOG_TARGET, "bare_eth_call: len: {encoded_len:?} fee: {fee:?}"); EthContractResult { gas_required: result.gas_required, storage_deposit: result.storage_deposit.charge_or_zero(), @@ -1339,7 +1345,7 @@ where let tx = TransactionLegacyUnsigned { gas: max_gas_fee.into(), nonce: nonce.into(), - value: value.into(), + value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), input: input.clone().into(), gas_price: GAS_PRICE.into(), chain_id: Some(T::ChainId::get().into()), @@ -1373,7 +1379,7 @@ where ) .into(); - log::debug!(target: LOG_TARGET, "Call dry run Result: dispatch_info: {dispatch_info:?} len: {encoded_len:?} fee: {fee:?}"); + log::trace!(target: LOG_TARGET, "bare_eth_call: len: {encoded_len:?} fee: {fee:?}"); EthContractResult { gas_required: result.gas_required, storage_deposit: result.storage_deposit.charge_or_zero(), From 657b5503a04e97737696fa7344641019350fb521 Mon Sep 17 00:00:00 2001 From: Giuseppe Re Date: Mon, 4 Nov 2024 10:48:47 +0100 Subject: [PATCH 009/166] Refactor pallet `claims` (#6318) - [x] Removing `without_storage_info` and adding bounds on the stored types for pallet `claims` - issue https://github.com/paritytech/polkadot-sdk/issues/6289 - [x] Migrating to benchmarking V2 - https://github.com/paritytech/polkadot-sdk/issues/6202 --------- Co-authored-by: Guillaume Thiolliere --- polkadot/runtime/common/src/claims.rs | 247 ++++++++++++++++---------- prdoc/pr_6318.prdoc | 14 ++ 2 files changed, 165 insertions(+), 96 deletions(-) create mode 100644 prdoc/pr_6318.prdoc diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 2b36c19efce7..b77cbfeff77c 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -19,7 +19,7 @@ #[cfg(not(feature = "std"))] use alloc::{format, string::String}; use alloc::{vec, vec::Vec}; -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use core::fmt::Debug; use frame_support::{ ensure, @@ -82,7 +82,17 @@ impl WeightInfo for TestWeightInfo { /// The kind of statement an account needs to make for a claim to be valid. #[derive( - Encode, Decode, Clone, Copy, Eq, PartialEq, RuntimeDebug, TypeInfo, Serialize, Deserialize, + Encode, + Decode, + Clone, + Copy, + Eq, + PartialEq, + RuntimeDebug, + TypeInfo, + Serialize, + Deserialize, + MaxEncodedLen, )] pub enum StatementKind { /// Statement required to be made by non-SAFT holders. @@ -116,7 +126,9 @@ impl Default for StatementKind { /// An Ethereum address (i.e. 20 bytes, used to represent an Ethereum account). /// /// This gets serialized to the 0x-prefixed hex representation. -#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo)] +#[derive( + Clone, Copy, PartialEq, Eq, Encode, Decode, Default, RuntimeDebug, TypeInfo, MaxEncodedLen, +)] pub struct EthereumAddress([u8; 20]); impl Serialize for EthereumAddress { @@ -150,7 +162,7 @@ impl<'de> Deserialize<'de> for EthereumAddress { } } -#[derive(Encode, Decode, Clone, TypeInfo)] +#[derive(Encode, Decode, Clone, TypeInfo, MaxEncodedLen)] pub struct EcdsaSignature(pub [u8; 65]); impl PartialEq for EcdsaSignature { @@ -172,7 +184,6 @@ pub mod pallet { use frame_system::pallet_prelude::*; #[pallet::pallet] - #[pallet::without_storage_info] pub struct Pallet(_); /// Configuration trait. @@ -1440,7 +1451,7 @@ mod tests { mod benchmarking { use super::*; use crate::claims::Call; - use frame_benchmarking::{account, benchmarks}; + use frame_benchmarking::v2::*; use frame_support::{ dispatch::{DispatchInfo, GetDispatchInfo}, traits::UnfilteredDispatchable, @@ -1485,136 +1496,168 @@ mod benchmarking { Ok(()) } - benchmarks! { - where_clause { where ::RuntimeCall: IsSubType> + From>, + #[benchmarks( + where + ::RuntimeCall: IsSubType> + From>, ::RuntimeCall: Dispatchable + GetDispatchInfo, <::RuntimeCall as Dispatchable>::RuntimeOrigin: AsSystemOriginSigner + AsTransactionAuthorizedOrigin + Clone, <::RuntimeCall as Dispatchable>::PostInfo: Default, - } + )] + mod benchmarks { + use super::*; // Benchmark `claim` including `validate_unsigned` logic. - claim { + #[benchmark] + fn claim() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&c.encode())).unwrap(); let eth_address = eth(&secret_key); let account: T::AccountId = account("user", c, SEED); let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); let signature = sig::(&secret_key, &account.encode(), &[][..]); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, None)?; + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + None, + )?; assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); let source = sp_runtime::transaction_validity::TransactionSource::External; - let call_enc = Call::::claim { - dest: account.clone(), - ethereum_signature: signature.clone() - }.encode(); - }: { - let call = as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct"); - super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; - call.dispatch_bypass_filter(RawOrigin::None.into())?; - } - verify { + let call_enc = + Call::::claim { dest: account.clone(), ethereum_signature: signature.clone() } + .encode(); + + #[block] + { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + super::Pallet::::validate_unsigned(source, &call) + .map_err(|e| -> &'static str { e.into() })?; + call.dispatch_bypass_filter(RawOrigin::None.into())?; + } + assert_eq!(Claims::::get(eth_address), None); + Ok(()) } // Benchmark `mint_claim` when there already exists `c` claims in storage. - mint_claim { + #[benchmark] + fn mint_claim() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - let eth_address = account("eth_address", 0, SEED); let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); let statement = StatementKind::Regular; - }: _(RawOrigin::Root, eth_address, VALUE.into(), vesting, Some(statement)) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, eth_address, VALUE.into(), vesting, Some(statement)); + assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); + Ok(()) } // Benchmark `claim_attest` including `validate_unsigned` logic. - claim_attest { + #[benchmark] + fn claim_attest() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - // Crate signature let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let secret_key = + libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); let eth_address = eth(&secret_key); let account: T::AccountId = account("user", c, SEED); let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); let statement = StatementKind::Regular; let signature = sig::(&secret_key, &account.encode(), statement.to_text()); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + Some(statement), + )?; assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); let call_enc = Call::::claim_attest { dest: account.clone(), ethereum_signature: signature.clone(), - statement: StatementKind::Regular.to_text().to_vec() - }.encode(); + statement: StatementKind::Regular.to_text().to_vec(), + } + .encode(); let source = sp_runtime::transaction_validity::TransactionSource::External; - }: { - let call = as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct"); - super::Pallet::::validate_unsigned(source, &call).map_err(|e| -> &'static str { e.into() })?; - call.dispatch_bypass_filter(RawOrigin::None.into())?; - } - verify { + + #[block] + { + let call = as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct"); + super::Pallet::::validate_unsigned(source, &call) + .map_err(|e| -> &'static str { e.into() })?; + call.dispatch_bypass_filter(RawOrigin::None.into())?; + } + assert_eq!(Claims::::get(eth_address), None); + Ok(()) } // Benchmark `attest` including prevalidate logic. - attest { + #[benchmark] + fn attest() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let secret_key = + libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); let eth_address = eth(&secret_key); let account: T::AccountId = account("user", c, SEED); let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); let statement = StatementKind::Regular; - let signature = sig::(&secret_key, &account.encode(), statement.to_text()); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + Some(statement), + )?; Preclaims::::insert(&account, eth_address); assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); let stmt = StatementKind::Regular.to_text().to_vec(); - }: - _(RawOrigin::Signed(account), stmt) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(account), stmt); + assert_eq!(Claims::::get(eth_address), None); + Ok(()) } - move_claim { + #[benchmark] + fn move_claim() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let secret_key = + libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); let eth_address = eth(&secret_key); - let new_secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&(u32::MAX/2).encode())).unwrap(); + let new_secret_key = + libsecp256k1::SecretKey::parse(&keccak_256(&(u32::MAX / 2).encode())).unwrap(); let new_eth_address = eth(&new_secret_key); let account: T::AccountId = account("user", c, SEED); @@ -1622,73 +1665,85 @@ mod benchmarking { assert!(Claims::::contains_key(eth_address)); assert!(!Claims::::contains_key(new_eth_address)); - }: _(RawOrigin::Root, eth_address, new_eth_address, Some(account)) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, eth_address, new_eth_address, Some(account)); + assert!(!Claims::::contains_key(eth_address)); assert!(Claims::::contains_key(new_eth_address)); + Ok(()) } // Benchmark the time it takes to do `repeat` number of keccak256 hashes - #[extra] - keccak256 { - let i in 0 .. 10_000; + #[benchmark(extra)] + fn keccak256(i: Linear<0, 10_000>) { let bytes = (i).encode(); - }: { - for index in 0 .. i { - let _hash = keccak_256(&bytes); + + #[block] + { + for _ in 0..i { + let _hash = keccak_256(&bytes); + } } } // Benchmark the time it takes to do `repeat` number of `eth_recover` - #[extra] - eth_recover { - let i in 0 .. 1_000; + #[benchmark(extra)] + fn eth_recover(i: Linear<0, 1_000>) { // Crate signature let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&i.encode())).unwrap(); let account: T::AccountId = account("user", i, SEED); let signature = sig::(&secret_key, &account.encode(), &[][..]); let data = account.using_encoded(to_ascii_hex); let extra = StatementKind::default().to_text(); - }: { - for _ in 0 .. i { - assert!(super::Pallet::::eth_recover(&signature, &data, extra).is_some()); + + #[block] + { + for _ in 0..i { + assert!(super::Pallet::::eth_recover(&signature, &data, extra).is_some()); + } } } - prevalidate_attests { + #[benchmark] + fn prevalidate_attests() -> Result<(), BenchmarkError> { let c = MAX_CLAIMS; - - for i in 0 .. c / 2 { + for _ in 0..c / 2 { create_claim::(c)?; create_claim_attest::(u32::MAX - c)?; } - let ext = PrevalidateAttests::::new(); - let call = super::Call::attest { - statement: StatementKind::Regular.to_text().to_vec(), - }; + let call = super::Call::attest { statement: StatementKind::Regular.to_text().to_vec() }; let call: ::RuntimeCall = call.into(); let info = call.get_dispatch_info(); let attest_c = u32::MAX - c; - let secret_key = libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); + let secret_key = + libsecp256k1::SecretKey::parse(&keccak_256(&attest_c.encode())).unwrap(); let eth_address = eth(&secret_key); let account: T::AccountId = account("user", c, SEED); let vesting = Some((100_000u32.into(), 1_000u32.into(), 100u32.into())); let statement = StatementKind::Regular; - let signature = sig::(&secret_key, &account.encode(), statement.to_text()); - super::Pallet::::mint_claim(RawOrigin::Root.into(), eth_address, VALUE.into(), vesting, Some(statement))?; + super::Pallet::::mint_claim( + RawOrigin::Root.into(), + eth_address, + VALUE.into(), + vesting, + Some(statement), + )?; Preclaims::::insert(&account, eth_address); assert_eq!(Claims::::get(eth_address), Some(VALUE.into())); - }: { - assert!(ext.test_run( - RawOrigin::Signed(account).into(), - &call, - &info, - 0, - |_| { - Ok(Default::default()) - } - ).unwrap().is_ok()); + + #[block] + { + assert!(ext + .test_run(RawOrigin::Signed(account).into(), &call, &info, 0, |_| { + Ok(Default::default()) + }) + .unwrap() + .is_ok()); + } + + Ok(()) } impl_benchmark_test_suite!( diff --git a/prdoc/pr_6318.prdoc b/prdoc/pr_6318.prdoc new file mode 100644 index 000000000000..b44a982f5992 --- /dev/null +++ b/prdoc/pr_6318.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Refactor pallet claims + +doc: + - audience: Runtime Dev + description: | + Adds bounds on stored types for pallet claims. + Migrates benchmarking from v1 to v2 for pallet claims. + +crates: + - name: polkadot-runtime-common + bump: patch From 2a8491744b7cb377898b47db029848ddf06057a1 Mon Sep 17 00:00:00 2001 From: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> Date: Mon, 4 Nov 2024 13:10:19 +0200 Subject: [PATCH 010/166] templates: make node compilation optional (#5954) # Description Closes #5940 ## Integration Node devs that rely on templates' nodes binaries for minimal or parachain would need to follow the updated templates' README.mds again to find how to build the nodes' binaries. ## Review Notes Conditional compilation of virtual workspaces would compile the `members` list as if we passed `--workspace` flag to `cargo build` , except when adding a `default-members` list which will be used for any cargo command executed in the virtual workspace root. To build the full members list needs passing `--workspace` flag. Other options investigated: - feature guard the `node` crate by defining a feature in the `node` crate, but it feels too complex since all code needs to be feature guarded. I haven't tried it but technically speaking it might work. I think though it looks awkward and my opinion is that the alternative is better. - defining features in the virtual workspace's Cargo.toml doesn't work (thought that I might create a feature that will have a dependency on the `node` crate and then not passing the feature to cargo build results in ignoring the `node` crate) - skipping compilation by using an environment variable, read in the build script, that will exit compilation abruptly if not set, but I couldn't make it work. - exclude the crate from the members list and build it specifically by passing `--package minimal-template-node` flag to the `cargo build` command. This has the disadvantage of not allowing IDEs based on rust analyzer to index/compile the node crate. My conclusion is that any option would require two commands to build the template, one with the node and one without, and both must be included in the README or templates usage documentation. If it comes which ones to pick I am in favor of the `default-members` option, which requires minimal intervention and expresses how cargo commands are executed on top of the workspace members, and what's left out from regular usage. ### Testing Testing was conducted as described bellow: - [x] zombienet with `minimal-template-node` , `parachain-template-node` and `polkadot-omni-node`. Things work as expected. - [x] no chopsticks testing was conducted - feels a bit out of scope for OmniNode related docs and overall testing when promoting it over the templates' nodes. - [x] testing the changes for the sync templates workflow (ignore the added comment from the Cargo.tomls, it was removed here on this branch: [99bff3e](https://github.com/paritytech/polkadot-sdk/pull/5954/commits/99bff3e2b577704ecb5cb1d40407a3fbdcb867bc)): [minimal](https://github.com/paritytech-stg/polkadot-sdk-minimal-template/pull/22/files#diff-2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542R9), [parachain](https://github.com/paritytech-stg/polkadot-sdk-parachain-template/pull/19/files#diff-2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542R9), [solochain](https://github.com/paritytech-stg/polkadot-sdk-solochain-template/pull/17/files#diff-2e9d962a08321605940b5a657135052fbcef87b5e360662bb527c96d9a615542R9). The links correspond to PRs opened by a bot after manually starting the sync-templates workflow on `paritytech-stg` org to test the end result of the `Cargo.toml` changes. --------- Signed-off-by: Iulian Barbu Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- .github/workflows/checks.yml | 4 +- .github/workflows/misc-sync-templates.yml | 6 + Cargo.lock | 147 ++++++++++--- Cargo.toml | 15 +- cumulus/polkadot-omni-node/README.md | 65 ++++++ cumulus/polkadot-omni-node/lib/README.md | 26 +++ cumulus/polkadot-omni-node/lib/src/lib.rs | 35 +-- prdoc/pr_5954.prdoc | 19 ++ .../bin/utils/chain-spec-builder/Cargo.toml | 17 +- .../utils/chain-spec-builder/README.docify.md | 102 +++++++++ .../bin/utils/chain-spec-builder/README.md | 140 ++++++++++++ .../bin/utils/chain-spec-builder/src/lib.rs | 104 +-------- .../tests/expected/create_with_full.json | 15 +- .../tests/expected/doc/create_default.json | 36 ++++ .../tests/expected/doc/create_full_plain.json | 66 ++++++ .../tests/expected/doc/create_full_raw.json | 39 ++++ .../doc/create_with_named_preset_staging.json | 39 ++++ .../expected/doc/create_with_patch_plain.json | 42 ++++ .../expected/doc/create_with_patch_raw.json | 37 ++++ .../tests/expected/doc/display_preset.json | 1 + .../expected/doc/display_preset_staging.json | 1 + .../tests/expected/doc/list_presets.json | 1 + .../chain-spec-builder/tests/input/full.json | 6 +- .../utils/chain-spec-builder/tests/test.rs | 203 ++++++++++++++++++ substrate/utils/wasm-builder/src/builder.rs | 5 +- substrate/utils/wasm-builder/src/lib.rs | 2 + templates/minimal/Dockerfile | 2 +- templates/minimal/README.md | 173 ++++++++++++--- templates/minimal/node/src/cli.rs | 3 + templates/minimal/node/src/service.rs | 1 + templates/minimal/zombienet-omni-node.toml | 9 + templates/minimal/zombienet.toml | 30 +++ templates/parachain/Dockerfile | 2 +- templates/parachain/README.md | 174 +++++++++++---- .../runtime/src/genesis_config_presets.rs | 8 +- templates/parachain/zombienet-omni-node.toml | 22 ++ templates/zombienet/tests/smoke.rs | 150 +++++++++++-- 37 files changed, 1468 insertions(+), 279 deletions(-) create mode 100644 cumulus/polkadot-omni-node/README.md create mode 100644 cumulus/polkadot-omni-node/lib/README.md create mode 100644 prdoc/pr_5954.prdoc create mode 100644 substrate/bin/utils/chain-spec-builder/README.docify.md create mode 100644 substrate/bin/utils/chain-spec-builder/README.md create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_default.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_plain.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_raw.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_named_preset_staging.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_plain.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_raw.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset_staging.json create mode 100644 substrate/bin/utils/chain-spec-builder/tests/expected/doc/list_presets.json create mode 100644 templates/minimal/zombienet-omni-node.toml create mode 100644 templates/minimal/zombienet.toml create mode 100644 templates/parachain/zombienet-omni-node.toml diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 0793c31dbb87..8ec3660307d4 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -32,8 +32,8 @@ jobs: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: script run: | - forklift cargo clippy --all-targets --locked --workspace --quiet - forklift cargo clippy --all-targets --all-features --locked --workspace --quiet + cargo clippy --all-targets --locked --workspace --quiet + cargo clippy --all-targets --all-features --locked --workspace --quiet check-try-runtime: runs-on: ${{ needs.preflight.outputs.RUNNER }} needs: [preflight] diff --git a/.github/workflows/misc-sync-templates.yml b/.github/workflows/misc-sync-templates.yml index b5db0538569b..7ff0705fe249 100644 --- a/.github/workflows/misc-sync-templates.yml +++ b/.github/workflows/misc-sync-templates.yml @@ -83,6 +83,12 @@ jobs: homepage = "https://paritytech.github.io/polkadot-sdk/" [workspace] + EOF + + [ ${{ matrix.template }} != "solochain" ] && echo "# Leave out the node compilation from regular template usage." \ + && echo "\"default-members\" = [\"pallets/template\", \"runtime\"]" >> Cargo.toml + [ ${{ matrix.template }} == "solochain" ] && echo "# The node isn't yet replaceable by Omni Node." + cat << EOF >> Cargo.toml members = [ "node", "pallets/template", diff --git a/Cargo.lock b/Cargo.lock index 520b088f913c..14ce58be7faa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3077,6 +3077,32 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" +[[package]] +name = "cmd_lib" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "371c15a3c178d0117091bd84414545309ca979555b1aad573ef591ad58818d41" +dependencies = [ + "cmd_lib_macros", + "env_logger 0.10.1", + "faccess", + "lazy_static", + "log", + "os_pipe", +] + +[[package]] +name = "cmd_lib_macros" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb844bd05be34d91eb67101329aeba9d3337094c04fd8507d821db7ebb488eaf" +dependencies = [ + "proc-macro-error2", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.82", +] + [[package]] name = "coarsetime" version = "0.1.23" @@ -5389,18 +5415,18 @@ checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" [[package]] name = "docify" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43a2f138ad521dc4a2ced1a4576148a6a610b4c5923933b062a263130a6802ce" +checksum = "a772b62b1837c8f060432ddcc10b17aae1453ef17617a99bc07789252d2a5896" dependencies = [ "docify_macros", ] [[package]] name = "docify_macros" -version = "0.2.8" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a081e51fb188742f5a7a1164ad752121abcb22874b21e2c3b0dd040c515fdad" +checksum = "60e6be249b0a462a14784a99b19bf35a667bb5e09de611738bb7362fa4c95ff7" dependencies = [ "common-path", "derive-syn-parse", @@ -5899,6 +5925,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "faccess" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ae66425802d6a903e268ae1a08b8c38ba143520f227a205edf4e9c7e3e26d5" +dependencies = [ + "bitflags 1.3.2", + "libc", + "winapi", +] + [[package]] name = "fallible-iterator" version = "0.2.0" @@ -10733,6 +10770,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "os_pipe" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982" +dependencies = [ + "libc", + "windows-sys 0.59.0", +] + [[package]] name = "os_str_bytes" version = "6.5.1" @@ -16771,6 +16818,28 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.82", +] + [[package]] name = "proc-macro-hack" version = "0.5.20+deprecated" @@ -23493,6 +23562,8 @@ name = "staging-chain-spec-builder" version = "1.6.1" dependencies = [ "clap 4.5.13", + "cmd_lib", + "docify", "log", "sc-chain-spec", "serde", @@ -26744,7 +26815,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" dependencies = [ "windows-core 0.52.0", - "windows-targets 0.52.0", + "windows-targets 0.52.6", ] [[package]] @@ -26762,7 +26833,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.6", ] [[package]] @@ -26789,7 +26860,16 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", ] [[package]] @@ -26824,17 +26904,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -26851,9 +26932,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" @@ -26869,9 +26950,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" @@ -26887,9 +26968,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" @@ -26905,9 +26992,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" @@ -26923,9 +27010,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" @@ -26941,9 +27028,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" @@ -26959,9 +27046,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" diff --git a/Cargo.toml b/Cargo.toml index e451529431ba..f3042a8a3bdf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -556,7 +556,13 @@ default-members = [ [workspace.lints.rust] suspicious_double_ref_op = { level = "allow", priority = 2 } # `substrate_runtime` is a common `cfg` condition name used in the repo. -unexpected_cfgs = { level = "warn", check-cfg = ['cfg(build_opt_level, values("3"))', 'cfg(build_profile, values("debug", "release"))', 'cfg(enable_alloc_error_handler)', 'cfg(fuzzing)', 'cfg(substrate_runtime)'] } +unexpected_cfgs = { level = "warn", check-cfg = [ + 'cfg(build_opt_level, values("3"))', + 'cfg(build_profile, values("debug", "release"))', + 'cfg(enable_alloc_error_handler)', + 'cfg(fuzzing)', + 'cfg(substrate_runtime)', +] } [workspace.lints.clippy] all = { level = "allow", priority = 0 } @@ -677,6 +683,7 @@ cid = { version = "0.9.0" } clap = { version = "4.5.13" } clap-num = { version = "1.0.2" } clap_complete = { version = "4.5.13" } +cmd_lib = { version = "1.9.5" } coarsetime = { version = "0.1.22" } codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" } collectives-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend" } @@ -735,7 +742,7 @@ derive_more = { version = "0.99.17", default-features = false } digest = { version = "0.10.3", default-features = false } directories = { version = "5.0.1" } dlmalloc = { version = "0.2.4" } -docify = { version = "0.2.8" } +docify = { version = "0.2.9" } dyn-clonable = { version = "0.9.0" } dyn-clone = { version = "1.0.16" } ed25519-dalek = { version = "2.1", default-features = false } @@ -1087,7 +1094,9 @@ polkavm-derive = "0.9.1" polkavm-linker = "0.9.2" portpicker = { version = "0.1.1" } pretty_assertions = { version = "1.3.0" } -primitive-types = { version = "0.13.1", default-features = false, features = ["num-traits"] } +primitive-types = { version = "0.13.1", default-features = false, features = [ + "num-traits", +] } proc-macro-crate = { version = "3.0.0" } proc-macro-warning = { version = "1.0.0", default-features = false } proc-macro2 = { version = "1.0.86" } diff --git a/cumulus/polkadot-omni-node/README.md b/cumulus/polkadot-omni-node/README.md new file mode 100644 index 000000000000..d87b3b63c407 --- /dev/null +++ b/cumulus/polkadot-omni-node/README.md @@ -0,0 +1,65 @@ +# Polkadot Omni Node + +This is a white labeled implementation based on [`polkadot-omni-node-lib`](https://crates.io/crates/polkadot-omni-node-lib). +It can be used to start a parachain node from a provided chain spec file. It is only compatible with runtimes that use block +number `u32` and `Aura` consensus. + +## Installation + +Download & expose it via `PATH`: + +```bash +# Download and set it on PATH. +wget https://github.com/paritytech/polkadot-sdk/releases/download//polkadot-omni-node +chmod +x polkadot-omni-node +export PATH="$PATH:`pwd`" +``` + +Compile & install via `cargo`: + +```bash +# Assuming ~/.cargo/bin is on the PATH +cargo install polkadot-omni-node +``` + +## Usage + +A basic example for an Omni Node run starts from a runtime which implements the [`sp_genesis_builder::GenesisBuilder`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html). +The interface mandates the runtime to expose a [`named-preset`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/#generate-chain-spec-using-runtime-provided-genesis-config-preset). + +### 1. Install chain-spec-builder + +**Note**: `chain-spec-builder` binary is published on [`crates.io`](https://crates.io) under +[`staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder) due to a name conflict. +Install it with `cargo` like bellow : + +```bash +cargo install staging-chain-spec-builder +``` + +### 2. Generate a chain spec + +Omni Node expects for the chain spec to contain parachains related fields like `relay_chain` and `para_id`. +These fields can be introduced by running [`staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder) +with additional flags: + +```bash +chain-spec-builder create --relay-chain --para-id -r named-preset +``` + +### 3. Run Omni Node + +And now with the generated chain spec we can start Omni Node like so: + +```bash +polkadot-omni-node --chain +``` + +## Useful links + +* [`Omni Node Polkadot SDK Docs`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/omni_node/index.html) +* [`Chain Spec Genesis Reference Docs`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/chain_spec_genesis/index.html) +* [`polkadot-parachain-bin`](https://crates.io/crates/polkadot-parachain-bin) +* [`polkadot-sdk-parachain-template`](https://github.com/paritytech/polkadot-sdk-parachain-template) +* [`frame-omni-bencher`](https://crates.io/crates/frame-omni-bencher) +* [`staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder) diff --git a/cumulus/polkadot-omni-node/lib/README.md b/cumulus/polkadot-omni-node/lib/README.md new file mode 100644 index 000000000000..5789a35a1016 --- /dev/null +++ b/cumulus/polkadot-omni-node/lib/README.md @@ -0,0 +1,26 @@ +# Polkadot Omni Node Library + +Helper library that can be used to run a parachain node. + +## Overview + +This library can be used to run a parachain node while also customizing the chain specs +that are supported by default by the `--chain-spec` argument of the node's `CLI` +and the parameters of the runtime that is associated with each of these chain specs. + +## API + +The library exposes the possibility to provide a [`RunConfig`]. Through this structure +2 optional configurations can be provided: +- a chain spec loader (an implementation of [`chain_spec::LoadSpec`]): this can be used for + providing the chain specs that are supported by default by the `--chain-spec` argument of the + node's `CLI` and the actual chain config associated with each one. +- a runtime resolver (an implementation of [`runtime::RuntimeResolver`]): this can be used for + providing the parameters of the runtime that is associated with each of the chain specs + +Apart from this, a [`CliConfig`] can also be provided, that can be used to customize some +user-facing binary author, support url, etc. + +## Examples + +For an example, see the [`polkadot-parachain-bin`](https://crates.io/crates/polkadot-parachain-bin) crate. diff --git a/cumulus/polkadot-omni-node/lib/src/lib.rs b/cumulus/polkadot-omni-node/lib/src/lib.rs index 3f01f4211144..ccc1b542b253 100644 --- a/cumulus/polkadot-omni-node/lib/src/lib.rs +++ b/cumulus/polkadot-omni-node/lib/src/lib.rs @@ -14,40 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . -//! # Polkadot Omni Node Library -//! -//! Helper library that can be used to run a parachain node. -//! -//! ## Overview -//! -//! This library can be used to run a parachain node while also customizing the chain specs -//! that are supported by default by the `--chain-spec` argument of the node's `CLI` -//! and the parameters of the runtime that is associated with each of these chain specs. -//! -//! ## API -//! -//! The library exposes the possibility to provide a [`RunConfig`]. Through this structure -//! 2 optional configurations can be provided: -//! - a chain spec loader (an implementation of [`chain_spec::LoadSpec`]): this can be used for -//! providing the chain specs that are supported by default by the `--chain-spec` argument of the -//! node's `CLI` and the actual chain config associated with each one. -//! - a runtime resolver (an implementation of [`runtime::RuntimeResolver`]): this can be used for -//! providing the parameters of the runtime that is associated with each of the chain specs -//! -//! Apart from this, a [`CliConfig`] can also be provided, that can be used to customize some -//! user-facing binary author, support url, etc. -//! -//! ## Examples -//! -//! For an example, see the [`polkadot-parachain-bin`](https://crates.io/crates/polkadot-parachain-bin) crate. -//! -//! ## Binary -//! -//! It can be used to start a parachain node from a provided chain spec file. -//! It is only compatible with runtimes that use block number `u32` and `Aura` consensus. -//! -//! Example: `polkadot-omni-node --chain ` - +#![doc = include_str!("../README.md")] #![deny(missing_docs)] pub mod cli; diff --git a/prdoc/pr_5954.prdoc b/prdoc/pr_5954.prdoc new file mode 100644 index 000000000000..2c9efcce7a6a --- /dev/null +++ b/prdoc/pr_5954.prdoc @@ -0,0 +1,19 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "templates: make node compilation optional" + +doc: + - audience: [Node Dev, Runtime Dev] + description: | + Node compilation for minimal and parachain templates is made optional, not part of the + templates `default-members` list. At the same time, we introduce OmniNode as alternative + to run the templates. + +crates: + - name: polkadot-omni-node + bump: patch + - name: polkadot-omni-node-lib + bump: patch + - name: staging-chain-spec-builder + bump: patch diff --git a/substrate/bin/utils/chain-spec-builder/Cargo.toml b/substrate/bin/utils/chain-spec-builder/Cargo.toml index f2fe8cb7e166..b71e935a918f 100644 --- a/substrate/bin/utils/chain-spec-builder/Cargo.toml +++ b/substrate/bin/utils/chain-spec-builder/Cargo.toml @@ -21,15 +21,28 @@ path = "bin/main.rs" name = "chain-spec-builder" [lib] -crate-type = ["rlib"] +# Docs tests are not needed since the code samples that would be executed +# are exercised already in the context of unit/integration tests, by virtue +# of using a combination of encapsulation in functions + `docify::export`. +# This is a practice we should use for new code samples if any. +doctest = false [dependencies] clap = { features = ["derive"], workspace = true } +docify = { workspace = true } log = { workspace = true, default-features = true } -sc-chain-spec = { features = ["clap"], workspace = true, default-features = true } +sc-chain-spec = { features = [ + "clap", +], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } serde = { workspace = true, default-features = true } sp-tracing = { workspace = true, default-features = true } [dev-dependencies] substrate-test-runtime = { workspace = true } +cmd_lib = { workspace = true } +docify = { workspace = true } + +[features] +# `cargo build --feature=generate-readme` updates the `README.md` file. +generate-readme = [] diff --git a/substrate/bin/utils/chain-spec-builder/README.docify.md b/substrate/bin/utils/chain-spec-builder/README.docify.md new file mode 100644 index 000000000000..bb4db4c666e0 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/README.docify.md @@ -0,0 +1,102 @@ +# Chain Spec Builder + +Substrate's chain spec builder utility. + +A chain-spec is short for `chain-specification`. See the [`sc-chain-spec`](https://crates.io/docs.rs/sc-chain-spec/latest/sc_chain_spec) +for more information. + +_Note:_ this binary is a more flexible alternative to the `build-spec` subcommand, contained in typical Substrate-based nodes. +This particular binary is capable of interacting with [`sp-genesis-builder`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/index.html) +implementation of any provided runtime allowing to build chain-spec JSON files. + +See [`ChainSpecBuilderCmd`](https://docs.rs/staging-chain-spec-builder/6.0.0/staging_chain_spec_builder/enum.ChainSpecBuilderCmd.html) +for a list of available commands. + +## Installation + +```bash +cargo install staging-chain-spec-builder +``` + +_Note:_ `chain-spec-builder` binary is published on [crates.io](https://crates.io) under +[`staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder) due to a name conflict. + +## Usage + +Please note that below usage is backed by integration tests. The commands' examples are wrapped +around by the `bash!(...)` macro calls. + +### Generate chains-spec using default config from runtime + +Query the default genesis config from the provided runtime WASM blob and use it in the chain spec. + + + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### Display the runtime's default `GenesisConfig` + + + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### Display the `GenesisConfig` preset with given name + + + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### List the names of `GenesisConfig` presets provided by runtime + + + +_Note:_ [`GenesisBuilder::preset_names`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.preset_names) +runtime function is called. + +### Generate chain spec using runtime provided genesis config preset + +Patch the runtime's default genesis config with the named preset provided by the runtime and generate the plain +version of chain spec: + + + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime functions are called. + +### Generate raw storage chain spec using genesis config patch + +Patch the runtime's default genesis config with provided `patch.json` and generate raw +storage (`-s`) version of chain spec: + + + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +and +[`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) +runtime functions are called. + +### Generate raw storage chain spec using full genesis config + +Build the chain spec using provided full genesis config json file. No defaults will be used: + + + +_Note_: [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) +runtime function is called. + +### Generate human readable chain spec using provided genesis config patch + + + +### Generate human readable chain spec using provided full genesis config + + + +### Extra tools + +The `chain-spec-builder` provides also some extra utilities: [`VerifyCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.VerifyCmd.html), +[`ConvertToRawCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.ConvertToRawCmd.html), +[`UpdateCodeCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.UpdateCodeCmd.html). diff --git a/substrate/bin/utils/chain-spec-builder/README.md b/substrate/bin/utils/chain-spec-builder/README.md new file mode 100644 index 000000000000..e03c710ce1b3 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/README.md @@ -0,0 +1,140 @@ +# Chain Spec Builder + +Substrate's chain spec builder utility. + +A chain-spec is short for `chain-specification`. See the [`sc-chain-spec`](https://crates.io/docs.rs/sc-chain-spec/latest/sc_chain_spec) +for more information. + +_Note:_ this binary is a more flexible alternative to the `build-spec` subcommand, contained in typical Substrate-based nodes. +This particular binary is capable of interacting with [`sp-genesis-builder`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/index.html) +implementation of any provided runtime allowing to build chain-spec JSON files. + +See [`ChainSpecBuilderCmd`](https://docs.rs/staging-chain-spec-builder/6.0.0/staging_chain_spec_builder/enum.ChainSpecBuilderCmd.html) +for a list of available commands. + +## Installation + +```bash +cargo install staging-chain-spec-builder +``` + +_Note:_ `chain-spec-builder` binary is published on [crates.io](https://crates.io) under +[`staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder) due to a name conflict. + +## Usage + +Please note that below usage is backed by integration tests. The commands' examples are wrapped +around by the `bash!(...)` macro calls. + +### Generate chains-spec using default config from runtime + +Query the default genesis config from the provided runtime WASM blob and use it in the chain spec. + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path default +) +``` + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### Display the runtime's default `GenesisConfig` + +```rust,ignore +bash!( + chain-spec-builder display-preset -r $runtime_path +) +``` + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### Display the `GenesisConfig` preset with given name + +```rust,ignore +fn cmd_display_preset(runtime_path: &str) -> String { + bash!( + chain-spec-builder display-preset -r $runtime_path -p "staging" + ) +} +``` + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime function is called. + +### List the names of `GenesisConfig` presets provided by runtime + +```rust,ignore +bash!( + chain-spec-builder list-presets -r $runtime_path +) +``` + +_Note:_ [`GenesisBuilder::preset_names`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.preset_names) +runtime function is called. + +### Generate chain spec using runtime provided genesis config preset + +Patch the runtime's default genesis config with the named preset provided by the runtime and generate the plain +version of chain spec: + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create --relay-chain "dev" --para-id 1000 -r $runtime_path named-preset "staging" +) +``` + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +runtime functions are called. + +### Generate raw storage chain spec using genesis config patch + +Patch the runtime's default genesis config with provided `patch.json` and generate raw +storage (`-s`) version of chain spec: + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create -s -r $runtime_path patch "tests/input/patch.json" +) +``` + +_Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) +and +[`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) +runtime functions are called. + +### Generate raw storage chain spec using full genesis config + +Build the chain spec using provided full genesis config json file. No defaults will be used: + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create -s -r $runtime_path full "tests/input/full.json" +) +``` + +_Note_: [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) +runtime function is called. + +### Generate human readable chain spec using provided genesis config patch + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path patch "tests/input/patch.json" +) +``` + +### Generate human readable chain spec using provided full genesis config + +```rust,ignore +bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path full "tests/input/full.json" +) +``` + +### Extra tools + +The `chain-spec-builder` provides also some extra utilities: [`VerifyCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.VerifyCmd.html), +[`ConvertToRawCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.ConvertToRawCmd.html), +[`UpdateCodeCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.UpdateCodeCmd.html). diff --git a/substrate/bin/utils/chain-spec-builder/src/lib.rs b/substrate/bin/utils/chain-spec-builder/src/lib.rs index 629edcf68568..98ff480b8ceb 100644 --- a/substrate/bin/utils/chain-spec-builder/src/lib.rs +++ b/substrate/bin/utils/chain-spec-builder/src/lib.rs @@ -15,107 +15,9 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . - -//! Substrate's chain spec builder utility. -//! -//! A chain-spec is short for `chain-configuration`. See the [`sc-chain-spec`] for more information. -//! -//! Note that this binary is analogous to the `build-spec` subcommand, contained in typical -//! substrate-based nodes. This particular binary is capable of interacting with -//! [`sp-genesis-builder`] implementation of any provided runtime allowing to build chain-spec JSON -//! files. -//! -//! See [`ChainSpecBuilderCmd`] for a list of available commands. -//! -//! ## Typical use-cases. -//! ##### Generate chains-spec using default config from runtime. -//! -//! Query the default genesis config from the provided `runtime.wasm` and use it in the chain -//! spec. -//! ```bash -//! chain-spec-builder create -r runtime.wasm default -//! ``` -//! -//! _Note:_ [`GenesisBuilder::get_preset`][sp-genesis-builder-get-preset] runtime function is -//! called. -//! -//! -//! ##### Display the runtime's default `GenesisConfig` -//! -//! Displays the content of the runtime's default `GenesisConfig` -//! ```bash -//! chain-spec-builder display-preset -r runtime.wasm -//! ``` -//! -//! _Note:_ [`GenesisBuilder::get_preset`][sp-genesis-builder-get-preset] runtime function is called. -//! -//! ##### Display the `GenesisConfig` preset with given name -//! -//! Displays the content of the `GenesisConfig` preset for given name -//! ```bash -//! chain-spec-builder display-preset -r runtime.wasm -p "staging" -//! ``` -//! -//! _Note:_ [`GenesisBuilder::get_preset`][sp-genesis-builder-get-preset] runtime function is called. -//! -//! ##### List the names of `GenesisConfig` presets provided by runtime. -//! -//! Displays the names of the presets of `GenesisConfigs` provided by runtime. -//! ```bash -//! chain-spec-builder list-presets -r runtime.wasm -//! ``` -//! -//! _Note:_ [`GenesisBuilder::preset_names`][sp-genesis-builder-list] runtime function is called. -//! -//! ##### Generate chain spec using runtime provided genesis config preset. -//! -//! Patch the runtime's default genesis config with the named preset provided by the runtime and generate the plain -//! version of chain spec: -//! ```bash -//! chain-spec-builder create -r runtime.wasm named-preset "staging" -//! ``` -//! -//! _Note:_ [`GenesisBuilder::get_preset`][sp-genesis-builder-get-preset] and [`GenesisBuilder::build_state`][sp-genesis-builder-build] runtime functions are called. -//! -//! ##### Generate raw storage chain spec using genesis config patch. -//! -//! Patch the runtime's default genesis config with provided `patch.json` and generate raw -//! storage (`-s`) version of chain spec: -//! ```bash -//! chain-spec-builder create -s -r runtime.wasm patch patch.json -//! ``` -//! -//! _Note:_ [`GenesisBuilder::build_state`][sp-genesis-builder-build] runtime function is called. -//! -//! ##### Generate raw storage chain spec using full genesis config. -//! -//! Build the chain spec using provided full genesis config json file. No defaults will be used: -//! ```bash -//! chain-spec-builder create -s -r runtime.wasm full full-genesis-config.json -//! ``` -//! -//! _Note_: [`GenesisBuilder::build_state`][sp-genesis-builder-build] runtime function is called. -//! -//! ##### Generate human readable chain spec using provided genesis config patch. -//! ```bash -//! chain-spec-builder create -r runtime.wasm patch patch.json -//! ``` -//! -//! ##### Generate human readable chain spec using provided full genesis config. -//! ```bash -//! chain-spec-builder create -r runtime.wasm full full-genesis-config.json -//! ``` -//! -//! ##### Extra tools. -//! The `chain-spec-builder` provides also some extra utilities: [`VerifyCmd`], [`ConvertToRawCmd`], -//! [`UpdateCodeCmd`]. -//! -//! [`sc-chain-spec`]: ../sc_chain_spec/index.html -//! [`node-cli`]: ../node_cli/index.html -//! [`sp-genesis-builder`]: ../sp_genesis_builder/index.html -//! [sp-genesis-builder-build]: ../sp_genesis_builder/trait.GenesisBuilder.html#method.build_state -//! [sp-genesis-builder-list]: ../sp_genesis_builder/trait.GenesisBuilder.html#method.preset_names -//! [sp-genesis-builder-get-preset]: ../sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset +#![doc = include_str!("../README.md")] +#[cfg(feature = "generate-readme")] +docify::compile_markdown!("README.docify.md", "README.md"); use clap::{Parser, Subcommand}; use sc_chain_spec::{ diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/create_with_full.json b/substrate/bin/utils/chain-spec-builder/tests/expected/create_with_full.json index 6d127b6c0aca..10071670179a 100644 --- a/substrate/bin/utils/chain-spec-builder/tests/expected/create_with_full.json +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/create_with_full.json @@ -16,9 +16,18 @@ "config": { "babe": { "authorities": [ - "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", - "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b" + [ + "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + 1 + ], + [ + "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", + 1 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 1 + ] ], "epochConfig": { "allowed_slots": "PrimaryAndSecondaryVRFSlots", diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_default.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_default.json new file mode 100644 index 000000000000..203b6716cb26 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_default.json @@ -0,0 +1,36 @@ +{ + "name": "Custom", + "id": "custom", + "chainType": "Live", + "bootNodes": [], + "telemetryEndpoints": null, + "protocolId": null, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "codeSubstitutes": {}, + "genesis": { + "runtimeGenesis": { + "config": { + "babe": { + "authorities": [], + "epochConfig": { + "allowed_slots": "PrimaryAndSecondaryVRFSlots", + "c": [ + 1, + 4 + ] + } + }, + "balances": { + "balances": [] + }, + "substrateTest": { + "authorities": [] + }, + "system": {} + } + } + } +} \ No newline at end of file diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_plain.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_plain.json new file mode 100644 index 000000000000..26868c3241a1 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_plain.json @@ -0,0 +1,66 @@ +{ + "name": "Custom", + "id": "custom", + "chainType": "Live", + "bootNodes": [], + "telemetryEndpoints": null, + "protocolId": null, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "codeSubstitutes": {}, + "genesis": { + "runtimeGenesis": { + "config": { + "babe": { + "authorities": [ + [ + "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + 1 + ], + [ + "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", + 1 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 1 + ] + ], + "epochConfig": { + "allowed_slots": "PrimaryAndSecondaryVRFSlots", + "c": [ + 2, + 4 + ] + } + }, + "balances": { + "balances": [ + [ + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + 2000000000000000 + ], + [ + "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", + 2000000000000000 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 5000000000000000 + ] + ] + }, + "substrateTest": { + "authorities": [ + "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b" + ] + }, + "system": {} + } + } + } +} \ No newline at end of file diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_raw.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_raw.json new file mode 100644 index 000000000000..523a266fc439 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_full_raw.json @@ -0,0 +1,39 @@ +{ + "name": "Custom", + "id": "custom", + "chainType": "Live", + "bootNodes": [], + "telemetryEndpoints": null, + "protocolId": null, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "codeSubstitutes": {}, + "genesis": { + "raw": { + "top": { + "0x00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x00771836bebdd29870ff246d305c578c5e0621c4869aa60c02be9adcc98a0d1d": "0x0cd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e", + "0x1cb6f36e027abb2091cfb5110ab5087f4e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x1cb6f36e027abb2091cfb5110ab5087f5e0621c4869aa60c02be9adcc98a0d1d": "0x0cd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d01000000000000001cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c0100000000000000186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e0100000000000000", + "0x1cb6f36e027abb2091cfb5110ab5087f66e8f035c8adbe7f1547b43c51e6f8a4": "0x00000000", + "0x1cb6f36e027abb2091cfb5110ab5087faacf00b9b41fda7a9268821c2a2b3e4c": "0x0cd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d01000000000000001cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c0100000000000000186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e0100000000000000", + "0x1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef": "0x0200000000000000040000000000000002", + "0x26aa394eea5630e07c48ae0c9558cef74e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x26aa394eea5630e07c48ae0c9558cef75684a022a34dd8bfa2baaf44f172b710": "0x01", + "0x26aa394eea5630e07c48ae0c9558cef78a42f33323cb5ced3b44dd825fda9fcc": "0x4545454545454545454545454545454545454545454545454545454545454545", + "0x26aa394eea5630e07c48ae0c9558cef7a44704b568d21667356a5a050c118746bb1bdbcacd6ac9340000000000000000": "0x4545454545454545454545454545454545454545454545454545454545454545", + "0x26aa394eea5630e07c48ae0c9558cef7a7fd6c28836b9a28522dc924110cf439": "0x01", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da92c2a60ec6dd16cd8ab911865ecf7555b186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e": "0x00000000000000000000000001000000000000000080e03779c311000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48": "0x000000000000000000000000010000000000000000008d49fd1a07000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9b0edae20838083f2cde1c4080db8cf8090b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22": "0x000000000000000000000000010000000000000000008d49fd1a07000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7f9cce9c888469bb1a0dceaa129672ef8": "0x0000", + "0x3a65787472696e7369635f696e646578": "0x00000000", + "0xc2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429": "0x0100", + "0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80": "0x0080faca73f91f00" + }, + "childrenDefault": {} + } + } +} diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_named_preset_staging.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_named_preset_staging.json new file mode 100644 index 000000000000..5cf51554b2cb --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_named_preset_staging.json @@ -0,0 +1,39 @@ +{ + "bootNodes": [], + "chainType": "Live", + "codeSubstitutes": {}, + "genesis": { + "runtimeGenesis": { + "patch": { + "balances": { + "balances": [ + [ + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + 1000000000000000 + ], + [ + "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", + 1000000000000000 + ] + ] + }, + "substrateTest": { + "authorities": [ + "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL" + ] + } + } + } + }, + "id": "custom", + "name": "Custom", + "para_id": 1000, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "protocolId": null, + "relay_chain": "dev", + "telemetryEndpoints": null +} \ No newline at end of file diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_plain.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_plain.json new file mode 100644 index 000000000000..b243534c0d61 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_plain.json @@ -0,0 +1,42 @@ +{ + "name": "Custom", + "id": "custom", + "chainType": "Live", + "bootNodes": [], + "telemetryEndpoints": null, + "protocolId": null, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "codeSubstitutes": {}, + "genesis": { + "runtimeGenesis": { + "patch": { + "balances": { + "balances": [ + [ + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + 1000000000000000 + ], + [ + "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", + 1000000000000000 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 5000000000000000 + ] + ] + }, + "substrateTest": { + "authorities": [ + "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", + "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b" + ] + } + } + } + } +} \ No newline at end of file diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_raw.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_raw.json new file mode 100644 index 000000000000..c4ac1cbe8ea1 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/create_with_patch_raw.json @@ -0,0 +1,37 @@ +{ + "name": "Custom", + "id": "custom", + "chainType": "Live", + "bootNodes": [], + "telemetryEndpoints": null, + "protocolId": null, + "properties": { + "tokenDecimals": 12, + "tokenSymbol": "UNIT" + }, + "codeSubstitutes": {}, + "genesis": { + "raw": { + "top": { + "0x00771836bebdd29870ff246d305c578c4e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x00771836bebdd29870ff246d305c578c5e0621c4869aa60c02be9adcc98a0d1d": "0x0cd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e", + "0x1cb6f36e027abb2091cfb5110ab5087f4e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x1cb6f36e027abb2091cfb5110ab5087f66e8f035c8adbe7f1547b43c51e6f8a4": "0x00000000", + "0x1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef": "0x0100000000000000040000000000000002", + "0x26aa394eea5630e07c48ae0c9558cef74e7b9012096b41c4eb3aaf947f6ea429": "0x0000", + "0x26aa394eea5630e07c48ae0c9558cef75684a022a34dd8bfa2baaf44f172b710": "0x01", + "0x26aa394eea5630e07c48ae0c9558cef78a42f33323cb5ced3b44dd825fda9fcc": "0x4545454545454545454545454545454545454545454545454545454545454545", + "0x26aa394eea5630e07c48ae0c9558cef7a44704b568d21667356a5a050c118746bb1bdbcacd6ac9340000000000000000": "0x4545454545454545454545454545454545454545454545454545454545454545", + "0x26aa394eea5630e07c48ae0c9558cef7a7fd6c28836b9a28522dc924110cf439": "0x01", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da92c2a60ec6dd16cd8ab911865ecf7555b186e1bafbb1430668c95d89b77217a402a74f64c3e103137b69e95e4b6e06b1e": "0x00000000000000000000000001000000000000000080e03779c311000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48": "0x00000000000000000000000001000000000000000080c6a47e8d03000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9b0edae20838083f2cde1c4080db8cf8090b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22": "0x00000000000000000000000001000000000000000080c6a47e8d03000000000000000000000000000000000000000000000000000000000000000080", + "0x26aa394eea5630e07c48ae0c9558cef7f9cce9c888469bb1a0dceaa129672ef8": "0x0000", + "0x3a65787472696e7369635f696e646578": "0x00000000", + "0xc2261276cc9d1f8598ea4b6a74b15c2f4e7b9012096b41c4eb3aaf947f6ea429": "0x0100", + "0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80": "0x00806d8176de1800" + }, + "childrenDefault": {} + } + } +} diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset.json new file mode 100644 index 000000000000..6aa6799af771 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset.json @@ -0,0 +1 @@ +{"babe":{"authorities":[],"epochConfig":{"allowed_slots":"PrimaryAndSecondaryVRFSlots","c":[1,4]}},"balances":{"balances":[]},"substrateTest":{"authorities":[]},"system":{}} diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset_staging.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset_staging.json new file mode 100644 index 000000000000..b0c8e40c23a9 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/display_preset_staging.json @@ -0,0 +1 @@ +{"balances":{"balances":[["5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty",1000000000000000],["5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y",1000000000000000]]},"substrateTest":{"authorities":["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY","5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL"]}} diff --git a/substrate/bin/utils/chain-spec-builder/tests/expected/doc/list_presets.json b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/list_presets.json new file mode 100644 index 000000000000..882462391888 --- /dev/null +++ b/substrate/bin/utils/chain-spec-builder/tests/expected/doc/list_presets.json @@ -0,0 +1 @@ +{"presets":["foobar","staging"]} diff --git a/substrate/bin/utils/chain-spec-builder/tests/input/full.json b/substrate/bin/utils/chain-spec-builder/tests/input/full.json index f05e3505a2bb..e34aede52cbe 100644 --- a/substrate/bin/utils/chain-spec-builder/tests/input/full.json +++ b/substrate/bin/utils/chain-spec-builder/tests/input/full.json @@ -1,9 +1,9 @@ { "babe": { "authorities": [ - "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", - "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", - "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b" + ["5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", 1], + ["5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL", 1], + ["5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", 1] ], "epochConfig": { "allowed_slots": "PrimaryAndSecondaryVRFSlots", diff --git a/substrate/bin/utils/chain-spec-builder/tests/test.rs b/substrate/bin/utils/chain-spec-builder/tests/test.rs index f553f05f20a0..5ac687d75fd4 100644 --- a/substrate/bin/utils/chain-spec-builder/tests/test.rs +++ b/substrate/bin/utils/chain-spec-builder/tests/test.rs @@ -19,7 +19,10 @@ use std::fs::File; use clap::Parser; + +use cmd_lib::spawn_with_output; use sc_chain_spec::update_code_in_json_chain_spec; +use serde_json::{from_reader, from_str, Value}; use staging_chain_spec_builder::ChainSpecBuilder; // note: the runtime path will not be read, runtime code will be set directly, to avoid hassle with @@ -28,6 +31,44 @@ const DUMMY_PATH: &str = "fake-runtime-path"; const OUTPUT_FILE: &str = "/tmp/chain_spec_builder.test_output_file.json"; +// Used for running commands visually pleasing in doc tests. +macro_rules! bash( + ( chain-spec-builder $($a:tt)* ) => {{ + let bin_path = env!("CARGO_BIN_EXE_chain-spec-builder"); + spawn_with_output!( + $bin_path $($a)* + ) + .expect("a process running. qed") + .wait_with_output() + .expect("to get output. qed.") + }} +); + +// Used specifically in docs tests. +fn doc_assert(output: String, expected_output_path: &str, remove_code: bool) { + let expected: Value = + from_reader(File::open(expected_output_path).unwrap()).expect("a valid JSON. qed."); + let output = if remove_code { + let mut output: Value = from_str(output.as_str()).expect("a valid JSON. qed."); + // Remove code sections gracefully for both `plain` & `raw`. + output + .get_mut("genesis") + .and_then(|inner| inner.get_mut("runtimeGenesis")) + .and_then(|inner| inner.as_object_mut()) + .and_then(|inner| inner.remove("code")); + output + .get_mut("genesis") + .and_then(|inner| inner.get_mut("raw")) + .and_then(|inner| inner.get_mut("top")) + .and_then(|inner| inner.as_object_mut()) + .and_then(|inner| inner.remove("0x3a636f6465")); + output + } else { + from_str::(output.as_str()).expect("a valid JSON. qed.") + }; + assert_eq!(output, expected); +} + /// Asserts that the JSON in output file matches the JSON in expected file. /// /// This helper function reads the JSON content from the file at `OUTPUT_FILE + suffix` path. If the @@ -192,3 +233,165 @@ fn test_add_code_substitute() { builder.run().unwrap(); assert_output_eq_expected(true, SUFFIX, "tests/expected/add_code_substitute.json"); } + +#[docify::export_content] +fn cmd_create_default(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path default + ) +} + +#[test] +fn create_default() { + doc_assert( + cmd_create_default( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_default.json", + true, + ); +} + +#[docify::export_content] +fn cmd_display_default_preset(runtime_path: &str) -> String { + bash!( + chain-spec-builder display-preset -r $runtime_path + ) +} + +#[test] +fn display_default_preset() { + doc_assert( + cmd_display_default_preset( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed."), + ), + "tests/expected/doc/display_preset.json", + false, + ); +} + +#[docify::export] +fn cmd_display_preset(runtime_path: &str) -> String { + bash!( + chain-spec-builder display-preset -r $runtime_path -p "staging" + ) +} + +#[test] +fn display_preset() { + doc_assert( + cmd_display_preset( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/display_preset_staging.json", + false, + ); +} + +#[docify::export_content] +fn cmd_list_presets(runtime_path: &str) -> String { + bash!( + chain-spec-builder list-presets -r $runtime_path + ) +} + +#[test] +fn list_presets() { + doc_assert( + cmd_list_presets( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/list_presets.json", + false, + ); +} + +#[docify::export_content] +fn cmd_create_with_named_preset(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create --relay-chain "dev" --para-id 1000 -r $runtime_path named-preset "staging" + ) +} + +#[test] +fn create_with_named_preset() { + doc_assert( + cmd_create_with_named_preset( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_with_named_preset_staging.json", + true, + ) +} + +#[docify::export_content] +fn cmd_create_with_patch_raw(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create -s -r $runtime_path patch "tests/input/patch.json" + ) +} + +#[test] +fn create_with_patch_raw() { + doc_assert( + cmd_create_with_patch_raw( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_with_patch_raw.json", + true, + ); +} + +#[docify::export_content] +fn cmd_create_with_patch_plain(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path patch "tests/input/patch.json" + ) +} + +#[test] +fn create_with_patch_plain() { + doc_assert( + cmd_create_with_patch_plain( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_with_patch_plain.json", + true, + ); +} + +#[docify::export_content] +fn cmd_create_full_plain(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create -r $runtime_path full "tests/input/full.json" + ) +} + +#[test] +fn create_full_plain() { + doc_assert( + cmd_create_full_plain( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_full_plain.json", + true, + ); +} + +#[docify::export_content] +fn cmd_create_full_raw(runtime_path: &str) -> String { + bash!( + chain-spec-builder -c "/dev/stdout" create -s -r $runtime_path full "tests/input/full.json" + ) +} + +#[test] +fn create_full_raw() { + doc_assert( + cmd_create_full_raw( + substrate_test_runtime::WASM_BINARY_PATH.expect("to be a valid path. qed"), + ), + "tests/expected/doc/create_full_raw.json", + true, + ); +} diff --git a/substrate/utils/wasm-builder/src/builder.rs b/substrate/utils/wasm-builder/src/builder.rs index eb761a103d62..a40aafe1d812 100644 --- a/substrate/utils/wasm-builder/src/builder.rs +++ b/substrate/utils/wasm-builder/src/builder.rs @@ -303,7 +303,8 @@ fn provide_dummy_wasm_binary_if_not_exist(file_path: &Path) { if !file_path.exists() { crate::write_file_if_changed( file_path, - "pub const WASM_BINARY: Option<&[u8]> = None;\ + "pub const WASM_BINARY_PATH: Option<&str> = None;\ + pub const WASM_BINARY: Option<&[u8]> = None;\ pub const WASM_BINARY_BLOATY: Option<&[u8]> = None;", ); } @@ -378,9 +379,11 @@ fn build_project( file_name, format!( r#" + pub const WASM_BINARY_PATH: Option<&str> = Some("{wasm_binary_path}"); pub const WASM_BINARY: Option<&[u8]> = Some(include_bytes!("{wasm_binary}")); pub const WASM_BINARY_BLOATY: Option<&[u8]> = Some(include_bytes!("{wasm_binary_bloaty}")); "#, + wasm_binary_path = wasm_binary, wasm_binary = wasm_binary, wasm_binary_bloaty = wasm_binary_bloaty, ), diff --git a/substrate/utils/wasm-builder/src/lib.rs b/substrate/utils/wasm-builder/src/lib.rs index e3f2ff5cd733..420ecd63e1dc 100644 --- a/substrate/utils/wasm-builder/src/lib.rs +++ b/substrate/utils/wasm-builder/src/lib.rs @@ -48,6 +48,8 @@ //! This will include the generated Wasm binary as two constants `WASM_BINARY` and //! `WASM_BINARY_BLOATY`. The former is a compact Wasm binary and the latter is the Wasm binary as //! being generated by the compiler. Both variables have `Option<&'static [u8]>` as type. +//! Additionally it will create the `WASM_BINARY_PATH` which is the path to the WASM blob on the +//! filesystem. //! //! ### Feature //! diff --git a/templates/minimal/Dockerfile b/templates/minimal/Dockerfile index 0c59192208fe..422f7f726a7e 100644 --- a/templates/minimal/Dockerfile +++ b/templates/minimal/Dockerfile @@ -4,7 +4,7 @@ WORKDIR /polkadot COPY . /polkadot RUN cargo fetch -RUN cargo build --locked --release +RUN cargo build --workspace --locked --release FROM docker.io/parity/base-bin:latest diff --git a/templates/minimal/README.md b/templates/minimal/README.md index fe1317a033c7..cf43d71d8849 100644 --- a/templates/minimal/README.md +++ b/templates/minimal/README.md @@ -11,30 +11,54 @@ -* 🤏 This template is a minimal (in terms of complexity and the number of components) +## Table of Contents + +- [Intro](#intro) + +- [Template Structure](#template-structure) + +- [Getting Started](#getting-started) + +- [Starting a Minimal Template Chain](#starting-a-minimal-template-chain) + + - [Omni Node](#omni-node) + - [Minimal Template Node](#minimal-template-node) + - [Zombienet with Omni Node](#zombienet-with-omni-node) + - [Zombienet with Minimal Template Node](#zombienet-with-minimal-template-node) + - [Connect with the Polkadot-JS Apps Front-End](#connect-with-the-polkadot-js-apps-front-end) + - [Takeaways](#takeaways) + +- [Contributing](#contributing) + +- [Getting Help](#getting-help) + +## Intro + +- 🤏 This template is a minimal (in terms of complexity and the number of components) template for building a blockchain node. -* 🔧 Its runtime is configured with a single custom pallet as a starting point, and a handful of ready-made pallets +- 🔧 Its runtime is configured with a single custom pallet as a starting point, and a handful of ready-made pallets such as a [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html). -* 👤 The template has no consensus configured - it is best for experimenting with a single node network. +- 👤 The template has no consensus configured - it is best for experimenting with a single node network. ## Template Structure A Polkadot SDK based project such as this one consists of: -* 💿 a [Node](./node/README.md) - the binary application. -* 🧮 the [Runtime](./runtime/README.md) - the core logic of the blockchain. -* 🎨 the [Pallets](./pallets/README.md) - from which the runtime is constructed. +- 🧮 the [Runtime](./runtime/README.md) - the core logic of the blockchain. +- 🎨 the [Pallets](./pallets/README.md) - from which the runtime is constructed. +- 💿 a [Node](./node/README.md) - the binary application (which is not part of the cargo default-members list and is not +compiled unless building the entire workspace). ## Getting Started -* 🦀 The template is using the Rust language. +- 🦀 The template is using the Rust language. -* 👉 Check the +- 👉 Check the [Rust installation instructions](https://www.rust-lang.org/tools/install) for your system. -* 🛠️ Depending on your operating system and Rust version, there might be additional +- 🛠️ Depending on your operating system and Rust version, there might be additional packages required to compile this template - please take note of the Rust compiler output. Fetch minimal template code: @@ -45,65 +69,152 @@ git clone https://github.com/paritytech/polkadot-sdk-minimal-template.git minima cd minimal-template ``` -### Build +## Starting a Minimal Template Chain + +### Omni Node + +[Omni Node](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/omni_node/index.html) can +be used to run the minimal template's runtime. `polkadot-omni-node` binary crate usage is described at a high-level +[on crates.io](https://crates.io/crates/polkadot-omni-node). + +#### Install `polkadot-omni-node` + +Please see installation section on [crates.io/omni-node](https://crates.io/crates/polkadot-omni-node). + +#### Build `minimal-template-runtime` + +```sh +cargo build -p minimal-template-runtime --release +``` + +#### Install `staging-chain-spec-builder` -🔨 Use the following command to build the node without launching it: +Please see the installation section at [`crates.io/staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder). + +#### Use chain-spec-builder to generate the chain_spec.json file ```sh -cargo build --release +chain-spec-builder create --relay-chain "dev" --para-id 1000 --runtime \ + target/release/wbuild/minimal-template-runtime/minimal_template_runtime.wasm named-preset development ``` -🐳 Alternatively, build the docker image: +**Note**: the `relay-chain` and `para-id` flags are extra bits of information required to +configure the node for the case of representing a parachain that is connected to a relay chain. +They are not relevant to minimal template business logic, but they are mandatory information for +Omni Node, nonetheless. + +#### Run Omni Node + +Start Omni Node with manual seal (3 seconds block times), minimal template runtime based +chain spec. We'll use `--tmp` flag to start the node with its configurations stored in a +temporary directory, which will be deleted at the end of the process. + +```sh +polkadot-omni-node --chain --dev-block-time 3000 --tmp +``` + +### Minimal Template Node + +#### Build both node & runtime + +```sh +cargo build --workspace --release +``` + +🐳 Alternatively, build the docker image which builds all the workspace members, +and has as entry point the node binary: ```sh docker build . -t polkadot-sdk-minimal-template ``` -### Single-Node Development Chain +#### Start the `minimal-template-node` -👤 The following command starts a single-node development chain: +The `minimal-template-node` has dependency on the `minimal-template-runtime`. It will use +the `minimal_template_runtime::WASM_BINARY` constant (which holds the WASM blob as a byte +array) for chain spec building, while starting. This is in contrast to Omni Node which doesn't +depend on a specific runtime, but asks for the chain spec at startup. ```sh -./target/release/minimal-template-node --dev + --tmp --consensus manual-seal-3000 +# or via docker +docker run --rm polkadot-sdk-minimal-template +``` + +### Zombienet with Omni Node + +#### Install `zombienet` + +We can install `zombienet` as described [here](https://paritytech.github.io/zombienet/install.html#installation), +and `zombienet-omni-node.toml` contains the network specification we want to start. + +#### Update `zombienet-omni-node.toml` with a valid chain spec path + +Before starting the network with zombienet we must update the network specification +with a valid chain spec path. If we need to generate one, we can look up at the previous +section for chain spec creation [here](#use-chain-spec-builder-to-generate-the-chain_specjson-file). -# docker version: -docker run --rm polkadot-sdk-minimal-template --dev +Then make the changes in the network specification like so: + +```toml +# ... +chain = "dev" +chain_spec_path = "" +default_args = ["--dev-block-time 3000"] +# .. +``` + +#### Start the network + +```sh +zombienet --provider native spawn zombienet-omni-node.toml ``` -Development chains: +### Zombienet with `minimal-template-node` -* 🧹 Do not persist the state. -* 💰 Are pre-configured with a genesis state that includes several pre-funded development accounts. -* 🧑‍⚖️ One development account (`ALICE`) is used as `sudo` accounts. +For this one we just need to have `zombienet` installed and run: + +```sh +zombienet --provider native spawn zombienet-multi-node.toml +``` ### Connect with the Polkadot-JS Apps Front-End -* 🌐 You can interact with your local node using the +- 🌐 You can interact with your local node using the hosted version of the [Polkadot/Substrate Portal](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944). -* 🪐 A hosted version is also +- 🪐 A hosted version is also available on [IPFS](https://dotapps.io/). -* 🧑‍🔧 You can also find the source code and instructions for hosting your own instance in the +- 🧑‍🔧 You can also find the source code and instructions for hosting your own instance in the [`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository. +### Takeaways + +Previously minimal template's development chains: + +- ❌ Started in a multi-node setup will produce forks because minimal lacks consensus. +- 🧹 Do not persist the state. +- 💰 Are pre-configured with a genesis state that includes several pre-funded development accounts. +- 🧑‍⚖️ One development account (`ALICE`) is used as `sudo` accounts. + ## Contributing -* 🔄 This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). +- 🔄 This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). -* ➡️ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/minimal). +- ➡️ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/minimal). -* 😇 Please refer to the monorepo's +- 😇 Please refer to the monorepo's [contribution guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) and [Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md). ## Getting Help -* 🧑‍🏫 To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. +- 🧑‍🏫 To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. -* 🧑‍🔧 For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are +- 🧑‍🔧 For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are the Polkadot SDK documentation resources. -* 👥 Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and +- 👥 Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and [Substrate StackExchange](https://substrate.stackexchange.com/). diff --git a/templates/minimal/node/src/cli.rs b/templates/minimal/node/src/cli.rs index 54107df75a36..f349f8c8da04 100644 --- a/templates/minimal/node/src/cli.rs +++ b/templates/minimal/node/src/cli.rs @@ -21,6 +21,7 @@ use polkadot_sdk::{sc_cli::RunCmd, *}; pub enum Consensus { ManualSeal(u64), InstantSeal, + None, } impl std::str::FromStr for Consensus { @@ -31,6 +32,8 @@ impl std::str::FromStr for Consensus { Consensus::InstantSeal } else if let Some(block_time) = s.strip_prefix("manual-seal-") { Consensus::ManualSeal(block_time.parse().map_err(|_| "invalid block time")?) + } else if s.to_lowercase() == "none" { + Consensus::None } else { return Err("incorrect consensus identifier".into()); }) diff --git a/templates/minimal/node/src/service.rs b/templates/minimal/node/src/service.rs index 169993e2e93a..f9a9d1e0f3cf 100644 --- a/templates/minimal/node/src/service.rs +++ b/templates/minimal/node/src/service.rs @@ -273,6 +273,7 @@ pub fn new_full::Ha authorship_future, ); }, + _ => {}, } network_starter.start_network(); diff --git a/templates/minimal/zombienet-omni-node.toml b/templates/minimal/zombienet-omni-node.toml new file mode 100644 index 000000000000..33b0fceba68c --- /dev/null +++ b/templates/minimal/zombienet-omni-node.toml @@ -0,0 +1,9 @@ +[relaychain] +default_command = "polkadot-omni-node" +chain = "dev" +chain_spec_path = "" +default_args = ["--dev-block-time 3000"] + +[[relaychain.nodes]] +name = "alice" +ws_port = 9944 diff --git a/templates/minimal/zombienet.toml b/templates/minimal/zombienet.toml new file mode 100644 index 000000000000..89df054bf652 --- /dev/null +++ b/templates/minimal/zombienet.toml @@ -0,0 +1,30 @@ +# The setup bellow allows only one node to produce +# blocks and the rest will follow. + +[relaychain] +chain = "dev" +default_command = "minimal-template-node" + +[[relaychain.nodes]] +name = "alice" +args = ["--consensus manual-seal-3000"] +validator = true +ws_port = 9944 + +[[relaychain.nodes]] +name = "bob" +args = ["--consensus None"] +validator = true +ws_port = 9955 + +[[relaychain.nodes]] +name = "charlie" +args = ["--consensus None"] +validator = true +ws_port = 9966 + +[[relaychain.nodes]] +name = "dave" +args = ["--consensus None"] +validator = true +ws_port = 9977 diff --git a/templates/parachain/Dockerfile b/templates/parachain/Dockerfile index 72a8f19fe79a..da1353d5fb9c 100644 --- a/templates/parachain/Dockerfile +++ b/templates/parachain/Dockerfile @@ -4,7 +4,7 @@ WORKDIR /polkadot COPY . /polkadot RUN cargo fetch -RUN cargo build --locked --release +RUN cargo build --workspace --locked --release FROM docker.io/parity/base-bin:latest diff --git a/templates/parachain/README.md b/templates/parachain/README.md index 3de85cbeb4dc..65a6979041f2 100644 --- a/templates/parachain/README.md +++ b/templates/parachain/README.md @@ -11,32 +11,55 @@ -* ⏫ This template provides a starting point to build a [parachain](https://wiki.polkadot.network/docs/learn-parachains). +## Table of Contents -* ☁️ It is based on the +- [Intro](#intro) + +- [Template Structure](#template-structure) + +- [Getting Started](#getting-started) + +- [Starting a Development Chain](#starting-a-development-chain) + + - [Omni Node](#omni-node-prerequisites) + - [Zombienet setup with Omni Node](#zombienet-setup-with-omni-node) + - [Parachain Template Node](#parachain-template-node) + - [Connect with the Polkadot-JS Apps Front-End](#connect-with-the-polkadot-js-apps-front-end) + - [Takeaways](#takeaways) + +- [Contributing](#contributing) +- [Getting Help](#getting-help) + +## Intro + +- ⏫ This template provides a starting point to build a [parachain](https://wiki.polkadot.network/docs/learn-parachains). + +- ☁️ It is based on the [Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html) framework. -* 🔧 Its runtime is configured with a single custom pallet as a starting point, and a handful of ready-made pallets +- 🔧 Its runtime is configured with a single custom pallet as a starting point, and a handful of ready-made pallets such as a [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html). -* 👉 Learn more about parachains [here](https://wiki.polkadot.network/docs/learn-parachains) +- 👉 Learn more about parachains [here](https://wiki.polkadot.network/docs/learn-parachains) ## Template Structure A Polkadot SDK based project such as this one consists of: -* 💿 a [Node](./node/README.md) - the binary application. -* 🧮 the [Runtime](./runtime/README.md) - the core logic of the parachain. -* 🎨 the [Pallets](./pallets/README.md) - from which the runtime is constructed. +- 🧮 the [Runtime](./runtime/README.md) - the core logic of the parachain. +- 🎨 the [Pallets](./pallets/README.md) - from which the runtime is constructed. +- 💿 a [Node](./node/README.md) - the binary application, not part of the project default-members list and not compiled unless +building the project with `--workspace` flag, which builds all workspace members, and is an alternative to +[Omni Node](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/omni_node/index.html). ## Getting Started -* 🦀 The template is using the Rust language. +- 🦀 The template is using the Rust language. -* 👉 Check the +- 👉 Check the [Rust installation instructions](https://www.rust-lang.org/tools/install) for your system. -* 🛠️ Depending on your operating system and Rust version, there might be additional +- 🛠️ Depending on your operating system and Rust version, there might be additional packages required to compile this template - please take note of the Rust compiler output. Fetch parachain template code: @@ -47,90 +70,149 @@ git clone https://github.com/paritytech/polkadot-sdk-parachain-template.git para cd parachain-template ``` -### Build +## Starting a Development Chain + +### Omni Node Prerequisites -🔨 Use the following command to build the node without launching it: +[Omni Node](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/omni_node/index.html) can +be used to run the parachain template's runtime. `polkadot-omni-node` binary crate usage is described at a high-level +[on crates.io](https://crates.io/crates/polkadot-omni-node). + +#### Install `polkadot-omni-node` + +Please see the installation section at [`crates.io/omni-node`](https://crates.io/crates/polkadot-omni-node). + +#### Build `parachain-template-runtime` ```sh cargo build --release ``` -🐳 Alternatively, build the docker image: +#### Install `staging-chain-spec-builder` + +Please see the installation section at [`crates.io/staging-chain-spec-builder`](https://crates.io/crates/staging-chain-spec-builder). + +#### Use `chain-spec-builder` to generate the `chain_spec.json` file ```sh -docker build . -t polkadot-sdk-parachain-template +chain-spec-builder create --relay-chain "rococo-local" --para-id 1000 --runtime \ + target/release/wbuild/parachain-template-runtime/parachain_template_runtime.wasm named-preset development ``` -### Local Development Chain +**Note**: the `relay-chain` and `para-id` flags are mandatory information required by +Omni Node, and for parachain template case the value for `para-id` must be set to `1000`, since this +is also the value injected through [ParachainInfo](https://docs.rs/staging-parachain-info/0.17.0/staging_parachain_info/) +pallet into the `parachain-template-runtime`'s storage. The `relay-chain` value is set in accordance +with the relay chain ID where this instantiation of parachain-template will connect to. -🧟 This project uses [Zombienet](https://github.com/paritytech/zombienet) to orchestrate the relaychain and parachain nodes. -You can grab a [released binary](https://github.com/paritytech/zombienet/releases/latest) or use an [npm version](https://www.npmjs.com/package/@zombienet/cli). +#### Run Omni Node -This template produces a parachain node. -You can install it in your environment by running: +Start Omni Node with the generated chain spec. We'll start it development mode (without a relay chain config), +with a temporary directory for configuration (given `--tmp`), and block production set to create a block with +every second. + +```bash +polkadot-omni-node --chain --tmp --dev-block-time 1000 -```sh -cargo install --path node ``` -You still need a relaychain node - you can download the `polkadot` -(and the accompanying `polkadot-prepare-worker` and `polkadot-execute-worker`) -binaries from [Polkadot SDK releases](https://github.com/paritytech/polkadot-sdk/releases/latest). +However, such a setup is not close to what would run in production, and for that we need to setup a local +relay chain network that will help with the block finalization. In this guide we'll setup a local relay chain +as well. We'll not do it manually, by starting one node at a time, but we'll use [zombienet](https://paritytech.github.io/zombienet/intro.html). + +Follow through the next section for more details on how to do it. -In addition to the installed parachain node, make sure to bring -`zombienet`, `polkadot`, `polkadot-prepare-worker`, and `polkadot-execute-worker` -into `PATH`, for example: +### Zombienet setup with Omni Node + +Assuming we continue from the last step of the previous section, we have a chain spec and we need to setup a relay chain. +We can install `zombienet` as described [here](https://paritytech.github.io/zombienet/install.html#installation), and +`zombienet-omni-node.toml` contains the network specification we want to start. + +#### Relay chain prerequisites + +Download the `polkadot` (and the accompanying `polkadot-prepare-worker` and `polkadot-execute-worker`) binaries from +[Polkadot SDK releases](https://github.com/paritytech/polkadot-sdk/releases). Then expose them on `PATH` like so: ```sh -export PATH=":$PATH" +export PATH="$PATH:" ``` -This way, we can conveniently use them in the following steps. +#### Update `zombienet-omni-node.toml` with a valid chain spec path + +```toml +# ... +[[parachains]] +id = 1000 +chain_spec_path = "" +# ... +``` -👥 The following command starts a local development chain, with a single relay chain node and a single parachain collator: +#### Start the network ```sh -zombienet --provider native spawn ./zombienet.toml +zombienet --provider native spawn zombienet-omni-node.toml +``` + +### Parachain Template Node + +As mentioned in the `Template Structure` section, the `node` crate is optionally compiled and it is an alternative +to `Omni Node`. Similarly, it requires setting up a relay chain, and we'll use `zombienet` once more. + +#### Install the `parachain-template-node` -# Alternatively, the npm version: -npx --yes @zombienet/cli --provider native spawn ./zombienet.toml +```sh +cargo install --path node ``` -Development chains: +#### Setup and start the network + +For setup, please consider the instructions for `zombienet` installation [here](https://paritytech.github.io/zombienet/install.html#installation) +and [relay chain prerequisites](#relay-chain-prerequisites). -* 🧹 Do not persist the state. -* 💰 Are preconfigured with a genesis state that includes several prefunded development accounts. -* 🧑‍⚖️ Development accounts are used as validators, collators, and `sudo` accounts. +We're left just with starting the network: + +```sh +zombienet --provider native spawn zombienet.toml +``` ### Connect with the Polkadot-JS Apps Front-End -* 🌐 You can interact with your local node using the +- 🌐 You can interact with your local node using the hosted version of the Polkadot/Substrate Portal: [relay chain](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944) and [parachain](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9988). -* 🪐 A hosted version is also +- 🪐 A hosted version is also available on [IPFS](https://dotapps.io/). -* 🧑‍🔧 You can also find the source code and instructions for hosting your own instance in the +- 🧑‍🔧 You can also find the source code and instructions for hosting your own instance in the [`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository. +### Takeaways + +Development parachains: + +- 🔗 Connect to relay chains, and we showcased how to connect to a local one. +- 🧹 Do not persist the state. +- 💰 Are preconfigured with a genesis state that includes several prefunded development accounts. +- 🧑‍⚖️ Development accounts are used as validators, collators, and `sudo` accounts. + ## Contributing -* 🔄 This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). +- 🔄 This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). -* ➡️ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/parachain). +- ➡️ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/parachain). -* 😇 Please refer to the monorepo's +- 😇 Please refer to the monorepo's [contribution guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) and [Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md). ## Getting Help -* 🧑‍🏫 To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. +- 🧑‍🏫 To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. -* 🧑‍🔧 For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are +- 🧑‍🔧 For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are the Polkadot SDK documentation resources. -* 👥 Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and +- 👥 Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and [Substrate StackExchange](https://substrate.stackexchange.com/). diff --git a/templates/parachain/runtime/src/genesis_config_presets.rs b/templates/parachain/runtime/src/genesis_config_presets.rs index 394bde0be770..9091db357005 100644 --- a/templates/parachain/runtime/src/genesis_config_presets.rs +++ b/templates/parachain/runtime/src/genesis_config_presets.rs @@ -15,6 +15,8 @@ use sp_keyring::Sr25519Keyring; /// The default XCM version to set in genesis config. const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; +/// Parachain id used for gensis config presets of parachain template. +const PARACHAIN_ID: u32 = 1000; /// Generate the session keys from individual elements. /// @@ -76,9 +78,7 @@ fn local_testnet_genesis() -> Value { ], Sr25519Keyring::well_known().map(|k| k.to_account_id()).collect(), Sr25519Keyring::Alice.to_account_id(), - // TODO: this is super opaque, how should one know they should configure this? add to - // README! - 1000.into(), + PARACHAIN_ID.into(), ) } @@ -91,7 +91,7 @@ fn development_config_genesis() -> Value { ], Sr25519Keyring::well_known().map(|k| k.to_account_id()).collect(), Sr25519Keyring::Alice.to_account_id(), - 1000.into(), + PARACHAIN_ID.into(), ) } diff --git a/templates/parachain/zombienet-omni-node.toml b/templates/parachain/zombienet-omni-node.toml new file mode 100644 index 000000000000..29e99cfcd493 --- /dev/null +++ b/templates/parachain/zombienet-omni-node.toml @@ -0,0 +1,22 @@ +[relaychain] +default_command = "polkadot" +chain = "rococo-local" + +[[relaychain.nodes]] +name = "alice" +validator = true +ws_port = 9944 + +[[relaychain.nodes]] +name = "bob" +validator = true +ws_port = 9955 + +[[parachains]] +id = 1000 +chain_spec_path = "" + +[parachains.collator] +name = "charlie" +ws_port = 9988 +command = "polkadot-omni-node" diff --git a/templates/zombienet/tests/smoke.rs b/templates/zombienet/tests/smoke.rs index ba5f42142f31..c0c9646d4e9c 100644 --- a/templates/zombienet/tests/smoke.rs +++ b/templates/zombienet/tests/smoke.rs @@ -7,28 +7,74 @@ //! `cargo build --package minimal-template-node --release` //! `export PATH=/target/release:$PATH //! -//! The you can run the test with -//! `cargo test -p template-zombienet-tests` +//! There are also some tests related to omni node which run basaed on pre-generated chain specs, +//! so to be able to run them you would need to generate the right chain spec (just minimal and +//! parachain tests supported for now). +//! +//! You can run the following command to generate a minimal chainspec, once the runtime wasm file is +//! compiled: +//!`chain-spec-builder create --relay-chain --para-id 1000 -r \ +//! named-preset development` +//! +//! Once the files are generated, you must export an environment variable called +//! `CHAIN_SPECS_DIR` which should point to the absolute path of the directory +//! that holds the generated chain specs. The chain specs file names should be +//! `minimal_chain_spec.json` for minimal and `parachain_chain_spec.json` for parachain +//! templates. +//! +//! To start all tests here we should run: +//! `cargo test -p template-zombienet-tests --features zombienet` #[cfg(feature = "zombienet")] mod smoke { + use std::path::PathBuf; + use anyhow::anyhow; use zombienet_sdk::{NetworkConfig, NetworkConfigBuilder, NetworkConfigExt}; - pub fn get_config(cmd: &str, para_cmd: Option<&str>) -> Result { - let chain = if cmd == "polkadot" { "rococo-local" } else { "dev" }; + const CHAIN_SPECS_DIR_PATH: &str = "CHAIN_SPECS_DIR"; + const PARACHAIN_ID: u32 = 1000; + + #[inline] + fn expect_env_var(var_name: &str) -> String { + std::env::var(var_name) + .unwrap_or_else(|_| panic!("{CHAIN_SPECS_DIR_PATH} environment variable is set. qed.")) + } + + #[derive(Default)] + struct NetworkSpec { + relaychain_cmd: &'static str, + relaychain_spec_path: Option, + // TODO: update the type to something like Option> after + // `zombienet-sdk` exposes `shared::types::Arg`. + relaychain_cmd_args: Option>, + para_cmd: Option<&'static str>, + para_cmd_args: Option>, + } + + fn get_config(network_spec: NetworkSpec) -> Result { + let chain = if network_spec.relaychain_cmd == "polkadot" { "rococo-local" } else { "dev" }; let config = NetworkConfigBuilder::new().with_relaychain(|r| { - r.with_chain(chain) - .with_default_command(cmd) - .with_node(|node| node.with_name("alice")) + let mut r = r.with_chain(chain).with_default_command(network_spec.relaychain_cmd); + if let Some(path) = network_spec.relaychain_spec_path { + r = r.with_chain_spec_path(path); + } + + if let Some(args) = network_spec.relaychain_cmd_args { + r = r.with_default_args(args.into_iter().map(|arg| arg.into()).collect()); + } + + r.with_node(|node| node.with_name("alice")) .with_node(|node| node.with_name("bob")) }); - let config = if let Some(para_cmd) = para_cmd { + let config = if let Some(para_cmd) = network_spec.para_cmd { config.with_parachain(|p| { - p.with_id(1000) - .with_default_command(para_cmd) - .with_collator(|n| n.with_name("collator")) + let mut p = p.with_id(PARACHAIN_ID).with_default_command(para_cmd); + if let Some(args) = network_spec.para_cmd_args { + p = p.with_default_args(args.into_iter().map(|arg| arg.into()).collect()); + } + p.with_collator(|n| n.with_name("collator")) }) } else { config @@ -46,14 +92,18 @@ mod smoke { env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"), ); - let config = get_config("polkadot", Some("parachain-template-node"))?; + let config = get_config(NetworkSpec { + relaychain_cmd: "polkadot", + para_cmd: Some("parachain-template-node"), + ..Default::default() + })?; let network = config.spawn_native().await?; // wait 6 blocks of the para let collator = network.get_node("collator")?; assert!(collator - .wait_metric("block_height{status=\"best\"}", |b| b > 5_f64) + .wait_metric("block_height{status=\"finalized\"}", |b| b > 5_f64) .await .is_ok()); @@ -66,13 +116,19 @@ mod smoke { env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"), ); - let config = get_config("solochain-template-node", None)?; + let config = get_config(NetworkSpec { + relaychain_cmd: "solochain-template-node", + ..Default::default() + })?; let network = config.spawn_native().await?; // wait 6 blocks let alice = network.get_node("alice")?; - assert!(alice.wait_metric("block_height{status=\"best\"}", |b| b > 5_f64).await.is_ok()); + assert!(alice + .wait_metric("block_height{status=\"finalized\"}", |b| b > 5_f64) + .await + .is_ok()); Ok(()) } @@ -83,13 +139,73 @@ mod smoke { env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"), ); - let config = get_config("minimal-template-node", None)?; + let config = get_config(NetworkSpec { + relaychain_cmd: "minimal-template-node", + ..Default::default() + })?; + + let network = config.spawn_native().await?; + + // wait 6 blocks + let alice = network.get_node("alice")?; + assert!(alice + .wait_metric("block_height{status=\"finalized\"}", |b| b > 5_f64) + .await + .is_ok()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn omni_node_with_minimal_runtime_block_production_test() -> Result<(), anyhow::Error> { + let _ = env_logger::try_init_from_env( + env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"), + ); + let chain_spec_path = expect_env_var(CHAIN_SPECS_DIR_PATH) + "/minimal_chain_spec.json"; + let config = get_config(NetworkSpec { + relaychain_cmd: "polkadot-omni-node", + relaychain_cmd_args: Some(vec![("--dev-block-time", "1000")]), + relaychain_spec_path: Some(chain_spec_path.into()), + ..Default::default() + })?; let network = config.spawn_native().await?; // wait 6 blocks let alice = network.get_node("alice")?; - assert!(alice.wait_metric("block_height{status=\"best\"}", |b| b > 5_f64).await.is_ok()); + assert!(alice + .wait_metric("block_height{status=\"finalized\"}", |b| b > 5_f64) + .await + .is_ok()); + + Ok(()) + } + + #[tokio::test(flavor = "multi_thread")] + async fn omni_node_with_parachain_runtime_block_production_test() -> Result<(), anyhow::Error> { + let _ = env_logger::try_init_from_env( + env_logger::Env::default().filter_or(env_logger::DEFAULT_FILTER_ENV, "info"), + ); + + let chain_spec_path = expect_env_var(CHAIN_SPECS_DIR_PATH) + "/parachain_chain_spec.json"; + + let config = get_config(NetworkSpec { + relaychain_cmd: "polkadot", + para_cmd: Some("polkadot-omni-node"), + // Leaking the `String` to be able to use it below as a static str, + // required by the `FromStr` implementation for zombienet-configuration + // `Arg` type, which is not exposed yet through `zombienet-sdk`. + para_cmd_args: Some(vec![("--chain", chain_spec_path.leak())]), + ..Default::default() + })?; + let network = config.spawn_native().await?; + + // wait 6 blocks + let alice = network.get_node("collator")?; + assert!(alice + .wait_metric("block_height{status=\"finalized\"}", |b| b > 5_f64) + .await + .is_ok()); Ok(()) } From f4ded5c442e447b4cc21fe0e022460bf3e01a3f2 Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Mon, 4 Nov 2024 19:53:44 +0800 Subject: [PATCH 011/166] Migrate pallet-glutton benchmark to v2 (#6296) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of: - #6202. --------- Co-authored-by: GitHub Action Co-authored-by: Oliver Tale-Yazdi Co-authored-by: Dónal Murray Co-authored-by: Giuseppe Re Co-authored-by: Dónal Murray --- prdoc/pr_6296.prdoc | 8 ++ substrate/frame/glutton/src/benchmarking.rs | 136 +++++++++++++------- 2 files changed, 97 insertions(+), 47 deletions(-) create mode 100644 prdoc/pr_6296.prdoc diff --git a/prdoc/pr_6296.prdoc b/prdoc/pr_6296.prdoc new file mode 100644 index 000000000000..dcc4ad9095f6 --- /dev/null +++ b/prdoc/pr_6296.prdoc @@ -0,0 +1,8 @@ +title: Migrate pallet-glutton benchmark to v2 +doc: +- audience: Runtime Dev + description: |- + Update `pallet-glutton` to benchmarks v2. +crates: +- name: pallet-glutton + bump: patch diff --git a/substrate/frame/glutton/src/benchmarking.rs b/substrate/frame/glutton/src/benchmarking.rs index 0b1309e63304..b5fbbd4cd200 100644 --- a/substrate/frame/glutton/src/benchmarking.rs +++ b/substrate/frame/glutton/src/benchmarking.rs @@ -20,80 +20,122 @@ //! Has to be compiled and run twice to calibrate on new hardware. #[cfg(feature = "runtime-benchmarks")] -use super::*; - -use frame_benchmarking::benchmarks; +use frame_benchmarking::v2::*; use frame_support::{pallet_prelude::*, weights::constants::*}; -use frame_system::RawOrigin as SystemOrigin; +use frame_system::RawOrigin; use sp_runtime::{traits::One, Perbill}; -use crate::Pallet as Glutton; -use frame_system::Pallet as System; +use crate::*; + +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn initialize_pallet_grow(n: Linear<0, 1_000>) -> Result<(), BenchmarkError> { + #[block] + { + Pallet::::initialize_pallet(RawOrigin::Root.into(), n, None)?; + } -benchmarks! { - initialize_pallet_grow { - let n in 0 .. 1_000; - }: { - Glutton::::initialize_pallet(SystemOrigin::Root.into(), n, None).unwrap() - } verify { assert_eq!(TrashDataCount::::get(), n); + + Ok(()) } - initialize_pallet_shrink { - let n in 0 .. 1_000; + #[benchmark] + fn initialize_pallet_shrink(n: Linear<0, 1_000>) -> Result<(), BenchmarkError> { + Pallet::::initialize_pallet(RawOrigin::Root.into(), n, None)?; + + #[block] + { + Pallet::::initialize_pallet(RawOrigin::Root.into(), 0, Some(n))?; + } - Glutton::::initialize_pallet(SystemOrigin::Root.into(), n, None).unwrap(); - }: { - Glutton::::initialize_pallet(SystemOrigin::Root.into(), 0, Some(n)).unwrap() - } verify { assert_eq!(TrashDataCount::::get(), 0); - } - waste_ref_time_iter { - let i in 0..100_000; - }: { - Glutton::::waste_ref_time_iter(vec![0u8; 64], i); + Ok(()) } - waste_proof_size_some { - let i in 0..5_000; + #[benchmark] + fn waste_ref_time_iter(i: Linear<0, 100_000>) { + #[block] + { + Pallet::::waste_ref_time_iter(vec![0u8; 64], i); + } + } + #[benchmark] + fn waste_proof_size_some(i: Linear<0, 5_000>) { (0..5000).for_each(|i| TrashData::::insert(i, [i as u8; 1024])); - }: { - (0..i).for_each(|i| { - TrashData::::get(i); - }) + + #[block] + { + (0..i).for_each(|i| { + TrashData::::get(i); + }) + } } // For manual verification only. - on_idle_high_proof_waste { + #[benchmark] + fn on_idle_high_proof_waste() { (0..5000).for_each(|i| TrashData::::insert(i, [i as u8; 1024])); - let _ = Glutton::::set_compute(SystemOrigin::Root.into(), One::one()); - let _ = Glutton::::set_storage(SystemOrigin::Root.into(), One::one()); - }: { - let weight = Glutton::::on_idle(System::::block_number(), Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS * 100, WEIGHT_PROOF_SIZE_PER_MB * 5)); + let _ = Pallet::::set_compute(RawOrigin::Root.into(), One::one()); + let _ = Pallet::::set_storage(RawOrigin::Root.into(), One::one()); + + #[block] + { + Pallet::::on_idle( + frame_system::Pallet::::block_number(), + Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS * 100, WEIGHT_PROOF_SIZE_PER_MB * 5), + ); + } } // For manual verification only. - on_idle_low_proof_waste { + #[benchmark] + fn on_idle_low_proof_waste() { (0..5000).for_each(|i| TrashData::::insert(i, [i as u8; 1024])); - let _ = Glutton::::set_compute(SystemOrigin::Root.into(), One::one()); - let _ = Glutton::::set_storage(SystemOrigin::Root.into(), One::one()); - }: { - let weight = Glutton::::on_idle(System::::block_number(), Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS * 100, WEIGHT_PROOF_SIZE_PER_KB * 20)); + let _ = Pallet::::set_compute(RawOrigin::Root.into(), One::one()); + let _ = Pallet::::set_storage(RawOrigin::Root.into(), One::one()); + + #[block] + { + Pallet::::on_idle( + frame_system::Pallet::::block_number(), + Weight::from_parts(WEIGHT_REF_TIME_PER_MILLIS * 100, WEIGHT_PROOF_SIZE_PER_KB * 20), + ); + } } - empty_on_idle { - }: { + #[benchmark] + fn empty_on_idle() { // Enough weight to do nothing. - Glutton::::on_idle(System::::block_number(), T::WeightInfo::empty_on_idle()); + #[block] + { + Pallet::::on_idle( + frame_system::Pallet::::block_number(), + T::WeightInfo::empty_on_idle(), + ); + } } - set_compute { - }: _(SystemOrigin::Root, FixedU64::from_perbill(Perbill::from_percent(50))) + #[benchmark] + fn set_compute() { + #[extrinsic_call] + _(RawOrigin::Root, FixedU64::from_perbill(Perbill::from_percent(50))); + } - set_storage { - }: _(SystemOrigin::Root, FixedU64::from_perbill(Perbill::from_percent(50))) + #[benchmark] + fn set_storage() { + #[extrinsic_call] + _(RawOrigin::Root, FixedU64::from_perbill(Perbill::from_percent(50))); + } - impl_benchmark_test_suite!(Glutton, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite! { + Pallet, + mock::new_test_ext(), + mock::Test + } } From 9353a2829d88ad620478d19ada000338d74274ef Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Mon, 4 Nov 2024 20:16:49 +0800 Subject: [PATCH 012/166] Migrate pallet-election-provider-multi-phase benchmark to v2 and improve doc (#6316) Part of: - #6202. --------- Co-authored-by: GitHub Action Co-authored-by: Guillaume Thiolliere Co-authored-by: Guillaume Thiolliere Co-authored-by: Oliver Tale-Yazdi --- prdoc/pr_6316.prdoc | 8 + .../src/benchmarking.rs | 438 +++++++++++------- 2 files changed, 274 insertions(+), 172 deletions(-) create mode 100644 prdoc/pr_6316.prdoc diff --git a/prdoc/pr_6316.prdoc b/prdoc/pr_6316.prdoc new file mode 100644 index 000000000000..00ad8699ff85 --- /dev/null +++ b/prdoc/pr_6316.prdoc @@ -0,0 +1,8 @@ +title: Migrate pallet-election-provider-multi-phase benchmark to v2 and improve doc +doc: +- audience: Runtime Dev + description: |- + Migrate pallet-election-provider-multi-phase benchmark to v2 and improve doc +crates: +- name: pallet-election-provider-multi-phase + bump: patch diff --git a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs index 2a3994ff2aa6..222e79ab99c6 100644 --- a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs @@ -17,10 +17,9 @@ //! Two phase election pallet benchmarking. -use super::*; -use crate::{unsigned::IndexAssignmentOf, Pallet as MultiPhase}; -use frame_benchmarking::account; -use frame_election_provider_support::bounds::DataProviderBounds; +use core::cmp::Reverse; +use frame_benchmarking::{v2::*, BenchmarkError}; +use frame_election_provider_support::{bounds::DataProviderBounds, IndexAssignment}; use frame_support::{ assert_ok, traits::{Hooks, TryCollect}, @@ -31,6 +30,8 @@ use rand::{prelude::SliceRandom, rngs::SmallRng, SeedableRng}; use sp_arithmetic::{per_things::Percent, traits::One}; use sp_runtime::InnerOf; +use crate::{unsigned::IndexAssignmentOf, *}; + const SEED: u32 = 999; /// Creates a **valid** solution with exactly the given size. @@ -133,7 +134,7 @@ fn solution_with_size( .map(|(voter, _stake, votes)| { let percent_per_edge: InnerOf> = (100 / votes.len()).try_into().unwrap_or_else(|_| panic!("failed to convert")); - crate::unsigned::Assignment:: { + unsigned::Assignment:: { who: voter.clone(), distribution: votes .iter() @@ -190,140 +191,179 @@ fn set_up_data_provider(v: u32, t: u32) { }); } -frame_benchmarking::benchmarks! { - on_initialize_nothing { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn on_initialize_nothing() { assert!(CurrentPhase::::get().is_off()); - }: { - MultiPhase::::on_initialize(1u32.into()); - } verify { + + #[block] + { + Pallet::::on_initialize(1_u32.into()); + } + assert!(CurrentPhase::::get().is_off()); } - on_initialize_open_signed { + #[benchmark] + fn on_initialize_open_signed() { assert!(Snapshot::::get().is_none()); assert!(CurrentPhase::::get().is_off()); - }: { - MultiPhase::::phase_transition(Phase::Signed); - } verify { + + #[block] + { + Pallet::::phase_transition(Phase::Signed); + } + assert!(Snapshot::::get().is_none()); assert!(CurrentPhase::::get().is_signed()); } - on_initialize_open_unsigned { + #[benchmark] + fn on_initialize_open_unsigned() { assert!(Snapshot::::get().is_none()); assert!(CurrentPhase::::get().is_off()); - }: { - let now = frame_system::Pallet::::block_number(); - MultiPhase::::phase_transition(Phase::Unsigned((true, now))); - } verify { + + #[block] + { + let now = frame_system::Pallet::::block_number(); + Pallet::::phase_transition(Phase::Unsigned((true, now))); + } + assert!(Snapshot::::get().is_none()); assert!(CurrentPhase::::get().is_unsigned()); } - finalize_signed_phase_accept_solution { + #[benchmark] + fn finalize_signed_phase_accept_solution() { let receiver = account("receiver", 0, SEED); - let initial_balance = T::Currency::minimum_balance() + 10u32.into(); + let initial_balance = T::Currency::minimum_balance() + 10_u32.into(); T::Currency::make_free_balance_be(&receiver, initial_balance); let ready = Default::default(); - let deposit: BalanceOf = 10u32.into(); + let deposit: BalanceOf = 10_u32.into(); let reward: BalanceOf = T::SignedRewardBase::get(); - let call_fee: BalanceOf = 30u32.into(); + let call_fee: BalanceOf = 30_u32.into(); assert_ok!(T::Currency::reserve(&receiver, deposit)); assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); - }: { - MultiPhase::::finalize_signed_phase_accept_solution( - ready, - &receiver, - deposit, - call_fee - ) - } verify { - assert_eq!( - T::Currency::free_balance(&receiver), - initial_balance + reward + call_fee - ); - assert_eq!(T::Currency::reserved_balance(&receiver), 0u32.into()); + + #[block] + { + Pallet::::finalize_signed_phase_accept_solution(ready, &receiver, deposit, call_fee); + } + + assert_eq!(T::Currency::free_balance(&receiver), initial_balance + reward + call_fee); + assert_eq!(T::Currency::reserved_balance(&receiver), 0_u32.into()); } - finalize_signed_phase_reject_solution { + #[benchmark] + fn finalize_signed_phase_reject_solution() { let receiver = account("receiver", 0, SEED); - let initial_balance = T::Currency::minimum_balance() + 10u32.into(); - let deposit: BalanceOf = 10u32.into(); + let initial_balance = T::Currency::minimum_balance() + 10_u32.into(); + let deposit: BalanceOf = 10_u32.into(); T::Currency::make_free_balance_be(&receiver, initial_balance); assert_ok!(T::Currency::reserve(&receiver, deposit)); assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); - assert_eq!(T::Currency::reserved_balance(&receiver), 10u32.into()); - }: { - MultiPhase::::finalize_signed_phase_reject_solution(&receiver, deposit) - } verify { + assert_eq!(T::Currency::reserved_balance(&receiver), 10_u32.into()); + + #[block] + { + Pallet::::finalize_signed_phase_reject_solution(&receiver, deposit) + } + assert_eq!(T::Currency::free_balance(&receiver), T::Currency::minimum_balance()); - assert_eq!(T::Currency::reserved_balance(&receiver), 0u32.into()); + assert_eq!(T::Currency::reserved_balance(&receiver), 0_u32.into()); } - create_snapshot_internal { - // number of votes in snapshot. - let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1]; - // number of targets in snapshot. - let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1]; - - // we don't directly need the data-provider to be populated, but it is just easy to use it. + #[benchmark] + fn create_snapshot_internal( + // Number of votes in snapshot. + v: Linear<{ T::BenchmarkingConfig::VOTERS[0] }, { T::BenchmarkingConfig::VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ T::BenchmarkingConfig::TARGETS[0] }, { T::BenchmarkingConfig::TARGETS[1] }>, + ) -> Result<(), BenchmarkError> { + // We don't directly need the data-provider to be populated, but it is just easy to use it. set_up_data_provider::(v, t); - // default bounds are unbounded. + // Default bounds are unbounded. let targets = T::DataProvider::electable_targets(DataProviderBounds::default())?; let voters = T::DataProvider::electing_voters(DataProviderBounds::default())?; let desired_targets = T::DataProvider::desired_targets()?; assert!(Snapshot::::get().is_none()); - }: { - MultiPhase::::create_snapshot_internal(targets, voters, desired_targets) - } verify { + + #[block] + { + Pallet::::create_snapshot_internal(targets, voters, desired_targets) + } + assert!(Snapshot::::get().is_some()); assert_eq!(SnapshotMetadata::::get().ok_or("metadata missing")?.voters, v); assert_eq!(SnapshotMetadata::::get().ok_or("metadata missing")?.targets, t); + + Ok(()) } - // a call to `::elect` where we only return the queued solution. - elect_queued { - // number of assignments, i.e. solution.len(). This means the active nominators, thus must be - // a subset of `v`. - let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1]; - // number of desired targets. Must be a subset of `t`. - let d in (T::BenchmarkingConfig::DESIRED_TARGETS[0]) .. T::BenchmarkingConfig::DESIRED_TARGETS[1]; - - // number of votes in snapshot. Not dominant. - let v = T::BenchmarkingConfig::VOTERS[1]; - // number of targets in snapshot. Not dominant. + // A call to `::elect` where we only return the queued solution. + #[benchmark] + fn elect_queued( + // Number of assignments, i.e. `solution.len()`. + // This means the active nominators, thus must be a subset of `v`. + a: Linear< + { T::BenchmarkingConfig::ACTIVE_VOTERS[0] }, + { T::BenchmarkingConfig::ACTIVE_VOTERS[1] }, + >, + // Number of desired targets. Must be a subset of `t`. + d: Linear< + { T::BenchmarkingConfig::DESIRED_TARGETS[0] }, + { T::BenchmarkingConfig::DESIRED_TARGETS[1] }, + >, + ) -> Result<(), BenchmarkError> { + // Number of votes in snapshot. Not dominant. + let v = T::BenchmarkingConfig::VOTERS[1]; + // Number of targets in snapshot. Not dominant. let t = T::BenchmarkingConfig::TARGETS[1]; let witness = SolutionOrSnapshotSize { voters: v, targets: t }; let raw_solution = solution_with_size::(witness, a, d)?; - let ready_solution = - MultiPhase::::feasibility_check(raw_solution, ElectionCompute::Signed) - .map_err(<&str>::from)?; + let ready_solution = Pallet::::feasibility_check(raw_solution, ElectionCompute::Signed) + .map_err(<&str>::from)?; CurrentPhase::::put(Phase::Signed); - // assume a queued solution is stored, regardless of where it comes from. + // Assume a queued solution is stored, regardless of where it comes from. QueuedSolution::::put(ready_solution); - // these are set by the `solution_with_size` function. + // These are set by the `solution_with_size` function. assert!(DesiredTargets::::get().is_some()); assert!(Snapshot::::get().is_some()); assert!(SnapshotMetadata::::get().is_some()); - }: { - assert_ok!( as ElectionProvider>::elect()); - } verify { + + let result; + + #[block] + { + result = as ElectionProvider>::elect(); + } + + assert!(result.is_ok()); assert!(QueuedSolution::::get().is_none()); assert!(DesiredTargets::::get().is_none()); assert!(Snapshot::::get().is_none()); assert!(SnapshotMetadata::::get().is_none()); - assert_eq!(CurrentPhase::::get(), >>::Off); + assert_eq!( + CurrentPhase::::get(), + >>::Off + ); + + Ok(()) } - submit { - // the queue is full and the solution is only better than the worse. - MultiPhase::::create_snapshot().map_err(<&str>::from)?; - MultiPhase::::phase_transition(Phase::Signed); + #[benchmark] + fn submit() -> Result<(), BenchmarkError> { + // The queue is full and the solution is only better than the worse. + Pallet::::create_snapshot().map_err(<&str>::from)?; + Pallet::::phase_transition(Phase::Signed); Round::::put(1); let mut signed_submissions = SignedSubmissions::::get(); @@ -331,7 +371,10 @@ frame_benchmarking::benchmarks! { // Insert `max` submissions for i in 0..(T::SignedMaxSubmissions::get() - 1) { let raw_solution = RawSolution { - score: ElectionScore { minimal_stake: 10_000_000u128 + (i as u128), ..Default::default() }, + score: ElectionScore { + minimal_stake: 10_000_000u128 + (i as u128), + ..Default::default() + }, ..Default::default() }; let signed_submission = SignedSubmission { @@ -344,67 +387,95 @@ frame_benchmarking::benchmarks! { } signed_submissions.put(); - // this score will eject the weakest one. + // This score will eject the weakest one. let solution = RawSolution { score: ElectionScore { minimal_stake: 10_000_000u128 + 1, ..Default::default() }, ..Default::default() }; let caller = frame_benchmarking::whitelisted_caller(); - let deposit = MultiPhase::::deposit_for( - &solution, - SnapshotMetadata::::get().unwrap_or_default(), + let deposit = + Pallet::::deposit_for(&solution, SnapshotMetadata::::get().unwrap_or_default()); + T::Currency::make_free_balance_be( + &caller, + T::Currency::minimum_balance() * 1000u32.into() + deposit, ); - T::Currency::make_free_balance_be(&caller, T::Currency::minimum_balance() * 1000u32.into() + deposit); - }: _(RawOrigin::Signed(caller), Box::new(solution)) - verify { - assert!(MultiPhase::::signed_submissions().len() as u32 == T::SignedMaxSubmissions::get()); - } + #[extrinsic_call] + _(RawOrigin::Signed(caller), Box::new(solution)); - submit_unsigned { - // number of votes in snapshot. - let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1]; - // number of targets in snapshot. - let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1]; - // number of assignments, i.e. solution.len(). This means the active nominators, thus must be - // a subset of `v` component. - let a in - (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1]; - // number of desired targets. Must be a subset of `t` component. - let d in - (T::BenchmarkingConfig::DESIRED_TARGETS[0]) .. - T::BenchmarkingConfig::DESIRED_TARGETS[1]; + assert!(Pallet::::signed_submissions().len() as u32 == T::SignedMaxSubmissions::get()); + Ok(()) + } + + #[benchmark] + fn submit_unsigned( + // Number of votes in snapshot. + v: Linear<{ T::BenchmarkingConfig::VOTERS[0] }, { T::BenchmarkingConfig::VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ T::BenchmarkingConfig::TARGETS[0] }, { T::BenchmarkingConfig::TARGETS[1] }>, + // Number of assignments, i.e. `solution.len()`. + // This means the active nominators, thus must be a subset of `v` component. + a: Linear< + { T::BenchmarkingConfig::ACTIVE_VOTERS[0] }, + { T::BenchmarkingConfig::ACTIVE_VOTERS[1] }, + >, + // Number of desired targets. Must be a subset of `t` component. + d: Linear< + { T::BenchmarkingConfig::DESIRED_TARGETS[0] }, + { T::BenchmarkingConfig::DESIRED_TARGETS[1] }, + >, + ) -> Result<(), BenchmarkError> { let witness = SolutionOrSnapshotSize { voters: v, targets: t }; let raw_solution = solution_with_size::(witness, a, d)?; assert!(QueuedSolution::::get().is_none()); - CurrentPhase::::put(Phase::Unsigned((true, 1u32.into()))); - }: _(RawOrigin::None, Box::new(raw_solution), witness) - verify { + CurrentPhase::::put(Phase::Unsigned((true, 1_u32.into()))); + + #[extrinsic_call] + _(RawOrigin::None, Box::new(raw_solution), witness); + assert!(QueuedSolution::::get().is_some()); + + Ok(()) } // This is checking a valid solution. The worse case is indeed a valid solution. - feasibility_check { - // number of votes in snapshot. - let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1]; - // number of targets in snapshot. - let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1]; - // number of assignments, i.e. solution.len(). This means the active nominators, thus must be - // a subset of `v` component. - let a in (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1]; - // number of desired targets. Must be a subset of `t` component. - let d in (T::BenchmarkingConfig::DESIRED_TARGETS[0]) .. T::BenchmarkingConfig::DESIRED_TARGETS[1]; - + #[benchmark] + fn feasibility_check( + // Number of votes in snapshot. + v: Linear<{ T::BenchmarkingConfig::VOTERS[0] }, { T::BenchmarkingConfig::VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ T::BenchmarkingConfig::TARGETS[0] }, { T::BenchmarkingConfig::TARGETS[1] }>, + // Number of assignments, i.e. `solution.len()`. + // This means the active nominators, thus must be a subset of `v` component. + a: Linear< + { T::BenchmarkingConfig::ACTIVE_VOTERS[0] }, + { T::BenchmarkingConfig::ACTIVE_VOTERS[1] }, + >, + // Number of desired targets. Must be a subset of `t` component. + d: Linear< + { T::BenchmarkingConfig::DESIRED_TARGETS[0] }, + { T::BenchmarkingConfig::DESIRED_TARGETS[1] }, + >, + ) -> Result<(), BenchmarkError> { let size = SolutionOrSnapshotSize { voters: v, targets: t }; let raw_solution = solution_with_size::(size, a, d)?; assert_eq!(raw_solution.solution.voter_count() as u32, a); assert_eq!(raw_solution.solution.unique_targets().len() as u32, d); - }: { - assert!(MultiPhase::::feasibility_check(raw_solution, ElectionCompute::Unsigned).is_ok()); + + let result; + + #[block] + { + result = Pallet::::feasibility_check(raw_solution, ElectionCompute::Unsigned); + } + + assert!(result.is_ok()); + + Ok(()) } // NOTE: this weight is not used anywhere, but the fact that it should succeed when execution in @@ -419,20 +490,23 @@ frame_benchmarking::benchmarks! { // This benchmark is doing more work than a raw call to `OffchainWorker_offchain_worker` runtime // api call, since it is also setting up some mock data, which will itself exhaust the heap to // some extent. - #[extra] - mine_solution_offchain_memory { - // number of votes in snapshot. Fixed to maximum. + #[benchmark(extra)] + fn mine_solution_offchain_memory() { + // Number of votes in snapshot. Fixed to maximum. let v = T::BenchmarkingConfig::MINER_MAXIMUM_VOTERS; - // number of targets in snapshot. Fixed to maximum. + // Number of targets in snapshot. Fixed to maximum. let t = T::BenchmarkingConfig::MAXIMUM_TARGETS; set_up_data_provider::(v, t); let now = frame_system::Pallet::::block_number(); CurrentPhase::::put(Phase::Unsigned((true, now))); - MultiPhase::::create_snapshot().unwrap(); - }: { - // we can't really verify this as it won't write anything to state, check logs. - MultiPhase::::offchain_worker(now) + Pallet::::create_snapshot().unwrap(); + + #[block] + { + // we can't really verify this as it won't write anything to state, check logs. + Pallet::::offchain_worker(now) + } } // NOTE: this weight is not used anywhere, but the fact that it should succeed when execution in @@ -441,41 +515,48 @@ frame_benchmarking::benchmarks! { // numbers. // // ONLY run this benchmark in isolation, and pass the `--extra` flag to enable it. - #[extra] - create_snapshot_memory { - // number of votes in snapshot. Fixed to maximum. + #[benchmark(extra)] + fn create_snapshot_memory() -> Result<(), BenchmarkError> { + // Number of votes in snapshot. Fixed to maximum. let v = T::BenchmarkingConfig::SNAPSHOT_MAXIMUM_VOTERS; - // number of targets in snapshot. Fixed to maximum. + // Number of targets in snapshot. Fixed to maximum. let t = T::BenchmarkingConfig::MAXIMUM_TARGETS; set_up_data_provider::(v, t); assert!(Snapshot::::get().is_none()); - }: { - MultiPhase::::create_snapshot().map_err(|_| "could not create snapshot")?; - } verify { + + #[block] + { + Pallet::::create_snapshot().map_err(|_| "could not create snapshot")?; + } + assert!(Snapshot::::get().is_some()); assert_eq!(SnapshotMetadata::::get().ok_or("snapshot missing")?.voters, v); assert_eq!(SnapshotMetadata::::get().ok_or("snapshot missing")?.targets, t); - } - #[extra] - trim_assignments_length { - // number of votes in snapshot. - let v in (T::BenchmarkingConfig::VOTERS[0]) .. T::BenchmarkingConfig::VOTERS[1]; - // number of targets in snapshot. - let t in (T::BenchmarkingConfig::TARGETS[0]) .. T::BenchmarkingConfig::TARGETS[1]; - // number of assignments, i.e. solution.len(). This means the active nominators, thus must be - // a subset of `v` component. - let a in - (T::BenchmarkingConfig::ACTIVE_VOTERS[0]) .. T::BenchmarkingConfig::ACTIVE_VOTERS[1]; - // number of desired targets. Must be a subset of `t` component. - let d in - (T::BenchmarkingConfig::DESIRED_TARGETS[0]) .. - T::BenchmarkingConfig::DESIRED_TARGETS[1]; - // Subtract this percentage from the actual encoded size - let f in 0 .. 95; - use frame_election_provider_support::IndexAssignment; + Ok(()) + } + #[benchmark(extra)] + fn trim_assignments_length( + // Number of votes in snapshot. + v: Linear<{ T::BenchmarkingConfig::VOTERS[0] }, { T::BenchmarkingConfig::VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ T::BenchmarkingConfig::TARGETS[0] }, { T::BenchmarkingConfig::TARGETS[1] }>, + // Number of assignments, i.e. `solution.len()`. + // This means the active nominators, thus must be a subset of `v` component. + a: Linear< + { T::BenchmarkingConfig::ACTIVE_VOTERS[0] }, + { T::BenchmarkingConfig::ACTIVE_VOTERS[1] }, + >, + // Number of desired targets. Must be a subset of `t` component. + d: Linear< + { T::BenchmarkingConfig::DESIRED_TARGETS[0] }, + { T::BenchmarkingConfig::DESIRED_TARGETS[1] }, + >, + // Subtract this percentage from the actual encoded size. + f: Linear<0, 95>, + ) -> Result<(), BenchmarkError> { // Compute a random solution, then work backwards to get the lists of voters, targets, and // assignments let witness = SolutionOrSnapshotSize { voters: v, targets: t }; @@ -483,7 +564,9 @@ frame_benchmarking::benchmarks! { let RoundSnapshot { voters, targets } = Snapshot::::get().ok_or("snapshot missing")?; let voter_at = helpers::voter_at_fn::(&voters); let target_at = helpers::target_at_fn::(&targets); - let mut assignments = solution.into_assignment(voter_at, target_at).expect("solution generated by `solution_with_size` must be valid."); + let mut assignments = solution + .into_assignment(voter_at, target_at) + .expect("solution generated by `solution_with_size` must be valid."); // make a voter cache and some helper functions for access let cache = helpers::generate_voter_cache::(&voters); @@ -491,12 +574,15 @@ frame_benchmarking::benchmarks! { let target_index = helpers::target_index_fn::(&targets); // sort assignments by decreasing voter stake - assignments.sort_by_key(|crate::unsigned::Assignment:: { who, .. }| { - let stake = cache.get(who).map(|idx| { - let (_, stake, _) = voters[*idx]; - stake - }).unwrap_or_default(); - core::cmp::Reverse(stake) + assignments.sort_by_key(|unsigned::Assignment:: { who, .. }| { + let stake = cache + .get(who) + .map(|idx| { + let (_, stake, _) = voters[*idx]; + stake + }) + .unwrap_or_default(); + Reverse(stake) }); let mut index_assignments = assignments @@ -506,20 +592,26 @@ frame_benchmarking::benchmarks! { .unwrap(); let encoded_size_of = |assignments: &[IndexAssignmentOf]| { - SolutionOf::::try_from(assignments).map(|solution| solution.encoded_size()) + SolutionOf::::try_from(assignments) + .map(|solution| solution.encoded_size()) }; let desired_size = Percent::from_percent(100 - f.saturated_into::()) .mul_ceil(encoded_size_of(index_assignments.as_slice()).unwrap()); log!(trace, "desired_size = {}", desired_size); - }: { - crate::Miner::::trim_assignments_length( - desired_size.saturated_into(), - &mut index_assignments, - &encoded_size_of, - ).unwrap(); - } verify { - let solution = SolutionOf::::try_from(index_assignments.as_slice()).unwrap(); + + #[block] + { + Miner::::trim_assignments_length( + desired_size.saturated_into(), + &mut index_assignments, + &encoded_size_of, + ) + .unwrap(); + } + + let solution = + SolutionOf::::try_from(index_assignments.as_slice()).unwrap(); let encoding = solution.encode(); log!( trace, @@ -528,11 +620,13 @@ frame_benchmarking::benchmarks! { ); log!(trace, "actual encoded size = {}", encoding.len()); assert!(encoding.len() <= desired_size); + + Ok(()) } - impl_benchmark_test_suite!( - MultiPhase, - crate::mock::ExtBuilder::default().build_offchainify(10).0, - crate::mock::Runtime, - ); + impl_benchmark_test_suite! { + Pallet, + mock::ExtBuilder::default().build_offchainify(10).0, + mock::Runtime, + } } From f4133b08b5d01e9109ba9b603f596bfa591f07a9 Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Mon, 4 Nov 2024 14:47:22 +0200 Subject: [PATCH 013/166] fix claim queue size (#6257) Reported in https://github.com/paritytech/polkadot-sdk/issues/6161#issuecomment-2432097120 Fixes a bug introduced in https://github.com/paritytech/polkadot-sdk/pull/5461, where the claim queue would contain entries even if the validator groups storage is empty (which happens during the first session). This PR sets the claim queue core count to be the minimum between the num_cores param and the number of validator groups TODO: - [x] prdoc - [x] unit test --- polkadot/runtime/parachains/src/scheduler.rs | 36 ++++++++++++------- .../runtime/parachains/src/scheduler/tests.rs | 20 ++++++++++- prdoc/pr_6257.prdoc | 10 ++++++ 3 files changed, 52 insertions(+), 14 deletions(-) create mode 100644 prdoc/pr_6257.prdoc diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 329df3a8a9de..9c111c2d28e7 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -45,7 +45,8 @@ use frame_support::{pallet_prelude::*, traits::Defensive}; use frame_system::pallet_prelude::BlockNumberFor; pub use polkadot_core_primitives::v2::BlockNumber; use polkadot_primitives::{ - CoreIndex, GroupIndex, GroupRotationInfo, Id as ParaId, ScheduledCore, ValidatorIndex, + CoreIndex, GroupIndex, GroupRotationInfo, Id as ParaId, ScheduledCore, SchedulerParams, + ValidatorIndex, }; use sp_runtime::traits::One; @@ -131,7 +132,7 @@ impl Pallet { pub(crate) fn initializer_on_new_session( notification: &SessionChangeNotification>, ) { - let SessionChangeNotification { validators, new_config, prev_config, .. } = notification; + let SessionChangeNotification { validators, new_config, .. } = notification; let config = new_config; let assigner_cores = config.scheduler_params.num_cores; @@ -186,7 +187,7 @@ impl Pallet { } // Resize and populate claim queue. - Self::maybe_resize_claim_queue(prev_config.scheduler_params.num_cores, assigner_cores); + Self::maybe_resize_claim_queue(); Self::populate_claim_queue_after_session_change(); let now = frame_system::Pallet::::block_number() + One::one(); @@ -203,6 +204,12 @@ impl Pallet { ValidatorGroups::::decode_len().unwrap_or(0) } + /// Expected claim queue len. Can be different than the real length if for example we don't have + /// assignments for a core. + fn expected_claim_queue_len(config: &SchedulerParams>) -> u32 { + core::cmp::min(config.num_cores, Self::num_availability_cores() as u32) + } + /// Get the group assigned to a specific core by index at the current block number. Result /// undefined if the core index is unknown or the block number is less than the session start /// index. @@ -325,11 +332,11 @@ impl Pallet { /// and fill the queue from the assignment provider. pub(crate) fn advance_claim_queue(except_for: &BTreeSet) { let config = configuration::ActiveConfig::::get(); - let num_assigner_cores = config.scheduler_params.num_cores; + let expected_claim_queue_len = Self::expected_claim_queue_len(&config.scheduler_params); // Extra sanity, config should already never be smaller than 1: let n_lookahead = config.scheduler_params.lookahead.max(1); - for core_idx in 0..num_assigner_cores { + for core_idx in 0..expected_claim_queue_len { let core_idx = CoreIndex::from(core_idx); if !except_for.contains(&core_idx) { @@ -345,13 +352,16 @@ impl Pallet { } // on new session - fn maybe_resize_claim_queue(old_core_count: u32, new_core_count: u32) { - if new_core_count < old_core_count { + fn maybe_resize_claim_queue() { + let cq = ClaimQueue::::get(); + let Some((old_max_core, _)) = cq.last_key_value() else { return }; + let config = configuration::ActiveConfig::::get(); + let new_core_count = Self::expected_claim_queue_len(&config.scheduler_params); + + if new_core_count < (old_max_core.0 + 1) { ClaimQueue::::mutate(|cq| { - let to_remove: Vec<_> = cq - .range(CoreIndex(new_core_count)..CoreIndex(old_core_count)) - .map(|(k, _)| *k) - .collect(); + let to_remove: Vec<_> = + cq.range(CoreIndex(new_core_count)..=*old_max_core).map(|(k, _)| *k).collect(); for key in to_remove { if let Some(dropped_assignments) = cq.remove(&key) { Self::push_back_to_assignment_provider(dropped_assignments.into_iter()); @@ -367,9 +377,9 @@ impl Pallet { let config = configuration::ActiveConfig::::get(); // Extra sanity, config should already never be smaller than 1: let n_lookahead = config.scheduler_params.lookahead.max(1); - let new_core_count = config.scheduler_params.num_cores; + let expected_claim_queue_len = Self::expected_claim_queue_len(&config.scheduler_params); - for core_idx in 0..new_core_count { + for core_idx in 0..expected_claim_queue_len { let core_idx = CoreIndex::from(core_idx); Self::fill_claim_queue(core_idx, n_lookahead); } diff --git a/polkadot/runtime/parachains/src/scheduler/tests.rs b/polkadot/runtime/parachains/src/scheduler/tests.rs index 5be7e084f3bc..431562c6e6fb 100644 --- a/polkadot/runtime/parachains/src/scheduler/tests.rs +++ b/polkadot/runtime/parachains/src/scheduler/tests.rs @@ -726,8 +726,26 @@ fn session_change_decreasing_number_of_cores() { [assignment_b.clone()].into_iter().collect::>() ); - // No more assignments now. Scheduler::advance_claim_queue(&Default::default()); + // No more assignments now. + assert_eq!(Scheduler::claim_queue_len(), 0); + + // Retain number of cores to 1 but remove all validator groups. The claim queue length + // should be the minimum of these two. + + // Add an assignment. + MockAssigner::add_test_assignment(assignment_b.clone()); + + run_to_block(4, |number| match number { + 4 => Some(SessionChangeNotification { + new_config: new_config.clone(), + prev_config: new_config.clone(), + validators: vec![], + ..Default::default() + }), + _ => None, + }); + assert_eq!(Scheduler::claim_queue_len(), 0); }); } diff --git a/prdoc/pr_6257.prdoc b/prdoc/pr_6257.prdoc new file mode 100644 index 000000000000..45f9810108ef --- /dev/null +++ b/prdoc/pr_6257.prdoc @@ -0,0 +1,10 @@ +title: 'fix claim queue size when validator groups count is smaller' +doc: +- audience: Runtime Dev + description: 'Fixes a bug introduced in https://github.com/paritytech/polkadot-sdk/pull/5461, where the claim queue + would contain entries even if the validator groups storage is empty (which happens during the first session). + This PR sets the claim queue core count to be the minimum between the num_cores param and the number of validator groups.' + +crates: +- name: polkadot-runtime-parachains + bump: patch From 8b6f8157dd4353c750ca9a8a8b96d3e0c1d3d02f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 4 Nov 2024 12:55:25 +0000 Subject: [PATCH 014/166] Bump the ci_dependencies group across 1 directory with 3 updates (#6340) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the ci_dependencies group with 3 updates in the / directory: [docker/build-push-action](https://github.com/docker/build-push-action), [actions/setup-node](https://github.com/actions/setup-node) and [lycheeverse/lychee-action](https://github.com/lycheeverse/lychee-action). Updates `docker/build-push-action` from 5 to 6

Release notes

Sourced from docker/build-push-action's releases.

v6.0.0

[!NOTE] This major release adds support for generating Build summary and exporting build record for your build. You can disable this feature by setting DOCKER_BUILD_NO_SUMMARY: true environment variable in your workflow.

Full Changelog: https://github.com/docker/build-push-action/compare/v5.4.0...v6.0.0

v5.4.0

Full Changelog: https://github.com/docker/build-push-action/compare/v5.3.0...v5.4.0

v5.3.0

Full Changelog: https://github.com/docker/build-push-action/compare/v5.2.0...v5.3.0

v5.2.0

Full Changelog: https://github.com/docker/build-push-action/compare/v5.1.0...v5.2.0

v5.1.0

Full Changelog: https://github.com/docker/build-push-action/compare/v5.0.0...v5.1.0

Commits
  • 4f58ea7 Merge pull request #1234 from docker/dependabot/npm_and_yarn/docker/actions-t...
  • 49b5ea6 chore: update generated content
  • 13c9fdd chore(deps): Bump @​docker/actions-toolkit from 0.38.0 to 0.39.0
  • e44afff Merge pull request #1232 from docker/dependabot/npm_and_yarn/path-to-regexp-6...
  • 67ebad3 chore(deps): Bump path-to-regexp from 6.2.2 to 6.3.0
  • 32945a3 Merge pull request #1230 from docker/dependabot/npm_and_yarn/docker/actions-t...
  • e0fe9cf chore: update generated content
  • 8f1ff6b chore(deps): Bump @​docker/actions-toolkit from 0.37.1 to 0.38.0
  • 5cd11c3 Merge pull request #1211 from crazy-max/summary-info-message
  • 0aba704 chore: update generated content
  • Additional commits viewable in compare view

Updates `actions/setup-node` from 4.0.4 to 4.1.0
Release notes

Sourced from actions/setup-node's releases.

v4.1.0

What's Changed

New Contributors

Full Changelog: https://github.com/actions/setup-node/compare/v4...v4.1.0

Commits

Updates `lycheeverse/lychee-action` from 2.0.1 to 2.0.2
Release notes

Sourced from lycheeverse/lychee-action's releases.

Version 2.0.2

What's Changed

New Contributors

Full Changelog: https://github.com/lycheeverse/lychee-action/compare/v2...v2.0.2

Commits

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build-publish-eth-rpc.yml | 4 ++-- .github/workflows/check-licenses.yml | 4 ++-- .github/workflows/check-links.yml | 2 +- .github/workflows/checks-quick.yml | 2 +- .github/workflows/release-50_publish-docker.yml | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build-publish-eth-rpc.yml b/.github/workflows/build-publish-eth-rpc.yml index 9dc575cf1be2..3aa1624096df 100644 --- a/.github/workflows/build-publish-eth-rpc.yml +++ b/.github/workflows/build-publish-eth-rpc.yml @@ -44,7 +44,7 @@ jobs: uses: actions/checkout@v4 - name: Build Docker image - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: context: . file: ./substrate/frame/revive/rpc/Dockerfile @@ -70,7 +70,7 @@ jobs: password: ${{ secrets.PARITYPR_DOCKERHUB_PASSWORD }} - name: Build Docker image - uses: docker/build-push-action@v5 + uses: docker/build-push-action@v6 with: context: . file: ./substrate/frame/revive/rpc/Dockerfile diff --git a/.github/workflows/check-licenses.yml b/.github/workflows/check-licenses.yml index 8bd87118201a..21e2756e8b76 100644 --- a/.github/workflows/check-licenses.yml +++ b/.github/workflows/check-licenses.yml @@ -21,7 +21,7 @@ jobs: steps: - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - - uses: actions/setup-node@v4.0.4 + - uses: actions/setup-node@v4.1.0 with: node-version: "18.x" registry-url: "https://npm.pkg.github.com" @@ -56,7 +56,7 @@ jobs: steps: - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - - uses: actions/setup-node@v4.0.4 + - uses: actions/setup-node@v4.1.0 with: node-version: "18.x" registry-url: "https://npm.pkg.github.com" diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml index 3bbb9baba46e..dd9d3eaf824f 100644 --- a/.github/workflows/check-links.yml +++ b/.github/workflows/check-links.yml @@ -33,7 +33,7 @@ jobs: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.0 (22. Sep 2023) - name: Lychee link checker - uses: lycheeverse/lychee-action@2bb232618be239862e31382c5c0eaeba12e5e966 # for v1.9.1 (10. Jan 2024) + uses: lycheeverse/lychee-action@7cd0af4c74a61395d455af97419279d86aafaede # for v1.9.1 (10. Jan 2024) with: args: >- --config .config/lychee.toml diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index eefe36d9791d..36deba7dfb78 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -102,7 +102,7 @@ jobs: - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: Setup Node.js - uses: actions/setup-node@v4.0.4 + uses: actions/setup-node@v4.1.0 with: node-version: "18.x" registry-url: "https://npm.pkg.github.com" diff --git a/.github/workflows/release-50_publish-docker.yml b/.github/workflows/release-50_publish-docker.yml index 211fa000f8f5..627e53bacd88 100644 --- a/.github/workflows/release-50_publish-docker.yml +++ b/.github/workflows/release-50_publish-docker.yml @@ -347,7 +347,7 @@ jobs: - name: Build and push id: docker_build - uses: docker/build-push-action@4f58ea79222b3b9dc2c8bbdd6debcef730109a75 # v6.9.0 + uses: docker/build-push-action@5e99dacf67635c4f273e532b9266ddb609b3025a # v6.9.0 with: push: true file: docker/dockerfiles/polkadot/polkadot_injected_debian.Dockerfile From b326540184a1c87c141c169896c2f0e58d41e24f Mon Sep 17 00:00:00 2001 From: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Date: Mon, 4 Nov 2024 15:01:49 +0200 Subject: [PATCH 015/166] inclusion emulator: correctly handle UMP signals (#6178) Changes inclusion emulator to not count the UMP signals when checking ump message constraints. --------- Signed-off-by: Andrei Sandu Co-authored-by: GitHub Action --- .../src/inclusion_emulator/mod.rs | 57 +++++++++++++++++-- polkadot/primitives/test-helpers/Cargo.toml | 2 +- 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs index a2a6095b765c..20ca62d41f5b 100644 --- a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs +++ b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs @@ -431,9 +431,9 @@ pub struct ConstraintModifications { pub hrmp_watermark: Option, /// Outbound HRMP channel modifications. pub outbound_hrmp: HashMap, - /// The amount of UMP messages sent. + /// The amount of UMP XCM messages sent. `UMPSignal` and separator are excluded. pub ump_messages_sent: usize, - /// The amount of UMP bytes sent. + /// The amount of UMP XCM bytes sent. `UMPSignal` and separator are excluded. pub ump_bytes_sent: usize, /// The amount of DMP messages processed. pub dmp_messages_processed: usize, @@ -600,6 +600,18 @@ impl Fragment { validation_code_hash: &ValidationCodeHash, persisted_validation_data: &PersistedValidationData, ) -> Result { + // Filter UMP signals and the separator. + let upward_messages = if let Some(separator_index) = + commitments.upward_messages.iter().position(|message| message.is_empty()) + { + commitments.upward_messages.split_at(separator_index).0 + } else { + &commitments.upward_messages + }; + + let ump_messages_sent = upward_messages.len(); + let ump_bytes_sent = upward_messages.iter().map(|msg| msg.len()).sum(); + let modifications = { ConstraintModifications { required_parent: Some(commitments.head_data.clone()), @@ -632,8 +644,8 @@ impl Fragment { outbound_hrmp }, - ump_messages_sent: commitments.upward_messages.len(), - ump_bytes_sent: commitments.upward_messages.iter().map(|msg| msg.len()).sum(), + ump_messages_sent, + ump_bytes_sent, dmp_messages_processed: commitments.processed_downward_messages as _, code_upgrade_applied: operating_constraints .future_validation_code @@ -750,7 +762,7 @@ fn validate_against_constraints( }) } - if commitments.upward_messages.len() > constraints.max_ump_num_per_candidate { + if modifications.ump_messages_sent > constraints.max_ump_num_per_candidate { return Err(FragmentValidityError::UmpMessagesPerCandidateOverflow { messages_allowed: constraints.max_ump_num_per_candidate, messages_submitted: commitments.upward_messages.len(), @@ -814,7 +826,11 @@ impl HypotheticalOrConcreteCandidate for HypotheticalCandidate { #[cfg(test)] mod tests { use super::*; - use polkadot_primitives::{HorizontalMessages, OutboundHrmpMessage, ValidationCode}; + use codec::Encode; + use polkadot_primitives::{ + vstaging::{ClaimQueueOffset, CoreSelector, UMPSignal, UMP_SEPARATOR}, + HorizontalMessages, OutboundHrmpMessage, ValidationCode, + }; #[test] fn stack_modifications() { @@ -1267,6 +1283,35 @@ mod tests { ); } + #[test] + fn ump_signals_ignored() { + let relay_parent = RelayChainBlockInfo { + number: 6, + hash: Hash::repeat_byte(0xbe), + storage_root: Hash::repeat_byte(0xff), + }; + + let constraints = make_constraints(); + let mut candidate = make_candidate(&constraints, &relay_parent); + let max_ump = constraints.max_ump_num_per_candidate; + + // Fill ump queue to the limit. + candidate + .commitments + .upward_messages + .try_extend((0..max_ump).map(|i| vec![i as u8])) + .unwrap(); + + // Add ump signals. + candidate.commitments.upward_messages.force_push(UMP_SEPARATOR); + candidate + .commitments + .upward_messages + .force_push(UMPSignal::SelectCore(CoreSelector(0), ClaimQueueOffset(1)).encode()); + + Fragment::new(relay_parent, constraints, Arc::new(candidate)).unwrap(); + } + #[test] fn fragment_relay_parent_too_old() { let relay_parent = RelayChainBlockInfo { diff --git a/polkadot/primitives/test-helpers/Cargo.toml b/polkadot/primitives/test-helpers/Cargo.toml index a44996ad6ef2..27de3c4b9c56 100644 --- a/polkadot/primitives/test-helpers/Cargo.toml +++ b/polkadot/primitives/test-helpers/Cargo.toml @@ -14,5 +14,5 @@ sp-keyring = { workspace = true, default-features = true } sp-application-crypto = { workspace = true } sp-runtime = { workspace = true, default-features = true } sp-core = { features = ["std"], workspace = true, default-features = true } -polkadot-primitives = { workspace = true, default-features = true } +polkadot-primitives = { features = ["test"], workspace = true, default-features = true } rand = { workspace = true, default-features = true } From b1084e7a374453945a8277b1a34844ba7d567bde Mon Sep 17 00:00:00 2001 From: clangenb <37865735+clangenb@users.noreply.github.com> Date: Mon, 4 Nov 2024 14:40:34 +0100 Subject: [PATCH 016/166] migrate pallet-recovery to benchmark V2 syntax (#6299) Part of: * #6202 --------- Co-authored-by: GitHub Action Co-authored-by: Oliver Tale-Yazdi --- prdoc/pr_6299.prdoc | 8 + substrate/frame/recovery/src/benchmarking.rs | 153 ++++++++----------- 2 files changed, 72 insertions(+), 89 deletions(-) create mode 100644 prdoc/pr_6299.prdoc diff --git a/prdoc/pr_6299.prdoc b/prdoc/pr_6299.prdoc new file mode 100644 index 000000000000..fe8906f6e153 --- /dev/null +++ b/prdoc/pr_6299.prdoc @@ -0,0 +1,8 @@ +title: migrate pallet-recovery to benchmark V2 syntax +doc: +- audience: Runtime Dev + description: |- + migrate pallet-recovery to benchmark V2 syntax +crates: +- name: pallet-recovery + bump: patch diff --git a/substrate/frame/recovery/src/benchmarking.rs b/substrate/frame/recovery/src/benchmarking.rs index b7639742a620..ee97cb77d301 100644 --- a/substrate/frame/recovery/src/benchmarking.rs +++ b/substrate/frame/recovery/src/benchmarking.rs @@ -21,7 +21,7 @@ use super::*; use crate::Pallet; use alloc::{boxed::Box, vec, vec::Vec}; -use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_support::traits::{Currency, Get}; use frame_system::RawOrigin; use sp_runtime::traits::Bounded; @@ -103,56 +103,55 @@ fn insert_recovery_account(caller: &T::AccountId, account: &T::Accoun >::insert(&account, recovery_config); } -benchmarks! { - as_recovered { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn as_recovered() { let caller: T::AccountId = whitelisted_caller(); let recovered_account: T::AccountId = account("recovered_account", 0, SEED); let recovered_account_lookup = T::Lookup::unlookup(recovered_account.clone()); - let call: ::RuntimeCall = frame_system::Call::::remark { remark: vec![] }.into(); + let call: ::RuntimeCall = + frame_system::Call::::remark { remark: vec![] }.into(); Proxy::::insert(&caller, &recovered_account); - }: _( - RawOrigin::Signed(caller), - recovered_account_lookup, - Box::new(call) - ) - set_recovered { + #[extrinsic_call] + _(RawOrigin::Signed(caller), recovered_account_lookup, Box::new(call)) + } + + #[benchmark] + fn set_recovered() { let lost: T::AccountId = whitelisted_caller(); let lost_lookup = T::Lookup::unlookup(lost.clone()); let rescuer: T::AccountId = whitelisted_caller(); let rescuer_lookup = T::Lookup::unlookup(rescuer.clone()); - }: _( - RawOrigin::Root, - lost_lookup, - rescuer_lookup - ) verify { + + #[extrinsic_call] + _(RawOrigin::Root, lost_lookup, rescuer_lookup); + assert_last_event::( - Event::AccountRecovered { - lost_account: lost, - rescuer_account: rescuer, - }.into() + Event::AccountRecovered { lost_account: lost, rescuer_account: rescuer }.into(), ); } - create_recovery { - let n in 1 .. T::MaxFriends::get(); - + #[benchmark] + fn create_recovery(n: Linear<1, { T::MaxFriends::get() }>) { let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); // Create friends let friends = generate_friends::(n); - }: _( - RawOrigin::Signed(caller.clone()), - friends, - n as u16, - DEFAULT_DELAY.into() - ) verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), friends, n as u16, DEFAULT_DELAY.into()); + assert_last_event::(Event::RecoveryCreated { account: caller }.into()); } - initiate_recovery { + #[benchmark] + fn initiate_recovery() { let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); @@ -160,28 +159,23 @@ benchmarks! { let lost_account_lookup = T::Lookup::unlookup(lost_account.clone()); insert_recovery_account::(&caller, &lost_account); - }: _( - RawOrigin::Signed(caller.clone()), - lost_account_lookup - ) verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), lost_account_lookup); + assert_last_event::( - Event::RecoveryInitiated { - lost_account: lost_account, - rescuer_account: caller, - }.into() + Event::RecoveryInitiated { lost_account, rescuer_account: caller }.into(), ); } - vouch_recovery { - let n in 1 .. T::MaxFriends::get(); - + #[benchmark] + fn vouch_recovery(n: Linear<1, { T::MaxFriends::get() }>) { let caller: T::AccountId = whitelisted_caller(); let lost_account: T::AccountId = account("lost_account", 0, SEED); let lost_account_lookup = T::Lookup::unlookup(lost_account.clone()); let rescuer_account: T::AccountId = account("rescuer_account", 0, SEED); let rescuer_account_lookup = T::Lookup::unlookup(rescuer_account.clone()); - // Create friends let friends = add_caller_and_generate_friends::(caller.clone(), n); let bounded_friends: FriendsOf = friends.try_into().unwrap(); @@ -212,23 +206,15 @@ benchmarks! { // Create the active recovery storage item >::insert(&lost_account, &rescuer_account, recovery_status); - }: _( - RawOrigin::Signed(caller.clone()), - lost_account_lookup, - rescuer_account_lookup - ) verify { + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), lost_account_lookup, rescuer_account_lookup); assert_last_event::( - Event::RecoveryVouched { - lost_account: lost_account, - rescuer_account: rescuer_account, - sender: caller, - }.into() + Event::RecoveryVouched { lost_account, rescuer_account, sender: caller }.into(), ); } - claim_recovery { - let n in 1 .. T::MaxFriends::get(); - + #[benchmark] + fn claim_recovery(n: Linear<1, { T::MaxFriends::get() }>) { let caller: T::AccountId = whitelisted_caller(); let lost_account: T::AccountId = account("lost_account", 0, SEED); let lost_account_lookup = T::Lookup::unlookup(lost_account.clone()); @@ -264,25 +250,20 @@ benchmarks! { // Create the active recovery storage item >::insert(&lost_account, &caller, recovery_status); - }: _( - RawOrigin::Signed(caller.clone()), - lost_account_lookup - ) verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), lost_account_lookup); assert_last_event::( - Event::AccountRecovered { - lost_account: lost_account, - rescuer_account: caller, - }.into() + Event::AccountRecovered { lost_account, rescuer_account: caller }.into(), ); } - close_recovery { + #[benchmark] + fn close_recovery(n: Linear<1, { T::MaxFriends::get() }>) { let caller: T::AccountId = whitelisted_caller(); let rescuer_account: T::AccountId = account("rescuer_account", 0, SEED); let rescuer_account_lookup = T::Lookup::unlookup(rescuer_account.clone()); - let n in 1 .. T::MaxFriends::get(); - T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); T::Currency::make_free_balance_be(&rescuer_account, BalanceOf::::max_value()); @@ -315,21 +296,16 @@ benchmarks! { // Create the active recovery storage item >::insert(&caller, &rescuer_account, recovery_status); - }: _( - RawOrigin::Signed(caller.clone()), - rescuer_account_lookup - ) verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), rescuer_account_lookup); assert_last_event::( - Event::RecoveryClosed { - lost_account: caller, - rescuer_account: rescuer_account, - }.into() + Event::RecoveryClosed { lost_account: caller, rescuer_account }.into(), ); } - remove_recovery { - let n in 1 .. T::MaxFriends::get(); - + #[benchmark] + fn remove_recovery(n: Linear<1, { T::MaxFriends::get() }>) { let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); @@ -353,17 +329,14 @@ benchmarks! { // Reserve deposit for recovery T::Currency::reserve(&caller, total_deposit).unwrap(); - }: _( - RawOrigin::Signed(caller.clone()) - ) verify { - assert_last_event::( - Event::RecoveryRemoved { - lost_account: caller - }.into() - ); + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); + assert_last_event::(Event::RecoveryRemoved { lost_account: caller }.into()); } - cancel_recovered { + #[benchmark] + fn cancel_recovered() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let account: T::AccountId = account("account", 0, SEED); let account_lookup = T::Lookup::unlookup(account.clone()); @@ -373,10 +346,12 @@ benchmarks! { frame_system::Pallet::::inc_consumers(&caller)?; Proxy::::insert(&caller, &account); - }: _( - RawOrigin::Signed(caller), - account_lookup - ) + + #[extrinsic_call] + _(RawOrigin::Signed(caller), account_lookup); + + Ok(()) + } impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); } From 028e61be43f05f6f6c88c5cca94160f8db075585 Mon Sep 17 00:00:00 2001 From: Javier Viola <363911+pepoviola@users.noreply.github.com> Date: Mon, 4 Nov 2024 15:05:40 +0100 Subject: [PATCH 017/166] Disable flaky tests reported in #6343 / #6345 (#6346) test: zombienet-polkadot-functional-0018-shared-core-idle-parachain Disable flaky test reported in https://github.com/paritytech/polkadot-sdk/issues/6343 test: zombienet-polkadot-functional-0016-approval-voting-parallel Disable flaky test reported in https://github.com/paritytech/polkadot-sdk/issues/6345 Co-authored-by: Oliver Tale-Yazdi --- .gitlab/pipeline/zombienet/polkadot.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab/pipeline/zombienet/polkadot.yml b/.gitlab/pipeline/zombienet/polkadot.yml index 9a907d8d9946..15d9a5fb5fca 100644 --- a/.gitlab/pipeline/zombienet/polkadot.yml +++ b/.gitlab/pipeline/zombienet/polkadot.yml @@ -225,7 +225,7 @@ zombienet-polkadot-functional-0015-coretime-shared-core: --local-dir="${LOCAL_DIR}/functional" --test="0015-coretime-shared-core.zndsl" -zombienet-polkadot-functional-0016-approval-voting-parallel: +.zombienet-polkadot-functional-0016-approval-voting-parallel: extends: - .zombienet-polkadot-common script: @@ -241,7 +241,7 @@ zombienet-polkadot-functional-0017-sync-backing: --local-dir="${LOCAL_DIR}/functional" --test="0017-sync-backing.zndsl" -zombienet-polkadot-functional-0018-shared-core-idle-parachain: +.zombienet-polkadot-functional-0018-shared-core-idle-parachain: extends: - .zombienet-polkadot-common before_script: From 38cd03c52ab129a8895dd3b66977f858a80bed8a Mon Sep 17 00:00:00 2001 From: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Date: Mon, 4 Nov 2024 17:17:54 +0200 Subject: [PATCH 018/166] `statement-distribution`: RFC103 implementation (#5883) Part of https://github.com/paritytech/polkadot-sdk/issues/5047 On top of https://github.com/paritytech/polkadot-sdk/pull/5679 --------- Signed-off-by: Andrei Sandu Co-authored-by: GitHub Action --- Cargo.lock | 1 + .../src/fragment_chain/tests.rs | 2 +- .../network/statement-distribution/Cargo.toml | 1 + .../statement-distribution/src/error.rs | 5 +- .../statement-distribution/src/v2/mod.rs | 153 +++--- .../statement-distribution/src/v2/requests.rs | 84 +++- .../src/v2/tests/cluster.rs | 12 + .../src/v2/tests/grid.rs | 17 + .../src/v2/tests/mod.rs | 67 ++- .../src/v2/tests/requests.rs | 462 +++++++++++++++++- polkadot/primitives/src/vstaging/mod.rs | 6 + polkadot/primitives/test-helpers/src/lib.rs | 43 +- prdoc/pr_5883.prdoc | 15 + 13 files changed, 731 insertions(+), 137 deletions(-) create mode 100644 prdoc/pr_5883.prdoc diff --git a/Cargo.lock b/Cargo.lock index 14ce58be7faa..59b6d92bde5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16046,6 +16046,7 @@ dependencies = [ "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand_chacha", + "rstest", "sc-keystore", "sc-network", "sp-application-crypto 30.0.0", diff --git a/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs b/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs index 9708b0871c2a..2f8a5525570c 100644 --- a/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs +++ b/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs @@ -71,7 +71,7 @@ fn make_committed_candidate( persisted_validation_data_hash: persisted_validation_data.hash(), pov_hash: Hash::repeat_byte(1), erasure_root: Hash::repeat_byte(1), - signature: test_helpers::dummy_collator_signature(), + signature: test_helpers::zero_collator_signature(), para_head: para_head.hash(), validation_code_hash: Hash::repeat_byte(42).into(), } diff --git a/polkadot/node/network/statement-distribution/Cargo.toml b/polkadot/node/network/statement-distribution/Cargo.toml index 08059353033d..de07937ffb0a 100644 --- a/polkadot/node/network/statement-distribution/Cargo.toml +++ b/polkadot/node/network/statement-distribution/Cargo.toml @@ -44,6 +44,7 @@ polkadot-primitives = { workspace = true, features = ["test"] } polkadot-primitives-test-helpers = { workspace = true } rand_chacha = { workspace = true, default-features = true } polkadot-subsystem-bench = { workspace = true } +rstest = { workspace = true } [[bench]] name = "statement-distribution-regression-bench" diff --git a/polkadot/node/network/statement-distribution/src/error.rs b/polkadot/node/network/statement-distribution/src/error.rs index d7f52162fe23..cff9afbf8667 100644 --- a/polkadot/node/network/statement-distribution/src/error.rs +++ b/polkadot/node/network/statement-distribution/src/error.rs @@ -72,9 +72,6 @@ pub enum Error { #[error("Fetching session info failed {0:?}")] FetchSessionInfo(RuntimeApiError), - #[error("Fetching availability cores failed {0:?}")] - FetchAvailabilityCores(RuntimeApiError), - #[error("Fetching disabled validators failed {0:?}")] FetchDisabledValidators(runtime::Error), @@ -82,7 +79,7 @@ pub enum Error { FetchValidatorGroups(RuntimeApiError), #[error("Fetching claim queue failed {0:?}")] - FetchClaimQueue(runtime::Error), + FetchClaimQueue(RuntimeApiError), #[error("Attempted to share statement when not a validator or not assigned")] InvalidShare, diff --git a/polkadot/node/network/statement-distribution/src/v2/mod.rs b/polkadot/node/network/statement-distribution/src/v2/mod.rs index c79ae3953ad9..6bb49e5de13d 100644 --- a/polkadot/node/network/statement-distribution/src/v2/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/mod.rs @@ -46,12 +46,15 @@ use polkadot_node_subsystem_util::{ backing_implicit_view::View as ImplicitView, reputation::ReputationAggregator, runtime::{ - fetch_claim_queue, request_min_backing_votes, ClaimQueueSnapshot, ProspectiveParachainsMode, + request_min_backing_votes, request_node_features, ClaimQueueSnapshot, + ProspectiveParachainsMode, }, }; use polkadot_primitives::{ - vstaging::CoreState, AuthorityDiscoveryId, CandidateHash, CompactStatement, CoreIndex, - GroupIndex, GroupRotationInfo, Hash, Id as ParaId, IndexedVec, SessionIndex, SessionInfo, + node_features::FeatureIndex, + vstaging::{transpose_claim_queue, CandidateDescriptorVersion, TransposedClaimQueue}, + AuthorityDiscoveryId, CandidateHash, CompactStatement, CoreIndex, GroupIndex, + GroupRotationInfo, Hash, Id as ParaId, IndexedVec, NodeFeatures, SessionIndex, SessionInfo, SignedStatement, SigningContext, UncheckedSignedStatement, ValidatorId, ValidatorIndex, }; @@ -137,6 +140,12 @@ const COST_UNREQUESTED_RESPONSE_STATEMENT: Rep = Rep::CostMajor("Un-requested Statement In Response"); const COST_INACCURATE_ADVERTISEMENT: Rep = Rep::CostMajor("Peer advertised a candidate inaccurately"); +const COST_UNSUPPORTED_DESCRIPTOR_VERSION: Rep = + Rep::CostMajor("Candidate Descriptor version is not supported"); +const COST_INVALID_CORE_INDEX: Rep = + Rep::CostMajor("Candidate Descriptor contains an invalid core index"); +const COST_INVALID_SESSION_INDEX: Rep = + Rep::CostMajor("Candidate Descriptor contains an invalid session index"); const COST_INVALID_REQUEST: Rep = Rep::CostMajor("Peer sent unparsable request"); const COST_INVALID_REQUEST_BITFIELD_SIZE: Rep = @@ -156,6 +165,7 @@ struct PerRelayParentState { statement_store: StatementStore, seconding_limit: usize, session: SessionIndex, + transposed_cq: TransposedClaimQueue, groups_per_para: HashMap>, disabled_validators: HashSet, } @@ -219,10 +229,17 @@ struct PerSessionState { // getting the topology from the gossip-support subsystem grid_view: Option, local_validator: Option, + // `true` if v2 candidate receipts are allowed by the runtime + allow_v2_descriptors: bool, } impl PerSessionState { - fn new(session_info: SessionInfo, keystore: &KeystorePtr, backing_threshold: u32) -> Self { + fn new( + session_info: SessionInfo, + keystore: &KeystorePtr, + backing_threshold: u32, + allow_v2_descriptors: bool, + ) -> Self { let groups = Groups::new(session_info.validator_groups.clone(), backing_threshold); let mut authority_lookup = HashMap::new(); for (i, ad) in session_info.discovery_keys.iter().cloned().enumerate() { @@ -235,7 +252,14 @@ impl PerSessionState { ) .map(|(_, index)| LocalValidatorIndex::Active(index)); - PerSessionState { session_info, groups, authority_lookup, grid_view: None, local_validator } + PerSessionState { + session_info, + groups, + authority_lookup, + grid_view: None, + local_validator, + allow_v2_descriptors, + } } fn supply_topology( @@ -271,6 +295,11 @@ impl PerSessionState { fn is_not_validator(&self) -> bool { self.grid_view.is_some() && self.local_validator.is_none() } + + /// Returns `true` if v2 candidate receipts are enabled + fn candidate_receipt_v2_enabled(&self) -> bool { + self.allow_v2_descriptors + } } pub(crate) struct State { @@ -615,8 +644,18 @@ pub(crate) async fn handle_active_leaves_update( let minimum_backing_votes = request_min_backing_votes(new_relay_parent, session_index, ctx.sender()).await?; - let mut per_session_state = - PerSessionState::new(session_info, &state.keystore, minimum_backing_votes); + let node_features = + request_node_features(new_relay_parent, session_index, ctx.sender()).await?; + let mut per_session_state = PerSessionState::new( + session_info, + &state.keystore, + minimum_backing_votes, + node_features + .unwrap_or(NodeFeatures::EMPTY) + .get(FeatureIndex::CandidateReceiptV2 as usize) + .map(|b| *b) + .unwrap_or(false), + ); if let Some(topology) = state.unused_topologies.remove(&session_index) { per_session_state.supply_topology(&topology.topology, topology.local_index); } @@ -642,18 +681,6 @@ pub(crate) async fn handle_active_leaves_update( continue } - // New leaf: fetch info from runtime API and initialize - // `per_relay_parent`. - - let availability_cores = polkadot_node_subsystem_util::request_availability_cores( - new_relay_parent, - ctx.sender(), - ) - .await - .await - .map_err(JfyiError::RuntimeApiUnavailable)? - .map_err(JfyiError::FetchAvailabilityCores)?; - let group_rotation_info = polkadot_node_subsystem_util::request_validator_groups(new_relay_parent, ctx.sender()) .await @@ -662,23 +689,22 @@ pub(crate) async fn handle_active_leaves_update( .map_err(JfyiError::FetchValidatorGroups)? .1; - let maybe_claim_queue = fetch_claim_queue(ctx.sender(), new_relay_parent) - .await - .unwrap_or_else(|err| { - gum::debug!(target: LOG_TARGET, ?new_relay_parent, ?err, "handle_active_leaves_update: `claim_queue` API not available"); - None - }); + let claim_queue = ClaimQueueSnapshot( + polkadot_node_subsystem_util::request_claim_queue(new_relay_parent, ctx.sender()) + .await + .await + .map_err(JfyiError::RuntimeApiUnavailable)? + .map_err(JfyiError::FetchClaimQueue)?, + ); let local_validator = per_session.local_validator.and_then(|v| { if let LocalValidatorIndex::Active(idx) = v { find_active_validator_state( idx, &per_session.groups, - &availability_cores, &group_rotation_info, - &maybe_claim_queue, + &claim_queue, seconding_limit, - max_candidate_depth, ) } else { Some(LocalValidatorState { grid_tracker: GridTracker::default(), active: None }) @@ -686,13 +712,14 @@ pub(crate) async fn handle_active_leaves_update( }); let groups_per_para = determine_groups_per_para( - availability_cores, + per_session.groups.all().len(), group_rotation_info, - &maybe_claim_queue, - max_candidate_depth, + &claim_queue, ) .await; + let transposed_cq = transpose_claim_queue(claim_queue.0); + state.per_relay_parent.insert( new_relay_parent, PerRelayParentState { @@ -702,6 +729,7 @@ pub(crate) async fn handle_active_leaves_update( session: session_index, groups_per_para, disabled_validators, + transposed_cq, }, ); } @@ -741,11 +769,9 @@ pub(crate) async fn handle_active_leaves_update( fn find_active_validator_state( validator_index: ValidatorIndex, groups: &Groups, - availability_cores: &[CoreState], group_rotation_info: &GroupRotationInfo, - maybe_claim_queue: &Option, + claim_queue: &ClaimQueueSnapshot, seconding_limit: usize, - max_candidate_depth: usize, ) -> Option { if groups.all().is_empty() { return None @@ -753,23 +779,8 @@ fn find_active_validator_state( let our_group = groups.by_validator_index(validator_index)?; - let core_index = group_rotation_info.core_for_group(our_group, availability_cores.len()); - let paras_assigned_to_core = if let Some(claim_queue) = maybe_claim_queue { - claim_queue.iter_claims_for_core(&core_index).copied().collect() - } else { - availability_cores - .get(core_index.0 as usize) - .and_then(|core_state| match core_state { - CoreState::Scheduled(scheduled_core) => Some(scheduled_core.para_id), - CoreState::Occupied(occupied_core) if max_candidate_depth >= 1 => occupied_core - .next_up_on_available - .as_ref() - .map(|scheduled_core| scheduled_core.para_id), - CoreState::Free | CoreState::Occupied(_) => None, - }) - .into_iter() - .collect() - }; + let core_index = group_rotation_info.core_for_group(our_group, groups.all().len()); + let paras_assigned_to_core = claim_queue.iter_claims_for_core(&core_index).copied().collect(); let group_validators = groups.get(our_group)?.to_owned(); Some(LocalValidatorState { @@ -2174,39 +2185,16 @@ async fn provide_candidate_to_grid( // Utility function to populate per relay parent `ParaId` to `GroupIndex` mappings. async fn determine_groups_per_para( - availability_cores: Vec, + n_cores: usize, group_rotation_info: GroupRotationInfo, - maybe_claim_queue: &Option, - max_candidate_depth: usize, + claim_queue: &ClaimQueueSnapshot, ) -> HashMap> { - let n_cores = availability_cores.len(); - // Determine the core indices occupied by each para at the current relay parent. To support // on-demand parachains we also consider the core indices at next blocks. - let schedule: HashMap> = if let Some(claim_queue) = maybe_claim_queue { - claim_queue - .iter_all_claims() - .map(|(core_index, paras)| (*core_index, paras.iter().copied().collect())) - .collect() - } else { - availability_cores - .into_iter() - .enumerate() - .filter_map(|(index, core)| match core { - CoreState::Scheduled(scheduled_core) => - Some((CoreIndex(index as u32), vec![scheduled_core.para_id])), - CoreState::Occupied(occupied_core) => - if max_candidate_depth >= 1 { - occupied_core.next_up_on_available.map(|scheduled_core| { - (CoreIndex(index as u32), vec![scheduled_core.para_id]) - }) - } else { - None - }, - CoreState::Free => None, - }) - .collect() - }; + let schedule: HashMap> = claim_queue + .iter_all_claims() + .map(|(core_index, paras)| (*core_index, paras.iter().copied().collect())) + .collect(); let mut groups_per_para = HashMap::new(); // Map from `CoreIndex` to `GroupIndex` and collect as `HashMap`. @@ -3106,11 +3094,12 @@ pub(crate) async fn handle_response( ) { let &requests::CandidateIdentifier { relay_parent, candidate_hash, group_index } = response.candidate_identifier(); + let peer = *response.requested_peer(); gum::trace!( target: LOG_TARGET, ?candidate_hash, - peer = ?response.requested_peer(), + ?peer, "Received response", ); @@ -3145,6 +3134,8 @@ pub(crate) async fn handle_response( expected_groups.iter().any(|g| g == &g_index) }, disabled_mask, + &relay_parent_state.transposed_cq, + per_session.candidate_receipt_v2_enabled(), ); for (peer, rep) in res.reputation_changes { diff --git a/polkadot/node/network/statement-distribution/src/v2/requests.rs b/polkadot/node/network/statement-distribution/src/v2/requests.rs index 74f29710956f..3b46922c2297 100644 --- a/polkadot/node/network/statement-distribution/src/v2/requests.rs +++ b/polkadot/node/network/statement-distribution/src/v2/requests.rs @@ -30,9 +30,11 @@ //! (which requires state not owned by the request manager). use super::{ - seconded_and_sufficient, BENEFIT_VALID_RESPONSE, BENEFIT_VALID_STATEMENT, - COST_IMPROPERLY_DECODED_RESPONSE, COST_INVALID_RESPONSE, COST_INVALID_SIGNATURE, - COST_UNREQUESTED_RESPONSE_STATEMENT, REQUEST_RETRY_DELAY, + seconded_and_sufficient, CandidateDescriptorVersion, TransposedClaimQueue, + BENEFIT_VALID_RESPONSE, BENEFIT_VALID_STATEMENT, COST_IMPROPERLY_DECODED_RESPONSE, + COST_INVALID_CORE_INDEX, COST_INVALID_RESPONSE, COST_INVALID_SESSION_INDEX, + COST_INVALID_SIGNATURE, COST_UNREQUESTED_RESPONSE_STATEMENT, + COST_UNSUPPORTED_DESCRIPTOR_VERSION, REQUEST_RETRY_DELAY, }; use crate::LOG_TARGET; @@ -566,6 +568,8 @@ impl UnhandledResponse { validator_key_lookup: impl Fn(ValidatorIndex) -> Option, allowed_para_lookup: impl Fn(ParaId, GroupIndex) -> bool, disabled_mask: BitVec, + transposed_cq: &TransposedClaimQueue, + allow_v2_descriptors: bool, ) -> ResponseValidationOutput { let UnhandledResponse { response: TaggedResponse { identifier, requested_peer, props, response }, @@ -650,6 +654,8 @@ impl UnhandledResponse { validator_key_lookup, allowed_para_lookup, disabled_mask, + transposed_cq, + allow_v2_descriptors, ); if let CandidateRequestStatus::Complete { .. } = output.request_status { @@ -670,6 +676,8 @@ fn validate_complete_response( validator_key_lookup: impl Fn(ValidatorIndex) -> Option, allowed_para_lookup: impl Fn(ParaId, GroupIndex) -> bool, disabled_mask: BitVec, + transposed_cq: &TransposedClaimQueue, + allow_v2_descriptors: bool, ) -> ResponseValidationOutput { let RequestProperties { backing_threshold, mut unwanted_mask } = props; @@ -687,39 +695,83 @@ fn validate_complete_response( unwanted_mask.validated_in_group.resize(group.len(), true); } - let invalid_candidate_output = || ResponseValidationOutput { + let invalid_candidate_output = |cost: Rep| ResponseValidationOutput { request_status: CandidateRequestStatus::Incomplete, - reputation_changes: vec![(requested_peer, COST_INVALID_RESPONSE)], + reputation_changes: vec![(requested_peer, cost)], requested_peer, }; + let mut rep_changes = Vec::new(); + // sanity-check candidate response. // note: roughly ascending cost of operations { if response.candidate_receipt.descriptor.relay_parent() != identifier.relay_parent { - return invalid_candidate_output() + return invalid_candidate_output(COST_INVALID_RESPONSE) } if response.candidate_receipt.descriptor.persisted_validation_data_hash() != response.persisted_validation_data.hash() { - return invalid_candidate_output() + return invalid_candidate_output(COST_INVALID_RESPONSE) } if !allowed_para_lookup( response.candidate_receipt.descriptor.para_id(), identifier.group_index, ) { - return invalid_candidate_output() + return invalid_candidate_output(COST_INVALID_RESPONSE) } if response.candidate_receipt.hash() != identifier.candidate_hash { - return invalid_candidate_output() + return invalid_candidate_output(COST_INVALID_RESPONSE) + } + + let candidate_hash = response.candidate_receipt.hash(); + + // V2 descriptors are invalid if not enabled by runtime. + if !allow_v2_descriptors && + response.candidate_receipt.descriptor.version() == CandidateDescriptorVersion::V2 + { + gum::debug!( + target: LOG_TARGET, + ?candidate_hash, + peer = ?requested_peer, + "Version 2 candidate receipts are not enabled by the runtime" + ); + return invalid_candidate_output(COST_UNSUPPORTED_DESCRIPTOR_VERSION) + } + // Validate the core index. + if let Err(err) = response.candidate_receipt.check_core_index(transposed_cq) { + gum::debug!( + target: LOG_TARGET, + ?candidate_hash, + ?err, + peer = ?requested_peer, + "Received candidate has invalid core index" + ); + return invalid_candidate_output(COST_INVALID_CORE_INDEX) + } + + // Check if `session_index` of relay parent matches candidate descriptor + // `session_index`. + if let Some(candidate_session_index) = response.candidate_receipt.descriptor.session_index() + { + if candidate_session_index != session { + gum::debug!( + target: LOG_TARGET, + ?candidate_hash, + peer = ?requested_peer, + session_index = session, + candidate_session_index, + "Received candidate has invalid session index" + ); + return invalid_candidate_output(COST_INVALID_SESSION_INDEX) + } } } // statement checks. - let mut rep_changes = Vec::new(); let statements = { let mut statements = Vec::with_capacity(std::cmp::min(response.statements.len(), group.len() * 2)); @@ -815,7 +867,7 @@ fn validate_complete_response( // Only accept responses which are sufficient, according to our // required backing threshold. if !seconded_and_sufficient(&received_filter, backing_threshold) { - return invalid_candidate_output() + return invalid_candidate_output(COST_INVALID_RESPONSE) } statements @@ -1091,6 +1143,8 @@ mod tests { validator_key_lookup, allowed_para_lookup, disabled_mask.clone(), + &Default::default(), + false, ); assert_eq!( output, @@ -1130,6 +1184,8 @@ mod tests { validator_key_lookup, allowed_para_lookup, disabled_mask, + &Default::default(), + false, ); assert_eq!( output, @@ -1214,6 +1270,8 @@ mod tests { validator_key_lookup, allowed_para_lookup, disabled_mask, + &Default::default(), + false, ); assert_eq!( output, @@ -1296,6 +1354,8 @@ mod tests { validator_key_lookup, allowed_para_lookup, disabled_mask, + &Default::default(), + false, ); assert_eq!( output, @@ -1434,6 +1494,8 @@ mod tests { validator_key_lookup, allowed_para_lookup, disabled_mask.clone(), + &Default::default(), + false, ); // First request served successfully diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/cluster.rs b/polkadot/node/network/statement-distribution/src/v2/tests/cluster.rs index fe51f953e244..040123f1774c 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/cluster.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/cluster.rs @@ -25,6 +25,7 @@ fn share_seconded_circulated_to_cluster() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -125,6 +126,7 @@ fn cluster_valid_statement_before_seconded_ignored() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -185,6 +187,7 @@ fn cluster_statement_bad_signature() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -258,6 +261,7 @@ fn useful_cluster_statement_from_non_cluster_peer_rejected() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -320,6 +324,7 @@ fn elastic_scaling_useful_cluster_statement_from_non_cluster_peer_rejected() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -379,6 +384,7 @@ fn statement_from_non_cluster_originator_unexpected() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -434,6 +440,7 @@ fn seconded_statement_leads_to_request() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -522,6 +529,7 @@ fn cluster_statements_shared_seconded_first() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -636,6 +644,7 @@ fn cluster_accounts_for_implicit_view() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -772,6 +781,7 @@ fn cluster_messages_imported_after_confirmed_candidate_importable_check() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -895,6 +905,7 @@ fn cluster_messages_imported_after_new_leaf_importable_check() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1031,6 +1042,7 @@ fn ensure_seconding_limit_is_respected() { max_candidate_depth: 1, allowed_ancestry_len: 3, }), + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs b/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs index d2bf031368c1..0133d9e219f6 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs @@ -31,6 +31,7 @@ fn backed_candidate_leads_to_advertisement() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -240,6 +241,7 @@ fn received_advertisement_before_confirmation_leads_to_request() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -412,6 +414,7 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; test_harness(config, |state, mut overseer| async move { @@ -593,6 +596,7 @@ fn receive_ack_for_unconfirmed_candidate() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; test_harness(config, |state, mut overseer| async move { @@ -654,6 +658,7 @@ fn received_acknowledgements_for_locally_confirmed() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; test_harness(config, |state, mut overseer| async move { @@ -816,6 +821,7 @@ fn received_acknowledgements_for_externally_confirmed() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; test_harness(config, |state, mut overseer| async move { @@ -951,6 +957,7 @@ fn received_advertisement_after_confirmation_before_backing() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1129,6 +1136,7 @@ fn additional_statements_are_shared_after_manifest_exchange() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1416,6 +1424,7 @@ fn advertisement_sent_when_peer_enters_relay_parent_view() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1629,6 +1638,7 @@ fn advertisement_not_re_sent_when_peer_re_enters_view() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1840,6 +1850,7 @@ fn inner_grid_statements_imported_to_backing(groups_for_first_para: usize) { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2048,6 +2059,7 @@ fn advertisements_rejected_from_incorrect_peers() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2184,6 +2196,7 @@ fn manifest_rejected_with_unknown_relay_parent() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2281,6 +2294,7 @@ fn manifest_rejected_when_not_a_validator() { group_size, local_validator: LocalRole::None, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2374,6 +2388,7 @@ fn manifest_rejected_when_group_does_not_match_para() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2472,6 +2487,7 @@ fn peer_reported_for_advertisement_conflicting_with_confirmed_candidate() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2662,6 +2678,7 @@ fn inactive_local_participates_in_grid() { group_size, local_validator: LocalRole::InactiveValidator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs index 9f2c36ad1018..46b72f5adac9 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs @@ -33,9 +33,9 @@ use polkadot_node_subsystem::messages::{ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_primitives::{ - vstaging::{CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CoreState}, - AssignmentPair, AsyncBackingParams, Block, BlockNumber, GroupRotationInfo, HeadData, Header, - IndexedVec, PersistedValidationData, ScheduledCore, SessionIndex, SessionInfo, ValidatorPair, + vstaging::CommittedCandidateReceiptV2 as CommittedCandidateReceipt, AssignmentPair, + AsyncBackingParams, Block, BlockNumber, GroupRotationInfo, HeadData, Header, IndexedVec, + PersistedValidationData, SessionIndex, SessionInfo, ValidatorPair, }; use sc_keystore::LocalKeystore; use sc_network::ProtocolName; @@ -82,6 +82,8 @@ struct TestConfig { // whether the local node should be a validator local_validator: LocalRole, async_backing_params: Option, + // allow v2 descriptors (feature bit) + allow_v2_descriptors: bool, } #[derive(Debug, Clone)] @@ -96,6 +98,7 @@ struct TestState { validators: Vec, session_info: SessionInfo, req_sender: async_channel::Sender, + node_features: NodeFeatures, } impl TestState { @@ -174,7 +177,13 @@ impl TestState { random_seed: [0u8; 32], }; - TestState { config, local, validators, session_info, req_sender } + let mut node_features = NodeFeatures::new(); + if config.allow_v2_descriptors { + node_features.resize(FeatureIndex::FirstUnassigned as usize, false); + node_features.set(FeatureIndex::CandidateReceiptV2 as usize, true); + } + + TestState { config, local, validators, session_info, req_sender, node_features } } fn make_dummy_leaf(&self, relay_parent: Hash) -> TestLeaf { @@ -186,20 +195,23 @@ impl TestState { relay_parent: Hash, groups_for_first_para: usize, ) -> TestLeaf { + let mut cq = std::collections::BTreeMap::new(); + + for i in 0..self.session_info.validator_groups.len() { + if i < groups_for_first_para { + cq.entry(CoreIndex(i as u32)) + .or_insert_with(|| vec![ParaId::from(0u32), ParaId::from(0u32)].into()); + } else { + cq.entry(CoreIndex(i as u32)) + .or_insert_with(|| vec![ParaId::from(i), ParaId::from(i)].into()); + }; + } + TestLeaf { number: 1, hash: relay_parent, parent_hash: Hash::repeat_byte(0), session: 1, - availability_cores: self.make_availability_cores(|i| { - let para_id = if i < groups_for_first_para { - ParaId::from(0u32) - } else { - ParaId::from(i as u32) - }; - - CoreState::Scheduled(ScheduledCore { para_id, collator: None }) - }), disabled_validators: Default::default(), para_data: (0..self.session_info.validator_groups.len()) .map(|i| { @@ -213,6 +225,7 @@ impl TestState { }) .collect(), minimum_backing_votes: 2, + claim_queue: ClaimQueueSnapshot(cq), } } @@ -232,10 +245,6 @@ impl TestState { TestLeaf { minimum_backing_votes, ..self.make_dummy_leaf(relay_parent) } } - fn make_availability_cores(&self, f: impl Fn(usize) -> CoreState) -> Vec { - (0..self.session_info.validator_groups.len()).map(f).collect() - } - fn make_dummy_topology(&self) -> NewGossipTopology { let validator_count = self.config.validator_count; let is_local_inactive = matches!(self.config.local_validator, LocalRole::InactiveValidator); @@ -423,10 +432,10 @@ struct TestLeaf { hash: Hash, parent_hash: Hash, session: SessionIndex, - availability_cores: Vec, pub disabled_validators: Vec, para_data: Vec<(ParaId, PerParaData)>, minimum_backing_votes: u32, + claim_queue: ClaimQueueSnapshot, } impl TestLeaf { @@ -574,9 +583,9 @@ async fn handle_leaf_activation( parent_hash, para_data, session, - availability_cores, disabled_validators, minimum_backing_votes, + claim_queue, } = leaf; assert_matches!( @@ -623,7 +632,7 @@ async fn handle_leaf_activation( _parent, RuntimeApiRequest::Version(tx), )) => { - tx.send(Ok(RuntimeApiRequest::DISABLED_VALIDATORS_RUNTIME_REQUIREMENT)).unwrap(); + tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); }, AllMessages::RuntimeApi(RuntimeApiMessage::Request( parent, @@ -657,12 +666,6 @@ async fn handle_leaf_activation( assert!(is_new_session, "only expecting this call in a new session"); tx.send(Ok(*minimum_backing_votes)).unwrap(); }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::AvailabilityCores(tx), - )) if parent == *hash => { - tx.send(Ok(availability_cores.clone())).unwrap(); - }, AllMessages::RuntimeApi(RuntimeApiMessage::Request( parent, RuntimeApiRequest::ValidatorGroups(tx), @@ -675,6 +678,18 @@ async fn handle_leaf_activation( }; tx.send(Ok((validator_groups, group_rotation_info))).unwrap(); }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::NodeFeatures(_session_index, tx), + )) if parent == *hash => { + tx.send(Ok(test_state.node_features.clone())).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::ClaimQueue(tx), + )) if parent == *hash => { + tx.send(Ok(claim_queue.0.clone())).unwrap(); + }, AllMessages::ProspectiveParachains( ProspectiveParachainsMessage::GetHypotheticalMembership(req, tx), ) => { diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/requests.rs b/polkadot/node/network/statement-distribution/src/v2/tests/requests.rs index dcb90bacdcde..fc880c1d9a83 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/requests.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/requests.rs @@ -21,19 +21,25 @@ use codec::{Decode, Encode}; use polkadot_node_network_protocol::{ request_response::v2 as request_v2, v2::BackedCandidateManifest, }; -use polkadot_primitives_test_helpers::make_candidate; +use polkadot_primitives_test_helpers::{make_candidate, make_candidate_v2}; use sc_network::config::{ IncomingRequest as RawIncomingRequest, OutgoingResponse as RawOutgoingResponse, }; -#[test] -fn cluster_peer_allowed_to_send_incomplete_statements() { +use polkadot_primitives::vstaging::MutateDescriptorV2; +use rstest::rstest; + +#[rstest] +#[case(false)] +#[case(true)] +fn cluster_peer_allowed_to_send_incomplete_statements(#[case] allow_v2_descriptors: bool) { let group_size = 3; let config = TestConfig { validator_count: 20, group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors, }; let relay_parent = Hash::repeat_byte(1); @@ -48,14 +54,28 @@ fn cluster_peer_allowed_to_send_incomplete_statements() { let test_leaf = state.make_dummy_leaf(relay_parent); - let (candidate, pvd) = make_candidate( - relay_parent, - 1, - local_para, - test_leaf.para_data(local_para).head_data.clone(), - vec![4, 5, 6].into(), - Hash::repeat_byte(42).into(), - ); + let (candidate, pvd) = if allow_v2_descriptors { + let (mut candidate, pvd) = make_candidate_v2( + relay_parent, + 1, + local_para, + test_leaf.para_data(local_para).head_data.clone(), + vec![4, 5, 6].into(), + Hash::repeat_byte(42).into(), + ); + candidate.descriptor.set_core_index(CoreIndex(local_group_index.0)); + (candidate, pvd) + } else { + make_candidate( + relay_parent, + 1, + local_para, + test_leaf.para_data(local_para).head_data.clone(), + vec![4, 5, 6].into(), + Hash::repeat_byte(42).into(), + ) + }; + let candidate_hash = candidate.hash(); let other_group_validators = state.group_validators(local_group_index, true); @@ -187,6 +207,7 @@ fn peer_reported_for_providing_statements_meant_to_be_masked_out() { max_candidate_depth: 1, allowed_ancestry_len: 3, }), + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -462,6 +483,7 @@ fn peer_reported_for_not_enough_statements() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -649,6 +671,7 @@ fn peer_reported_for_duplicate_statements() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -802,6 +825,7 @@ fn peer_reported_for_providing_statements_with_invalid_signatures() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -925,6 +949,415 @@ fn peer_reported_for_providing_statements_with_invalid_signatures() { }); } +#[test] +fn peer_reported_for_invalid_v2_descriptor() { + let group_size = 3; + let config = TestConfig { + validator_count: 20, + group_size, + local_validator: LocalRole::Validator, + async_backing_params: None, + allow_v2_descriptors: true, + }; + + let relay_parent = Hash::repeat_byte(1); + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); + + test_harness(config, |state, mut overseer| async move { + let local_validator = state.local.clone().unwrap(); + let local_group_index = local_validator.group_index.unwrap(); + let local_para = ParaId::from(local_group_index.0); + + let test_leaf = state.make_dummy_leaf(relay_parent); + + let (mut candidate, pvd) = make_candidate_v2( + relay_parent, + 1, + local_para, + test_leaf.para_data(local_para).head_data.clone(), + vec![4, 5, 6].into(), + Hash::repeat_byte(42).into(), + ); + + candidate.descriptor.set_core_index(CoreIndex(100)); + + let candidate_hash = candidate.hash(); + + let other_group_validators = state.group_validators(local_group_index, true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = other_group_validators[1]; + + // peer A is in group, has relay parent in view. + // peer B is in group, has no relay parent in view. + // peer C is not in group, has relay parent in view. + { + connect_peer( + &mut overseer, + peer_a.clone(), + Some(vec![state.discovery_id(other_group_validators[0])].into_iter().collect()), + ) + .await; + + connect_peer( + &mut overseer, + peer_b.clone(), + Some(vec![state.discovery_id(other_group_validators[1])].into_iter().collect()), + ) + .await; + + connect_peer(&mut overseer, peer_c.clone(), None).await; + + send_peer_view_change(&mut overseer, peer_a.clone(), view![relay_parent]).await; + send_peer_view_change(&mut overseer, peer_c.clone(), view![relay_parent]).await; + } + + activate_leaf(&mut overseer, &test_leaf, &state, true, vec![]).await; + + // Peer in cluster sends a statement, triggering a request. + { + let a_seconded = state + .sign_statement( + v_a, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + + send_peer_message( + &mut overseer, + peer_a.clone(), + protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded), + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_STATEMENT_FIRST.into() => { } + ); + } + + // Send a request to peer and mock its response to include a candidate with invalid core + // index. + { + let b_seconded_invalid = state + .sign_statement( + v_b, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + let statements = vec![b_seconded_invalid.clone()]; + + handle_sent_request( + &mut overseer, + peer_a, + candidate_hash, + StatementFilter::blank(group_size), + candidate.clone(), + pvd.clone(), + statements, + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == COST_INVALID_CORE_INDEX.into() => { } + ); + } + + // Test invalid session index + candidate.descriptor.set_session_index(100); + // Set good core index + candidate.descriptor.set_core_index(CoreIndex(local_group_index.0)); + + let candidate_hash = candidate.hash(); + + // Peer in cluster sends a statement, triggering a request. + { + let a_seconded = state + .sign_statement( + v_a, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + + send_peer_message( + &mut overseer, + peer_a.clone(), + protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded), + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_STATEMENT_FIRST.into() => { } + ); + } + + // Send a request to peer and mock its response to include a candidate with invalid session + // index. + { + let b_seconded_invalid = state + .sign_statement( + v_b, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + let statements = vec![b_seconded_invalid.clone()]; + + handle_sent_request( + &mut overseer, + peer_a, + candidate_hash, + StatementFilter::blank(group_size), + candidate.clone(), + pvd.clone(), + statements, + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == COST_INVALID_SESSION_INDEX.into() => { } + ); + } + + // Test valid candidate does not lead to punishment + candidate.descriptor.set_session_index(1); + + let candidate_hash = candidate.hash(); + + // Peer in cluster sends a statement, triggering a request. + { + let a_seconded = state + .sign_statement( + v_a, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + + send_peer_message( + &mut overseer, + peer_a.clone(), + protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded), + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_STATEMENT_FIRST.into() => { } + ); + } + + // Send a request to peer and mock its response to include a valid candidate. + { + let b_seconded_invalid = state + .sign_statement( + v_b, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + let statements = vec![b_seconded_invalid.clone()]; + + handle_sent_request( + &mut overseer, + peer_a, + candidate_hash, + StatementFilter::blank(group_size), + candidate.clone(), + pvd.clone(), + statements, + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_STATEMENT.into() => { } + ); + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_RESPONSE.into() => { } + ); + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( + peers, + Versioned::V2(protocol_v2::ValidationProtocol::StatementDistribution( + protocol_v2::StatementDistributionMessage::Statement( + r, + s, + ) + )) + )) => { + assert_eq!(peers, vec![peer_a.clone()]); + assert_eq!(r, relay_parent); + assert_eq!(s.unchecked_payload(), &CompactStatement::Seconded(candidate_hash)); + assert_eq!(s.unchecked_validator_index(), v_c); + } + ); + + answer_expected_hypothetical_membership_request(&mut overseer, vec![]).await; + } + overseer + }); +} + +#[rstest] +#[case(false)] +#[case(true)] +// Test if v2 descriptors are filtered and peers punished if the node feature is disabled. +// Also test if the peer is rewarded for providing v2 descriptor if the node feature is enabled. +fn v2_descriptors_filtered(#[case] allow_v2_descriptors: bool) { + let group_size = 3; + let config = TestConfig { + validator_count: 20, + group_size, + local_validator: LocalRole::Validator, + async_backing_params: None, + allow_v2_descriptors, + }; + + let relay_parent = Hash::repeat_byte(1); + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); + + test_harness(config, |state, mut overseer| async move { + let local_validator = state.local.clone().unwrap(); + let local_group_index = local_validator.group_index.unwrap(); + let local_para = ParaId::from(local_group_index.0); + + let test_leaf = state.make_dummy_leaf(relay_parent); + + let (mut candidate, pvd) = make_candidate_v2( + relay_parent, + 1, + local_para, + test_leaf.para_data(local_para).head_data.clone(), + vec![4, 5, 6].into(), + Hash::repeat_byte(42).into(), + ); + + // Makes the candidate invalid. + candidate.descriptor.set_core_index(CoreIndex(100)); + + let candidate_hash = candidate.hash(); + + let other_group_validators = state.group_validators(local_group_index, true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + + // peer A is in group, has relay parent in view. + // peer B is in group, has no relay parent in view. + // peer C is not in group, has relay parent in view. + { + connect_peer( + &mut overseer, + peer_a.clone(), + Some(vec![state.discovery_id(other_group_validators[0])].into_iter().collect()), + ) + .await; + + connect_peer( + &mut overseer, + peer_b.clone(), + Some(vec![state.discovery_id(other_group_validators[1])].into_iter().collect()), + ) + .await; + + connect_peer(&mut overseer, peer_c.clone(), None).await; + + send_peer_view_change(&mut overseer, peer_a.clone(), view![relay_parent]).await; + send_peer_view_change(&mut overseer, peer_c.clone(), view![relay_parent]).await; + } + + activate_leaf(&mut overseer, &test_leaf, &state, true, vec![]).await; + + // Peer in cluster sends a statement, triggering a request. + { + let a_seconded = state + .sign_statement( + v_a, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + + send_peer_message( + &mut overseer, + peer_a.clone(), + protocol_v2::StatementDistributionMessage::Statement(relay_parent, a_seconded), + ) + .await; + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == BENEFIT_VALID_STATEMENT_FIRST.into() => { } + ); + } + + // Send a request to peer and mock its response to include a candidate with invalid core + // index. + { + let b_seconded_invalid = state + .sign_statement( + v_b, + CompactStatement::Seconded(candidate_hash), + &SigningContext { parent_hash: relay_parent, session_index: 1 }, + ) + .as_unchecked() + .clone(); + let statements = vec![b_seconded_invalid.clone()]; + + handle_sent_request( + &mut overseer, + peer_a, + candidate_hash, + StatementFilter::blank(group_size), + candidate.clone(), + pvd.clone(), + statements, + ) + .await; + + let expected_rep_change = if allow_v2_descriptors { + COST_INVALID_CORE_INDEX.into() + } else { + COST_UNSUPPORTED_DESCRIPTOR_VERSION.into() + }; + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_a && r == expected_rep_change => { } + ); + } + + overseer + }); +} #[test] fn peer_reported_for_providing_statements_with_wrong_validator_id() { let group_size = 3; @@ -933,6 +1366,7 @@ fn peer_reported_for_providing_statements_with_wrong_validator_id() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1063,6 +1497,7 @@ fn disabled_validators_added_to_unwanted_mask() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1229,6 +1664,7 @@ fn disabling_works_from_relay_parent_not_the_latest_state() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_1 = Hash::repeat_byte(1); @@ -1428,6 +1864,7 @@ fn local_node_sanity_checks_incoming_requests() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1629,6 +2066,7 @@ fn local_node_checks_that_peer_can_request_before_responding() { group_size: 3, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -1828,6 +2266,7 @@ fn local_node_respects_statement_mask() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); @@ -2070,6 +2509,7 @@ fn should_delay_before_retrying_dropped_requests() { group_size, local_validator: LocalRole::Validator, async_backing_params: None, + allow_v2_descriptors: false, }; let relay_parent = Hash::repeat_byte(1); diff --git a/polkadot/primitives/src/vstaging/mod.rs b/polkadot/primitives/src/vstaging/mod.rs index 94b7b200e68f..ca9c3e1bebad 100644 --- a/polkadot/primitives/src/vstaging/mod.rs +++ b/polkadot/primitives/src/vstaging/mod.rs @@ -204,6 +204,8 @@ pub trait MutateDescriptorV2 { fn set_version(&mut self, version: InternalVersion); /// Set the PVD of the descriptor. fn set_persisted_validation_data_hash(&mut self, persisted_validation_data_hash: Hash); + /// Set the validation code hash of the descriptor. + fn set_validation_code_hash(&mut self, validation_code_hash: ValidationCodeHash); /// Set the erasure root of the descriptor. fn set_erasure_root(&mut self, erasure_root: Hash); /// Set the para head of the descriptor. @@ -244,6 +246,10 @@ impl MutateDescriptorV2 for CandidateDescriptorV2 { self.persisted_validation_data_hash = persisted_validation_data_hash; } + fn set_validation_code_hash(&mut self, validation_code_hash: ValidationCodeHash) { + self.validation_code_hash = validation_code_hash; + } + fn set_erasure_root(&mut self, erasure_root: Hash) { self.erasure_root = erasure_root; } diff --git a/polkadot/primitives/test-helpers/src/lib.rs b/polkadot/primitives/test-helpers/src/lib.rs index c2eccafef788..1717dd5b0eda 100644 --- a/polkadot/primitives/test-helpers/src/lib.rs +++ b/polkadot/primitives/test-helpers/src/lib.rs @@ -23,13 +23,15 @@ //! Note that `dummy_` prefixed values are meant to be fillers, that should not matter, and will //! contain randomness based data. use polkadot_primitives::{ - vstaging::{CandidateDescriptorV2, CandidateReceiptV2, CommittedCandidateReceiptV2}, + vstaging::{ + CandidateDescriptorV2, CandidateReceiptV2, CommittedCandidateReceiptV2, MutateDescriptorV2, + }, CandidateCommitments, CandidateDescriptor, CandidateReceipt, CollatorId, CollatorSignature, CommittedCandidateReceipt, CoreIndex, Hash, HeadData, Id as ParaId, PersistedValidationData, SessionIndex, ValidationCode, ValidationCodeHash, ValidatorId, }; pub use rand; -use sp_application_crypto::sr25519; +use sp_application_crypto::{sr25519, ByteArray}; use sp_keyring::Sr25519Keyring; use sp_runtime::generic::Digest; @@ -199,8 +201,15 @@ pub fn dummy_collator() -> CollatorId { CollatorId::from(sr25519::Public::default()) } -/// Create a meaningless collator signature. +/// Create a meaningless collator signature. It is important to not be 0, as we'd confuse +/// v1 and v2 descriptors. pub fn dummy_collator_signature() -> CollatorSignature { + CollatorSignature::from_slice(&mut (0..64).into_iter().collect::>().as_slice()) + .expect("64 bytes; qed") +} + +/// Create a zeroed collator signature. +pub fn zero_collator_signature() -> CollatorSignature { CollatorSignature::from(sr25519::Signature::default()) } @@ -250,6 +259,34 @@ pub fn make_candidate( (candidate, pvd) } +/// Create a meaningless v2 candidate, returning its receipt and PVD. +pub fn make_candidate_v2( + relay_parent_hash: Hash, + relay_parent_number: u32, + para_id: ParaId, + parent_head: HeadData, + head_data: HeadData, + validation_code_hash: ValidationCodeHash, +) -> (CommittedCandidateReceiptV2, PersistedValidationData) { + let pvd = dummy_pvd(parent_head, relay_parent_number); + let commitments = CandidateCommitments { + head_data, + horizontal_messages: Default::default(), + upward_messages: Default::default(), + new_validation_code: None, + processed_downward_messages: 0, + hrmp_watermark: relay_parent_number, + }; + + let mut descriptor = dummy_candidate_descriptor_v2(relay_parent_hash); + descriptor.set_para_id(para_id); + descriptor.set_persisted_validation_data_hash(pvd.hash()); + descriptor.set_validation_code_hash(validation_code_hash); + let candidate = CommittedCandidateReceiptV2 { descriptor, commitments }; + + (candidate, pvd) +} + /// Create a new candidate descriptor, and apply a valid signature /// using the provided `collator` key. pub fn make_valid_candidate_descriptor>( diff --git a/prdoc/pr_5883.prdoc b/prdoc/pr_5883.prdoc new file mode 100644 index 000000000000..96225a89bc99 --- /dev/null +++ b/prdoc/pr_5883.prdoc @@ -0,0 +1,15 @@ +title: 'statement-distribution RFC103 implementation' + +doc: + - audience: Node Dev + description: | + Introduces checks for the new candidate descriptor fields: `core_index` and `session_index`. + +crates: + - name: polkadot-statement-distribution + bump: minor + - name: polkadot-primitives + bump: major + - name: polkadot-primitives-test-helpers + bump: major + From d69a80e64ffd0310d10f26d3cab835df10550caf Mon Sep 17 00:00:00 2001 From: Cyrill Leutwiler Date: Mon, 4 Nov 2024 16:38:14 +0100 Subject: [PATCH 019/166] [pallet-revive] rework balance transfers (#6187) This PR removes the `transfer` syscall and changes balance transfers to make the existential deposit (ED) fully transparent for contracts. The `transfer` API is removed since there is no corresponding EVM opcode and transferring via a call introduces barely any overhead. We make the ED transparent to contracts by transferring the ED from the call origin to nonexistent accounts. Without this change, transfers to nonexistant accounts will transfer the supplied value minus the ED from the contracts viewpoint, and consequentially fail if the supplied value lies below the ED. Changing this behavior removes the need for contract code to handle this rather annoying corner case and aligns better with the EVM. The EVM charges a similar deposit from the gas meter, so transferring the ED from the call origin is practically the same as the call origin pays for gas. --------- Signed-off-by: xermicus Signed-off-by: Cyrill Leutwiler Co-authored-by: command-bot <> Co-authored-by: GitHub Action Co-authored-by: PG Herveou --- .../assets/asset-hub-westend/src/lib.rs | 8 +- prdoc/pr_6187.prdoc | 16 ++ substrate/bin/node/runtime/src/lib.rs | 5 +- .../frame/revive/fixtures/contracts/drain.rs | 11 +- .../fixtures/contracts/return_data_api.rs | 30 +--- .../contracts/transfer_return_code.rs | 11 +- .../frame/revive/src/benchmarking/mod.rs | 32 +--- substrate/frame/revive/src/exec.rs | 151 +++++++++++++----- substrate/frame/revive/src/tests.rs | 23 +-- substrate/frame/revive/src/wasm/runtime.rs | 26 --- substrate/frame/revive/src/weights.rs | 21 --- substrate/frame/revive/uapi/src/host.rs | 12 -- .../frame/revive/uapi/src/host/riscv32.rs | 6 - 13 files changed, 173 insertions(+), 179 deletions(-) create mode 100644 prdoc/pr_6187.prdoc 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 bbd686b5cf50..baa3aad95fda 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -45,7 +45,10 @@ use frame_support::{ ord_parameter_types, parameter_types, traits::{ fungible, fungibles, - tokens::{imbalance::ResolveAssetTo, nonfungibles_v2::Inspect}, + tokens::{ + imbalance::ResolveAssetTo, nonfungibles_v2::Inspect, Fortitude::Polite, + Preservation::Expendable, + }, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, InstanceFilter, Nothing, TransformOrigin, }, @@ -2073,8 +2076,9 @@ impl_runtime_apis! { impl pallet_revive::ReviveApi for Runtime { fn balance(address: H160) -> Balance { + use frame_support::traits::fungible::Inspect; let account = ::AddressMapper::to_account_id(&address); - Balances::usable_balance(account) + Balances::reducible_balance(&account, Expendable, Polite) } fn nonce(address: H160) -> Nonce { diff --git a/prdoc/pr_6187.prdoc b/prdoc/pr_6187.prdoc new file mode 100644 index 000000000000..92d801987969 --- /dev/null +++ b/prdoc/pr_6187.prdoc @@ -0,0 +1,16 @@ +title: '[pallet-revive] rework balance transfers' +doc: +- audience: Runtime Dev + description: |- + This PR removes the `transfer` syscall and changes balance transfers to make the existential deposit (ED) fully transparent for contracts. + + The `transfer` API is removed since there is no corresponding EVM opcode and transferring via a call introduces barely any overhead. + + We make the ED transparent to contracts by transferring the ED from the call origin to nonexistent accounts. Without this change, transfers to nonexistant accounts will transfer the supplied value minus the ED from the contracts viewpoint, and consequentially fail if the supplied value lies below the ED. Changing this behavior removes the need for contract code to handle this rather annoying corner case and aligns better with the EVM. The EVM charges a similar deposit from the gas meter, so transferring the ED from the call origin is practically the same as the call origin pays for gas. +crates: +- name: pallet-revive + bump: major +- name: pallet-revive-fixtures + bump: patch +- name: pallet-revive-uapi + bump: major diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index d407aafb452b..8c2992bdb696 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::{ }, tokens::{ imbalance::ResolveAssetTo, nonfungibles_v2::Inspect, pay::PayAssetFromAccount, - GetSalary, PayFromAccount, + Fortitude::Polite, GetSalary, PayFromAccount, Preservation::Preserve, }, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, Contains, Currency, EitherOfDiverse, EnsureOriginWithArg, EqualPrivilegeOnly, Imbalance, InsideBoth, @@ -3165,8 +3165,9 @@ impl_runtime_apis! { impl pallet_revive::ReviveApi for Runtime { fn balance(address: H160) -> Balance { + use frame_support::traits::fungible::Inspect; let account = ::AddressMapper::to_account_id(&address); - Balances::usable_balance(account) + Balances::reducible_balance(&account, Preserve, Polite) } fn nonce(address: H160) -> Nonce { diff --git a/substrate/frame/revive/fixtures/contracts/drain.rs b/substrate/frame/revive/fixtures/contracts/drain.rs index 0d644a4238c4..6e3e708a6b3d 100644 --- a/substrate/frame/revive/fixtures/contracts/drain.rs +++ b/substrate/frame/revive/fixtures/contracts/drain.rs @@ -36,6 +36,15 @@ pub extern "C" fn call() { // Try to self-destruct by sending more balance to the 0 address. // The call will fail because a contract transfer has a keep alive requirement. - let res = api::transfer(&[0u8; 20], &u256_bytes(balance)); + let res = api::call( + uapi::CallFlags::empty(), + &[0u8; 20], + 0, + 0, + None, + &u256_bytes(balance), + &[], + None, + ); assert!(matches!(res, Err(uapi::ReturnErrorCode::TransferFailed))); } diff --git a/substrate/frame/revive/fixtures/contracts/return_data_api.rs b/substrate/frame/revive/fixtures/contracts/return_data_api.rs index 846396b0944d..2a390296a419 100644 --- a/substrate/frame/revive/fixtures/contracts/return_data_api.rs +++ b/substrate/frame/revive/fixtures/contracts/return_data_api.rs @@ -35,11 +35,11 @@ static INPUT_DATA: [u8; INPUT_BUF_SIZE] = [0xFF; INPUT_BUF_SIZE]; const OUTPUT_BUF_SIZE: usize = INPUT_BUF_SIZE - 4; static OUTPUT_DATA: [u8; OUTPUT_BUF_SIZE] = [0xEE; OUTPUT_BUF_SIZE]; +/// Assert correct return data after calls and finally reset the return data. fn assert_return_data_after_call(input: &[u8]) { assert_return_data_size_of(OUTPUT_BUF_SIZE as u64); - assert_plain_transfer_does_not_reset(OUTPUT_BUF_SIZE as u64); assert_return_data_copy(&input[4..]); - reset_return_data(); + assert_balance_transfer_does_reset(); } /// Assert that what we get from [api::return_data_copy] matches `whole_return_data`, @@ -73,22 +73,6 @@ fn recursion_guard() -> [u8; 20] { own_address } -/// Call ourselves recursively, which panics the callee and thus resets the return data. -fn reset_return_data() { - api::call( - uapi::CallFlags::ALLOW_REENTRY, - &recursion_guard(), - 0u64, - 0u64, - None, - &[0u8; 32], - &[0u8; 32], - None, - ) - .unwrap_err(); - assert_return_data_size_of(0); -} - /// Assert [api::return_data_size] to match the `expected` value. fn assert_return_data_size_of(expected: u64) { let mut return_data_size = [0xff; 32]; @@ -96,11 +80,11 @@ fn assert_return_data_size_of(expected: u64) { assert_eq!(return_data_size, u256_bytes(expected)); } -/// Assert [api::return_data_size] to match the `expected` value after a plain transfer -/// (plain transfers don't issue a call and so should not reset the return data) -fn assert_plain_transfer_does_not_reset(expected: u64) { - api::transfer(&[0; 20], &u256_bytes(128)).unwrap(); - assert_return_data_size_of(expected); +/// Assert the return data to be reset after a balance transfer. +fn assert_balance_transfer_does_reset() { + api::call(uapi::CallFlags::empty(), &[0u8; 20], 0, 0, None, &u256_bytes(128), &[], None) + .unwrap(); + assert_return_data_size_of(0); } #[no_mangle] diff --git a/substrate/frame/revive/fixtures/contracts/transfer_return_code.rs b/substrate/frame/revive/fixtures/contracts/transfer_return_code.rs index bfeca9b8b4a4..09d45d0a8411 100644 --- a/substrate/frame/revive/fixtures/contracts/transfer_return_code.rs +++ b/substrate/frame/revive/fixtures/contracts/transfer_return_code.rs @@ -28,7 +28,16 @@ pub extern "C" fn deploy() {} #[no_mangle] #[polkavm_derive::polkavm_export] pub extern "C" fn call() { - let ret_code = match api::transfer(&[0u8; 20], &u256_bytes(100u64)) { + let ret_code = match api::call( + uapi::CallFlags::empty(), + &[0u8; 20], + 0, + 0, + None, + &u256_bytes(100u64), + &[], + None, + ) { Ok(_) => 0u32, Err(code) => code as u32, }; diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index 3d1d7d2a224a..593c16cbb2d8 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -169,7 +169,7 @@ where }; if key == &key_new { - continue + continue; } child::put_raw(&child_trie_info, &key_new, &value); } @@ -1507,36 +1507,6 @@ mod benchmarks { Ok(()) } - // We transfer to unique accounts. - #[benchmark(pov_mode = Measured)] - fn seal_transfer() { - let account = account::("receiver", 0, 0); - let value = Pallet::::min_balance(); - assert!(value > 0u32.into()); - - let mut setup = CallSetup::::default(); - setup.set_balance(value); - let (mut ext, _) = setup.ext(); - let mut runtime = crate::wasm::Runtime::<_, [u8]>::new(&mut ext, vec![]); - - let account_bytes = account.encode(); - let account_len = account_bytes.len() as u32; - let value_bytes = Into::::into(value).encode(); - let mut memory = memory!(account_bytes, value_bytes,); - - let result; - #[block] - { - result = runtime.bench_transfer( - memory.as_mut_slice(), - 0, // account_ptr - account_len, // value_ptr - ); - } - - assert_ok!(result); - } - // t: with or without some value to transfer // i: size of the input data #[benchmark(pov_mode = Measured)] diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 943c377e504d..4f90b41b0de5 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -236,9 +236,6 @@ pub trait Ext: sealing::Sealed { /// call stack. fn terminate(&mut self, beneficiary: &H160) -> DispatchResult; - /// Transfer some amount of funds into the specified account. - fn transfer(&mut self, to: &H160, value: U256) -> DispatchResult; - /// Returns the storage entry of the executing account by the given `key`. /// /// Returns `None` if the `key` wasn't previously set by `set_storage` or @@ -775,7 +772,7 @@ where )? { stack.run(executable, input_data).map(|_| stack.first_frame.last_frame_output) } else { - Self::transfer_from_origin(&origin, &dest, value) + Self::transfer_from_origin(&origin, &origin, &dest, value) } } @@ -1069,7 +1066,12 @@ where // If it is a delegate call, then we've already transferred tokens in the // last non-delegate frame. if delegated_code_hash.is_none() { - Self::transfer_from_origin(&caller, &frame.account_id, frame.value_transferred)?; + Self::transfer_from_origin( + &self.origin, + &caller, + &frame.account_id, + frame.value_transferred, + )?; } let contract_address = T::AddressMapper::to_address(&top_frame!(self).account_id); @@ -1265,19 +1267,48 @@ where } /// Transfer some funds from `from` to `to`. - fn transfer(from: &T::AccountId, to: &T::AccountId, value: BalanceOf) -> ExecResult { - // this avoids events to be emitted for zero balance transfers - if !value.is_zero() { - T::Currency::transfer(from, to, value, Preservation::Preserve).map_err(|err| { - log::debug!(target: LOG_TARGET, "Transfer of {value:?} from {from:?} to {to:?} failed: {err:?}"); - Error::::TransferFailed - })?; + /// + /// This is a no-op for zero `value`, avoiding events to be emitted for zero balance transfers. + /// + /// If the destination account does not exist, it is pulled into existence by transferring the + /// ED from `origin` to the new account. The total amount transferred to `to` will be ED + + /// `value`. This makes the ED fully transparent for contracts. + /// The ED transfer is executed atomically with the actual transfer, avoiding the possibility of + /// the ED transfer succeeding but the actual transfer failing. In other words, if the `to` does + /// not exist, the transfer does fail and nothing will be sent to `to` if either `origin` can + /// not provide the ED or transferring `value` from `from` to `to` fails. + /// Note: This will also fail if `origin` is root. + fn transfer( + origin: &Origin, + from: &T::AccountId, + to: &T::AccountId, + value: BalanceOf, + ) -> ExecResult { + if value.is_zero() { + return Ok(Default::default()); + } + + if >::account_exists(to) { + return T::Currency::transfer(from, to, value, Preservation::Preserve) + .map(|_| Default::default()) + .map_err(|_| Error::::TransferFailed.into()); } - Ok(Default::default()) + + let origin = origin.account_id()?; + let ed = ::Currency::minimum_balance(); + with_transaction(|| -> TransactionOutcome { + match T::Currency::transfer(origin, to, ed, Preservation::Preserve) + .and_then(|_| T::Currency::transfer(from, to, value, Preservation::Preserve)) + { + Ok(_) => TransactionOutcome::Commit(Ok(Default::default())), + Err(_) => TransactionOutcome::Rollback(Err(Error::::TransferFailed.into())), + } + }) } /// Same as `transfer` but `from` is an `Origin`. fn transfer_from_origin( + origin: &Origin, from: &Origin, to: &T::AccountId, value: BalanceOf, @@ -1289,7 +1320,7 @@ where Origin::Root if value.is_zero() => return Ok(Default::default()), Origin::Root => return Err(DispatchError::RootNotAllowed.into()), }; - Self::transfer(from, to, value) + Self::transfer(origin, from, to, value) } /// Reference to the current (top) frame. @@ -1413,7 +1444,13 @@ where )? { self.run(executable, input_data) } else { - Self::transfer(&self.account_id(), &dest, value).map(|_| ()) + Self::transfer_from_origin( + &self.origin, + &Origin::from_account_id(self.account_id().clone()), + &dest, + value, + )?; + Ok(()) } }; @@ -1511,16 +1548,6 @@ where Ok(()) } - fn transfer(&mut self, to: &H160, value: U256) -> DispatchResult { - Self::transfer( - &self.top_frame().account_id, - &T::AddressMapper::to_account_id(to), - value.try_into().map_err(|_| Error::::BalanceConversionFailed)?, - ) - .map(|_| ()) - .map_err(|error| error.error) - } - fn get_storage(&mut self, key: &Key) -> Option> { self.top_frame_mut().contract_info().read(key) } @@ -2058,10 +2085,50 @@ mod tests { set_balance(&ALICE, 100); set_balance(&BOB, 0); - MockStack::transfer(&ALICE, &BOB, 55).unwrap(); + let origin = Origin::from_account_id(ALICE); + MockStack::transfer(&origin, &ALICE, &BOB, 55).unwrap(); - assert_eq!(get_balance(&ALICE), 45); - assert_eq!(get_balance(&BOB), 55); + let min_balance = ::Currency::minimum_balance(); + assert_eq!(get_balance(&ALICE), 45 - min_balance); + assert_eq!(get_balance(&BOB), 55 + min_balance); + }); + } + + #[test] + fn transfer_to_nonexistent_account_works() { + // This test verifies that a contract is able to transfer + // some funds to a nonexistant account and that those transfers + // are not able to reap accounts. + ExtBuilder::default().build().execute_with(|| { + let ed = ::Currency::minimum_balance(); + let value = 1024; + + // Transfers to nonexistant accounts should work + set_balance(&ALICE, ed * 2); + set_balance(&BOB, ed + value); + + assert_ok!(MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &CHARLIE, value)); + assert_eq!(get_balance(&ALICE), ed); + assert_eq!(get_balance(&BOB), ed); + assert_eq!(get_balance(&CHARLIE), ed + value); + + // Do not reap the origin account + set_balance(&ALICE, ed); + set_balance(&BOB, ed + value); + assert_err!( + MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &DJANGO, value), + >::TransferFailed + ); + + // Do not reap the sender account + set_balance(&ALICE, ed * 2); + set_balance(&BOB, value); + assert_err!( + MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &EVE, value), + >::TransferFailed + ); + // The ED transfer would work. But it should only be executed with the actual transfer + assert!(!System::account_exists(&EVE)); }); } @@ -2172,16 +2239,17 @@ mod tests { fn balance_too_low() { // This test verifies that a contract can't send value if it's // balance is too low. - let origin = ALICE; + let from = ALICE; + let origin = Origin::from_account_id(ALICE); let dest = BOB; ExtBuilder::default().build().execute_with(|| { - set_balance(&origin, 0); + set_balance(&from, 0); - let result = MockStack::transfer(&origin, &dest, 100); + let result = MockStack::transfer(&origin, &from, &dest, 100); assert_eq!(result, Err(Error::::TransferFailed.into())); - assert_eq!(get_balance(&origin), 0); + assert_eq!(get_balance(&from), 0); assert_eq!(get_balance(&dest), 0); }); } @@ -4385,12 +4453,19 @@ mod tests { &ExecReturnValue { flags: ReturnFlags::empty(), data: vec![127] } ); - // Plain transfers should not set the output - ctx.ext.transfer(&address, U256::from(1)).unwrap(); - assert_eq!( - ctx.ext.last_frame_output(), - &ExecReturnValue { flags: ReturnFlags::empty(), data: vec![127] } - ); + // Balance transfers should reset the output + ctx.ext + .call( + Weight::zero(), + U256::zero(), + &address, + U256::from(1), + vec![], + true, + false, + ) + .unwrap(); + assert_eq!(ctx.ext.last_frame_output(), &Default::default()); // Reverted instantiation should set the output ctx.ext diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 2d9cae16c441..a35e4d908601 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -631,7 +631,10 @@ fn calling_plain_account_is_balance_transfer() { assert!(!>::contains_key(BOB_ADDR)); assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 0); let result = builder::bare_call(BOB_ADDR).value(42).build_and_unwrap_result(); - assert_eq!(test_utils::get_balance(&BOB_FALLBACK), 42); + assert_eq!( + test_utils::get_balance(&BOB_FALLBACK), + 42 + ::Currency::minimum_balance() + ); assert_eq!(result, Default::default()); }); } @@ -1508,20 +1511,8 @@ fn call_return_code() { .build_and_unwrap_result(); assert_return_code!(result, RuntimeReturnCode::TransferFailed); - // Sending less than the minimum balance will also make the transfer fail - let result = builder::bare_call(bob.addr) - .data( - AsRef::<[u8]>::as_ref(&DJANGO_ADDR) - .iter() - .chain(&u256_bytes(42)) - .cloned() - .collect(), - ) - .build_and_unwrap_result(); - assert_return_code!(result, RuntimeReturnCode::TransferFailed); - - // Sending at least the minimum balance should result in success but - // no code called. + // Sending below the minimum balance should result in success. + // The ED is charged from the call origin. assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 0); let result = builder::bare_call(bob.addr) .data( @@ -1533,7 +1524,7 @@ fn call_return_code() { ) .build_and_unwrap_result(); assert_return_code!(result, RuntimeReturnCode::Success); - assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 55); + assert_eq!(test_utils::get_balance(&DJANGO_FALLBACK), 55 + min_balance); let django = builder::bare_instantiate(Code::Upload(callee_code)) .origin(RuntimeOrigin::signed(CHARLIE)) diff --git a/substrate/frame/revive/src/wasm/runtime.rs b/substrate/frame/revive/src/wasm/runtime.rs index 95257bee1c6b..8310fe701013 100644 --- a/substrate/frame/revive/src/wasm/runtime.rs +++ b/substrate/frame/revive/src/wasm/runtime.rs @@ -358,8 +358,6 @@ pub enum RuntimeCosts { GetTransientStorage(u32), /// Weight of calling `seal_take_transient_storage` for the given size. TakeTransientStorage(u32), - /// Weight of calling `seal_transfer`. - Transfer, /// Base weight of calling `seal_call`. CallBase, /// Weight of calling `seal_delegate_call` for the given input size. @@ -503,7 +501,6 @@ impl Token for RuntimeCosts { TakeTransientStorage(len) => { cost_storage!(write_transient, seal_take_transient_storage, len) }, - Transfer => T::WeightInfo::seal_transfer(), CallBase => T::WeightInfo::seal_call(0, 0), DelegateCallBase => T::WeightInfo::seal_delegate_call(), CallTransferSurcharge => cost_args!(seal_call, 1, 0), @@ -1235,29 +1232,6 @@ pub mod env { self.take_storage(memory, flags, key_ptr, key_len, out_ptr, out_len_ptr) } - /// Transfer some value to another account. - /// See [`pallet_revive_uapi::HostFn::transfer`]. - #[api_version(0)] - #[mutating] - fn transfer( - &mut self, - memory: &mut M, - address_ptr: u32, - value_ptr: u32, - ) -> Result { - self.charge_gas(RuntimeCosts::Transfer)?; - let callee = memory.read_h160(address_ptr)?; - let value: U256 = memory.read_u256(value_ptr)?; - let result = self.ext.transfer(&callee, value); - match result { - Ok(()) => Ok(ReturnErrorCode::Success), - Err(err) => { - let code = Self::err_into_return_code(err)?; - Ok(code) - }, - } - } - /// Make a call to another contract. /// See [`pallet_revive_uapi::HostFn::call`]. #[api_version(0)] diff --git a/substrate/frame/revive/src/weights.rs b/substrate/frame/revive/src/weights.rs index d1b1a63b4db6..3c6a0be6ee75 100644 --- a/substrate/frame/revive/src/weights.rs +++ b/substrate/frame/revive/src/weights.rs @@ -106,7 +106,6 @@ pub trait WeightInfo { fn seal_get_transient_storage(n: u32, ) -> Weight; fn seal_contains_transient_storage(n: u32, ) -> Weight; fn seal_take_transient_storage(n: u32, ) -> Weight; - fn seal_transfer() -> Weight; fn seal_call(t: u32, i: u32, ) -> Weight; fn seal_delegate_call() -> Weight; fn seal_instantiate(i: u32, ) -> Weight; @@ -792,16 +791,6 @@ impl WeightInfo for SubstrateWeight { } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) - fn seal_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `315` - // Estimated: `3780` - // Minimum execution time: 14_740_000 picoseconds. - Weight::from_parts(15_320_000, 3780) - .saturating_add(T::DbWeight::get().reads(1_u64)) - } - /// Storage: `Revive::AddressSuffix` (r:1 w:0) - /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) /// Storage: `Revive::CodeInfoOf` (r:1 w:0) @@ -1631,16 +1620,6 @@ impl WeightInfo for () { } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) - fn seal_transfer() -> Weight { - // Proof Size summary in bytes: - // Measured: `315` - // Estimated: `3780` - // Minimum execution time: 14_740_000 picoseconds. - Weight::from_parts(15_320_000, 3780) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - } - /// Storage: `Revive::AddressSuffix` (r:1 w:0) - /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) /// Storage: `Revive::CodeInfoOf` (r:1 w:0) diff --git a/substrate/frame/revive/uapi/src/host.rs b/substrate/frame/revive/uapi/src/host.rs index cf4cdeee0f28..cb52cf93540b 100644 --- a/substrate/frame/revive/uapi/src/host.rs +++ b/substrate/frame/revive/uapi/src/host.rs @@ -600,18 +600,6 @@ pub trait HostFn: private::Sealed { /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] fn take_storage(flags: StorageFlags, key: &[u8], output: &mut &mut [u8]) -> Result; - /// Transfer some amount of funds into the specified account. - /// - /// # Parameters - /// - /// - `address`: The address of the account to transfer funds to. - /// - `value`: The U256 value to transfer. - /// - /// # Errors - /// - /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] - fn transfer(address: &[u8; 20], value: &[u8; 32]) -> Result; - /// Remove the calling account and transfer remaining **free** balance. /// /// This function never returns. Either the termination was successful and the diff --git a/substrate/frame/revive/uapi/src/host/riscv32.rs b/substrate/frame/revive/uapi/src/host/riscv32.rs index fc55bfbde186..199a0abc3ddc 100644 --- a/substrate/frame/revive/uapi/src/host/riscv32.rs +++ b/substrate/frame/revive/uapi/src/host/riscv32.rs @@ -58,7 +58,6 @@ mod sys { out_ptr: *mut u8, out_len_ptr: *mut u32, ) -> ReturnCode; - pub fn transfer(address_ptr: *const u8, value_ptr: *const u8) -> ReturnCode; pub fn call(ptr: *const u8) -> ReturnCode; pub fn delegate_call( flags: u32, @@ -332,11 +331,6 @@ impl HostFn for HostFnImpl { ret_code.into() } - fn transfer(address: &[u8; 20], value: &[u8; 32]) -> Result { - let ret_code = unsafe { sys::transfer(address.as_ptr(), value.as_ptr()) }; - ret_code.into() - } - fn deposit_event(topics: &[[u8; 32]], data: &[u8]) { unsafe { sys::deposit_event( From f1e416a5501521832495472eaa9c851acbe05d47 Mon Sep 17 00:00:00 2001 From: s0me0ne-unkn0wn <48632512+s0me0ne-unkn0wn@users.noreply.github.com> Date: Mon, 4 Nov 2024 19:24:56 +0100 Subject: [PATCH 020/166] Silent annoying log (#6351) The logline in question doesn't indeed present any interest for a node operator (I mean, there is not much he can do about that warning), but in a heavy transaction load situation, when each of 5000 transactions in txpool produces a warning, it's really annoying. Still, it's useful for a developer, so I propose to log it at the `debug` level. --- cumulus/primitives/storage-weight-reclaim/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cumulus/primitives/storage-weight-reclaim/src/lib.rs b/cumulus/primitives/storage-weight-reclaim/src/lib.rs index 5471640695ca..5cbe662e2700 100644 --- a/cumulus/primitives/storage-weight-reclaim/src/lib.rs +++ b/cumulus/primitives/storage-weight-reclaim/src/lib.rs @@ -198,7 +198,7 @@ where let block_weight_proof_size = current.total().proof_size(); let missing_from_node = node_side_pov_size.saturating_sub(block_weight_proof_size); if missing_from_node > 0 { - log::warn!( + log::debug!( target: LOG_TARGET, "Node-side PoV size higher than runtime proof size weight. node-side: {node_side_pov_size} extrinsic_len: {extrinsic_len} runtime: {block_weight_proof_size}, missing: {missing_from_node}. Setting to node-side proof size." ); From 2ae79be8e028a995b850621ee55f46c041eceefe Mon Sep 17 00:00:00 2001 From: davidk-pt Date: Tue, 5 Nov 2024 09:31:48 +0200 Subject: [PATCH 021/166] Bounty Pallet: add `approve_bounty_with_curator` call to `bounties` pallet (#5961) Resolves issue https://github.com/paritytech/polkadot-sdk/issues/5928 Adds `approve_bounty_with_curator` call to the `bounties` pallet to combine functions of `approve_bounty` and `propose_curator` into one call. Also adds a new status `ApprovedWithCurator` required to distinguish if bounty was approved with curator when skipping through `Funded` status and moving to `CuratorProposed` status. If `unassign_curator` is called after `approve_bounty_with_curator` the process will fall back to the old flow of calling `propose_curator` separately. --------- Co-authored-by: DavidK Co-authored-by: command-bot <> Co-authored-by: Ankan <10196091+Ank4n@users.noreply.github.com> --- .../rococo/src/weights/pallet_bounties.rs | 82 +++--- prdoc/pr_5961.prdoc | 15 ++ substrate/frame/bounties/src/benchmarking.rs | 15 ++ substrate/frame/bounties/src/lib.rs | 72 +++++- substrate/frame/bounties/src/tests.rs | 233 +++++++++++++++++- substrate/frame/bounties/src/weights.rs | 191 +++++++------- 6 files changed, 482 insertions(+), 126 deletions(-) create mode 100644 prdoc/pr_5961.prdoc diff --git a/polkadot/runtime/rococo/src/weights/pallet_bounties.rs b/polkadot/runtime/rococo/src/weights/pallet_bounties.rs index 8f8be5f2386f..e1f630ec4ce7 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_bounties.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_bounties.rs @@ -17,25 +17,23 @@ //! Autogenerated weights for `pallet_bounties` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-02-29, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("rococo-dev")`, DB CACHE: 1024 // Executed Command: -// ./target/production/polkadot +// target/production/polkadot // benchmark // pallet -// --chain=rococo-dev // --steps=50 // --repeat=20 -// --no-storage-info -// --no-median-slopes -// --no-min-squares -// --pallet=pallet_bounties // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_bounties +// --chain=rococo-dev // --header=./polkadot/file_header.txt // --output=./polkadot/runtime/rococo/src/weights/ @@ -63,11 +61,11 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `210` // Estimated: `3593` - // Minimum execution time: 21_772_000 picoseconds. - Weight::from_parts(22_861_341, 0) + // Minimum execution time: 26_614_000 picoseconds. + Weight::from_parts(28_274_660, 0) .saturating_add(Weight::from_parts(0, 3593)) - // Standard Error: 3 - .saturating_add(Weight::from_parts(721, 0).saturating_mul(d.into())) + // Standard Error: 4 + .saturating_add(Weight::from_parts(779, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -79,8 +77,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `302` // Estimated: `3642` - // Minimum execution time: 11_218_000 picoseconds. - Weight::from_parts(11_796_000, 0) + // Minimum execution time: 14_692_000 picoseconds. + Weight::from_parts(15_070_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -91,22 +89,36 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `322` // Estimated: `3642` - // Minimum execution time: 10_959_000 picoseconds. - Weight::from_parts(11_658_000, 0) + // Minimum execution time: 13_695_000 picoseconds. + Weight::from_parts(14_220_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `Bounties::BountyApprovals` (r:1 w:1) + /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + fn approve_bounty_with_curator() -> Weight { + // Proof Size summary in bytes: + // Measured: `322` + // Estimated: `3642` + // Minimum execution time: 18_428_000 picoseconds. + Weight::from_parts(19_145_000, 0) + .saturating_add(Weight::from_parts(0, 3642)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Bounties::Bounties` (r:1 w:1) + /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn unassign_curator() -> Weight { // Proof Size summary in bytes: // Measured: `498` // Estimated: `3642` - // Minimum execution time: 37_419_000 picoseconds. - Weight::from_parts(38_362_000, 0) + // Minimum execution time: 44_648_000 picoseconds. + Weight::from_parts(45_860_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -119,8 +131,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `494` // Estimated: `3642` - // Minimum execution time: 27_328_000 picoseconds. - Weight::from_parts(27_661_000, 0) + // Minimum execution time: 33_973_000 picoseconds. + Weight::from_parts(34_979_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -133,8 +145,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `400` // Estimated: `3642` - // Minimum execution time: 16_067_000 picoseconds. - Weight::from_parts(16_865_000, 0) + // Minimum execution time: 20_932_000 picoseconds. + Weight::from_parts(21_963_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) @@ -151,8 +163,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `764` // Estimated: `8799` - // Minimum execution time: 101_153_000 picoseconds. - Weight::from_parts(102_480_000, 0) + // Minimum execution time: 114_942_000 picoseconds. + Weight::from_parts(117_653_000, 0) .saturating_add(Weight::from_parts(0, 8799)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(6)) @@ -169,8 +181,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `444` // Estimated: `3642` - // Minimum execution time: 38_838_000 picoseconds. - Weight::from_parts(39_549_000, 0) + // Minimum execution time: 47_649_000 picoseconds. + Weight::from_parts(49_016_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(3)) @@ -187,8 +199,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `680` // Estimated: `6196` - // Minimum execution time: 68_592_000 picoseconds. - Weight::from_parts(70_727_000, 0) + // Minimum execution time: 80_298_000 picoseconds. + Weight::from_parts(82_306_000, 0) .saturating_add(Weight::from_parts(0, 6196)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(4)) @@ -199,8 +211,8 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `358` // Estimated: `3642` - // Minimum execution time: 11_272_000 picoseconds. - Weight::from_parts(11_592_000, 0) + // Minimum execution time: 14_237_000 picoseconds. + Weight::from_parts(14_969_000, 0) .saturating_add(Weight::from_parts(0, 3642)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) @@ -216,11 +228,11 @@ impl pallet_bounties::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0 + b * (297 ±0)` // Estimated: `1887 + b * (5206 ±0)` - // Minimum execution time: 2_844_000 picoseconds. - Weight::from_parts(2_900_000, 0) + // Minimum execution time: 3_174_000 picoseconds. + Weight::from_parts(3_336_000, 0) .saturating_add(Weight::from_parts(0, 1887)) - // Standard Error: 9_467 - .saturating_add(Weight::from_parts(32_326_595, 0).saturating_mul(b.into())) + // Standard Error: 10_408 + .saturating_add(Weight::from_parts(37_811_366, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/prdoc/pr_5961.prdoc b/prdoc/pr_5961.prdoc new file mode 100644 index 000000000000..46a5be8e49d5 --- /dev/null +++ b/prdoc/pr_5961.prdoc @@ -0,0 +1,15 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "Bounties Pallet: add `approve_bounty_with_curator` call" + +doc: + - audience: [Runtime Dev, Runtime User] + description: | + Adds `approve_bounty_with_curator` call to the bounties pallet to combine `approve_bounty` and `propose_curator` into one call. If `unassign_curator` is called after `approve_bounty_with_curator` the process falls back to the previous flow of calling `propose_curator` separately. Introduces a new `ApprovedWithCurator` bounty status when bounty is approved with curator. + +crates: + - name: pallet-bounties + bump: major + - name: rococo-runtime + bump: minor diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index 6fa60e6938b6..8ad85d5420ed 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -125,6 +125,21 @@ benchmarks_instance_pallet! { Treasury::::on_initialize(frame_system::Pallet::::block_number()); }: _(approve_origin, bounty_id, curator_lookup, fee) + approve_bounty_with_curator { + setup_pot_account::(); + let (caller, curator, fee, value, reason) = setup_bounty::(0, T::MaximumReasonLength::get()); + let curator_lookup = T::Lookup::unlookup(curator.clone()); + Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; + let bounty_id = BountyCount::::get() - 1; + let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + Treasury::::on_initialize(BlockNumberFor::::zero()); + }: _(approve_origin, bounty_id, curator_lookup, fee) + verify { + assert_last_event::( + Event::CuratorProposed { bounty_id, curator }.into() + ); + } + // Worst case when curator is inactive and any sender unassigns the curator. unassign_curator { setup_pot_account::(); diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 9d5931f4a608..6e0bfa6084e1 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -73,6 +73,8 @@ //! - `approve_bounty` - Accept a specific treasury amount to be earmarked for a predefined body of //! work. //! - `propose_curator` - Assign an account to a bounty as candidate curator. +//! - `approve_bounty_with_curator` - Accept a specific treasury amount for a predefined body of +//! work with assigned candidate curator account. //! - `accept_curator` - Accept a bounty assignment from the Council, setting a curator deposit. //! - `extend_bounty_expiry` - Extend the expiry block number of the bounty and stay active. //! - `award_bounty` - Close and pay out the specified amount for the completed work. @@ -174,6 +176,11 @@ pub enum BountyStatus { /// When the bounty can be claimed. unlock_at: BlockNumber, }, + /// The bounty is approved with curator assigned. + ApprovedWithCurator { + /// The assigned curator of this bounty. + curator: AccountId, + }, } /// The child bounty manager. @@ -471,6 +478,15 @@ pub mod pallet { // No curator to unassign at this point. return Err(Error::::UnexpectedStatus.into()) }, + BountyStatus::ApprovedWithCurator { ref curator } => { + // Bounty not yet funded, but bounty was approved with curator. + // `RejectOrigin` or curator himself can unassign from this bounty. + ensure!(maybe_sender.map_or(true, |sender| sender == *curator), BadOrigin); + // This state can only be while the bounty is not yet funded so we return + // bounty to the `Approved` state without curator + bounty.status = BountyStatus::Approved; + return Ok(()); + }, BountyStatus::CuratorProposed { ref curator } => { // A curator has been proposed, but not accepted yet. // Either `RejectOrigin` or the proposed curator can unassign the curator. @@ -723,7 +739,7 @@ pub mod pallet { Some(>::WeightInfo::close_bounty_proposed()).into() ) }, - BountyStatus::Approved => { + BountyStatus::Approved | BountyStatus::ApprovedWithCurator { .. } => { // For weight reasons, we don't allow a council to cancel in this phase. // We ask for them to wait until it is funded before they can cancel. return Err(Error::::UnexpectedStatus.into()) @@ -804,6 +820,52 @@ pub mod pallet { Self::deposit_event(Event::::BountyExtended { index: bounty_id }); Ok(()) } + + /// Approve bountry and propose a curator simultaneously. + /// This call is a shortcut to calling `approve_bounty` and `propose_curator` separately. + /// + /// May only be called from `T::SpendOrigin`. + /// + /// - `bounty_id`: Bounty ID to approve. + /// - `curator`: The curator account whom will manage this bounty. + /// - `fee`: The curator fee. + /// + /// ## Complexity + /// - O(1). + #[pallet::call_index(9)] + #[pallet::weight(>::WeightInfo::approve_bounty_with_curator())] + pub fn approve_bounty_with_curator( + origin: OriginFor, + #[pallet::compact] bounty_id: BountyIndex, + curator: AccountIdLookupOf, + #[pallet::compact] fee: BalanceOf, + ) -> DispatchResult { + let max_amount = T::SpendOrigin::ensure_origin(origin)?; + let curator = T::Lookup::lookup(curator)?; + Bounties::::try_mutate_exists(bounty_id, |maybe_bounty| -> DispatchResult { + // approve bounty + let bounty = maybe_bounty.as_mut().ok_or(Error::::InvalidIndex)?; + ensure!( + bounty.value <= max_amount, + pallet_treasury::Error::::InsufficientPermission + ); + ensure!(bounty.status == BountyStatus::Proposed, Error::::UnexpectedStatus); + ensure!(fee < bounty.value, Error::::InvalidFee); + + BountyApprovals::::try_append(bounty_id) + .map_err(|()| Error::::TooManyQueued)?; + + bounty.status = BountyStatus::ApprovedWithCurator { curator: curator.clone() }; + bounty.fee = fee; + + Ok(()) + })?; + + Self::deposit_event(Event::::BountyApproved { index: bounty_id }); + Self::deposit_event(Event::::CuratorProposed { bounty_id, curator }); + + Ok(()) + } } #[pallet::hooks] @@ -946,7 +1008,13 @@ impl, I: 'static> pallet_treasury::SpendFunds for Pallet BountiesEvent { - System::events() +fn last_events(n: usize) -> Vec> { + let mut res = System::events() .into_iter() - .map(|r| r.event) - .filter_map(|e| if let RuntimeEvent::Bounties(inner) = e { Some(inner) } else { None }) - .last() - .unwrap() + .rev() + .filter_map( + |e| if let RuntimeEvent::Bounties(inner) = e.event { Some(inner) } else { None }, + ) + .take(n) + .collect::>(); + res.reverse(); + res +} + +fn last_event() -> BountiesEvent { + last_events(1).into_iter().next().unwrap() +} + +fn expect_events(e: Vec>) { + assert_eq!(last_events(e.len()), e); } #[test] @@ -1181,3 +1193,212 @@ fn propose_curator_instance1_insufficient_spend_limit_errors() { ); }); } + +#[test] +fn approve_bounty_with_curator_works() { + ExtBuilder::default().build_and_execute(|| { + let fee = 10; + let curator = 4; + System::set_block_number(1); + Balances::make_free_balance_be(&Treasury::account_id(), 101); + + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_noop!( + Bounties::approve_bounty_with_curator(RuntimeOrigin::signed(1), 0, curator, 10), + BadOrigin + ); + + SpendLimit::set(1); + assert_noop!( + Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 10), + TreasuryError::InsufficientPermission + ); + SpendLimit::set(u64::MAX); + + assert_noop!( + Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 51), + Error::::InvalidFee + ); + + assert_eq!(pallet_bounties::BountyApprovals::::get().len(), 0); + assert_ok!(Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 10)); + assert_eq!(pallet_bounties::BountyApprovals::::get().len(), 1); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::ApprovedWithCurator { curator }, + } + ); + + expect_events(vec![ + BountiesEvent::BountyApproved { index: 0 }, + BountiesEvent::CuratorProposed { bounty_id: 0, curator }, + ]); + + assert_noop!( + Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 10), + Error::::UnexpectedStatus + ); + + System::set_block_number(2); + >::on_initialize(2); + assert_eq!(pallet_bounties::BountyApprovals::::get().len(), 0); + + expect_events(vec![BountiesEvent::BountyBecameActive { index: 0 }]); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::CuratorProposed { curator }, + } + ); + + assert_noop!( + Bounties::accept_curator(RuntimeOrigin::signed(curator), 0), + pallet_balances::Error::::InsufficientBalance + ); + Balances::make_free_balance_be(&curator, 6); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(curator), 0)); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 5, + value: 50, + bond: 85, + status: BountyStatus::Active { curator, update_due: 22 }, + } + ); + + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(curator), 0, 5)); + System::set_block_number(5); + >::on_initialize(5); + assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(curator), 0)); + assert_eq!( + last_event(), + BountiesEvent::BountyClaimed { index: 0, payout: 40, beneficiary: 5 } + ); + assert_eq!(Balances::free_balance(5), 40); // 50 - 10 + }); +} + +#[test] +fn approve_bounty_with_curator_early_unassign_works() { + ExtBuilder::default().build_and_execute(|| { + let fee = 10; + let curator = 4; + System::set_block_number(1); + Balances::make_free_balance_be(&Treasury::account_id(), 101); + + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 10)); + + // unassign curator while bounty is not yet funded + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::root(), 0)); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::Approved, + } + ); + + assert_eq!(last_event(), BountiesEvent::CuratorUnassigned { bounty_id: 0 }); + + System::set_block_number(2); + >::on_initialize(2); + assert_eq!(last_event(), BountiesEvent::BountyBecameActive { index: 0 }); + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::Funded, + } + ); + + // assign curator again through separate process + let new_fee = 15; + let new_curator = 5; + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, new_curator, new_fee)); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee: new_fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::CuratorProposed { curator: new_curator }, + } + ); + assert_eq!( + last_event(), + BountiesEvent::CuratorProposed { bounty_id: 0, curator: new_curator } + ); + }); +} + +#[test] +fn approve_bounty_with_curator_proposed_unassign_works() { + ExtBuilder::default().build_and_execute(|| { + let fee = 10; + let curator = 4; + System::set_block_number(1); + Balances::make_free_balance_be(&Treasury::account_id(), 101); + + assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::approve_bounty_with_curator(RuntimeOrigin::root(), 0, curator, 10)); + + System::set_block_number(2); + >::on_initialize(2); + + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::CuratorProposed { curator }, + } + ); + + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(curator), 0)); + assert_eq!( + pallet_bounties::Bounties::::get(0).unwrap(), + Bounty { + proposer: 0, + fee, + curator_deposit: 0, + value: 50, + bond: 85, + status: BountyStatus::Funded, + } + ); + assert_eq!(last_event(), BountiesEvent::CuratorUnassigned { bounty_id: 0 }); + }); +} diff --git a/substrate/frame/bounties/src/weights.rs b/substrate/frame/bounties/src/weights.rs index c9f551ec9bb2..7230fa4a6a77 100644 --- a/substrate/frame/bounties/src/weights.rs +++ b/substrate/frame/bounties/src/weights.rs @@ -18,27 +18,25 @@ //! Autogenerated weights for `pallet_bounties` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// ./target/production/substrate-node +// target/production/substrate-node // benchmark // pallet -// --chain=dev // --steps=50 // --repeat=20 -// --pallet=pallet_bounties -// --no-storage-info -// --no-median-slopes -// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --output=./substrate/frame/bounties/src/weights.rs +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_bounties +// --chain=dev // --header=./substrate/HEADER-APACHE2 +// --output=./substrate/frame/bounties/src/weights.rs // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -54,6 +52,7 @@ pub trait WeightInfo { fn propose_bounty(d: u32, ) -> Weight; fn approve_bounty() -> Weight; fn propose_curator() -> Weight; + fn approve_bounty_with_curator() -> Weight; fn unassign_curator() -> Weight; fn accept_curator() -> Weight; fn award_bounty() -> Weight; @@ -78,12 +77,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `d` is `[0, 300]`. fn propose_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `309` + // Measured: `343` // Estimated: `3593` - // Minimum execution time: 25_206_000 picoseconds. - Weight::from_parts(26_925_800, 3593) - // Standard Error: 239 - .saturating_add(Weight::from_parts(501, 0).saturating_mul(d.into())) + // Minimum execution time: 31_284_000 picoseconds. + Weight::from_parts(33_484_932, 3593) + // Standard Error: 299 + .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -93,10 +92,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn approve_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `401` + // Measured: `434` // Estimated: `3642` - // Minimum execution time: 13_150_000 picoseconds. - Weight::from_parts(13_708_000, 3642) + // Minimum execution time: 17_656_000 picoseconds. + Weight::from_parts(18_501_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -104,23 +103,36 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn propose_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `421` + // Measured: `454` // Estimated: `3642` - // Minimum execution time: 12_277_000 picoseconds. - Weight::from_parts(12_769_000, 3642) + // Minimum execution time: 15_416_000 picoseconds. + Weight::from_parts(16_463_000, 3642) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `Bounties::BountyApprovals` (r:1 w:1) + /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + fn approve_bounty_with_curator() -> Weight { + // Proof Size summary in bytes: + // Measured: `454` + // Estimated: `3642` + // Minimum execution time: 21_802_000 picoseconds. + Weight::from_parts(22_884_000, 3642) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) + } + /// Storage: `Bounties::Bounties` (r:1 w:1) + /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn unassign_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `597` + // Measured: `630` // Estimated: `3642` - // Minimum execution time: 29_041_000 picoseconds. - Weight::from_parts(29_979_000, 3642) + // Minimum execution time: 45_843_000 picoseconds. + Weight::from_parts(47_558_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -130,10 +142,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn accept_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `593` + // Measured: `626` // Estimated: `3642` - // Minimum execution time: 27_936_000 picoseconds. - Weight::from_parts(28_925_000, 3642) + // Minimum execution time: 35_720_000 picoseconds. + Weight::from_parts(37_034_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -143,10 +155,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn award_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `605` + // Measured: `638` // Estimated: `3642` - // Minimum execution time: 16_759_000 picoseconds. - Weight::from_parts(17_699_000, 3642) + // Minimum execution time: 23_318_000 picoseconds. + Weight::from_parts(24_491_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -160,10 +172,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn claim_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `969` + // Measured: `1069` // Estimated: `8799` - // Minimum execution time: 112_056_000 picoseconds. - Weight::from_parts(114_275_000, 8799) + // Minimum execution time: 127_643_000 picoseconds. + Weight::from_parts(130_844_000, 8799) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -177,10 +189,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_proposed() -> Weight { // Proof Size summary in bytes: - // Measured: `649` + // Measured: `683` // Estimated: `3642` - // Minimum execution time: 32_625_000 picoseconds. - Weight::from_parts(33_719_000, 3642) + // Minimum execution time: 49_963_000 picoseconds. + Weight::from_parts(51_484_000, 3642) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -194,10 +206,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `885` + // Measured: `985` // Estimated: `6196` - // Minimum execution time: 76_895_000 picoseconds. - Weight::from_parts(79_161_000, 6196) + // Minimum execution time: 89_310_000 picoseconds. + Weight::from_parts(92_223_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -205,10 +217,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn extend_bounty_expiry() -> Weight { // Proof Size summary in bytes: - // Measured: `457` + // Measured: `490` // Estimated: `3642` - // Minimum execution time: 12_635_000 picoseconds. - Weight::from_parts(13_423_000, 3642) + // Minimum execution time: 16_630_000 picoseconds. + Weight::from_parts(17_171_000, 3642) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -221,12 +233,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `b` is `[0, 100]`. fn spend_funds(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `37 + b * (297 ±0)` + // Measured: `205 + b * (297 ±0)` // Estimated: `1887 + b * (5206 ±0)` - // Minimum execution time: 2_840_000 picoseconds. - Weight::from_parts(6_076_743, 1887) - // Standard Error: 18_569 - .saturating_add(Weight::from_parts(34_771_846, 0).saturating_mul(b.into())) + // Minimum execution time: 4_334_000 picoseconds. + Weight::from_parts(1_256_424, 1887) + // Standard Error: 42_406 + .saturating_add(Weight::from_parts(36_979_844, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -248,12 +260,12 @@ impl WeightInfo for () { /// The range of component `d` is `[0, 300]`. fn propose_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `309` + // Measured: `343` // Estimated: `3593` - // Minimum execution time: 25_206_000 picoseconds. - Weight::from_parts(26_925_800, 3593) - // Standard Error: 239 - .saturating_add(Weight::from_parts(501, 0).saturating_mul(d.into())) + // Minimum execution time: 31_284_000 picoseconds. + Weight::from_parts(33_484_932, 3593) + // Standard Error: 299 + .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(d.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -263,10 +275,10 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn approve_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `401` + // Measured: `434` // Estimated: `3642` - // Minimum execution time: 13_150_000 picoseconds. - Weight::from_parts(13_708_000, 3642) + // Minimum execution time: 17_656_000 picoseconds. + Weight::from_parts(18_501_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -274,23 +286,36 @@ impl WeightInfo for () { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn propose_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `421` + // Measured: `454` // Estimated: `3642` - // Minimum execution time: 12_277_000 picoseconds. - Weight::from_parts(12_769_000, 3642) + // Minimum execution time: 15_416_000 picoseconds. + Weight::from_parts(16_463_000, 3642) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) + /// Storage: `Bounties::BountyApprovals` (r:1 w:1) + /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + fn approve_bounty_with_curator() -> Weight { + // Proof Size summary in bytes: + // Measured: `454` + // Estimated: `3642` + // Minimum execution time: 21_802_000 picoseconds. + Weight::from_parts(22_884_000, 3642) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) + } + /// Storage: `Bounties::Bounties` (r:1 w:1) + /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn unassign_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `597` + // Measured: `630` // Estimated: `3642` - // Minimum execution time: 29_041_000 picoseconds. - Weight::from_parts(29_979_000, 3642) + // Minimum execution time: 45_843_000 picoseconds. + Weight::from_parts(47_558_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -300,10 +325,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn accept_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `593` + // Measured: `626` // Estimated: `3642` - // Minimum execution time: 27_936_000 picoseconds. - Weight::from_parts(28_925_000, 3642) + // Minimum execution time: 35_720_000 picoseconds. + Weight::from_parts(37_034_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -313,10 +338,10 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn award_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `605` + // Measured: `638` // Estimated: `3642` - // Minimum execution time: 16_759_000 picoseconds. - Weight::from_parts(17_699_000, 3642) + // Minimum execution time: 23_318_000 picoseconds. + Weight::from_parts(24_491_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -330,10 +355,10 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn claim_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `969` + // Measured: `1069` // Estimated: `8799` - // Minimum execution time: 112_056_000 picoseconds. - Weight::from_parts(114_275_000, 8799) + // Minimum execution time: 127_643_000 picoseconds. + Weight::from_parts(130_844_000, 8799) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -347,10 +372,10 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_proposed() -> Weight { // Proof Size summary in bytes: - // Measured: `649` + // Measured: `683` // Estimated: `3642` - // Minimum execution time: 32_625_000 picoseconds. - Weight::from_parts(33_719_000, 3642) + // Minimum execution time: 49_963_000 picoseconds. + Weight::from_parts(51_484_000, 3642) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -364,10 +389,10 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `885` + // Measured: `985` // Estimated: `6196` - // Minimum execution time: 76_895_000 picoseconds. - Weight::from_parts(79_161_000, 6196) + // Minimum execution time: 89_310_000 picoseconds. + Weight::from_parts(92_223_000, 6196) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -375,10 +400,10 @@ impl WeightInfo for () { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) fn extend_bounty_expiry() -> Weight { // Proof Size summary in bytes: - // Measured: `457` + // Measured: `490` // Estimated: `3642` - // Minimum execution time: 12_635_000 picoseconds. - Weight::from_parts(13_423_000, 3642) + // Minimum execution time: 16_630_000 picoseconds. + Weight::from_parts(17_171_000, 3642) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -391,12 +416,12 @@ impl WeightInfo for () { /// The range of component `b` is `[0, 100]`. fn spend_funds(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `37 + b * (297 ±0)` + // Measured: `205 + b * (297 ±0)` // Estimated: `1887 + b * (5206 ±0)` - // Minimum execution time: 2_840_000 picoseconds. - Weight::from_parts(6_076_743, 1887) - // Standard Error: 18_569 - .saturating_add(Weight::from_parts(34_771_846, 0).saturating_mul(b.into())) + // Minimum execution time: 4_334_000 picoseconds. + Weight::from_parts(1_256_424, 1887) + // Standard Error: 42_406 + .saturating_add(Weight::from_parts(36_979_844, 0).saturating_mul(b.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(b.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) From 762f824cb3adf23c72a6645f575057bfb543850b Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Tue, 5 Nov 2024 11:22:28 +0200 Subject: [PATCH 022/166] authority-discovery: Populate DHT records with public listen addresses (#6298) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR's main goal is to add public listen addresses to the DHT authorities records. This change improves the discoverability of validators that did not provide the `--public-addresses` flag. This PR populates the authority DHT records with public listen addresses if any. The change effectively ensures that addresses are added to the DHT record in following order: 1. Public addresses provided by CLI `--public-addresses` 2. Maximum of 4 public (global) listen addresses (if any) 3. Any external addresses discovered from the network (ie from `/identify` protocol) While at it, this PR adds the following constraints on the number of addresses: - Total number of addresses cached is bounded at 16 (increased from 10). - A maximum number of 32 addresses are published to DHT records (previously unbounded). - A maximum of 4 global listen addresses are utilized. This PR also removes the following warning: `WARNING: No public address specified, validator node may not be reachable.` ### Next Steps - [ ] deploy and monitor in versi network Closes: https://github.com/paritytech/polkadot-sdk/issues/6280 Part of: https://github.com/paritytech/polkadot-sdk/issues/5266 cc @paritytech/networking --------- Signed-off-by: Alexandru Vasile Co-authored-by: Dmitry Markin Co-authored-by: Bastian Köcher --- prdoc/pr_6298.prdoc | 25 +++ .../client/authority-discovery/src/worker.rs | 176 +++++++++++++----- .../authority-discovery/src/worker/tests.rs | 4 +- substrate/client/cli/src/commands/run_cmd.rs | 12 +- 4 files changed, 153 insertions(+), 64 deletions(-) create mode 100644 prdoc/pr_6298.prdoc diff --git a/prdoc/pr_6298.prdoc b/prdoc/pr_6298.prdoc new file mode 100644 index 000000000000..fa8d73b11943 --- /dev/null +++ b/prdoc/pr_6298.prdoc @@ -0,0 +1,25 @@ +title: Populate authority DHT records with public listen addresses + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + This PR populates the authority DHT records with public listen addresses if any. + The change effectively ensures that addresses are added to the DHT record in the + following order: + 1. Public addresses provided by CLI `--public-addresses` + 2. Maximum of 4 public (global) listen addresses (if any) + 3. Any external addresses discovered from the network (ie from `/identify` protocol) + + While at it, this PR adds the following constraints on the number of addresses: + - Total number of addresses cached is bounded at 16 (increased from 10). + - A maximum number of 32 addresses are published to DHT records (previously unbounded). + - A maximum of 4 global listen addresses are utilized. + + This PR replaces the following warning: + `WARNING: No public address specified, validator node may not be reachable.` + with a more descriptive one originated from the authority-discovery + mechanism itself: `No public addresses configured and no global listen addresses found`. + +crates: + - name: sc-authority-discovery + bump: patch diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index 6f4fbac77e05..9319fbe6321e 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -71,7 +71,13 @@ pub mod tests; const LOG_TARGET: &str = "sub-authority-discovery"; /// Maximum number of addresses cached per authority. Additional addresses are discarded. -const MAX_ADDRESSES_PER_AUTHORITY: usize = 10; +const MAX_ADDRESSES_PER_AUTHORITY: usize = 16; + +/// Maximum number of global listen addresses published by the node. +const MAX_GLOBAL_LISTEN_ADDRESSES: usize = 4; + +/// Maximum number of addresses to publish in a single record. +const MAX_ADDRESSES_TO_PUBLISH: usize = 32; /// Maximum number of in-flight DHT lookups at any given point in time. const MAX_IN_FLIGHT_LOOKUPS: usize = 8; @@ -174,6 +180,9 @@ pub struct Worker { metrics: Option, + /// Flag to ensure the warning about missing public addresses is only printed once. + warn_public_addresses: bool, + role: Role, phantom: PhantomData, @@ -271,20 +280,7 @@ where config .public_addresses .into_iter() - .map(|mut address| { - if let Some(multiaddr::Protocol::P2p(peer_id)) = address.iter().last() { - if peer_id != *local_peer_id.as_ref() { - error!( - target: LOG_TARGET, - "Discarding invalid local peer ID in public address {address}.", - ); - } - // Always discard `/p2p/...` protocol for proper address comparison (local - // peer id will be added before publishing). - address.pop(); - } - address - }) + .map(|address| AddressType::PublicAddress(address).without_p2p(local_peer_id)) .collect() }; @@ -309,6 +305,7 @@ where addr_cache, role, metrics, + warn_public_addresses: false, phantom: PhantomData, last_known_records: HashMap::new(), } @@ -373,47 +370,70 @@ where } } - fn addresses_to_publish(&self) -> impl Iterator { + fn addresses_to_publish(&mut self) -> impl Iterator { let local_peer_id = self.network.local_peer_id(); let publish_non_global_ips = self.publish_non_global_ips; + + // Checks that the address is global. + let address_is_global = |address: &Multiaddr| { + address.iter().all(|protocol| match protocol { + // The `ip_network` library is used because its `is_global()` method is stable, + // while `is_global()` in the standard library currently isn't. + multiaddr::Protocol::Ip4(ip) => IpNetwork::from(ip).is_global(), + multiaddr::Protocol::Ip6(ip) => IpNetwork::from(ip).is_global(), + _ => true, + }) + }; + + // These are the addresses the node is listening for incoming connections, + // as reported by installed protocols (tcp / websocket etc). + // + // We double check the address is global. In other words, we double check the node + // is not running behind a NAT. + // Note: we do this regardless of the `publish_non_global_ips` setting, since the + // node discovers many external addresses via the identify protocol. + let mut global_listen_addresses = self + .network + .listen_addresses() + .into_iter() + .filter_map(|address| { + address_is_global(&address) + .then(|| AddressType::GlobalListenAddress(address).without_p2p(local_peer_id)) + }) + .take(MAX_GLOBAL_LISTEN_ADDRESSES) + .peekable(); + + // Similar to listen addresses that takes into consideration `publish_non_global_ips`. + let mut external_addresses = self + .network + .external_addresses() + .into_iter() + .filter_map(|address| { + (publish_non_global_ips || address_is_global(&address)) + .then(|| AddressType::ExternalAddress(address).without_p2p(local_peer_id)) + }) + .peekable(); + + let has_global_listen_addresses = global_listen_addresses.peek().is_some(); + trace!( + target: LOG_TARGET, + "Node has public addresses: {}, global listen addresses: {}, external addresses: {}", + !self.public_addresses.is_empty(), + has_global_listen_addresses, + external_addresses.peek().is_some(), + ); + + let mut seen_addresses = HashSet::new(); + let addresses = self .public_addresses .clone() .into_iter() - .chain(self.network.external_addresses().into_iter().filter_map(|mut address| { - // Make sure the reported external address does not contain `/p2p/...` protocol. - if let Some(multiaddr::Protocol::P2p(peer_id)) = address.iter().last() { - if peer_id != *local_peer_id.as_ref() { - error!( - target: LOG_TARGET, - "Network returned external address '{address}' with peer id \ - not matching the local peer id '{local_peer_id}'.", - ); - debug_assert!(false); - } - address.pop(); - } - - if self.public_addresses.contains(&address) { - // Already added above. - None - } else { - Some(address) - } - })) - .filter(move |address| { - if publish_non_global_ips { - return true - } - - address.iter().all(|protocol| match protocol { - // The `ip_network` library is used because its `is_global()` method is stable, - // while `is_global()` in the standard library currently isn't. - multiaddr::Protocol::Ip4(ip) if !IpNetwork::from(ip).is_global() => false, - multiaddr::Protocol::Ip6(ip) if !IpNetwork::from(ip).is_global() => false, - _ => true, - }) - }) + .chain(global_listen_addresses) + .chain(external_addresses) + // Deduplicate addresses. + .filter(|address| seen_addresses.insert(address.clone())) + .take(MAX_ADDRESSES_TO_PUBLISH) .collect::>(); if !addresses.is_empty() { @@ -421,6 +441,21 @@ where target: LOG_TARGET, "Publishing authority DHT record peer_id='{local_peer_id}' with addresses='{addresses:?}'", ); + + if !self.warn_public_addresses && + self.public_addresses.is_empty() && + !has_global_listen_addresses + { + self.warn_public_addresses = true; + + error!( + target: LOG_TARGET, + "No public addresses configured and no global listen addresses found. \ + Authority DHT record may contain unreachable addresses. \ + Consider setting `--public-addr` to the public IP address of this node. \ + This will become a hard requirement in future versions for authorities." + ); + } } // The address must include the local peer id. @@ -437,7 +472,8 @@ where let key_store = match &self.role { Role::PublishAndDiscover(key_store) => key_store, Role::Discover => return Ok(()), - }; + } + .clone(); let addresses = serialize_addresses(self.addresses_to_publish()); if addresses.is_empty() { @@ -946,6 +982,44 @@ where } } +/// Removes the `/p2p/..` from the address if it is present. +#[derive(Debug, Clone, PartialEq, Eq)] +enum AddressType { + /// The address is specified as a public address via the CLI. + PublicAddress(Multiaddr), + /// The address is a global listen address. + GlobalListenAddress(Multiaddr), + /// The address is discovered via the network (ie /identify protocol). + ExternalAddress(Multiaddr), +} + +impl AddressType { + /// Removes the `/p2p/..` from the address if it is present. + /// + /// In case the peer id in the address does not match the local peer id, an error is logged for + /// `ExternalAddress` and `GlobalListenAddress`. + fn without_p2p(self, local_peer_id: PeerId) -> Multiaddr { + // Get the address and the source str for logging. + let (mut address, source) = match self { + AddressType::PublicAddress(address) => (address, "public address"), + AddressType::GlobalListenAddress(address) => (address, "global listen address"), + AddressType::ExternalAddress(address) => (address, "external address"), + }; + + if let Some(multiaddr::Protocol::P2p(peer_id)) = address.iter().last() { + if peer_id != *local_peer_id.as_ref() { + error!( + target: LOG_TARGET, + "Network returned '{source}' '{address}' with peer id \ + not matching the local peer id '{local_peer_id}'.", + ); + } + address.pop(); + } + address + } +} + /// NetworkProvider provides [`Worker`] with all necessary hooks into the /// underlying Substrate networking. Using this trait abstraction instead of /// `sc_network::NetworkService` directly is necessary to unit test [`Worker`]. diff --git a/substrate/client/authority-discovery/src/worker/tests.rs b/substrate/client/authority-discovery/src/worker/tests.rs index d71a85db8b81..8018b5ea492d 100644 --- a/substrate/client/authority-discovery/src/worker/tests.rs +++ b/substrate/client/authority-discovery/src/worker/tests.rs @@ -1018,7 +1018,7 @@ fn addresses_to_publish_adds_p2p() { )); let (_to_worker, from_service) = mpsc::channel(0); - let worker = Worker::new( + let mut worker = Worker::new( from_service, Arc::new(TestApi { authorities: vec![] }), network.clone(), @@ -1056,7 +1056,7 @@ fn addresses_to_publish_respects_existing_p2p_protocol() { }); let (_to_worker, from_service) = mpsc::channel(0); - let worker = Worker::new( + let mut worker = Worker::new( from_service, Arc::new(TestApi { authorities: vec![] }), network.clone(), diff --git a/substrate/client/cli/src/commands/run_cmd.rs b/substrate/client/cli/src/commands/run_cmd.rs index f91d18aca749..f79e5b558e37 100644 --- a/substrate/client/cli/src/commands/run_cmd.rs +++ b/substrate/client/cli/src/commands/run_cmd.rs @@ -201,17 +201,7 @@ impl CliConfiguration for RunCmd { } fn network_params(&self) -> Option<&NetworkParams> { - let network_params = &self.network_params; - let is_authority = self.role(self.is_dev().ok()?).ok()?.is_authority(); - if is_authority && network_params.public_addr.is_empty() { - eprintln!( - "WARNING: No public address specified, validator node may not be reachable. - Consider setting `--public-addr` to the public IP address of this node. - This will become a hard requirement in future versions." - ); - } - - Some(network_params) + Some(&self.network_params) } fn keystore_params(&self) -> Option<&KeystoreParams> { From 6969be36057efd54d2f11e239bc88ff4b9a65418 Mon Sep 17 00:00:00 2001 From: Adrian Catangiu Date: Tue, 5 Nov 2024 11:47:22 +0200 Subject: [PATCH 023/166] snowbridge: allow account conversion for Ethereum accounts (#6221) Replace `GlobalConsensusEthereumConvertsFor` with `EthereumLocationsConverterFor` that allows `Location` to `AccountId` conversion for the Ethereum network root as before, but also for Ethereum contracts and accounts. The new converter only matches explicit `parents: 2` Ethereum locations, meaning it should be used only on/by parachains. --- .../primitives/router/src/inbound/mod.rs | 15 ++++++++---- .../primitives/router/src/inbound/tests.rs | 24 +++++++++++++++---- .../bridge-hub-rococo/src/tests/snowbridge.rs | 5 ++-- .../src/tests/snowbridge.rs | 6 ++--- .../assets/asset-hub-rococo/src/xcm_config.rs | 4 ++-- .../asset-hub-westend/src/xcm_config.rs | 4 ++-- prdoc/pr_6221.prdoc | 10 ++++++++ 7 files changed, 48 insertions(+), 20 deletions(-) create mode 100644 prdoc/pr_6221.prdoc diff --git a/bridges/snowbridge/primitives/router/src/inbound/mod.rs b/bridges/snowbridge/primitives/router/src/inbound/mod.rs index a9324ac42470..357f77f831cc 100644 --- a/bridges/snowbridge/primitives/router/src/inbound/mod.rs +++ b/bridges/snowbridge/primitives/router/src/inbound/mod.rs @@ -253,7 +253,7 @@ where let bridge_location = Location::new(2, GlobalConsensus(network)); - let owner = GlobalConsensusEthereumConvertsFor::<[u8; 32]>::from_chain_id(&chain_id); + let owner = EthereumLocationsConverterFor::<[u8; 32]>::from_chain_id(&chain_id); let asset_id = Self::convert_token_address(network, token); let create_call_index: [u8; 2] = CreateAssetCall::get(); let inbound_queue_pallet_index = InboundQueuePalletInstance::get(); @@ -454,22 +454,27 @@ where } } -pub struct GlobalConsensusEthereumConvertsFor(PhantomData); -impl ConvertLocation for GlobalConsensusEthereumConvertsFor +pub struct EthereumLocationsConverterFor(PhantomData); +impl ConvertLocation for EthereumLocationsConverterFor where AccountId: From<[u8; 32]> + Clone, { fn convert_location(location: &Location) -> Option { match location.unpack() { - (_, [GlobalConsensus(Ethereum { chain_id })]) => + (2, [GlobalConsensus(Ethereum { chain_id })]) => Some(Self::from_chain_id(chain_id).into()), + (2, [GlobalConsensus(Ethereum { chain_id }), AccountKey20 { network: _, key }]) => + Some(Self::from_chain_id_with_key(chain_id, *key).into()), _ => None, } } } -impl GlobalConsensusEthereumConvertsFor { +impl EthereumLocationsConverterFor { pub fn from_chain_id(chain_id: &u64) -> [u8; 32] { (b"ethereum-chain", chain_id).using_encoded(blake2_256) } + pub fn from_chain_id_with_key(chain_id: &u64, key: [u8; 20]) -> [u8; 32] { + (b"ethereum-chain", chain_id, key).using_encoded(blake2_256) + } } diff --git a/bridges/snowbridge/primitives/router/src/inbound/tests.rs b/bridges/snowbridge/primitives/router/src/inbound/tests.rs index e0e90e516be1..786aa594f653 100644 --- a/bridges/snowbridge/primitives/router/src/inbound/tests.rs +++ b/bridges/snowbridge/primitives/router/src/inbound/tests.rs @@ -1,4 +1,4 @@ -use super::GlobalConsensusEthereumConvertsFor; +use super::EthereumLocationsConverterFor; use crate::inbound::CallIndex; use frame_support::{assert_ok, parameter_types}; use hex_literal::hex; @@ -17,14 +17,28 @@ parameter_types! { } #[test] -fn test_contract_location_with_network_converts_successfully() { +fn test_ethereum_network_converts_successfully() { let expected_account: [u8; 32] = hex!("ce796ae65569a670d0c1cc1ac12515a3ce21b5fbf729d63d7b289baad070139d"); let contract_location = Location::new(2, [GlobalConsensus(NETWORK)]); let account = - GlobalConsensusEthereumConvertsFor::<[u8; 32]>::convert_location(&contract_location) - .unwrap(); + EthereumLocationsConverterFor::<[u8; 32]>::convert_location(&contract_location).unwrap(); + + assert_eq!(account, expected_account); +} + +#[test] +fn test_contract_location_with_network_converts_successfully() { + let expected_account: [u8; 32] = + hex!("9038d35aba0e78e072d29b2d65be9df5bb4d7d94b4609c9cf98ea8e66e544052"); + let contract_location = Location::new( + 2, + [GlobalConsensus(NETWORK), AccountKey20 { network: None, key: [123u8; 20] }], + ); + + let account = + EthereumLocationsConverterFor::<[u8; 32]>::convert_location(&contract_location).unwrap(); assert_eq!(account, expected_account); } @@ -34,7 +48,7 @@ fn test_contract_location_with_incorrect_location_fails_convert() { let contract_location = Location::new(2, [GlobalConsensus(Polkadot), Parachain(1000)]); assert_eq!( - GlobalConsensusEthereumConvertsFor::<[u8; 32]>::convert_location(&contract_location), + EthereumLocationsConverterFor::<[u8; 32]>::convert_location(&contract_location), None, ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index d91a0c6895f9..912e74af6981 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -25,7 +25,7 @@ use snowbridge_pallet_inbound_queue_fixtures::{ }; use snowbridge_pallet_system; use snowbridge_router_primitives::inbound::{ - Command, Destination, GlobalConsensusEthereumConvertsFor, MessageV1, VersionedMessage, + Command, Destination, EthereumLocationsConverterFor, MessageV1, VersionedMessage, }; use sp_core::H256; use sp_runtime::{DispatchError::Token, TokenError::FundsUnavailable}; @@ -318,8 +318,7 @@ fn send_token_from_ethereum_to_penpal() { // Fund ethereum sovereign on AssetHub let ethereum_sovereign: AccountId = - GlobalConsensusEthereumConvertsFor::::convert_location(&origin_location) - .unwrap(); + EthereumLocationsConverterFor::::convert_location(&origin_location).unwrap(); AssetHubRococo::fund_accounts(vec![(ethereum_sovereign.clone(), INITIAL_FUND)]); // Create asset on the Penpal parachain. diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs index 4e9dd5a77dd7..f1c27aedf164 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs @@ -22,7 +22,7 @@ use hex_literal::hex; use rococo_westend_system_emulated_network::asset_hub_westend_emulated_chain::genesis::AssetHubWestendAssetOwner; use snowbridge_core::{outbound::OperatingMode, AssetMetadata, TokenIdOf}; use snowbridge_router_primitives::inbound::{ - Command, Destination, GlobalConsensusEthereumConvertsFor, MessageV1, VersionedMessage, + Command, Destination, EthereumLocationsConverterFor, MessageV1, VersionedMessage, }; use sp_core::H256; use testnet_parachains_constants::westend::snowbridge::EthereumNetwork; @@ -297,7 +297,7 @@ fn transfer_relay_token() { let expected_token_id = TokenIdOf::convert_location(&expected_asset_id).unwrap(); let ethereum_sovereign: AccountId = - GlobalConsensusEthereumConvertsFor::<[u8; 32]>::convert_location(&Location::new( + EthereumLocationsConverterFor::<[u8; 32]>::convert_location(&Location::new( 2, [GlobalConsensus(EthereumNetwork::get())], )) @@ -445,7 +445,7 @@ fn transfer_ah_token() { let ethereum_destination = Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]); let ethereum_sovereign: AccountId = - GlobalConsensusEthereumConvertsFor::<[u8; 32]>::convert_location(ðereum_destination) + EthereumLocationsConverterFor::<[u8; 32]>::convert_location(ðereum_destination) .unwrap() .into(); AssetHubWestend::fund_accounts(vec![(ethereum_sovereign.clone(), INITIAL_FUND)]); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 637c5900f7da..56310959aa80 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -42,7 +42,7 @@ use parachains_common::{ }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; -use snowbridge_router_primitives::inbound::GlobalConsensusEthereumConvertsFor; +use snowbridge_router_primitives::inbound::EthereumLocationsConverterFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto, TryConvertInto}; use testnet_parachains_constants::rococo::snowbridge::{ EthereumNetwork, INBOUND_QUEUE_PALLET_INDEX, @@ -104,7 +104,7 @@ pub type LocationToAccountId = ( GlobalConsensusParachainConvertsFor, // Ethereum contract sovereign account. // (Used to get convert ethereum contract locations to sovereign account) - GlobalConsensusEthereumConvertsFor, + EthereumLocationsConverterFor, ); /// Means for transacting the native currency on this chain. diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index b554d00508be..f16dbcc02519 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -42,7 +42,7 @@ use parachains_common::{ }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; -use snowbridge_router_primitives::inbound::GlobalConsensusEthereumConvertsFor; +use snowbridge_router_primitives::inbound::EthereumLocationsConverterFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto, TryConvertInto}; use xcm::latest::prelude::*; use xcm_builder::{ @@ -100,7 +100,7 @@ pub type LocationToAccountId = ( GlobalConsensusParachainConvertsFor, // Ethereum contract sovereign account. // (Used to get convert ethereum contract locations to sovereign account) - GlobalConsensusEthereumConvertsFor, + EthereumLocationsConverterFor, ); /// Means for transacting the native currency on this chain. diff --git a/prdoc/pr_6221.prdoc b/prdoc/pr_6221.prdoc new file mode 100644 index 000000000000..57c81b322f92 --- /dev/null +++ b/prdoc/pr_6221.prdoc @@ -0,0 +1,10 @@ +title: "snowbridge: allow account conversion for Ethereum accounts" + +doc: + - audience: Runtime Dev + description: | + Replaced `GlobalConsensusEthereumConvertsFor` with `EthereumLocationsConverterFor` that allows `Location` + to `AccountId` conversion for the Ethereum network root as before, but also for Ethereum contracts and accounts. +crates: + - name: snowbridge-router-primitives + bump: major From ec61396ec8315989f6df33253ccff5445e99f848 Mon Sep 17 00:00:00 2001 From: Adrian Catangiu Date: Tue, 5 Nov 2024 12:25:51 +0200 Subject: [PATCH 024/166] Remove leftover references of Wococo (#6361) Remove references of now defunct Wococo network. The XCM `NetworkId::Wococo` will also be removed with [XCMv5 PR](https://github.com/paritytech/polkadot-sdk/pull/4826) --- bridges/primitives/messages/src/lane.rs | 4 ++-- .../parachains/runtimes/assets/common/src/matching.rs | 10 +++++----- polkadot/cli/src/cli.rs | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/bridges/primitives/messages/src/lane.rs b/bridges/primitives/messages/src/lane.rs index 0f14ce93e114..75237a44d538 100644 --- a/bridges/primitives/messages/src/lane.rs +++ b/bridges/primitives/messages/src/lane.rs @@ -108,8 +108,8 @@ impl TypeId for LegacyLaneId { /// concatenation (separated by some binary data). I.e.: /// /// ```nocompile -/// let endpoint1 = X2(GlobalConsensus(NetworkId::Rococo), Parachain(42)); -/// let endpoint2 = X2(GlobalConsensus(NetworkId::Wococo), Parachain(777)); +/// let endpoint1 = X2(GlobalConsensus(NetworkId::Polkadot), Parachain(42)); +/// let endpoint2 = X2(GlobalConsensus(NetworkId::Kusama), Parachain(777)); /// /// let final_lane_key = if endpoint1 < endpoint2 { /// (endpoint1, VALUES_SEPARATOR, endpoint2) diff --git a/cumulus/parachains/runtimes/assets/common/src/matching.rs b/cumulus/parachains/runtimes/assets/common/src/matching.rs index 9ac2056a67f4..5a452f6eed1b 100644 --- a/cumulus/parachains/runtimes/assets/common/src/matching.rs +++ b/cumulus/parachains/runtimes/assets/common/src/matching.rs @@ -149,7 +149,7 @@ mod tests { parameter_types! { pub UniversalLocation: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into(); - pub ExpectedNetworkId: NetworkId = Wococo; + pub ExpectedNetworkId: NetworkId = Westend; } #[test] @@ -158,13 +158,13 @@ mod tests { let asset: Location = ( Parent, Parent, - GlobalConsensus(Wococo), + GlobalConsensus(Westend), Parachain(1000), PalletInstance(1), GeneralIndex(1), ) .into(); - let origin: Location = (Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into(); + let origin: Location = (Parent, Parent, GlobalConsensus(Westend), Parachain(1000)).into(); assert!(FromNetwork::::contains(&asset, &origin)); // asset and origin from local consensus fails @@ -195,14 +195,14 @@ mod tests { GeneralIndex(1), ) .into(); - let origin: Location = (Parent, Parent, GlobalConsensus(Wococo), Parachain(1000)).into(); + let origin: Location = (Parent, Parent, GlobalConsensus(Westend), Parachain(1000)).into(); assert!(!FromNetwork::::contains(&asset, &origin)); // origin from different consensus fails let asset: Location = ( Parent, Parent, - GlobalConsensus(Wococo), + GlobalConsensus(Westend), Parachain(1000), PalletInstance(1), GeneralIndex(1), diff --git a/polkadot/cli/src/cli.rs b/polkadot/cli/src/cli.rs index eb67a3956342..777bb9c60671 100644 --- a/polkadot/cli/src/cli.rs +++ b/polkadot/cli/src/cli.rs @@ -79,7 +79,7 @@ pub struct RunCmd { /// Disable the BEEFY gadget. /// - /// Currently enabled by default on 'Rococo', 'Wococo' and 'Versi'. + /// Currently enabled by default. #[arg(long)] pub no_beefy: bool, From 3c6ea86a2645b0d944101806e9cb1c1aeb4eb643 Mon Sep 17 00:00:00 2001 From: clangenb <37865735+clangenb@users.noreply.github.com> Date: Tue, 5 Nov 2024 12:08:37 +0100 Subject: [PATCH 025/166] migrate pallet-remarks to v2 bench syntax (#6291) Part of: * #6202 --------- Co-authored-by: Oliver Tale-Yazdi Co-authored-by: GitHub Action Co-authored-by: Giuseppe Re --- prdoc/pr_6291.prdoc | 9 ++++++++ substrate/frame/remark/src/benchmarking.rs | 25 ++++++++++++++++------ 2 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 prdoc/pr_6291.prdoc diff --git a/prdoc/pr_6291.prdoc b/prdoc/pr_6291.prdoc new file mode 100644 index 000000000000..73053c9d47bd --- /dev/null +++ b/prdoc/pr_6291.prdoc @@ -0,0 +1,9 @@ +title: migrate pallet-remarks to v2 bench syntax +doc: +- audience: Runtime Dev + description: |- + Part of: + * #6202 +crates: +- name: pallet-remark + bump: patch diff --git a/substrate/frame/remark/src/benchmarking.rs b/substrate/frame/remark/src/benchmarking.rs index 15b72b4748dd..41d49c3b930b 100644 --- a/substrate/frame/remark/src/benchmarking.rs +++ b/substrate/frame/remark/src/benchmarking.rs @@ -21,7 +21,7 @@ use super::*; use alloc::vec; -use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_system::{EventRecord, Pallet as System, RawOrigin}; #[cfg(test)] @@ -34,13 +34,24 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { assert_eq!(event, &system_event); } -benchmarks! { - store { - let l in 1 .. 1024*1024; +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn store(l: Linear<1, { 1024 * 1024 }>) { let caller: T::AccountId = whitelisted_caller(); - }: _(RawOrigin::Signed(caller.clone()), vec![0u8; l as usize]) - verify { - assert_last_event::(Event::Stored { sender: caller, content_hash: sp_io::hashing::blake2_256(&vec![0u8; l as usize]).into() }.into()); + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), vec![0u8; l as usize]); + + assert_last_event::( + Event::Stored { + sender: caller, + content_hash: sp_io::hashing::blake2_256(&vec![0u8; l as usize]).into(), + } + .into(), + ); } impl_benchmark_test_suite!(Remark, crate::mock::new_test_ext(), crate::mock::Test); From be26d6288351f57f3b94e3fb7ee24c875fca1e32 Mon Sep 17 00:00:00 2001 From: Ankan <10196091+Ank4n@users.noreply.github.com> Date: Tue, 5 Nov 2024 12:20:09 +0100 Subject: [PATCH 026/166] [pallet-staking] Additional check for virtual stakers (#5985) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes https://github.com/paritytech/polkadot-sdk/issues/5791. This is not strictly necessary but serves as a defensive check. The staking pallet exposes [apis](https://paritytech.github.io/polkadot-sdk/master/sp_staking/trait.StakingUnchecked.html#tymethod.virtual_bond) that other runtime pallets (pallet-delegated-staking) can use to create virtual stakers. However, there’s no way for pallet-staking to ensure that the staker is truly keyless. If the caller (this is a trusted caller so this would only happen due to a bug) registers an account with a private key as a virtual_staker, these accounts could later interact directly with pallet-staking dispatchables (such as [bond_extra](https://paritytech.github.io/polkadot-sdk/master/pallet_staking/dispatchables/fn.bond_extra.html)) and bypass any locking mechanism. The check above ensures this scenario can never occur by performing an integrity check. --------- Co-authored-by: Bastian Köcher Co-authored-by: command-bot <> --- substrate/frame/staking/src/pallet/impls.rs | 10 +++++++++- substrate/primitives/panic-handler/src/lib.rs | 4 ++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index 6c4fe8140e8e..649903741140 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -1881,8 +1881,12 @@ impl StakingInterface for Pallet { } /// Whether `who` is a virtual staker whose funds are managed by another pallet. + /// + /// There is an assumption that, this account is keyless and managed by another pallet in the + /// runtime. Hence, it can never sign its own transactions. fn is_virtual_staker(who: &T::AccountId) -> bool { - VirtualStakers::::contains_key(who) + frame_system::Pallet::::account_nonce(who).is_zero() && + VirtualStakers::::contains_key(who) } fn slash_reward_fraction() -> Perbill { @@ -2103,6 +2107,10 @@ impl Pallet { Ledger::::get(stash.clone()).unwrap().stash == stash, "ledger corrupted for virtual staker" ); + ensure!( + frame_system::Pallet::::account_nonce(&stash).is_zero(), + "virtual stakers are keyless and should not have any nonce" + ); let reward_destination = >::get(stash.clone()).unwrap(); if let RewardDestination::Account(payee) = reward_destination { ensure!( diff --git a/substrate/primitives/panic-handler/src/lib.rs b/substrate/primitives/panic-handler/src/lib.rs index 81ccaaee828e..c4a7eb8dc67c 100644 --- a/substrate/primitives/panic-handler/src/lib.rs +++ b/substrate/primitives/panic-handler/src/lib.rs @@ -30,7 +30,7 @@ use std::{ cell::Cell, io::{self, Write}, marker::PhantomData, - panic::{self, PanicHookInfo}, + panic::{self, PanicInfo}, sync::LazyLock, thread, }; @@ -149,7 +149,7 @@ fn strip_control_codes(input: &str) -> std::borrow::Cow { } /// Function being called when a panic happens. -fn panic_hook(info: &PanicHookInfo, report_url: &str, version: &str) { +fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) { let location = info.location(); let file = location.as_ref().map(|l| l.file()).unwrap_or(""); let line = location.as_ref().map(|l| l.line()).unwrap_or(0); From 94389a939c222a866affa0bb9b66541e36614810 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Tue, 5 Nov 2024 13:56:41 +0200 Subject: [PATCH 027/166] litep2p: Update litep2p to v0.8.0 (#6353) This PR updates litep2p to the latest release. - `KademliaEvent::PutRecordSucess` is renamed to fix word typo - `KademliaEvent::GetProvidersSuccess` and `KademliaEvent::IncomingProvider` are needed for bootnodes on DHT work and will be utilized later ### Added - kad: Providers part 8: unit, e2e, and `libp2p` conformance tests ([#258](https://github.com/paritytech/litep2p/pull/258)) - kad: Providers part 7: better types and public API, public addresses & known providers ([#246](https://github.com/paritytech/litep2p/pull/246)) - kad: Providers part 6: stop providing ([#245](https://github.com/paritytech/litep2p/pull/245)) - kad: Providers part 5: `GET_PROVIDERS` query ([#236](https://github.com/paritytech/litep2p/pull/236)) - kad: Providers part 4: refresh local providers ([#235](https://github.com/paritytech/litep2p/pull/235)) - kad: Providers part 3: publish provider records (start providing) ([#234](https://github.com/paritytech/litep2p/pull/234)) ### Changed - transport_service: Improve connection stability by downgrading connections on substream inactivity ([#260](https://github.com/paritytech/litep2p/pull/260)) - transport: Abort canceled dial attempts for TCP, WebSocket and Quic ([#255](https://github.com/paritytech/litep2p/pull/255)) - kad/executor: Add timeout for writting frames ([#277](https://github.com/paritytech/litep2p/pull/277)) - kad: Avoid cloning the `KademliaMessage` and use reference for `RoutingTable::closest` ([#233](https://github.com/paritytech/litep2p/pull/233)) - peer_state: Robust state machine transitions ([#251](https://github.com/paritytech/litep2p/pull/251)) - address_store: Improve address tracking and add eviction algorithm ([#250](https://github.com/paritytech/litep2p/pull/250)) - kad: Remove unused serde cfg ([#262](https://github.com/paritytech/litep2p/pull/262)) - req-resp: Refactor to move functionality to dedicated methods ([#244](https://github.com/paritytech/litep2p/pull/244)) - transport_service: Improve logs and move code from tokio::select macro ([#254](https://github.com/paritytech/litep2p/pull/254)) ### Fixed - tcp/websocket/quic: Fix cancel memory leak ([#272](https://github.com/paritytech/litep2p/pull/272)) - transport: Fix pending dials memory leak ([#271](https://github.com/paritytech/litep2p/pull/271)) - ping: Fix memory leak of unremoved `pending_opens` ([#274](https://github.com/paritytech/litep2p/pull/274)) - identify: Fix memory leak of unused `pending_opens` ([#273](https://github.com/paritytech/litep2p/pull/273)) - kad: Fix not retrieving local records ([#221](https://github.com/paritytech/litep2p/pull/221)) See release changelog for more details: https://github.com/paritytech/litep2p/releases/tag/v0.8.0 cc @paritytech/networking --------- Signed-off-by: Alexandru Vasile Co-authored-by: Dmitry Markin --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- prdoc/pr_6353.prdoc | 10 ++++++++++ substrate/client/network/src/litep2p/discovery.rs | 5 ++++- 4 files changed, 17 insertions(+), 4 deletions(-) create mode 100644 prdoc/pr_6353.prdoc diff --git a/Cargo.lock b/Cargo.lock index 59b6d92bde5d..a870c0bd9d4c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9400,9 +9400,9 @@ dependencies = [ [[package]] name = "litep2p" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4ab2528b02b6dbbc3e6ec4b55ccde885647c622a315b7da45081ed2dfe4b813" +checksum = "7286b1971f85d1d60be40ef49e81c1f3b5a0d8b83cfa02ab53591cdacae22901" dependencies = [ "async-trait", "bs58", diff --git a/Cargo.toml b/Cargo.toml index f3042a8a3bdf..5f4d78ef3213 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -848,7 +848,7 @@ linked-hash-map = { version = "0.5.4" } linked_hash_set = { version = "0.1.4" } linregress = { version = "0.5.1" } lite-json = { version = "0.2.0", default-features = false } -litep2p = { version = "0.7.0", features = ["websocket"] } +litep2p = { version = "0.8.0", features = ["websocket"] } log = { version = "0.4.22", default-features = false } macro_magic = { version = "0.5.1" } maplit = { version = "1.0.2" } diff --git a/prdoc/pr_6353.prdoc b/prdoc/pr_6353.prdoc new file mode 100644 index 000000000000..8a5a152628a0 --- /dev/null +++ b/prdoc/pr_6353.prdoc @@ -0,0 +1,10 @@ +title: Update litep2p network backend to version 0.8.0 + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + Release 0.8.0 of litep2p includes several improvements and memory leak fixes enhancing the stability and performance of the litep2p network backend. + +crates: + - name: sc-network + bump: patch diff --git a/substrate/client/network/src/litep2p/discovery.rs b/substrate/client/network/src/litep2p/discovery.rs index 13cf8a4c6ee0..7b2e713dffd2 100644 --- a/substrate/client/network/src/litep2p/discovery.rs +++ b/substrate/client/network/src/litep2p/discovery.rs @@ -553,7 +553,7 @@ impl Stream for Discovery { return Poll::Ready(Some(DiscoveryEvent::GetRecordSuccess { query_id, records })); }, - Poll::Ready(Some(KademliaEvent::PutRecordSucess { query_id, key: _ })) => + Poll::Ready(Some(KademliaEvent::PutRecordSuccess { query_id, key: _ })) => return Poll::Ready(Some(DiscoveryEvent::PutRecordSuccess { query_id })), Poll::Ready(Some(KademliaEvent::QueryFailed { query_id })) => { match this.find_node_query_id == Some(query_id) { @@ -576,6 +576,9 @@ impl Stream for Discovery { return Poll::Ready(Some(DiscoveryEvent::IncomingRecord { record })) }, + // Content provider events are ignored for now. + Poll::Ready(Some(KademliaEvent::GetProvidersSuccess { .. })) | + Poll::Ready(Some(KademliaEvent::IncomingProvider { .. })) => {}, } match Pin::new(&mut this.identify_event_stream).poll_next(cx) { From 74ec1ee226ace087748f38dfeffc869cd5534ac8 Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Tue, 5 Nov 2024 14:05:31 +0200 Subject: [PATCH 028/166] refactor and harden check_core_index (#6217) Resolves https://github.com/paritytech/polkadot-sdk/issues/6179 --- .../consensus/aura/src/collators/lookahead.rs | 8 +- .../slot_based/block_builder_task.rs | 6 +- cumulus/pallets/parachain-system/src/lib.rs | 4 +- cumulus/primitives/core/src/lib.rs | 4 - .../node/collation-generation/src/error.rs | 4 +- polkadot/node/collation-generation/src/lib.rs | 2 +- .../src/inclusion_emulator/mod.rs | 15 +- polkadot/primitives/src/vstaging/mod.rs | 206 ++++++++++-------- .../runtime/parachains/src/inclusion/mod.rs | 38 +--- .../parachains/src/paras_inherent/tests.rs | 7 +- prdoc/pr_6217.prdoc | 24 ++ 11 files changed, 162 insertions(+), 156 deletions(-) create mode 100644 prdoc/pr_6217.prdoc diff --git a/cumulus/client/consensus/aura/src/collators/lookahead.rs b/cumulus/client/consensus/aura/src/collators/lookahead.rs index 8ac43fbd116e..2dbcf5eb58e9 100644 --- a/cumulus/client/consensus/aura/src/collators/lookahead.rs +++ b/cumulus/client/consensus/aura/src/collators/lookahead.rs @@ -36,17 +36,15 @@ use cumulus_client_collator::service::ServiceInterface as CollatorServiceInterfa use cumulus_client_consensus_common::{self as consensus_common, ParachainBlockImportMarker}; use cumulus_client_consensus_proposer::ProposerInterface; use cumulus_primitives_aura::AuraUnincludedSegmentApi; -use cumulus_primitives_core::{ - ClaimQueueOffset, CollectCollationInfo, PersistedValidationData, DEFAULT_CLAIM_QUEUE_OFFSET, -}; +use cumulus_primitives_core::{ClaimQueueOffset, CollectCollationInfo, PersistedValidationData}; use cumulus_relay_chain_interface::RelayChainInterface; use polkadot_node_primitives::{PoV, SubmitCollationParams}; use polkadot_node_subsystem::messages::CollationGenerationMessage; use polkadot_overseer::Handle as OverseerHandle; use polkadot_primitives::{ - BlockNumber as RBlockNumber, CollatorPair, Hash as RHash, HeadData, Id as ParaId, - OccupiedCoreAssumption, + vstaging::DEFAULT_CLAIM_QUEUE_OFFSET, BlockNumber as RBlockNumber, CollatorPair, Hash as RHash, + HeadData, Id as ParaId, OccupiedCoreAssumption, }; use futures::prelude::*; diff --git a/cumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs b/cumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs index e75b52aeebd3..425151230704 100644 --- a/cumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs +++ b/cumulus/client/consensus/aura/src/collators/slot_based/block_builder_task.rs @@ -20,13 +20,11 @@ use cumulus_client_collator::service::ServiceInterface as CollatorServiceInterfa use cumulus_client_consensus_common::{self as consensus_common, ParachainBlockImportMarker}; use cumulus_client_consensus_proposer::ProposerInterface; use cumulus_primitives_aura::AuraUnincludedSegmentApi; -use cumulus_primitives_core::{ - GetCoreSelectorApi, PersistedValidationData, DEFAULT_CLAIM_QUEUE_OFFSET, -}; +use cumulus_primitives_core::{GetCoreSelectorApi, PersistedValidationData}; use cumulus_relay_chain_interface::RelayChainInterface; use polkadot_primitives::{ - vstaging::{ClaimQueueOffset, CoreSelector}, + vstaging::{ClaimQueueOffset, CoreSelector, DEFAULT_CLAIM_QUEUE_OFFSET}, BlockId, CoreIndex, Hash as RelayHash, Header as RelayHeader, Id as ParaId, OccupiedCoreAssumption, }; diff --git a/cumulus/pallets/parachain-system/src/lib.rs b/cumulus/pallets/parachain-system/src/lib.rs index 98989a852b8d..39fc8321a072 100644 --- a/cumulus/pallets/parachain-system/src/lib.rs +++ b/cumulus/pallets/parachain-system/src/lib.rs @@ -35,12 +35,12 @@ use core::{cmp, marker::PhantomData}; use cumulus_primitives_core::{ relay_chain::{ self, - vstaging::{ClaimQueueOffset, CoreSelector}, + vstaging::{ClaimQueueOffset, CoreSelector, DEFAULT_CLAIM_QUEUE_OFFSET}, }, AbridgedHostConfiguration, ChannelInfo, ChannelStatus, CollationInfo, GetChannelInfo, InboundDownwardMessage, InboundHrmpMessage, ListChannelInfos, MessageSendError, OutboundHrmpMessage, ParaId, PersistedValidationData, UpwardMessage, UpwardMessageSender, - XcmpMessageHandler, XcmpMessageSource, DEFAULT_CLAIM_QUEUE_OFFSET, + XcmpMessageHandler, XcmpMessageSource, }; use cumulus_primitives_parachain_inherent::{MessageQueueChain, ParachainInherentData}; use frame_support::{ diff --git a/cumulus/primitives/core/src/lib.rs b/cumulus/primitives/core/src/lib.rs index dfb574ef3301..f88e663db19e 100644 --- a/cumulus/primitives/core/src/lib.rs +++ b/cumulus/primitives/core/src/lib.rs @@ -333,10 +333,6 @@ pub mod rpsr_digest { } } -/// The default claim queue offset to be used if it's not configured/accessible in the parachain -/// runtime -pub const DEFAULT_CLAIM_QUEUE_OFFSET: u8 = 0; - /// Information about a collation. /// /// This was used in version 1 of the [`CollectCollationInfo`] runtime api. diff --git a/polkadot/node/collation-generation/src/error.rs b/polkadot/node/collation-generation/src/error.rs index 68902f58579a..2599026080df 100644 --- a/polkadot/node/collation-generation/src/error.rs +++ b/polkadot/node/collation-generation/src/error.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use polkadot_primitives::vstaging::CandidateReceiptError; +use polkadot_primitives::vstaging::CommittedCandidateReceiptError; use thiserror::Error; #[derive(Debug, Error)] @@ -34,7 +34,7 @@ pub enum Error { #[error("Collation submitted before initialization")] SubmittedBeforeInit, #[error("V2 core index check failed: {0}")] - CandidateReceiptCheck(CandidateReceiptError), + CandidateReceiptCheck(CommittedCandidateReceiptError), #[error("PoV size {0} exceeded maximum size of {1}")] POVSizeExceeded(usize, usize), } diff --git a/polkadot/node/collation-generation/src/lib.rs b/polkadot/node/collation-generation/src/lib.rs index 9e975acf10b8..b371017a8289 100644 --- a/polkadot/node/collation-generation/src/lib.rs +++ b/polkadot/node/collation-generation/src/lib.rs @@ -554,7 +554,7 @@ async fn construct_and_distribute_receipt( ccr.to_plain() } else { - if commitments.selected_core().is_some() { + if commitments.core_selector().map_err(Error::CandidateReceiptCheck)?.is_some() { gum::warn!( target: LOG_TARGET, ?pov_hash, diff --git a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs index 20ca62d41f5b..48d3f27b1fa6 100644 --- a/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs +++ b/polkadot/node/subsystem-util/src/inclusion_emulator/mod.rs @@ -82,9 +82,9 @@ /// in practice at most once every few weeks. use polkadot_node_subsystem::messages::HypotheticalCandidate; use polkadot_primitives::{ - async_backing::Constraints as PrimitiveConstraints, BlockNumber, CandidateCommitments, - CandidateHash, Hash, HeadData, Id as ParaId, PersistedValidationData, UpgradeRestriction, - ValidationCodeHash, + async_backing::Constraints as PrimitiveConstraints, vstaging::skip_ump_signals, BlockNumber, + CandidateCommitments, CandidateHash, Hash, HeadData, Id as ParaId, PersistedValidationData, + UpgradeRestriction, ValidationCodeHash, }; use std::{collections::HashMap, sync::Arc}; @@ -601,13 +601,8 @@ impl Fragment { persisted_validation_data: &PersistedValidationData, ) -> Result { // Filter UMP signals and the separator. - let upward_messages = if let Some(separator_index) = - commitments.upward_messages.iter().position(|message| message.is_empty()) - { - commitments.upward_messages.split_at(separator_index).0 - } else { - &commitments.upward_messages - }; + let upward_messages = + skip_ump_signals(commitments.upward_messages.iter()).collect::>(); let ump_messages_sent = upward_messages.len(); let ump_bytes_sent = upward_messages.iter().map(|msg| msg.len()).sum(); diff --git a/polkadot/primitives/src/vstaging/mod.rs b/polkadot/primitives/src/vstaging/mod.rs index ca9c3e1bebad..271f78efe090 100644 --- a/polkadot/primitives/src/vstaging/mod.rs +++ b/polkadot/primitives/src/vstaging/mod.rs @@ -39,6 +39,10 @@ use sp_staking::SessionIndex; /// Async backing primitives pub mod async_backing; +/// The default claim queue offset to be used if it's not configured/accessible in the parachain +/// runtime +pub const DEFAULT_CLAIM_QUEUE_OFFSET: u8 = 0; + /// A type representing the version of the candidate descriptor and internal version number. #[derive(PartialEq, Eq, Encode, Decode, Clone, TypeInfo, RuntimeDebug, Copy)] #[cfg_attr(feature = "std", derive(Hash))] @@ -430,49 +434,45 @@ pub enum UMPSignal { /// Separator between `XCM` and `UMPSignal`. pub const UMP_SEPARATOR: Vec = vec![]; -impl CandidateCommitments { - /// Returns the core selector and claim queue offset the candidate has committed to, if any. - pub fn selected_core(&self) -> Option<(CoreSelector, ClaimQueueOffset)> { - // We need at least 2 messages for the separator and core selector - if self.upward_messages.len() < 2 { - return None - } - - let separator_pos = - self.upward_messages.iter().rposition(|message| message == &UMP_SEPARATOR)?; - - // Use first commitment - let message = self.upward_messages.get(separator_pos + 1)?; +/// Utility function for skipping the ump signals. +pub fn skip_ump_signals<'a>( + upward_messages: impl Iterator>, +) -> impl Iterator> { + upward_messages.take_while(|message| *message != &UMP_SEPARATOR) +} - match UMPSignal::decode(&mut message.as_slice()).ok()? { - UMPSignal::SelectCore(core_selector, cq_offset) => Some((core_selector, cq_offset)), - } - } +impl CandidateCommitments { + /// Returns the core selector and claim queue offset determined by `UMPSignal::SelectCore` + /// commitment, if present. + pub fn core_selector( + &self, + ) -> Result, CommittedCandidateReceiptError> { + let mut signals_iter = + self.upward_messages.iter().skip_while(|message| *message != &UMP_SEPARATOR); + + if signals_iter.next().is_some() { + let Some(core_selector_message) = signals_iter.next() else { return Ok(None) }; + // We should have exactly one signal beyond the separator + if signals_iter.next().is_some() { + return Err(CommittedCandidateReceiptError::TooManyUMPSignals) + } - /// Returns the core index determined by `UMPSignal::SelectCore` commitment - /// and `assigned_cores`. - /// - /// Returns `None` if there is no `UMPSignal::SelectCore` commitment or - /// assigned cores is empty. - /// - /// `assigned_cores` must be a sorted vec of all core indices assigned to a parachain. - pub fn committed_core_index(&self, assigned_cores: &[&CoreIndex]) -> Option { - if assigned_cores.is_empty() { - return None + match UMPSignal::decode(&mut core_selector_message.as_slice()) + .map_err(|_| CommittedCandidateReceiptError::UmpSignalDecode)? + { + UMPSignal::SelectCore(core_index_selector, cq_offset) => + Ok(Some((core_index_selector, cq_offset))), + } + } else { + Ok(None) } - - self.selected_core().and_then(|(core_selector, _cq_offset)| { - let core_index = - **assigned_cores.get(core_selector.0 as usize % assigned_cores.len())?; - Some(core_index) - }) } } -/// CandidateReceipt construction errors. +/// CommittedCandidateReceiptError construction errors. #[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo, RuntimeDebug)] #[cfg_attr(feature = "std", derive(thiserror::Error))] -pub enum CandidateReceiptError { +pub enum CommittedCandidateReceiptError { /// The specified core index is invalid. #[cfg_attr(feature = "std", error("The specified core index is invalid"))] InvalidCoreIndex, @@ -485,6 +485,9 @@ pub enum CandidateReceiptError { /// The core selector or claim queue offset is invalid. #[cfg_attr(feature = "std", error("The core selector or claim queue offset is invalid"))] InvalidSelectedCore, + #[cfg_attr(feature = "std", error("Could not decode UMP signal"))] + /// Could not decode UMP signal. + UmpSignalDecode, /// The parachain is not assigned to any core at specified claim queue offset. #[cfg_attr( feature = "std", @@ -498,6 +501,10 @@ pub enum CandidateReceiptError { /// Unknown version. #[cfg_attr(feature = "std", error("Unknown internal version"))] UnknownVersion(InternalVersion), + /// The allowed number of `UMPSignal` messages in the queue was exceeded. + /// Currenly only one such message is allowed. + #[cfg_attr(feature = "std", error("Too many UMP signals"))] + TooManyUMPSignals, } macro_rules! impl_getter { @@ -590,57 +597,63 @@ impl CandidateDescriptorV2 { impl CommittedCandidateReceiptV2 { /// Checks if descriptor core index is equal to the committed core index. - /// Input `cores_per_para` is a claim queue snapshot stored as a mapping - /// between `ParaId` and the cores assigned per depth. + /// Input `cores_per_para` is a claim queue snapshot at the candidate's relay parent, stored as + /// a mapping between `ParaId` and the cores assigned per depth. pub fn check_core_index( &self, cores_per_para: &TransposedClaimQueue, - ) -> Result<(), CandidateReceiptError> { + ) -> Result<(), CommittedCandidateReceiptError> { match self.descriptor.version() { // Don't check v1 descriptors. CandidateDescriptorVersion::V1 => return Ok(()), CandidateDescriptorVersion::V2 => {}, CandidateDescriptorVersion::Unknown => - return Err(CandidateReceiptError::UnknownVersion(self.descriptor.version)), + return Err(CommittedCandidateReceiptError::UnknownVersion(self.descriptor.version)), } - if cores_per_para.is_empty() { - return Err(CandidateReceiptError::NoAssignment) - } - - let (offset, core_selected) = - if let Some((_core_selector, cq_offset)) = self.commitments.selected_core() { - (cq_offset.0, true) - } else { - // If no core has been selected then we use offset 0 (top of claim queue) - (0, false) - }; + let (maybe_core_index_selector, cq_offset) = self.commitments.core_selector()?.map_or_else( + || (None, ClaimQueueOffset(DEFAULT_CLAIM_QUEUE_OFFSET)), + |(sel, off)| (Some(sel), off), + ); - // The cores assigned to the parachain at above computed offset. let assigned_cores = cores_per_para .get(&self.descriptor.para_id()) - .ok_or(CandidateReceiptError::NoAssignment)? - .get(&offset) - .ok_or(CandidateReceiptError::NoAssignment)? - .into_iter() - .collect::>(); - - let core_index = if core_selected { - self.commitments - .committed_core_index(assigned_cores.as_slice()) - .ok_or(CandidateReceiptError::NoAssignment)? - } else { - // `SelectCore` commitment is mandatory for elastic scaling parachains. - if assigned_cores.len() > 1 { - return Err(CandidateReceiptError::NoCoreSelected) - } + .ok_or(CommittedCandidateReceiptError::NoAssignment)? + .get(&cq_offset.0) + .ok_or(CommittedCandidateReceiptError::NoAssignment)?; - **assigned_cores.get(0).ok_or(CandidateReceiptError::NoAssignment)? - }; + if assigned_cores.is_empty() { + return Err(CommittedCandidateReceiptError::NoAssignment) + } let descriptor_core_index = CoreIndex(self.descriptor.core_index as u32); + + let core_index_selector = if let Some(core_index_selector) = maybe_core_index_selector { + // We have a committed core selector, we can use it. + core_index_selector + } else if assigned_cores.len() > 1 { + // We got more than one assigned core and no core selector. Special care is needed. + if !assigned_cores.contains(&descriptor_core_index) { + // core index in the descriptor is not assigned to the para. Error. + return Err(CommittedCandidateReceiptError::InvalidCoreIndex) + } else { + // the descriptor core index is indeed assigned to the para. This is the most we can + // check for now + return Ok(()) + } + } else { + // No core selector but there's only one assigned core, use it. + CoreSelector(0) + }; + + let core_index = assigned_cores + .iter() + .nth(core_index_selector.0 as usize % assigned_cores.len()) + .ok_or(CommittedCandidateReceiptError::InvalidSelectedCore) + .copied()?; + if core_index != descriptor_core_index { - return Err(CandidateReceiptError::CoreIndexMismatch) + return Err(CommittedCandidateReceiptError::CoreIndexMismatch) } Ok(()) @@ -1037,7 +1050,7 @@ mod tests { assert_eq!(new_ccr.descriptor.version(), CandidateDescriptorVersion::Unknown); assert_eq!( new_ccr.check_core_index(&BTreeMap::new()), - Err(CandidateReceiptError::UnknownVersion(InternalVersion(100))) + Err(CommittedCandidateReceiptError::UnknownVersion(InternalVersion(100))) ) } @@ -1075,7 +1088,6 @@ mod tests { new_ccr.descriptor.core_index = 0; new_ccr.descriptor.para_id = ParaId::new(1000); - new_ccr.commitments.upward_messages.force_push(UMP_SEPARATOR); new_ccr.commitments.upward_messages.force_push(UMP_SEPARATOR); let mut cq = BTreeMap::new(); @@ -1089,7 +1101,14 @@ mod tests { new_ccr.commitments.upward_messages.force_push(vec![0, 13, 200].encode()); // No `SelectCore` can be decoded. - assert_eq!(new_ccr.commitments.selected_core(), None); + assert_eq!( + new_ccr.commitments.core_selector(), + Err(CommittedCandidateReceiptError::UmpSignalDecode) + ); + + // Has two cores assigned but no core commitment. Will pass the check if the descriptor core + // index is indeed assigned to the para. + new_ccr.commitments.upward_messages.clear(); let mut cq = BTreeMap::new(); cq.insert( @@ -1100,28 +1119,46 @@ mod tests { CoreIndex(100), vec![new_ccr.descriptor.para_id(), new_ccr.descriptor.para_id()].into(), ); + assert_eq!(new_ccr.check_core_index(&transpose_claim_queue(cq.clone())), Ok(())); + new_ccr.descriptor.set_core_index(CoreIndex(1)); assert_eq!( new_ccr.check_core_index(&transpose_claim_queue(cq.clone())), - Err(CandidateReceiptError::NoCoreSelected) + Err(CommittedCandidateReceiptError::InvalidCoreIndex) ); + new_ccr.descriptor.set_core_index(CoreIndex(0)); new_ccr.commitments.upward_messages.clear(); new_ccr.commitments.upward_messages.force_push(UMP_SEPARATOR); - new_ccr .commitments .upward_messages .force_push(UMPSignal::SelectCore(CoreSelector(0), ClaimQueueOffset(1)).encode()); - // Duplicate + // No assignments. + assert_eq!( + new_ccr.check_core_index(&transpose_claim_queue(Default::default())), + Err(CommittedCandidateReceiptError::NoAssignment) + ); + + // Mismatch between descriptor index and commitment. + new_ccr.descriptor.set_core_index(CoreIndex(1)); + assert_eq!( + new_ccr.check_core_index(&transpose_claim_queue(cq.clone())), + Err(CommittedCandidateReceiptError::CoreIndexMismatch) + ); + new_ccr.descriptor.set_core_index(CoreIndex(0)); + + // Too many UMP signals. new_ccr .commitments .upward_messages .force_push(UMPSignal::SelectCore(CoreSelector(1), ClaimQueueOffset(1)).encode()); - // Duplicate doesn't override first signal. - assert_eq!(new_ccr.check_core_index(&transpose_claim_queue(cq)), Ok(())); + assert_eq!( + new_ccr.check_core_index(&transpose_claim_queue(cq)), + Err(CommittedCandidateReceiptError::TooManyUMPSignals) + ); } #[test] @@ -1191,7 +1228,7 @@ mod tests { Decode::decode(&mut encoded_ccr.as_slice()).unwrap(); assert_eq!(v1_ccr.descriptor.version(), CandidateDescriptorVersion::V1); - assert!(v1_ccr.commitments.selected_core().is_some()); + assert!(v1_ccr.commitments.core_selector().unwrap().is_some()); let mut cq = BTreeMap::new(); cq.insert(CoreIndex(0), vec![v1_ccr.descriptor.para_id()].into()); @@ -1199,11 +1236,6 @@ mod tests { assert!(v1_ccr.check_core_index(&transpose_claim_queue(cq)).is_ok()); - assert_eq!( - v1_ccr.commitments.committed_core_index(&vec![&CoreIndex(10), &CoreIndex(5)]), - Some(CoreIndex(5)), - ); - assert_eq!(v1_ccr.descriptor.core_index(), None); } @@ -1228,11 +1260,9 @@ mod tests { cq.insert(CoreIndex(0), vec![new_ccr.descriptor.para_id()].into()); cq.insert(CoreIndex(1), vec![new_ccr.descriptor.para_id()].into()); - // Should fail because 2 cores are assigned, - assert_eq!( - new_ccr.check_core_index(&transpose_claim_queue(cq)), - Err(CandidateReceiptError::NoCoreSelected) - ); + // Passes even if 2 cores are assigned, because elastic scaling MVP could still inject the + // core index in the `BackedCandidate`. + assert_eq!(new_ccr.check_core_index(&transpose_claim_queue(cq)), Ok(())); // Adding collator signature should make it decode as v1. old_ccr.descriptor.signature = dummy_collator_signature(); diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index ea3a5d3cdda9..8ad9711a0f38 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -46,7 +46,7 @@ use pallet_message_queue::OnQueueChanged; use polkadot_primitives::{ effective_minimum_backing_votes, supermajority_threshold, vstaging::{ - BackedCandidate, CandidateDescriptorV2 as CandidateDescriptor, + skip_ump_signals, BackedCandidate, CandidateDescriptorV2 as CandidateDescriptor, CandidateReceiptV2 as CandidateReceipt, CommittedCandidateReceiptV2 as CommittedCandidateReceipt, }, @@ -412,11 +412,6 @@ pub(crate) enum UmpAcceptanceCheckErr { TotalSizeExceeded { total_size: u64, limit: u64 }, /// A para-chain cannot send UMP messages while it is offboarding. IsOffboarding, - /// The allowed number of `UMPSignal` messages in the queue was exceeded. - /// Currenly only one such message is allowed. - TooManyUMPSignals { count: u32 }, - /// The UMP queue contains an invalid `UMPSignal` - NoUmpSignal, } impl fmt::Debug for UmpAcceptanceCheckErr { @@ -445,12 +440,6 @@ impl fmt::Debug for UmpAcceptanceCheckErr { UmpAcceptanceCheckErr::IsOffboarding => { write!(fmt, "upward message rejected because the para is off-boarding") }, - UmpAcceptanceCheckErr::TooManyUMPSignals { count } => { - write!(fmt, "the ump queue has too many `UMPSignal` messages ({} > 1 )", count) - }, - UmpAcceptanceCheckErr::NoUmpSignal => { - write!(fmt, "Required UMP signal not found") - }, } } } @@ -925,25 +914,7 @@ impl Pallet { upward_messages: &[UpwardMessage], ) -> Result<(), UmpAcceptanceCheckErr> { // Filter any pending UMP signals and the separator. - let upward_messages = if let Some(separator_index) = - upward_messages.iter().position(|message| message.is_empty()) - { - let (upward_messages, ump_signals) = upward_messages.split_at(separator_index); - - if ump_signals.len() > 2 { - return Err(UmpAcceptanceCheckErr::TooManyUMPSignals { - count: ump_signals.len() as u32, - }) - } - - if ump_signals.len() == 1 { - return Err(UmpAcceptanceCheckErr::NoUmpSignal) - } - - upward_messages - } else { - upward_messages - }; + let upward_messages = skip_ump_signals(upward_messages.iter()).collect::>(); // Cannot send UMP messages while off-boarding. if paras::Pallet::::is_offboarding(para) { @@ -997,10 +968,7 @@ impl Pallet { /// to deal with the messages as given. Messages that are too long will be ignored since such /// candidates should have already been rejected in [`Self::check_upward_messages`]. pub(crate) fn receive_upward_messages(para: ParaId, upward_messages: &[Vec]) { - let bounded = upward_messages - .iter() - // Stop once we hit the `UMPSignal` separator. - .take_while(|message| !message.is_empty()) + let bounded = skip_ump_signals(upward_messages.iter()) .filter_map(|d| { BoundedSlice::try_from(&d[..]) .inspect_err(|_| { diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index eef26b83368f..146be0ee0aad 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -1864,11 +1864,8 @@ mod enter { v2_descriptor: true, candidate_modifier: Some(|mut candidate: CommittedCandidateReceiptV2| { if candidate.descriptor.para_id() == 1.into() { - // Drop the core selector to make it invalid - candidate - .commitments - .upward_messages - .truncate(candidate.commitments.upward_messages.len() - 1); + // Make the core selector invalid + candidate.commitments.upward_messages[1].truncate(0); } candidate }), diff --git a/prdoc/pr_6217.prdoc b/prdoc/pr_6217.prdoc new file mode 100644 index 000000000000..2fa800b58d2c --- /dev/null +++ b/prdoc/pr_6217.prdoc @@ -0,0 +1,24 @@ +title: 'Unify and harden UMP signal checks in check_core_index' +doc: +- audience: [Runtime Dev, Node Dev] + description: | + Refactors and hardens the core index checks on the candidate commitments. + Also adds a utility for skipping the ump signals + +crates: +- name: cumulus-client-consensus-aura + bump: patch +- name: cumulus-pallet-parachain-system + bump: patch +- name: cumulus-primitives-core + bump: major +- name: polkadot-node-collation-generation + bump: major +- name: polkadot-node-core-candidate-validation + bump: patch +- name: polkadot-node-subsystem-util + bump: patch +- name: polkadot-primitives + bump: major +- name: polkadot-runtime-parachains + bump: patch From 7725890d114ea420e2d946b4d9e0a823d20cf0d8 Mon Sep 17 00:00:00 2001 From: davidk-pt Date: Tue, 5 Nov 2024 14:32:19 +0200 Subject: [PATCH 029/166] [Deprecation] deprecate treasury `spend_local` call and related items (#6169) Resolves https://github.com/paritytech/polkadot-sdk/issues/5930 `spend_local` from `treasury` pallet and associated types are deprecated. `spend_local` was being used before with native currency in the treasury. This PR provides a documentation on how to migrate to the `spend` call instead. ### Migration #### For users who were using only `spend_local` before To replace `spend_local` functionality configure `Paymaster` pallet configuration to be `PayFromAccount` and configure `AssetKind` to be `()` and use `spend` call instead. This way `spend` call will function as deprecated `spend_local`. Example: ``` impl pallet_treasury::Config for Runtime { .. type AssetKind = (); type Paymaster = PayFromAccount; // convert balance 1:1 ratio with native currency type BalanceConverter = UnityAssetBalanceConversion; .. } ``` #### For users who were already using `spend` with all other assets, except the native asset Use `NativeOrWithId` type for `AssetKind` and have a `UnionOf` for native and non-native assets, then use that with `PayAssetFromAccount`. Example from `kitchensink-runtime`: ``` // Union of native currency and assets pub type NativeAndAssets = UnionOf, AccountId>; impl pallet_treasury::Config for Runtime { .. type AssetKind = NativeOrWithId; type Paymaster = PayAssetFromAccount; type BalanceConverter = AssetRate; .. } // AssetRate pallet configuration impl pallet_asset_rate::Config for Runtime { .. type Currency = Balances; type AssetKind = NativeOrWithId; .. } ``` --------- Co-authored-by: DavidK Co-authored-by: Muharem --- prdoc/pr_6169.prdoc | 63 +++++++++++++++++ substrate/bin/node/runtime/src/lib.rs | 47 +++++++++++-- substrate/frame/bounties/src/lib.rs | 1 + substrate/frame/bounties/src/tests.rs | 7 ++ substrate/frame/child-bounties/src/tests.rs | 1 + substrate/frame/tips/src/tests.rs | 1 + substrate/frame/treasury/src/benchmarking.rs | 6 +- substrate/frame/treasury/src/lib.rs | 38 ++++++++++ substrate/frame/treasury/src/migration.rs | 2 + substrate/frame/treasury/src/tests.rs | 74 ++++++++++++++------ 10 files changed, 213 insertions(+), 27 deletions(-) create mode 100644 prdoc/pr_6169.prdoc diff --git a/prdoc/pr_6169.prdoc b/prdoc/pr_6169.prdoc new file mode 100644 index 000000000000..0416fe008051 --- /dev/null +++ b/prdoc/pr_6169.prdoc @@ -0,0 +1,63 @@ +title: "[Deprecation] deprecate treasury `spend_local` call and related items" + +doc: + - audience: Runtime Dev + description: | + Deprecates `spend_local` from the treasury pallet and items associated with it. + + ### Migration + + #### For users who were using only `spend_local` before + + To replace `spend_local` functionality configure `Paymaster` pallet configuration to be `PayFromAccount` and configure `AssetKind` to be `()` and use `spend` call instead. + This way `spend` call will function as deprecated `spend_local`. + + Example: + ``` + impl pallet_treasury::Config for Runtime { + .. + type AssetKind = (); + type Paymaster = PayFromAccount; + // convert balance 1:1 ratio with native currency + type BalanceConverter = UnityAssetBalanceConversion; + .. + } + ``` + + #### For users who were already using `spend` with all other assets, except the native asset + + Use `NativeOrWithId` type for `AssetKind` and have a `UnionOf` for native and non-native assets, then use that with `PayAssetFromAccount`. + + Example from `kitchensink-runtime`: + ``` + // Union of native currency and assets + pub type NativeAndAssets = + UnionOf, AccountId>; + + impl pallet_treasury::Config for Runtime { + .. + type AssetKind = NativeOrWithId; + type Paymaster = PayAssetFromAccount; + type BalanceConverter = AssetRate; + .. + } + + // AssetRate pallet configuration + impl pallet_asset_rate::Config for Runtime { + .. + type Currency = Balances; + type AssetKind = NativeOrWithId; + .. + } + ``` + + +crates: +- name: pallet-treasury + bump: patch +- name: pallet-bounties + bump: patch +- name: pallet-child-bounties + bump: patch +- name: pallet-tips + bump: patch diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 8c2992bdb696..76b09c127c35 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -24,6 +24,13 @@ extern crate alloc; +#[cfg(feature = "runtime-benchmarks")] +use pallet_asset_rate::AssetKindFactory; +#[cfg(feature = "runtime-benchmarks")] +use pallet_treasury::ArgumentsFactory; +#[cfg(feature = "runtime-benchmarks")] +use polkadot_sdk::sp_core::crypto::FromEntropy; + use polkadot_sdk::*; use alloc::{vec, vec::Vec}; @@ -267,6 +274,36 @@ impl Contains> for TxPauseWhitelistedCalls { } } +#[cfg(feature = "runtime-benchmarks")] +pub struct AssetRateArguments; +#[cfg(feature = "runtime-benchmarks")] +impl AssetKindFactory> for AssetRateArguments { + fn create_asset_kind(seed: u32) -> NativeOrWithId { + if seed % 2 > 0 { + NativeOrWithId::Native + } else { + NativeOrWithId::WithId(seed / 2) + } + } +} + +#[cfg(feature = "runtime-benchmarks")] +pub struct PalletTreasuryArguments; +#[cfg(feature = "runtime-benchmarks")] +impl ArgumentsFactory, AccountId> for PalletTreasuryArguments { + fn create_asset_kind(seed: u32) -> NativeOrWithId { + if seed % 2 > 0 { + NativeOrWithId::Native + } else { + NativeOrWithId::WithId(seed / 2) + } + } + + fn create_beneficiary(seed: [u8; 32]) -> AccountId { + AccountId::from_entropy(&mut seed.as_slice()).unwrap() + } +} + impl pallet_tx_pause::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; @@ -1260,15 +1297,15 @@ impl pallet_treasury::Config for Runtime { type WeightInfo = pallet_treasury::weights::SubstrateWeight; type MaxApprovals = MaxApprovals; type SpendOrigin = EnsureWithSuccess, AccountId, MaxBalance>; - type AssetKind = u32; + type AssetKind = NativeOrWithId; type Beneficiary = AccountId; type BeneficiaryLookup = Indices; - type Paymaster = PayAssetFromAccount; + type Paymaster = PayAssetFromAccount; type BalanceConverter = AssetRate; type PayoutPeriod = SpendPayoutPeriod; type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type BenchmarkHelper = PalletTreasuryArguments; } impl pallet_asset_rate::Config for Runtime { @@ -1276,11 +1313,11 @@ impl pallet_asset_rate::Config for Runtime { type RemoveOrigin = EnsureRoot; type UpdateOrigin = EnsureRoot; type Currency = Balances; - type AssetKind = u32; + type AssetKind = NativeOrWithId; type RuntimeEvent = RuntimeEvent; type WeightInfo = pallet_asset_rate::weights::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); + type BenchmarkHelper = AssetRateArguments; } parameter_types! { diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 6e0bfa6084e1..06b0e76cfc7e 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -333,6 +333,7 @@ pub mod pallet { /// Bounty indices that have been approved but not yet funded. #[pallet::storage] + #[allow(deprecated)] pub type BountyApprovals, I: 'static = ()> = StorageValue<_, BoundedVec, ValueQuery>; diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index fcc854e83be0..447d0edb4122 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -231,6 +231,7 @@ fn expect_events(e: Vec>) { } #[test] +#[allow(deprecated)] fn genesis_config_works() { ExtBuilder::default().build_and_execute(|| { assert_eq!(Treasury::pot(), 0); @@ -248,6 +249,7 @@ fn minting_works() { } #[test] +#[allow(deprecated)] fn accepted_spend_proposal_ignored_outside_spend_period() { ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -274,6 +276,7 @@ fn unused_pot_should_diminish() { } #[test] +#[allow(deprecated)] fn accepted_spend_proposal_enacted_on_spend_period() { ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -288,6 +291,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { } #[test] +#[allow(deprecated)] fn pot_underflow_should_not_diminish() { ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -308,6 +312,7 @@ fn pot_underflow_should_not_diminish() { // Treasury account doesn't get deleted if amount approved to spend is all its free balance. // i.e. pot should not include existential deposit needed for account survival. #[test] +#[allow(deprecated)] fn treasury_account_doesnt_get_deleted() { ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -330,6 +335,7 @@ fn treasury_account_doesnt_get_deleted() { // In case treasury account is not existing then it works fine. // This is useful for chain that will just update runtime. #[test] +#[allow(deprecated)] fn inexistent_account_works() { let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(0, 100), (1, 99), (2, 1)] } @@ -423,6 +429,7 @@ fn propose_bounty_validation_works() { } #[test] +#[allow(deprecated)] fn close_bounty_works() { ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 96d01b03560d..0e58f7c91780 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -161,6 +161,7 @@ fn last_event() -> ChildBountiesEvent { } #[test] +#[allow(deprecated)] fn genesis_config_works() { new_test_ext().execute_with(|| { assert_eq!(Treasury::pot(), 0); diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index f6f130b7e261..530efb708e41 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -209,6 +209,7 @@ fn last_event() -> TipEvent { } #[test] +#[allow(deprecated)] fn genesis_config_works() { build_and_execute(|| { assert_eq!(Treasury::pot(), 0); diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index 650e5376fa4b..a03ee149db9b 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -78,6 +78,7 @@ fn create_approved_proposals, I: 'static>(n: u32) -> Result<(), &'s for i in 0..n { let (_, value, lookup) = setup_proposal::(i); + #[allow(deprecated)] if let Ok(origin) = &spender { Treasury::::spend_local(origin.clone(), value, lookup)?; } @@ -136,6 +137,7 @@ mod benchmarks { let (spend_exists, proposal_id) = if let Ok(origin) = T::SpendOrigin::try_successful_origin() { let (_, value, beneficiary_lookup) = setup_proposal::(SEED); + #[allow(deprecated)] Treasury::::spend_local(origin, value, beneficiary_lookup)?; let proposal_id = ProposalCount::::get() - 1; @@ -149,8 +151,8 @@ mod benchmarks { #[block] { - let res = - Treasury::::remove_approval(reject_origin as T::RuntimeOrigin, proposal_id); + #[allow(deprecated)] + let res = Treasury::::remove_approval(reject_origin as T::RuntimeOrigin, proposal_id); if spend_exists { assert_ok!(res); diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index b21a36949357..faacda1c0783 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -240,6 +240,9 @@ pub mod pallet { /// Runtime hooks to external pallet using treasury to compute spend funds. type SpendFunds: SpendFunds; + /// DEPRECATED: associated with `spend_local` call and will be removed in May 2025. + /// Refer to for migration to `spend`. + /// /// The maximum number of approvals that can wait in the spending queue. /// /// NOTE: This parameter is also used within the Bounties Pallet extension if enabled. @@ -284,10 +287,16 @@ pub mod pallet { type BlockNumberProvider: BlockNumberProvider>; } + /// DEPRECATED: associated with `spend_local` call and will be removed in May 2025. + /// Refer to for migration to `spend`. + /// /// Number of proposals that have been made. #[pallet::storage] pub type ProposalCount = StorageValue<_, ProposalIndex, ValueQuery>; + /// DEPRECATED: associated with `spend_local` call and will be removed in May 2025. + /// Refer to for migration to `spend`. + /// /// Proposals that have been made. #[pallet::storage] pub type Proposals, I: 'static = ()> = StorageMap< @@ -303,6 +312,9 @@ pub mod pallet { pub type Deactivated, I: 'static = ()> = StorageValue<_, BalanceOf, ValueQuery>; + /// DEPRECATED: associated with `spend_local` call and will be removed in May 2025. + /// Refer to for migration to `spend`. + /// /// Proposal indices that have been approved but not yet awarded. #[pallet::storage] pub type Approvals, I: 'static = ()> = @@ -494,6 +506,10 @@ pub mod pallet { /// Emits [`Event::SpendApproved`] if successful. #[pallet::call_index(3)] #[pallet::weight(T::WeightInfo::spend_local())] + #[deprecated( + note = "The `spend_local` call will be removed by May 2025. Migrate to the new flow and use the `spend` call." + )] + #[allow(deprecated)] pub fn spend_local( origin: OriginFor, #[pallet::compact] amount: BalanceOf, @@ -523,7 +539,9 @@ pub mod pallet { .unwrap_or(Ok(()))?; let beneficiary = T::Lookup::lookup(beneficiary)?; + #[allow(deprecated)] let proposal_index = ProposalCount::::get(); + #[allow(deprecated)] Approvals::::try_append(proposal_index) .map_err(|_| Error::::TooManyApprovals)?; let proposal = Proposal { @@ -532,7 +550,9 @@ pub mod pallet { beneficiary: beneficiary.clone(), bond: Default::default(), }; + #[allow(deprecated)] Proposals::::insert(proposal_index, proposal); + #[allow(deprecated)] ProposalCount::::put(proposal_index + 1); Self::deposit_event(Event::SpendApproved { proposal_index, amount, beneficiary }); @@ -562,12 +582,17 @@ pub mod pallet { /// in the first place. #[pallet::call_index(4)] #[pallet::weight((T::WeightInfo::remove_approval(), DispatchClass::Operational))] + #[deprecated( + note = "The `remove_approval` call will be removed by May 2025. It associated with the deprecated `spend_local` call." + )] + #[allow(deprecated)] pub fn remove_approval( origin: OriginFor, #[pallet::compact] proposal_id: ProposalIndex, ) -> DispatchResult { T::RejectOrigin::ensure_origin(origin)?; + #[allow(deprecated)] Approvals::::try_mutate(|v| -> DispatchResult { if let Some(index) = v.iter().position(|x| x == &proposal_id) { v.remove(index); @@ -836,16 +861,28 @@ impl, I: 'static> Pallet { } /// Public function to proposal_count storage. + #[deprecated( + note = "This function will be removed by May 2025. Configure pallet to use PayFromAccount for Paymaster type instead" + )] pub fn proposal_count() -> ProposalIndex { + #[allow(deprecated)] ProposalCount::::get() } /// Public function to proposals storage. + #[deprecated( + note = "This function will be removed by May 2025. Configure pallet to use PayFromAccount for Paymaster type instead" + )] pub fn proposals(index: ProposalIndex) -> Option>> { + #[allow(deprecated)] Proposals::::get(index) } /// Public function to approvals storage. + #[deprecated( + note = "This function will be removed by May 2025. Configure pallet to use PayFromAccount for Paymaster type instead" + )] + #[allow(deprecated)] pub fn approvals() -> BoundedVec { Approvals::::get() } @@ -864,6 +901,7 @@ impl, I: 'static> Pallet { let mut missed_any = false; let mut imbalance = PositiveImbalanceOf::::zero(); + #[allow(deprecated)] let proposals_len = Approvals::::mutate(|v| { let proposals_approvals_len = v.len() as u32; v.retain(|&index| { diff --git a/substrate/frame/treasury/src/migration.rs b/substrate/frame/treasury/src/migration.rs index c0de4ce43108..7c8c587f1664 100644 --- a/substrate/frame/treasury/src/migration.rs +++ b/substrate/frame/treasury/src/migration.rs @@ -43,11 +43,13 @@ pub mod cleanup_proposals { { fn on_runtime_upgrade() -> frame_support::weights::Weight { let mut approval_index = BTreeSet::new(); + #[allow(deprecated)] for approval in Approvals::::get().iter() { approval_index.insert(*approval); } let mut proposals_processed = 0; + #[allow(deprecated)] for (proposal_index, p) in Proposals::::iter() { if !approval_index.contains(&proposal_index) { let err_amount = T::Currency::unreserve(&p.proposer, p.bond); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index a99dd0dd4449..e9efb7c0956f 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -249,6 +249,7 @@ fn genesis_config_works() { #[test] fn spend_local_origin_permissioning_works() { + #[allow(deprecated)] ExtBuilder::default().build().execute_with(|| { assert_noop!(Treasury::spend_local(RuntimeOrigin::signed(1), 1, 1), BadOrigin); assert_noop!( @@ -273,6 +274,7 @@ fn spend_local_origin_permissioning_works() { #[docify::export] #[test] fn spend_local_origin_works() { + #[allow(deprecated)] ExtBuilder::default().build().execute_with(|| { // Check that accumulate works when we have Some value in Dummy already. Balances::make_free_balance_be(&Treasury::account_id(), 102); @@ -309,7 +311,10 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + } go_to_block(1); assert_eq!(Balances::free_balance(3), 0); @@ -336,7 +341,10 @@ fn accepted_spend_proposal_enacted_on_spend_period() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + } go_to_block(2); assert_eq!(Balances::free_balance(3), 100); @@ -350,7 +358,10 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 150, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 150, 3)); + } go_to_block(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -370,13 +381,19 @@ fn treasury_account_doesnt_get_deleted() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); + >::on_initialize(2); + assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); - go_to_block(2); - assert_eq!(Treasury::pot(), 100); // Pot hasn't changed + go_to_block(2); + assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), Treasury::pot(), 3)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), Treasury::pot(), 3)); + } go_to_block(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -399,8 +416,11 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 99, 3)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 99, 3)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + } go_to_block(2); @@ -439,6 +459,7 @@ fn genesis_funding_works() { #[test] fn max_approvals_limited() { + #[allow(deprecated)] ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), u64::MAX); Balances::make_free_balance_be(&0, u64::MAX); @@ -457,6 +478,7 @@ fn max_approvals_limited() { #[test] fn remove_already_removed_approval_fails() { + #[allow(deprecated)] ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -796,7 +818,10 @@ fn try_state_proposals_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Add a proposal and approve using `spend_local` - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + } assert_eq!(Proposals::::iter().count(), 1); assert_eq!(ProposalCount::::get(), 1); @@ -816,8 +841,11 @@ fn try_state_proposals_invariant_1_works() { fn try_state_proposals_invariant_2_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal and approve using `spend_local` - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + #[allow(deprecated)] + { + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + } assert_eq!(Proposals::::iter().count(), 1); assert_eq!(Approvals::::get().len(), 1); @@ -846,7 +874,10 @@ fn try_state_proposals_invariant_3_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; // Add a proposal and approve using `spend_local` - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 10, 3)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 10, 3)); + } assert_eq!(Proposals::::iter().count(), 1); assert_eq!(Approvals::::get().len(), 1); @@ -952,13 +983,16 @@ fn multiple_spend_periods_work() { // 100 will be spent, 1024 will be the burn amount, 1 for ED Balances::make_free_balance_be(&Treasury::account_id(), 100 + 1024 + 1); // approve spend of total amount 100 to beneficiary `6`. - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(11), 10, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(12), 20, 6)); - assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(13), 50, 6)); + #[allow(deprecated)] + { + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(10), 5, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(11), 10, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(12), 20, 6)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(13), 50, 6)); + } // free balance of `6` is zero, spend period has not passed. go_to_block(1); assert_eq!(Balances::free_balance(6), 0); From 16e877be9afef58e3376d46ea96067aecd5b0dad Mon Sep 17 00:00:00 2001 From: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Date: Tue, 5 Nov 2024 13:54:29 +0100 Subject: [PATCH 030/166] Run check semver in MQ (#6287) For marking `Check SemVer` required --- .github/workflows/check-semver.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/check-semver.yml b/.github/workflows/check-semver.yml index 65f3339b7ac7..78602410cdf6 100644 --- a/.github/workflows/check-semver.yml +++ b/.github/workflows/check-semver.yml @@ -4,6 +4,7 @@ on: pull_request: types: [opened, synchronize, reopened, ready_for_review] workflow_dispatch: + merge_group: concurrency: group: check-semver-${{ github.event.pull_request.number || github.ref }} From c4ef438f9d15921c1b9d27907c12e5e5024c1c2b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 5 Nov 2024 13:35:17 +0000 Subject: [PATCH 031/166] Bump the known_good_semver group across 1 directory with 3 updates (#6339) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the known_good_semver group with 2 updates in the / directory: [serde](https://github.com/serde-rs/serde) and [syn](https://github.com/dtolnay/syn). Updates `serde` from 1.0.210 to 1.0.214
Release notes

Sourced from serde's releases.

v1.0.214

  • Implement IntoDeserializer for all Deserializers in serde::de::value module (#2568, thanks @​Mingun)

v1.0.213

  • Fix support for macro-generated with attributes inside a newtype struct (#2847)

v1.0.212

  • Fix hygiene of macro-generated local variable accesses in serde(with) wrappers (#2845)

v1.0.211

  • Improve error reporting about mismatched signature in with and default attributes (#2558, thanks @​Mingun)
  • Show variant aliases in error message when variant deserialization fails (#2566, thanks @​Mingun)
  • Improve binary size of untagged enum and internally tagged enum deserialization by about 12% (#2821)
Commits
  • 4180621 Release 1.0.214
  • 210373b Merge pull request #2568 from Mingun/into_deserializer-for-deserializers
  • 9cda015 Implement IntoDeserializer for all Deserializers in serde::de::value module
  • 58a8d22 Release 1.0.213
  • ef0ed22 Merge pull request #2847 from dtolnay/newtypewith
  • 79925ac Ignore dead_code warning in regression test
  • b60e409 Hygiene for macro-generated newtype struct deserialization with 'with' attr
  • fdc36e5 Add regression test for issue 2846
  • 49e11ce Ignore trivially_copy_pass_by_ref pedantic clippy lint in test
  • 7ae1b5f Release 1.0.212
  • Additional commits viewable in compare view

Updates `serde_derive` from 1.0.210 to 1.0.214
Release notes

Sourced from serde_derive's releases.

v1.0.214

  • Implement IntoDeserializer for all Deserializers in serde::de::value module (#2568, thanks @​Mingun)

v1.0.213

  • Fix support for macro-generated with attributes inside a newtype struct (#2847)

v1.0.212

  • Fix hygiene of macro-generated local variable accesses in serde(with) wrappers (#2845)

v1.0.211

  • Improve error reporting about mismatched signature in with and default attributes (#2558, thanks @​Mingun)
  • Show variant aliases in error message when variant deserialization fails (#2566, thanks @​Mingun)
  • Improve binary size of untagged enum and internally tagged enum deserialization by about 12% (#2821)
Commits
  • 4180621 Release 1.0.214
  • 210373b Merge pull request #2568 from Mingun/into_deserializer-for-deserializers
  • 9cda015 Implement IntoDeserializer for all Deserializers in serde::de::value module
  • 58a8d22 Release 1.0.213
  • ef0ed22 Merge pull request #2847 from dtolnay/newtypewith
  • 79925ac Ignore dead_code warning in regression test
  • b60e409 Hygiene for macro-generated newtype struct deserialization with 'with' attr
  • fdc36e5 Add regression test for issue 2846
  • 49e11ce Ignore trivially_copy_pass_by_ref pedantic clippy lint in test
  • 7ae1b5f Release 1.0.212
  • Additional commits viewable in compare view

Updates `syn` from 2.0.82 to 2.0.87
Release notes

Sourced from syn's releases.

2.0.87

2.0.86

  • Support peeking the end of a parse stream (#1689)
  • Allow parse_quote! to produce Vec<Attribute> (#1775)

2.0.85

  • Preserve extern static unsafety in ForeignItem::Verbatim (#1773)

2.0.84

2.0.83

  • Documentation improvements
Commits
  • a777cff Release 2.0.87
  • 1f103d4 Merge pull request #1779 from dtolnay/scan
  • 0986a66 Ignore enum_glob_use pedantic clippy lint
  • ca97c7d Translate expr scanner to table driven
  • 8039cb3 Test that every expr can be scanned
  • 0132c44 Make scan_expr compilable from integration test
  • 7c102c3 Extract non-full expr scanner to module
  • ceaf4d6 Merge pull request #1778 from dtolnay/exprpeek
  • a890e9d Expose can_begin_expr as Expr::peek
  • 12f068c Merge pull request #1777 from dtolnay/anygroup
  • Additional commits viewable in compare view

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
--------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Oliver Tale-Yazdi Co-authored-by: Bastian Köcher Co-authored-by: Guillaume Thiolliere --- Cargo.lock | 198 +++++++++--------- Cargo.toml | 4 +- .../deprecated_where_block.stderr | 2 +- 3 files changed, 102 insertions(+), 102 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a870c0bd9d4c..6703a0250de9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -168,7 +168,7 @@ dependencies = [ "proc-macro-error", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", "syn-solidity", "tiny-keccak", ] @@ -295,7 +295,7 @@ dependencies = [ "proc-macro-error", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -753,7 +753,7 @@ checksum = "7378575ff571966e99a744addeff0bff98b8ada0dedf1956d59e634db95eaac1" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", "synstructure 0.13.1", ] @@ -776,7 +776,7 @@ checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -1385,7 +1385,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -1402,7 +1402,7 @@ checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -1617,7 +1617,7 @@ dependencies = [ "regex", "rustc-hash 1.1.0", "shlex", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -3059,7 +3059,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -3100,7 +3100,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -4443,7 +4443,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -4999,7 +4999,7 @@ checksum = "83fdaf97f4804dcebfa5862639bc9ce4121e82140bec2a987ac5140294865b5b" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5039,7 +5039,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "scratch", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5056,7 +5056,7 @@ checksum = "50c49547d73ba8dcfd4ad7325d64c6d5391ff4224d498fc39a6f3f49825a530d" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5104,7 +5104,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "strsim 0.11.1", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5126,7 +5126,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core 0.20.10", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5243,7 +5243,7 @@ checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5254,7 +5254,7 @@ checksum = "62d671cc41a825ebabc75757b62d3d168c577f9149b2d49ece1dad1f72119d25" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5265,7 +5265,7 @@ checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5373,7 +5373,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5434,7 +5434,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "regex", - "syn 2.0.82", + "syn 2.0.87", "termcolor", "toml 0.8.12", "walkdir", @@ -5666,7 +5666,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5686,7 +5686,7 @@ checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5697,7 +5697,7 @@ checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5912,7 +5912,7 @@ dependencies = [ "prettyplease", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -5995,7 +5995,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -6354,7 +6354,7 @@ dependencies = [ "quote 1.0.37", "scale-info", "sp-arithmetic 23.0.0", - "syn 2.0.82", + "syn 2.0.87", "trybuild", ] @@ -6576,7 +6576,7 @@ dependencies = [ "sp-metadata-ir 0.6.0", "sp-runtime 31.0.1", "static_assertions", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -6587,7 +6587,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -6596,7 +6596,7 @@ version = "11.0.0" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -6850,7 +6850,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -8385,7 +8385,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9139,7 +9139,7 @@ dependencies = [ "proc-macro-warning 0.4.2", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9547,7 +9547,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9561,7 +9561,7 @@ dependencies = [ "macro_magic_core_macros", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9572,7 +9572,7 @@ checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9583,7 +9583,7 @@ checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -9920,7 +9920,7 @@ dependencies = [ "cfg-if", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -10525,7 +10525,7 @@ checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -10701,7 +10701,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -11483,7 +11483,7 @@ version = "18.0.0" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -12636,7 +12636,7 @@ version = "0.1.0" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -12881,7 +12881,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "sp-runtime 31.0.1", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -13898,7 +13898,7 @@ dependencies = [ "pest_meta", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -13939,7 +13939,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16457,7 +16457,7 @@ dependencies = [ "polkavm-common 0.8.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16469,7 +16469,7 @@ dependencies = [ "polkavm-common 0.9.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16481,7 +16481,7 @@ dependencies = [ "polkavm-common 0.14.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16491,7 +16491,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15e85319a0d5129dc9f021c62607e0804f5fb777a05cdda44d750ac0732def66" dependencies = [ "polkavm-derive-impl 0.8.0", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16501,7 +16501,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ba81f7b5faac81e528eb6158a6f3c9e0bb1008e0ffa19653bc8dea925ecb429" dependencies = [ "polkavm-derive-impl 0.9.0", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16511,7 +16511,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b569754b15060d03000c09e3bf11509d527f60b75d79b4c30c3625b5071d9702" dependencies = [ "polkavm-derive-impl 0.14.0", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16728,7 +16728,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c64d9ba0963cdcea2e1b2230fbae2bab30eb25a174be395c41e764bfb65dd62" dependencies = [ "proc-macro2 1.0.86", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16838,7 +16838,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16855,7 +16855,7 @@ checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16866,7 +16866,7 @@ checksum = "9b698b0b09d40e9b7c1a47b132d66a8b54bcd20583d9b6d06e4535e383b4405c" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -16947,7 +16947,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -17029,7 +17029,7 @@ dependencies = [ "prost 0.13.2", "prost-types", "regex", - "syn 2.0.82", + "syn 2.0.87", "tempfile", ] @@ -17056,7 +17056,7 @@ dependencies = [ "itertools 0.12.1", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -17069,7 +17069,7 @@ dependencies = [ "itertools 0.12.1", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -17529,7 +17529,7 @@ checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -18149,7 +18149,7 @@ dependencies = [ "regex", "relative-path", "rustc_version 0.4.0", - "syn 2.0.82", + "syn 2.0.87", "unicode-ident", ] @@ -18690,7 +18690,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -20055,7 +20055,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -20238,7 +20238,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "scale-info", - "syn 2.0.82", + "syn 2.0.87", "thiserror", ] @@ -20517,9 +20517,9 @@ checksum = "f97841a747eef040fcd2e7b3b9a220a7205926e60488e673d9e4926d27772ce5" [[package]] name = "serde" -version = "1.0.210" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a" +checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" dependencies = [ "serde_derive", ] @@ -20554,13 +20554,13 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.210" +version = "1.0.214" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f" +checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -20662,7 +20662,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -21633,7 +21633,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -21648,7 +21648,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22258,7 +22258,7 @@ version = "0.1.0" dependencies = [ "quote 1.0.37", "sp-crypto-hashing 0.1.0", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22269,7 +22269,7 @@ checksum = "b85d0f1f1e44bd8617eb2a48203ee854981229e3e79e6f468c7175d5fd37489b" dependencies = [ "quote 1.0.37", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22287,7 +22287,7 @@ source = "git+https://github.com/paritytech/polkadot-sdk#82912acb33a9030c0ef3bf5 dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22296,7 +22296,7 @@ version = "14.0.0" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22307,7 +22307,7 @@ checksum = "48d09fa0a5f7299fb81ee25ae3853d26200f7a348148aed6de76be905c007dbe" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22869,7 +22869,7 @@ dependencies = [ "proc-macro-crate 1.3.1", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22881,7 +22881,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -22895,7 +22895,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -23370,7 +23370,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "sp-version 29.0.0", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -23382,7 +23382,7 @@ dependencies = [ "parity-scale-codec", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -23851,7 +23851,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "rustversion", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -23864,7 +23864,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "rustversion", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -24353,7 +24353,7 @@ dependencies = [ "scale-info", "scale-typegen", "subxt-metadata", - "syn 2.0.82", + "syn 2.0.87", "thiserror", "tokio", ] @@ -24416,7 +24416,7 @@ dependencies = [ "quote 1.0.37", "scale-typegen", "subxt-codegen", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -24571,9 +24571,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.82" +version = "2.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83540f837a8afc019423a8edb95b52a8effe46957ee402287f4292fae35be021" +checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -24589,7 +24589,7 @@ dependencies = [ "paste", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -24618,7 +24618,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -24748,7 +24748,7 @@ checksum = "5999e24eaa32083191ba4e425deb75cdf25efefabe5aaccb7446dd0d4122a3f5" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -24923,7 +24923,7 @@ checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -25085,7 +25085,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -25361,7 +25361,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -25403,7 +25403,7 @@ dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -26055,7 +26055,7 @@ dependencies = [ "once_cell", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", "wasm-bindgen-shared", ] @@ -26089,7 +26089,7 @@ checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -27241,7 +27241,7 @@ dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", "staging-xcm", - "syn 2.0.82", + "syn 2.0.87", "trybuild", ] @@ -27412,7 +27412,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] @@ -27432,7 +27432,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", - "syn 2.0.82", + "syn 2.0.87", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5f4d78ef3213..edfea7b8efa9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1205,7 +1205,7 @@ seccompiler = { version = "0.4.0" } secp256k1 = { version = "0.28.0", default-features = false } secrecy = { version = "0.8.0", default-features = false } separator = { version = "0.4.1" } -serde = { version = "1.0.210", default-features = false } +serde = { version = "1.0.214", default-features = false } serde-big-array = { version = "0.3.2" } serde_derive = { version = "1.0.117" } serde_json = { version = "1.0.132", default-features = false } @@ -1319,7 +1319,7 @@ substrate-test-utils = { path = "substrate/test-utils" } substrate-wasm-builder = { path = "substrate/utils/wasm-builder", default-features = false } subxt = { version = "0.37", default-features = false } subxt-signer = { version = "0.37" } -syn = { version = "2.0.82" } +syn = { version = "2.0.87" } sysinfo = { version = "0.30" } tar = { version = "0.4" } tempfile = { version = "3.8.1" } diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr b/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr index 55b19ac1a652..726b09cf54c9 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr @@ -751,7 +751,7 @@ error[E0277]: the trait bound `Runtime: Config` is not satisfied = help: the trait `Serialize` is implemented for `GenesisConfig` = note: required for `GenesisConfig` to implement `Serialize` note: required by a bound in `frame_support::sp_runtime::serde::ser::SerializeStruct::serialize_field` - --> $CARGO/serde-1.0.210/src/ser/mod.rs + --> $CARGO/serde-1.0.214/src/ser/mod.rs | | fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> | --------------- required by a bound in this associated function From 32e116a663fcc2bbc71623f690fa98e8af5d4126 Mon Sep 17 00:00:00 2001 From: Egor_P Date: Tue, 5 Nov 2024 15:32:09 +0100 Subject: [PATCH 032/166] [Release|CI/CD] adjust release pipelines (#6366) This PR contains adjustments to the release pipelines. - RC Automation and Branchoff pipelines now use the PGPKMS key generated by the release team to sign related commits directly in the Github flow - RC Automation does not use old tagging action. Instead, it creates a tag and pushes it using git - RC binary is going to be done on the larger github runners setup in the` paritytech-release` org Closes: https://github.com/paritytech/release-engineering/issues/233 --- .github/scripts/common/lib.sh | 3 +- .../workflows/release-10_rc-automation.yml | 47 ++++++++++++++++--- .../workflows/release-branchoff-stable.yml | 24 ++++++---- .github/workflows/release-build-rc.yml | 8 ++++ .../workflows/release-reusable-rc-buid.yml | 2 +- 5 files changed, 66 insertions(+), 18 deletions(-) diff --git a/.github/scripts/common/lib.sh b/.github/scripts/common/lib.sh index 56d0371d678e..e3dd6224f29b 100755 --- a/.github/scripts/common/lib.sh +++ b/.github/scripts/common/lib.sh @@ -306,9 +306,10 @@ function import_gpg_keys() { EGOR="E6FC4D4782EB0FA64A4903CCDB7D3555DD3932D3" MORGAN="2E92A9D8B15D7891363D1AE8AF9E6C43F7F8C4CF" PARITY_RELEASES="90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE" + PARITY_RELEASES_SIGN_COMMITS="D8018FBB3F534D866A45998293C5FB5F6A367B51" echo "Importing GPG keys from $GPG_KEYSERVER" - for key in $SEC $EGOR $MORGAN $PARITY_RELEASES; do + for key in $SEC $EGOR $MORGAN $PARITY_RELEASES $PARITY_RELEASES_SIGN_COMMITS; do ( echo "Importing GPG key $key" gpg --no-tty --quiet --keyserver $GPG_KEYSERVER --recv-keys $key diff --git a/.github/workflows/release-10_rc-automation.yml b/.github/workflows/release-10_rc-automation.yml index 41783f6cc721..4ec4c05252b3 100644 --- a/.github/workflows/release-10_rc-automation.yml +++ b/.github/workflows/release-10_rc-automation.yml @@ -23,12 +23,46 @@ jobs: - name: "RelEng: Polkadot Release Coordination" room: '!cqAmzdIcbOFwrdrubV:parity.io' environment: release + env: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_SIGN_COMMITS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} steps: + - name: Install pgpkkms + run: | + # Install pgpkms that is used to sign commits + pip install git+https://github.com/paritytech-release/pgpkms.git@5a8f82fbb607ea102d8c178e761659de54c7af69 + + - name: Generate content write token for the release automation + id: generate_write_token + uses: actions/create-github-app-token@v1 + with: + app-id: ${{ vars.RELEASE_AUTOMATION_APP_ID }} + private-key: ${{ secrets.RELEASE_AUTOMATION_APP_PRIVATE_KEY }} + owner: paritytech-release + - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 with: fetch-depth: 0 + token: ${{ steps.generate_write_token.outputs.token }} + + - name: Import gpg keys + run: | + . ./.github/scripts/common/lib.sh + + import_gpg_keys + + - name: Config git + run: | + git config --global commit.gpgsign true + git config --global gpg.program /home/runner/.local/bin/pgpkms-git + git config --global user.name "ParityReleases" + git config --global user.email "release-team@parity.io" + git config --global user.signingKey "D8018FBB3F534D866A45998293C5FB5F6A367B51" - name: Compute next rc tag # if: ${{ steps.get_rel_product.outputs.product == 'polkadot' }} @@ -58,13 +92,12 @@ jobs: fi - name: Apply new tag - uses: tvdias/github-tagger@ed7350546e3e503b5e942dffd65bc8751a95e49d # v0.0.2 - with: - # We can't use the normal GITHUB_TOKEN for the following reason: - # https://docs.github.com/en/actions/reference/events-that-trigger-workflows#triggering-new-workflows-using-a-personal-access-token - # RELEASE_BRANCH_TOKEN requires public_repo OAuth scope - repo-token: "${{ secrets.RELEASE_BRANCH_TOKEN }}" - tag: ${{ steps.compute_tag.outputs.new_tag }} + env: + GH_TOKEN: ${{ steps.generate_write_token.outputs.token }} + RC_TAG: ${{ steps.compute_tag.outputs.new_tag }} + run: | + git tag -s $RC_TAG -m "new rc tag $RC_TAG" + git push origin $RC_TAG - name: Send Matrix message to ${{ matrix.channel.name }} uses: s3krit/matrix-message-action@70ad3fb812ee0e45ff8999d6af11cafad11a6ecf # v0.0.3 diff --git a/.github/workflows/release-branchoff-stable.yml b/.github/workflows/release-branchoff-stable.yml index 3086c0d21f42..4249a274ffd7 100644 --- a/.github/workflows/release-branchoff-stable.yml +++ b/.github/workflows/release-branchoff-stable.yml @@ -13,13 +13,7 @@ on: required: true jobs: - check-workflow-can-run: - uses: paritytech-release/sync-workflows/.github/workflows/check-syncronization.yml@main - - prepare-tooling: - needs: [check-workflow-can-run] - if: needs.check-workflow-can-run.outputs.checks_passed == 'true' runs-on: ubuntu-latest outputs: node_version: ${{ steps.validate_inputs.outputs.node_version }} @@ -45,7 +39,7 @@ jobs: runs-on: ubuntu-latest environment: release env: - PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_KEY: ${{ secrets.PGP_KMS_SIGN_COMMITS_KEY }} PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} @@ -58,10 +52,19 @@ jobs: # Install pgpkms that is used to sign commits pip install git+https://github.com/paritytech-release/pgpkms.git@5a8f82fbb607ea102d8c178e761659de54c7af69 + - name: Generate content write token for the release automation + id: generate_write_token + uses: actions/create-github-app-token@v1 + with: + app-id: ${{ vars.RELEASE_AUTOMATION_APP_ID }} + private-key: ${{ secrets.RELEASE_AUTOMATION_APP_PRIVATE_KEY }} + owner: paritytech-release + - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 with: ref: master + token: ${{ steps.generate_write_token.outputs.token }} - name: Import gpg keys run: | @@ -69,14 +72,13 @@ jobs: import_gpg_keys - - name: Config git run: | git config --global commit.gpgsign true git config --global gpg.program /home/runner/.local/bin/pgpkms-git git config --global user.name "ParityReleases" git config --global user.email "release-team@parity.io" - git config --global user.signingKey "90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE" + git config --global user.signingKey "D8018FBB3F534D866A45998293C5FB5F6A367B51" - name: Create stable branch run: | @@ -84,6 +86,8 @@ jobs: git show-ref "$STABLE_BRANCH_NAME" - name: Bump versions, reorder prdocs and push stable branch + env: + GH_TOKEN: ${{ steps.generate_write_token.outputs.token }} run: | . ./.github/scripts/release/release_lib.sh @@ -101,4 +105,6 @@ jobs: reorder_prdocs $STABLE_BRANCH_NAME + gh auth setup-git + git push origin "$STABLE_BRANCH_NAME" diff --git a/.github/workflows/release-build-rc.yml b/.github/workflows/release-build-rc.yml index 5c25e3c749b8..94bacf320898 100644 --- a/.github/workflows/release-build-rc.yml +++ b/.github/workflows/release-build-rc.yml @@ -55,6 +55,10 @@ jobs: AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read build-polkadot-parachain-binary: needs: [validate-inputs] @@ -72,3 +76,7 @@ jobs: AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read diff --git a/.github/workflows/release-reusable-rc-buid.yml b/.github/workflows/release-reusable-rc-buid.yml index ae6c430b6d37..d76f36e95c8d 100644 --- a/.github/workflows/release-reusable-rc-buid.yml +++ b/.github/workflows/release-reusable-rc-buid.yml @@ -58,7 +58,7 @@ jobs: build-rc: needs: [set-image] - runs-on: ubuntu-latest + runs-on: ubuntu-latest-m environment: release container: image: ${{ needs.set-image.outputs.IMAGE }} From 76f297da1219b58581765e0a4cb17fea39ce16be Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Tue, 5 Nov 2024 15:41:06 +0100 Subject: [PATCH 033/166] [eth-rpc] proxy /health (#6360) make the eth-rpc proxy /health and /health/readiness from the proxied substrate chain see #4802 --------- Co-authored-by: GitHub Action --- Cargo.lock | 1 + prdoc/pr_6360.prdoc | 9 ++++ substrate/frame/revive/rpc/Cargo.toml | 1 + substrate/frame/revive/rpc/src/cli.rs | 15 ++++-- substrate/frame/revive/rpc/src/client.rs | 9 +++- substrate/frame/revive/rpc/src/lib.rs | 3 ++ substrate/frame/revive/rpc/src/rpc_health.rs | 50 ++++++++++++++++++++ 7 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 prdoc/pr_6360.prdoc create mode 100644 substrate/frame/revive/rpc/src/rpc_health.rs diff --git a/Cargo.lock b/Cargo.lock index 6703a0250de9..a8e7d7d4cdda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12562,6 +12562,7 @@ dependencies = [ "rlp 0.6.1", "sc-cli", "sc-rpc", + "sc-rpc-api", "sc-service", "scale-info", "secp256k1", diff --git a/prdoc/pr_6360.prdoc b/prdoc/pr_6360.prdoc new file mode 100644 index 000000000000..270af29e37af --- /dev/null +++ b/prdoc/pr_6360.prdoc @@ -0,0 +1,9 @@ +title: '[eth-rpc] proxy /health' +doc: +- audience: Runtime Dev + description: |- + make the eth-rpc proxy /health and /health/readiness from the proxied substrate chain + see #4802 +crates: +- name: pallet-revive-eth-rpc + bump: minor diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 56db91f920fa..8bf930240240 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -56,6 +56,7 @@ sp-core = { workspace = true, default-features = true } sp-weights = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } sc-rpc = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } sc-cli = { workspace = true, default-features = true } sc-service = { workspace = true, default-features = true } prometheus-endpoint = { workspace = true, default-features = true } diff --git a/substrate/frame/revive/rpc/src/cli.rs b/substrate/frame/revive/rpc/src/cli.rs index fcb84e6b54b0..c0f81fcafd77 100644 --- a/substrate/frame/revive/rpc/src/cli.rs +++ b/substrate/frame/revive/rpc/src/cli.rs @@ -15,7 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. //! The Ethereum JSON-RPC server. -use crate::{client::Client, EthRpcServer, EthRpcServerImpl}; +use crate::{ + client::Client, EthRpcServer, EthRpcServerImpl, SystemHealthRpcServer, + SystemHealthRpcServerImpl, +}; use clap::Parser; use futures::{pin_mut, FutureExt}; use jsonrpsee::server::RpcModule; @@ -118,7 +121,10 @@ pub fn run(cmd: CliCommand) -> anyhow::Result<()> { match tokio_handle.block_on(signals.try_until_signal(fut)) { Ok(Ok(client)) => rpc_module(is_dev, client), - Ok(Err(err)) => Err(sc_service::Error::Application(err.into())), + Ok(Err(err)) => { + log::error!("Error connecting to the node at {node_rpc_url}: {err}"); + Err(sc_service::Error::Application(err.into())) + }, Err(_) => Err(sc_service::Error::Application("Client connection interrupted".into())), } }; @@ -142,11 +148,14 @@ pub fn run(cmd: CliCommand) -> anyhow::Result<()> { /// Create the JSON-RPC module. fn rpc_module(is_dev: bool, client: Client) -> Result, sc_service::Error> { - let eth_api = EthRpcServerImpl::new(client) + let eth_api = EthRpcServerImpl::new(client.clone()) .with_accounts(if is_dev { vec![crate::Account::default()] } else { vec![] }) .into_rpc(); + let health_api = SystemHealthRpcServerImpl::new(client).into_rpc(); + let mut module = RpcModule::new(()); module.merge(eth_api).map_err(|e| sc_service::Error::Application(e.into()))?; + module.merge(health_api).map_err(|e| sc_service::Error::Application(e.into()))?; Ok(module) } diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index ba93d0af62ac..a0552189f443 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -44,7 +44,7 @@ use std::{ }; use subxt::{ backend::{ - legacy::LegacyRpcMethods, + legacy::{rpc_methods::SystemHealth, LegacyRpcMethods}, rpc::{ reconnecting_rpc_client::{Client as ReconnectingRpcClient, ExponentialBackoff}, RpcClient, @@ -192,6 +192,7 @@ impl BlockCache { } /// A client connect to a node and maintains a cache of the last `CACHE_SIZE` blocks. +#[derive(Clone)] pub struct Client { /// The inner state of the client. inner: Arc, @@ -555,6 +556,12 @@ impl Client { cache.tx_hashes_by_block_and_index.get(block_hash).map(|v| v.len()) } + /// Get the system health. + pub async fn system_health(&self) -> Result { + let health = self.inner.rpc.system_health().await?; + Ok(health) + } + /// Get the balance of the given address. pub async fn balance( &self, diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index a6d47063ef90..88a3cb641784 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -35,6 +35,9 @@ pub mod subxt_client; #[cfg(test)] mod tests; +mod rpc_health; +pub use rpc_health::*; + mod rpc_methods_gen; pub use rpc_methods_gen::*; diff --git a/substrate/frame/revive/rpc/src/rpc_health.rs b/substrate/frame/revive/rpc/src/rpc_health.rs new file mode 100644 index 000000000000..f94d4b82a80f --- /dev/null +++ b/substrate/frame/revive/rpc/src/rpc_health.rs @@ -0,0 +1,50 @@ +// 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. +//! Heatlh JSON-RPC methods. + +use super::*; +use jsonrpsee::{core::RpcResult, proc_macros::rpc}; +use sc_rpc_api::system::helpers::Health; + +#[rpc(server, client)] +pub trait SystemHealthRpc { + /// Proxy the substrate chain system_health RPC call. + #[method(name = "system_health")] + async fn system_health(&self) -> RpcResult; +} + +pub struct SystemHealthRpcServerImpl { + client: client::Client, +} + +impl SystemHealthRpcServerImpl { + pub fn new(client: client::Client) -> Self { + Self { client } + } +} + +#[async_trait] +impl SystemHealthRpcServer for SystemHealthRpcServerImpl { + async fn system_health(&self) -> RpcResult { + let health = self.client.system_health().await?; + Ok(Health { + peers: health.peers, + is_syncing: health.is_syncing, + should_have_peers: health.should_have_peers, + }) + } +} From 6f078d183bd689a1ae460fffafee635f2f30c98a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Thei=C3=9Fen?= Date: Tue, 5 Nov 2024 17:16:09 +0100 Subject: [PATCH 034/166] pallet-revive: Use `RUSTUP_TOOLCHAIN` if set (#6365) We were not passing through the `RUSTUP_TOOLCHAIN` variable to the `build.rs` script of our fixtures. This means that setting the toolchain like `cargo +1.81 build` had no effect on the fixture build. It would always fall back to the default toolchain. --------- Co-authored-by: GitHub Action --- prdoc/pr_6365.prdoc | 10 ++++++++++ substrate/frame/revive/fixtures/build.rs | 5 +++-- 2 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 prdoc/pr_6365.prdoc diff --git a/prdoc/pr_6365.prdoc b/prdoc/pr_6365.prdoc new file mode 100644 index 000000000000..b99a7ae4035e --- /dev/null +++ b/prdoc/pr_6365.prdoc @@ -0,0 +1,10 @@ +title: 'pallet-revive: Use `RUSTUP_TOOLCHAIN` if set' +doc: +- audience: Runtime Dev + description: We were not passing through the `RUSTUP_TOOLCHAIN` variable to the + `build.rs` script of our fixtures. This means that setting the toolchain like + `cargo +1.81 build` had no effect on the fixture build. It would always fall back + to the default toolchain. +crates: +- name: pallet-revive-fixtures + bump: major diff --git a/substrate/frame/revive/fixtures/build.rs b/substrate/frame/revive/fixtures/build.rs index bbd986d9d44c..a5b23e58c0d6 100644 --- a/substrate/frame/revive/fixtures/build.rs +++ b/substrate/frame/revive/fixtures/build.rs @@ -120,6 +120,7 @@ fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) .env("RUSTC_BOOTSTRAP", "1") .env("RUSTUP_HOME", env::var("RUSTUP_HOME").unwrap_or_default()) + .env("RUSTUP_TOOLCHAIN", env::var("RUSTUP_TOOLCHAIN").unwrap_or_default()) .args([ "build", "--release", @@ -147,8 +148,8 @@ fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { /// Post-process the compiled code. fn post_process(input_path: &Path, output_path: &Path) -> Result<()> { - let strip = std::env::var(OVERRIDE_STRIP_ENV_VAR).map_or(false, |value| value == "1"); - let optimize = std::env::var(OVERRIDE_OPTIMIZE_ENV_VAR).map_or(true, |value| value == "1"); + let strip = env::var(OVERRIDE_STRIP_ENV_VAR).map_or(false, |value| value == "1"); + let optimize = env::var(OVERRIDE_OPTIMIZE_ENV_VAR).map_or(true, |value| value == "1"); let mut config = polkavm_linker::Config::default(); config.set_strip(strip); From 8b6c6eb278726624708696690405502d81809537 Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Wed, 6 Nov 2024 01:36:45 +0800 Subject: [PATCH 035/166] Migrate pallet-im-online benchmark to v2 (#6295) Part of: - #6202. --------- Co-authored-by: GitHub Action Co-authored-by: Giuseppe Re --- prdoc/pr_6295.prdoc | 10 +++ substrate/frame/im-online/src/benchmarking.rs | 65 ++++++++++++------- 2 files changed, 52 insertions(+), 23 deletions(-) create mode 100644 prdoc/pr_6295.prdoc diff --git a/prdoc/pr_6295.prdoc b/prdoc/pr_6295.prdoc new file mode 100644 index 000000000000..c7e4282208ee --- /dev/null +++ b/prdoc/pr_6295.prdoc @@ -0,0 +1,10 @@ +title: Migrate pallet-im-online benchmark to v2 +doc: +- audience: Runtime Dev + description: |- + Part of: + + - #6202. +crates: +- name: pallet-im-online + bump: patch diff --git a/substrate/frame/im-online/src/benchmarking.rs b/substrate/frame/im-online/src/benchmarking.rs index d8170d4817e3..439720bcab38 100644 --- a/substrate/frame/im-online/src/benchmarking.rs +++ b/substrate/frame/im-online/src/benchmarking.rs @@ -19,9 +19,7 @@ #![cfg(feature = "runtime-benchmarks")] -use super::*; - -use frame_benchmarking::v1::benchmarks; +use frame_benchmarking::v2::*; use frame_support::{traits::UnfilteredDispatchable, WeakBoundedVec}; use frame_system::RawOrigin; use sp_runtime::{ @@ -29,7 +27,7 @@ use sp_runtime::{ transaction_validity::TransactionSource, }; -use crate::Pallet as ImOnline; +use crate::*; const MAX_KEYS: u32 = 1000; @@ -64,34 +62,55 @@ pub fn create_heartbeat( Ok((input_heartbeat, signature)) } -benchmarks! { - #[extra] - heartbeat { - let k in 1 .. MAX_KEYS; +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark(extra)] + fn heartbeat(k: Linear<1, MAX_KEYS>) -> Result<(), BenchmarkError> { let (input_heartbeat, signature) = create_heartbeat::(k)?; - }: _(RawOrigin::None, input_heartbeat, signature) - #[extra] - validate_unsigned { - let k in 1 .. MAX_KEYS; + #[extrinsic_call] + _(RawOrigin::None, input_heartbeat, signature); + + Ok(()) + } + + #[benchmark(extra)] + fn validate_unsigned(k: Linear<1, MAX_KEYS>) -> Result<(), BenchmarkError> { let (input_heartbeat, signature) = create_heartbeat::(k)?; let call = Call::heartbeat { heartbeat: input_heartbeat, signature }; - }: { - ImOnline::::validate_unsigned(TransactionSource::InBlock, &call) - .map_err(<&str>::from)?; + + #[block] + { + Pallet::::validate_unsigned(TransactionSource::InBlock, &call) + .map_err(<&str>::from)?; + } + + Ok(()) } - validate_unsigned_and_then_heartbeat { - let k in 1 .. MAX_KEYS; + #[benchmark] + fn validate_unsigned_and_then_heartbeat(k: Linear<1, MAX_KEYS>) -> Result<(), BenchmarkError> { let (input_heartbeat, signature) = create_heartbeat::(k)?; let call = Call::heartbeat { heartbeat: input_heartbeat, signature }; let call_enc = call.encode(); - }: { - ImOnline::::validate_unsigned(TransactionSource::InBlock, &call).map_err(<&str>::from)?; - as Decode>::decode(&mut &*call_enc) - .expect("call is encoded above, encoding must be correct") - .dispatch_bypass_filter(RawOrigin::None.into())?; + + #[block] + { + Pallet::::validate_unsigned(TransactionSource::InBlock, &call) + .map_err(<&str>::from)?; + as Decode>::decode(&mut &*call_enc) + .expect("call is encoded above, encoding must be correct") + .dispatch_bypass_filter(RawOrigin::None.into())?; + } + + Ok(()) } - impl_benchmark_test_suite!(ImOnline, crate::mock::new_test_ext(), crate::mock::Runtime); + impl_benchmark_test_suite! { + Pallet, + mock::new_test_ext(), + mock::Runtime + } } From 52a7325e0e8f46a7914f7a868bd4b9b00f54f6c2 Mon Sep 17 00:00:00 2001 From: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Date: Tue, 5 Nov 2024 19:52:17 +0200 Subject: [PATCH 036/166] Fix statement distribution benchmark (#6369) I've broken this test with https://github.com/paritytech/polkadot-sdk/pull/5883 and this is the fix. The benchmark is now updated to use proper core index and session index for the generated candidates. TODO: - [ ] PRDoc --------- Signed-off-by: Andrei Sandu --- .../src/lib/availability/mod.rs | 6 +-- .../src/lib/availability/test_state.rs | 4 +- .../src/lib/mock/runtime_api.rs | 40 ++++++++++++++++--- .../src/lib/statement/test_state.rs | 14 +++++-- 4 files changed, 48 insertions(+), 16 deletions(-) diff --git a/polkadot/node/subsystem-bench/src/lib/availability/mod.rs b/polkadot/node/subsystem-bench/src/lib/availability/mod.rs index 8ac9796acb62..23dc6bd1caf9 100644 --- a/polkadot/node/subsystem-bench/src/lib/availability/mod.rs +++ b/polkadot/node/subsystem-bench/src/lib/availability/mod.rs @@ -22,9 +22,7 @@ use crate::{ av_store::{MockAvailabilityStore, NetworkAvailabilityState}, chain_api::{ChainApiState, MockChainApi}, network_bridge::{self, MockNetworkBridgeRx, MockNetworkBridgeTx}, - runtime_api::{ - node_features_with_chunk_mapping_enabled, MockRuntimeApi, MockRuntimeApiCoreState, - }, + runtime_api::{default_node_features, MockRuntimeApi, MockRuntimeApiCoreState}, AlwaysSupportsParachains, }, network::new_network, @@ -394,7 +392,7 @@ pub async fn benchmark_availability_write( expected_erasure_root: backed_candidate.descriptor().erasure_root(), tx, core_index: CoreIndex(core_index as u32), - node_features: node_features_with_chunk_mapping_enabled(), + node_features: default_node_features(), }, )) .await; diff --git a/polkadot/node/subsystem-bench/src/lib/availability/test_state.rs b/polkadot/node/subsystem-bench/src/lib/availability/test_state.rs index 511795970e6c..764572ffe192 100644 --- a/polkadot/node/subsystem-bench/src/lib/availability/test_state.rs +++ b/polkadot/node/subsystem-bench/src/lib/availability/test_state.rs @@ -17,7 +17,7 @@ use crate::{ configuration::{TestAuthorities, TestConfiguration}, environment::GENESIS_HASH, - mock::runtime_api::node_features_with_chunk_mapping_enabled, + mock::runtime_api::default_node_features, }; use bitvec::bitvec; use codec::Encode; @@ -118,7 +118,7 @@ impl TestState { test_state.chunk_indices = (0..config.n_cores) .map(|core_index| { availability_chunk_indices( - Some(&node_features_with_chunk_mapping_enabled()), + Some(&default_node_features()), config.n_validators, CoreIndex(core_index as u32), ) diff --git a/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs b/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs index 6c54d14448a1..69e838eb864e 100644 --- a/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs +++ b/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs @@ -28,12 +28,13 @@ use polkadot_node_subsystem_types::OverseerSignal; use polkadot_primitives::{ node_features, vstaging::{CandidateEvent, CandidateReceiptV2 as CandidateReceipt, CoreState, OccupiedCore}, - ApprovalVotingParams, AsyncBackingParams, GroupIndex, GroupRotationInfo, IndexedVec, - NodeFeatures, ScheduledCore, SessionIndex, SessionInfo, ValidationCode, ValidatorIndex, + ApprovalVotingParams, AsyncBackingParams, CoreIndex, GroupIndex, GroupRotationInfo, + Id as ParaId, IndexedVec, NodeFeatures, ScheduledCore, SessionIndex, SessionInfo, + ValidationCode, ValidatorIndex, }; use sp_consensus_babe::Epoch as BabeEpoch; use sp_core::H256; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap, VecDeque}; const LOG_TARGET: &str = "subsystem-bench::runtime-api-mock"; @@ -51,6 +52,8 @@ pub struct RuntimeApiState { babe_epoch: Option, // The session child index, session_index: SessionIndex, + // The claim queue + claim_queue: BTreeMap>, } #[derive(Clone)] @@ -80,7 +83,25 @@ impl MockRuntimeApi { core_state: MockRuntimeApiCoreState, ) -> MockRuntimeApi { // Enable chunk mapping feature to make systematic av-recovery possible. - let node_features = node_features_with_chunk_mapping_enabled(); + let node_features = default_node_features(); + let validator_group_count = + session_info_for_peers(&config, &authorities).validator_groups.len(); + + // Each para gets one core assigned and there is only one candidate per + // parachain per relay chain block (no elastic scaling). + let claim_queue = candidate_hashes + .iter() + .next() + .expect("Candidates are generated at test start") + .1 + .iter() + .enumerate() + .map(|(index, candidate_receipt)| { + // Ensure test breaks if badly configured. + assert!(index < validator_group_count); + (CoreIndex(index as u32), vec![candidate_receipt.descriptor.para_id()].into()) + }) + .collect(); Self { state: RuntimeApiState { @@ -90,6 +111,7 @@ impl MockRuntimeApi { babe_epoch, session_index, node_features, + claim_queue, }, config, core_state, @@ -305,6 +327,9 @@ impl MockRuntimeApi { if let Err(err) = tx.send(Ok(ApprovalVotingParams::default())) { gum::error!(target: LOG_TARGET, ?err, "Voting params weren't received"); }, + RuntimeApiMessage::Request(_parent, RuntimeApiRequest::ClaimQueue(tx)) => { + tx.send(Ok(self.state.claim_queue.clone())).unwrap(); + }, // Long term TODO: implement more as needed. message => { unimplemented!("Unexpected runtime-api message: {:?}", message) @@ -316,9 +341,12 @@ impl MockRuntimeApi { } } -pub fn node_features_with_chunk_mapping_enabled() -> NodeFeatures { +pub fn default_node_features() -> NodeFeatures { let mut node_features = NodeFeatures::new(); - node_features.resize(node_features::FeatureIndex::AvailabilityChunkMapping as usize + 1, false); + node_features.resize(node_features::FeatureIndex::FirstUnassigned as usize, false); node_features.set(node_features::FeatureIndex::AvailabilityChunkMapping as u8 as usize, true); + node_features.set(node_features::FeatureIndex::ElasticScalingMVP as u8 as usize, true); + node_features.set(node_features::FeatureIndex::CandidateReceiptV2 as u8 as usize, true); + node_features } diff --git a/polkadot/node/subsystem-bench/src/lib/statement/test_state.rs b/polkadot/node/subsystem-bench/src/lib/statement/test_state.rs index 2d2e9434b767..e9b586522d2b 100644 --- a/polkadot/node/subsystem-bench/src/lib/statement/test_state.rs +++ b/polkadot/node/subsystem-bench/src/lib/statement/test_state.rs @@ -45,8 +45,9 @@ use polkadot_primitives::{ CandidateReceiptV2 as CandidateReceipt, CommittedCandidateReceiptV2 as CommittedCandidateReceipt, MutateDescriptorV2, }, - BlockNumber, CandidateHash, CompactStatement, Hash, Header, Id, PersistedValidationData, - SessionInfo, SignedStatement, SigningContext, UncheckedSigned, ValidatorIndex, ValidatorPair, + BlockNumber, CandidateHash, CompactStatement, CoreIndex, Hash, Header, Id, + PersistedValidationData, SessionInfo, SignedStatement, SigningContext, UncheckedSigned, + ValidatorIndex, ValidatorPair, }; use polkadot_primitives_test_helpers::{ dummy_committed_candidate_receipt_v2, dummy_hash, dummy_head_data, dummy_pvd, @@ -61,6 +62,8 @@ use std::{ }, }; +const SESSION_INDEX: u32 = 0; + #[derive(Clone)] pub struct TestState { // Full test config @@ -130,6 +133,8 @@ impl TestState { let mut receipt = receipt_templates[candidate_index].clone(); receipt.descriptor.set_para_id(Id::new(core_idx as u32 + 1)); receipt.descriptor.set_relay_parent(block_info.hash); + receipt.descriptor.set_core_index(CoreIndex(core_idx as u32)); + receipt.descriptor.set_session_index(SESSION_INDEX); state.candidate_receipts.entry(block_info.hash).or_default().push( CandidateReceipt { @@ -193,7 +198,7 @@ fn sign_statement( validator_index: ValidatorIndex, pair: &ValidatorPair, ) -> UncheckedSigned { - let context = SigningContext { parent_hash: relay_parent, session_index: 0 }; + let context = SigningContext { parent_hash: relay_parent, session_index: SESSION_INDEX }; let payload = statement.signing_payload(&context); SignedStatement::new( @@ -320,7 +325,8 @@ impl HandleNetworkMessage for TestState { } let statement = CompactStatement::Valid(candidate_hash); - let context = SigningContext { parent_hash: relay_parent, session_index: 0 }; + let context = + SigningContext { parent_hash: relay_parent, session_index: SESSION_INDEX }; let payload = statement.signing_payload(&context); let pair = self.test_authorities.validator_pairs.get(index).unwrap(); let signature = pair.sign(&payload[..]); From c5444f381fdba68aa9cb73b39cc63f34604da156 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Tue, 5 Nov 2024 23:32:31 +0200 Subject: [PATCH 037/166] Remove `sp_runtime::RuntimeString` and replace with `Cow<'static, str>` or `String` depending on use case (#5693) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description As described in https://github.com/paritytech/polkadot-sdk/issues/4001 `RuntimeVersion` was not encoded consistently using serde. Turned out it was a remnant of old times and no longer actually needed. As such I removed it completely in this PR and replaced with `Cow<'static, str>` for spec/impl names and `String` for error cases. Fixes https://github.com/paritytech/polkadot-sdk/issues/4001. ## Integration For downstream projects the upgrade will primarily consist of following two changes: ```diff #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("statemine"), - impl_name: create_runtime_str!("statemine"), + spec_name: alloc::borrow::Cow::Borrowed("statemine"), + impl_name: alloc::borrow::Cow::Borrowed("statemine"), ``` ```diff fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { ``` SCALE encoding/decoding remains the same as before, but serde encoding in runtime has changed from bytes to string (it was like this in `std` environment already), which most projects shouldn't have issues with. I consider the impact of serde encoding here low due to the type only being used in runtime version struct and mostly limited to runtime internals, where serde encoding/decoding of this data structure is quite unlikely (though we did hit exactly this edge-case ourselves :sweat_smile:). ## Review Notes Most of the changes are trivial and mechanical, the only non-trivial change is in `substrate/primitives/version/proc-macro/src/decl_runtime_version.rs` where macro call expectation in `sp_version::runtime_version` implementation was replaced with function call expectation. # Checklist * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. * [ ] My PR follows the [labeling requirements]( https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process ) of this project (at minimum one label for `T` required) * External contributors: ask maintainers to put the right label on your PR. * [ ] I have made corresponding changes to the documentation (if applicable) --------- Co-authored-by: GitHub Action Co-authored-by: Guillaume Thiolliere Co-authored-by: Bastian Köcher --- cumulus/client/network/src/tests.rs | 4 +- cumulus/client/pov-recovery/src/tests.rs | 4 +- cumulus/pallets/parachain-system/src/mock.rs | 4 +- .../src/genesis_config_presets.rs | 8 +- .../assets/asset-hub-rococo/src/lib.rs | 8 +- .../src/genesis_config_presets.rs | 8 +- .../assets/asset-hub-westend/src/lib.rs | 8 +- .../src/genesis_config_presets.rs | 6 +- .../bridge-hubs/bridge-hub-rococo/src/lib.rs | 8 +- .../src/genesis_config_presets.rs | 6 +- .../bridge-hubs/bridge-hub-westend/src/lib.rs | 8 +- .../src/genesis_config_presets.rs | 6 +- .../collectives-westend/src/lib.rs | 8 +- .../contracts/contracts-rococo/src/lib.rs | 8 +- .../coretime/coretime-rococo/src/lib.rs | 8 +- .../coretime/coretime-westend/src/lib.rs | 8 +- .../glutton/glutton-westend/src/lib.rs | 8 +- .../runtimes/people/people-rococo/src/lib.rs | 8 +- .../runtimes/people/people-westend/src/lib.rs | 8 +- .../runtimes/testing/penpal/src/lib.rs | 8 +- .../testing/rococo-parachain/src/lib.rs | 6 +- .../lib/src/fake_runtime_api/utils.rs | 2 +- .../runtime/src/genesis_config_presets.rs | 6 +- cumulus/test/runtime/src/lib.rs | 10 +- .../packages/guides/first-runtime/src/lib.rs | 8 +- .../chain_spec_runtime/src/presets.rs | 12 +- .../chain_spec_runtime/src/runtime.rs | 4 +- .../rococo/src/genesis_config_presets.rs | 10 +- polkadot/runtime/rococo/src/lib.rs | 8 +- polkadot/runtime/test-runtime/src/lib.rs | 5 +- .../westend/src/genesis_config_presets.rs | 8 +- polkadot/runtime/westend/src/lib.rs | 8 +- prdoc/pr_5693.prdoc | 84 +++++++++ substrate/bin/node/runtime/src/lib.rs | 7 +- .../bin/utils/chain-spec-builder/src/lib.rs | 10 -- substrate/client/consensus/pow/src/lib.rs | 3 +- substrate/client/executor/src/wasm_runtime.rs | 8 +- substrate/frame/benchmarking/src/utils.rs | 2 +- substrate/frame/benchmarking/src/v1.rs | 4 +- substrate/frame/revive/src/evm/runtime.rs | 2 +- substrate/frame/src/lib.rs | 5 +- .../support/src/genesis_builder_helper.rs | 9 +- .../support/test/compile_pass/src/lib.rs | 8 +- substrate/frame/system/src/lib.rs | 12 +- substrate/frame/system/src/mock.rs | 4 +- substrate/primitives/api/src/lib.rs | 8 +- .../primitives/genesis-builder/src/lib.rs | 6 +- substrate/primitives/runtime/src/lib.rs | 24 ++- .../primitives/runtime/src/runtime_string.rs | 168 ------------------ .../proc-macro/src/decl_runtime_version.rs | 52 ++++-- substrate/primitives/version/src/lib.rs | 19 +- substrate/test-utils/runtime/src/lib.rs | 33 ++-- templates/minimal/runtime/src/lib.rs | 8 +- templates/parachain/runtime/src/apis.rs | 2 +- .../runtime/src/genesis_config_presets.rs | 6 +- templates/parachain/runtime/src/lib.rs | 6 +- templates/solochain/runtime/src/apis.rs | 2 +- .../runtime/src/genesis_config_presets.rs | 6 +- templates/solochain/runtime/src/lib.rs | 6 +- 59 files changed, 339 insertions(+), 394 deletions(-) create mode 100644 prdoc/pr_5693.prdoc delete mode 100644 substrate/primitives/runtime/src/runtime_string.rs diff --git a/cumulus/client/network/src/tests.rs b/cumulus/client/network/src/tests.rs index 009f922008b1..cccb710bf18f 100644 --- a/cumulus/client/network/src/tests.rs +++ b/cumulus/client/network/src/tests.rs @@ -321,8 +321,8 @@ impl RelayChainInterface for DummyRelayChainInterface { .to_vec(); Ok(RuntimeVersion { - spec_name: sp_version::create_runtime_str!("test"), - impl_name: sp_version::create_runtime_str!("test"), + spec_name: Cow::Borrowed("test"), + impl_name: Cow::Borrowed("test"), authoring_version: 1, spec_version: 1, impl_version: 0, diff --git a/cumulus/client/pov-recovery/src/tests.rs b/cumulus/client/pov-recovery/src/tests.rs index d528a92a52a8..91b462e06bf8 100644 --- a/cumulus/client/pov-recovery/src/tests.rs +++ b/cumulus/client/pov-recovery/src/tests.rs @@ -322,8 +322,8 @@ impl RelayChainInterface for Relaychain { .to_vec(); Ok(RuntimeVersion { - spec_name: sp_version::create_runtime_str!("test"), - impl_name: sp_version::create_runtime_str!("test"), + spec_name: Cow::Borrowed("test"), + impl_name: Cow::Borrowed("test"), authoring_version: 1, spec_version: 1, impl_version: 0, diff --git a/cumulus/pallets/parachain-system/src/mock.rs b/cumulus/pallets/parachain-system/src/mock.rs index 1f5e4f4dbcf3..5b59be0482e7 100644 --- a/cumulus/pallets/parachain-system/src/mock.rs +++ b/cumulus/pallets/parachain-system/src/mock.rs @@ -57,8 +57,8 @@ frame_support::construct_runtime!( parameter_types! { pub Version: RuntimeVersion = RuntimeVersion { - spec_name: sp_version::create_runtime_str!("test"), - impl_name: sp_version::create_runtime_str!("system-test"), + spec_name: alloc::borrow::Cow::Borrowed("test"), + impl_name: alloc::borrow::Cow::Borrowed("system-test"), authoring_version: 1, spec_version: 1, impl_version: 1, diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/genesis_config_presets.rs index d15dd971a819..d58d2f6d5f4d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/genesis_config_presets.rs @@ -67,8 +67,8 @@ mod preset_names { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { use preset_names::*; - let patch = match id.try_into() { - Ok(PRESET_GENESIS) => asset_hub_rococo_genesis( + let patch = match id.as_ref() { + PRESET_GENESIS => asset_hub_rococo_genesis( // initial collators. vec![ // E8XC6rTJRsioKCp6KMy6zd24ykj4gWsusZ3AkSeyavpVBAG @@ -100,7 +100,7 @@ pub fn get_preset(id: &PresetId) -> Option> { ASSET_HUB_ROCOCO_ED * 524_288, 1000.into(), ), - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => asset_hub_rococo_genesis( + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => asset_hub_rococo_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), @@ -110,7 +110,7 @@ pub fn get_preset(id: &PresetId) -> Option> { testnet_parachains_constants::rococo::currency::UNITS * 1_000_000, 1000.into(), ), - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => asset_hub_rococo_genesis( + sp_genesis_builder::DEV_RUNTIME_PRESET => asset_hub_rococo_genesis( // initial collators. vec![(Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into())], vec![ diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index 420fa67f41f3..474434448bb9 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -42,7 +42,7 @@ use cumulus_primitives_core::{AggregateMessageOrigin, ClaimQueueOffset, CoreSele use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, Saturating, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Permill, @@ -120,8 +120,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("statemine"), - impl_name: create_runtime_str!("statemine"), + spec_name: alloc::borrow::Cow::Borrowed("statemine"), + impl_name: alloc::borrow::Cow::Borrowed("statemine"), authoring_version: 1, spec_version: 1_016_002, impl_version: 0, @@ -1556,7 +1556,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs index 758ce3f40609..f440b5a2f421 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs @@ -76,8 +76,8 @@ mod preset_names { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { use preset_names::*; - let patch = match id.try_into() { - Ok(PRESET_GENESIS) => asset_hub_westend_genesis( + let patch = match id.as_ref() { + PRESET_GENESIS => asset_hub_westend_genesis( // initial collators. vec![ ( @@ -105,7 +105,7 @@ pub fn get_preset(id: &PresetId) -> Option> { ASSET_HUB_WESTEND_ED * 4096, 1000.into(), ), - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => asset_hub_westend_genesis( + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => asset_hub_westend_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), @@ -115,7 +115,7 @@ pub fn get_preset(id: &PresetId) -> Option> { WND * 1_000_000, 1000.into(), ), - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => asset_hub_westend_genesis( + sp_genesis_builder::DEV_RUNTIME_PRESET => asset_hub_westend_genesis( // initial collators. vec![(Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into())], vec![ 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 baa3aad95fda..7261680677d4 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -70,7 +70,7 @@ use parachains_common::{ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, Saturating, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug, @@ -124,8 +124,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { // Note: "westmint" is the legacy name for this chain. It has been renamed to // "asset-hub-westend". Many wallets/tools depend on the `spec_name`, so it remains "westmint" // for the time being. Wallets/tools should update to treat "asset-hub-westend" equally. - spec_name: create_runtime_str!("westmint"), - impl_name: create_runtime_str!("westmint"), + spec_name: alloc::borrow::Cow::Borrowed("westmint"), + impl_name: alloc::borrow::Cow::Borrowed("westmint"), authoring_version: 1, spec_version: 1_016_004, impl_version: 0, @@ -1736,7 +1736,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs index d1b599967bf3..8b749ae301b5 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs @@ -89,8 +89,8 @@ fn bridge_hub_rococo_genesis( /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => bridge_hub_rococo_genesis( + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => bridge_hub_rococo_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), @@ -106,7 +106,7 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option bridge_hub_rococo_genesis( + sp_genesis_builder::DEV_RUNTIME_PRESET => bridge_hub_rococo_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index f63e1f8fcf65..9a44dd17b646 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -47,7 +47,7 @@ use pallet_bridge_messages::LaneIdOf; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::Block as BlockT, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -235,8 +235,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("bridge-hub-rococo"), - impl_name: create_runtime_str!("bridge-hub-rococo"), + spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"), + impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-rococo"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -1070,7 +1070,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs index 2949ae01fdcc..e639b899149a 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs @@ -89,8 +89,8 @@ fn bridge_hub_westend_genesis( /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => bridge_hub_westend_genesis( + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => bridge_hub_westend_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), @@ -106,7 +106,7 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option bridge_hub_westend_genesis( + sp_genesis_builder::DEV_RUNTIME_PRESET => bridge_hub_westend_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs index 1d7cd5de40eb..7c71f30b356b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs @@ -45,7 +45,7 @@ use cumulus_primitives_core::{ClaimQueueOffset, CoreSelector, ParaId}; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::Block as BlockT, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -220,8 +220,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("bridge-hub-westend"), - impl_name: create_runtime_str!("bridge-hub-westend"), + spec_name: alloc::borrow::Cow::Borrowed("bridge-hub-westend"), + impl_name: alloc::borrow::Cow::Borrowed("bridge-hub-westend"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -955,7 +955,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs index aec8e96cedc0..77e971ff8ad7 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs @@ -69,8 +69,8 @@ fn collectives_westend_genesis( /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => collectives_westend_genesis( + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => collectives_westend_genesis( // initial collators. vec![ (Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into()), @@ -79,7 +79,7 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option collectives_westend_genesis( + sp_genesis_builder::DEV_RUNTIME_PRESET => collectives_westend_genesis( // initial collators. vec![(Sr25519Keyring::Alice.to_account_id(), Sr25519Keyring::Alice.public().into())], vec![ diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index 8cb2e42cb31b..c3e105a84fb6 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -56,7 +56,7 @@ use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp}; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{AccountIdConversion, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, @@ -123,8 +123,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("collectives-westend"), - impl_name: create_runtime_str!("collectives-westend"), + spec_name: alloc::borrow::Cow::Borrowed("collectives-westend"), + impl_name: alloc::borrow::Cow::Borrowed("collectives-westend"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -1061,7 +1061,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index 2fc3fe4f3141..f661a8bdccfe 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -37,7 +37,7 @@ use cumulus_primitives_core::{AggregateMessageOrigin, ClaimQueueOffset, CoreSele use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::Block as BlockT, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, @@ -141,8 +141,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("contracts-rococo"), - impl_name: create_runtime_str!("contracts-rococo"), + spec_name: alloc::borrow::Cow::Borrowed("contracts-rococo"), + impl_name: alloc::borrow::Cow::Borrowed("contracts-rococo"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -772,7 +772,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index f2ccb9c552e3..a4ff48bfc0a0 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -67,7 +67,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, RuntimeDebug, @@ -146,8 +146,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("coretime-rococo"), - impl_name: create_runtime_str!("coretime-rococo"), + spec_name: alloc::borrow::Cow::Borrowed("coretime-rococo"), + impl_name: alloc::borrow::Cow::Borrowed("coretime-rococo"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -918,7 +918,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index 2f944e79fe00..edede5aeb46b 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -67,7 +67,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, RuntimeDebug, @@ -146,8 +146,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("coretime-westend"), - impl_name: create_runtime_str!("coretime-westend"), + spec_name: alloc::borrow::Cow::Borrowed("coretime-westend"), + impl_name: alloc::borrow::Cow::Borrowed("coretime-westend"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -910,7 +910,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs index ad656cdbb83a..fdf467ab64b8 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs @@ -55,7 +55,7 @@ use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -99,8 +99,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("glutton-westend"), - impl_name: create_runtime_str!("glutton-westend"), + spec_name: alloc::borrow::Cow::Borrowed("glutton-westend"), + impl_name: alloc::borrow::Cow::Borrowed("glutton-westend"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -460,7 +460,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs index bb290c0af97d..25356a84806d 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs @@ -58,7 +58,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -134,8 +134,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("people-rococo"), - impl_name: create_runtime_str!("people-rococo"), + spec_name: alloc::borrow::Cow::Borrowed("people-rococo"), + impl_name: alloc::borrow::Cow::Borrowed("people-rococo"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -886,7 +886,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs index 7a586504badb..1c5183636c49 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs @@ -58,7 +58,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -133,8 +133,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("people-westend"), - impl_name: create_runtime_str!("people-westend"), + spec_name: alloc::borrow::Cow::Borrowed("people-westend"), + impl_name: alloc::borrow::Cow::Borrowed("people-westend"), authoring_version: 1, spec_version: 1_016_001, impl_version: 0, @@ -884,7 +884,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index 136592c56026..6c9e3f7f23a5 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -73,7 +73,7 @@ use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Dispatchable}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -242,8 +242,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("penpal-parachain"), - impl_name: create_runtime_str!("penpal-parachain"), + spec_name: alloc::borrow::Cow::Borrowed("penpal-parachain"), + impl_name: alloc::borrow::Cow::Borrowed("penpal-parachain"), authoring_version: 1, spec_version: 1, impl_version: 0, @@ -1117,7 +1117,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{Benchmarking, BenchmarkBatch}; use sp_storage::TrackedStorageKey; diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 34bd45b6ef99..095f571974f0 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -30,7 +30,7 @@ use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::OpaqueMetadata; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, Hash as HashT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, @@ -106,8 +106,8 @@ impl_opaque_keys! { /// This runtime version. #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("test-parachain"), - impl_name: create_runtime_str!("test-parachain"), + spec_name: alloc::borrow::Cow::Borrowed("test-parachain"), + impl_name: alloc::borrow::Cow::Borrowed("test-parachain"), authoring_version: 1, spec_version: 1_014_000, impl_version: 0, diff --git a/cumulus/polkadot-omni-node/lib/src/fake_runtime_api/utils.rs b/cumulus/polkadot-omni-node/lib/src/fake_runtime_api/utils.rs index 0b1ed5d82889..6bfd5f4f4cbd 100644 --- a/cumulus/polkadot-omni-node/lib/src/fake_runtime_api/utils.rs +++ b/cumulus/polkadot-omni-node/lib/src/fake_runtime_api/utils.rs @@ -202,7 +202,7 @@ macro_rules! impl_node_runtime_apis { fn dispatch_benchmark( _: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, String> { unimplemented!() } } diff --git a/cumulus/test/runtime/src/genesis_config_presets.rs b/cumulus/test/runtime/src/genesis_config_presets.rs index 6cf56ef5363f..84ba71ae795f 100644 --- a/cumulus/test/runtime/src/genesis_config_presets.rs +++ b/cumulus/test/runtime/src/genesis_config_presets.rs @@ -58,9 +58,9 @@ pub fn preset_names() -> Vec { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) | - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => + let patch = match id.as_ref() { + sp_genesis_builder::DEV_RUNTIME_PRESET | + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => testnet_genesis_with_default_endowed(100.into()), _ => return None, }; diff --git a/cumulus/test/runtime/src/lib.rs b/cumulus/test/runtime/src/lib.rs index 01c1571f343f..b1649c410581 100644 --- a/cumulus/test/runtime/src/lib.rs +++ b/cumulus/test/runtime/src/lib.rs @@ -45,7 +45,7 @@ use sp_core::{ConstBool, ConstU32, ConstU64, OpaqueMetadata}; use cumulus_primitives_core::{ClaimQueueOffset, CoreSelector}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, MultiAddress, MultiSignature, @@ -126,8 +126,8 @@ const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; #[cfg(not(feature = "increment-spec-version"))] #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("cumulus-test-parachain"), - impl_name: create_runtime_str!("cumulus-test-parachain"), + spec_name: alloc::borrow::Cow::Borrowed("cumulus-test-parachain"), + impl_name: alloc::borrow::Cow::Borrowed("cumulus-test-parachain"), authoring_version: 1, // Read the note above. spec_version: 1, @@ -140,8 +140,8 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { #[cfg(feature = "increment-spec-version")] #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("cumulus-test-parachain"), - impl_name: create_runtime_str!("cumulus-test-parachain"), + spec_name: alloc::borrow::Cow::Borrowed("cumulus-test-parachain"), + impl_name: alloc::borrow::Cow::Borrowed("cumulus-test-parachain"), authoring_version: 1, // Read the note above. spec_version: 2, diff --git a/docs/sdk/packages/guides/first-runtime/src/lib.rs b/docs/sdk/packages/guides/first-runtime/src/lib.rs index 92d51962b6fe..7c96f5653e52 100644 --- a/docs/sdk/packages/guides/first-runtime/src/lib.rs +++ b/docs/sdk/packages/guides/first-runtime/src/lib.rs @@ -31,8 +31,8 @@ use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, RuntimeDispatchInfo #[docify::export] #[runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("first-runtime"), - impl_name: create_runtime_str!("first-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("first-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("first-runtime"), authoring_version: 1, spec_version: 0, impl_version: 1, @@ -152,8 +152,8 @@ pub mod genesis_config_presets { /// Get the set of the available genesis config presets. #[docify::export] pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(DEV_RUNTIME_PRESET) => development_config_genesis(), + let patch = match id.as_ref() { + DEV_RUNTIME_PRESET => development_config_genesis(), _ => return None, }; Some( diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs index c1316b2f8734..5918f2b8ccd5 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs @@ -121,12 +121,12 @@ fn preset_invalid() -> Value { /// If no preset with given `id` exits `None` is returned. #[docify::export] pub fn get_builtin_preset(id: &sp_genesis_builder::PresetId) -> Option> { - let preset = match id.try_into() { - Ok(PRESET_1) => preset_1(), - Ok(PRESET_2) => preset_2(), - Ok(PRESET_3) => preset_3(), - Ok(PRESET_4) => preset_4(), - Ok(PRESET_INVALID) => preset_invalid(), + let preset = match id.as_ref() { + PRESET_1 => preset_1(), + PRESET_2 => preset_2(), + PRESET_3 => preset_3(), + PRESET_4 => preset_4(), + PRESET_INVALID => preset_invalid(), _ => return None, }; diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs index 5be3a59dc7bb..282fc1ff489c 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs @@ -39,8 +39,8 @@ use sp_genesis_builder::PresetId; /// The runtime version. #[runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("minimal-template-runtime"), - impl_name: create_runtime_str!("minimal-template-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("minimal-template-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("minimal-template-runtime"), authoring_version: 1, spec_version: 0, impl_version: 1, diff --git a/polkadot/runtime/rococo/src/genesis_config_presets.rs b/polkadot/runtime/rococo/src/genesis_config_presets.rs index d609548aed27..39c862660894 100644 --- a/polkadot/runtime/rococo/src/genesis_config_presets.rs +++ b/polkadot/runtime/rococo/src/genesis_config_presets.rs @@ -490,11 +490,11 @@ fn versi_local_testnet_genesis() -> serde_json::Value { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => rococo_local_testnet_genesis(), - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => rococo_development_config_genesis(), - Ok("staging_testnet") => rococo_staging_testnet_config_genesis(), - Ok("versi_local_testnet") => versi_local_testnet_genesis(), + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => rococo_local_testnet_genesis(), + sp_genesis_builder::DEV_RUNTIME_PRESET => rococo_development_config_genesis(), + "staging_testnet" => rococo_staging_testnet_config_genesis(), + "versi_local_testnet" => versi_local_testnet_genesis(), _ => return None, }; Some( diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index e02a28353d29..88e738cc980d 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -100,7 +100,7 @@ use pallet_session::historical as session_historical; use pallet_transaction_payment::{FeeDetails, FungibleAdapter, RuntimeDispatchInfo}; use sp_core::{ConstU128, ConstU8, Get, OpaqueMetadata, H256}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{ AccountIdConversion, BlakeTwo256, Block as BlockT, ConstU32, ConvertInto, IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, Verify, @@ -168,8 +168,8 @@ pub mod fast_runtime_binary { /// Runtime version (Rococo). #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("rococo"), - impl_name: create_runtime_str!("parity-rococo-v2.0"), + spec_name: alloc::borrow::Cow::Borrowed("rococo"), + impl_name: alloc::borrow::Cow::Borrowed("parity-rococo-v2.0"), authoring_version: 0, spec_version: 1_016_001, impl_version: 0, @@ -2435,7 +2435,7 @@ sp_api::impl_runtime_apis! { config: frame_benchmarking::BenchmarkConfig, ) -> Result< Vec, - sp_runtime::RuntimeString, + alloc::string::String, > { use frame_support::traits::WhitelistedStorageKeys; use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index 9e7ee488af72..bb46b19956e8 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -80,7 +80,6 @@ use sp_consensus_beefy::ecdsa_crypto::{AuthorityId as BeefyId, Signature as Beef use sp_core::{ConstU32, OpaqueMetadata}; use sp_mmr_primitives as mmr; use sp_runtime::{ - create_runtime_str, curve::PiecewiseLinear, generic, impl_opaque_keys, traits::{ @@ -119,8 +118,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); /// Runtime version (Test). #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("polkadot-test-runtime"), - impl_name: create_runtime_str!("parity-polkadot-test-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("polkadot-test-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("parity-polkadot-test-runtime"), authoring_version: 2, spec_version: 1056, impl_version: 0, diff --git a/polkadot/runtime/westend/src/genesis_config_presets.rs b/polkadot/runtime/westend/src/genesis_config_presets.rs index a9e22898ddb4..b074d54fb582 100644 --- a/polkadot/runtime/westend/src/genesis_config_presets.rs +++ b/polkadot/runtime/westend/src/genesis_config_presets.rs @@ -411,10 +411,10 @@ fn westend_local_testnet_genesis() -> serde_json::Value { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => westend_local_testnet_genesis(), - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => westend_development_config_genesis(), - Ok("staging_testnet") => westend_staging_testnet_config_genesis(), + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => westend_local_testnet_genesis(), + sp_genesis_builder::DEV_RUNTIME_PRESET => westend_development_config_genesis(), + "staging_testnet" => westend_staging_testnet_config_genesis(), _ => return None, }; Some( diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 251d92b03bbb..21790e259f07 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -95,7 +95,7 @@ use sp_consensus_beefy::{ }; use sp_core::{ConstU8, OpaqueMetadata, RuntimeDebug, H256}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{ AccountIdConversion, BlakeTwo256, Block as BlockT, ConvertInto, IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, Verify, @@ -168,8 +168,8 @@ pub mod fast_runtime_binary { /// Runtime version (Westend). #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("westend"), - impl_name: create_runtime_str!("parity-westend"), + spec_name: alloc::borrow::Cow::Borrowed("westend"), + impl_name: alloc::borrow::Cow::Borrowed("parity-westend"), authoring_version: 2, spec_version: 1_016_001, impl_version: 0, @@ -2592,7 +2592,7 @@ sp_api::impl_runtime_apis! { config: frame_benchmarking::BenchmarkConfig, ) -> Result< Vec, - sp_runtime::RuntimeString, + alloc::string::String, > { use frame_support::traits::WhitelistedStorageKeys; use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; diff --git a/prdoc/pr_5693.prdoc b/prdoc/pr_5693.prdoc new file mode 100644 index 000000000000..d8afae7ba0bc --- /dev/null +++ b/prdoc/pr_5693.prdoc @@ -0,0 +1,84 @@ +title: Remove `sp_runtime::RuntimeString` and replace with `Cow<'static, str>` or + `String` depending on use case +doc: + - audience: Runtime Dev + description: | + Deprecate `RuntimeString`, replace with `String` or `Cow<'static, str>` where appropriate. + + For downstream projects the upgrade will primarily consist of following two changes: + ```diff + #[sp_version::runtime_version] + pub const VERSION: RuntimeVersion = RuntimeVersion { + - spec_name: create_runtime_str!("statemine"), + - impl_name: create_runtime_str!("statemine"), + + spec_name: alloc::borrow::Cow::Borrowed("statemine"), + + impl_name: alloc::borrow::Cow::Borrowed("statemine"), + ``` + ```diff + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + - ) -> Result, sp_runtime::RuntimeString> { + + ) -> Result, alloc::string::String> { + ``` + SCALE encoding/decoding remains the same as before, but serde encoding in runtime has changed from bytes to string (it was like this in `std` environment already). +crates: +- name: cumulus-client-network + bump: major +- name: cumulus-client-pov-recovery + bump: major +- name: cumulus-pallet-parachain-system + bump: major +- name: asset-hub-rococo-runtime + bump: major +- name: asset-hub-westend-runtime + bump: major +- name: bridge-hub-rococo-runtime + bump: major +- name: bridge-hub-westend-runtime + bump: major +- name: collectives-westend-runtime + bump: major +- name: contracts-rococo-runtime + bump: major +- name: coretime-rococo-runtime + bump: major +- name: coretime-westend-runtime + bump: major +- name: glutton-westend-runtime + bump: major +- name: people-rococo-runtime + bump: major +- name: people-westend-runtime + bump: major +- name: penpal-runtime + bump: major +- name: rococo-parachain-runtime + bump: major +- name: rococo-runtime + bump: major +- name: westend-runtime + bump: major +- name: staging-chain-spec-builder + bump: major +- name: sc-consensus-pow + bump: major +- name: sc-executor + bump: major +- name: frame-benchmarking + bump: major +- name: polkadot-sdk-frame + bump: major +- name: frame-support + bump: major +- name: frame-system + bump: major +- name: sp-api + bump: major +- name: sp-genesis-builder + bump: major +- name: sp-runtime + bump: major +- name: sp-version-proc-macro + bump: major +- name: sp-version + bump: major diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 76b09c127c35..18db43b1c120 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -102,7 +102,6 @@ use sp_consensus_grandpa::AuthorityId as GrandpaId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ - create_runtime_str, curve::PiecewiseLinear, generic, impl_opaque_keys, traits::{ @@ -168,8 +167,8 @@ pub fn wasm_binary_unwrap() -> &'static [u8] { /// Runtime version. #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("node"), - impl_name: create_runtime_str!("substrate-node"), + spec_name: alloc::borrow::Cow::Borrowed("node"), + impl_name: alloc::borrow::Cow::Borrowed("substrate-node"), authoring_version: 10, // Per convention: if the runtime behavior changes, increment spec_version // and set impl_version to 0. If only runtime @@ -3613,7 +3612,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch}; use sp_storage::TrackedStorageKey; diff --git a/substrate/bin/utils/chain-spec-builder/src/lib.rs b/substrate/bin/utils/chain-spec-builder/src/lib.rs index 98ff480b8ceb..6f3128ed7eb0 100644 --- a/substrate/bin/utils/chain-spec-builder/src/lib.rs +++ b/substrate/bin/utils/chain-spec-builder/src/lib.rs @@ -293,16 +293,6 @@ impl ChainSpecBuilder { let presets = caller .preset_names() .map_err(|e| format!("getting default config from runtime should work: {e}"))?; - let presets: Vec = presets - .into_iter() - .map(|preset| { - String::from( - TryInto::<&str>::try_into(&preset) - .unwrap_or_else(|_| "cannot display preset id") - .to_string(), - ) - }) - .collect(); println!("{}", serde_json::json!({"presets":presets}).to_string()); }, ChainSpecBuilderCmd::DisplayPreset(DisplayPresetCmd { runtime, preset_name }) => { diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index cd7da128549f..882f3440e164 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -62,7 +62,6 @@ use sp_inherents::{CreateInherentDataProviders, InherentDataProvider}; use sp_runtime::{ generic::{BlockId, Digest, DigestItem}, traits::{Block as BlockT, Header as HeaderT}, - RuntimeString, }; use std::{cmp::Ordering, marker::PhantomData, sync::Arc, time::Duration}; @@ -110,7 +109,7 @@ pub enum Error { #[error("{0}")] Environment(String), #[error("{0}")] - Runtime(RuntimeString), + Runtime(String), #[error("{0}")] Other(String), } diff --git a/substrate/client/executor/src/wasm_runtime.rs b/substrate/client/executor/src/wasm_runtime.rs index 77dfc09c8807..8f189ca92388 100644 --- a/substrate/client/executor/src/wasm_runtime.rs +++ b/substrate/client/executor/src/wasm_runtime.rs @@ -441,18 +441,20 @@ where #[cfg(test)] mod tests { + extern crate alloc; + use super::*; + use alloc::borrow::Cow; use codec::Encode; use sp_api::{Core, RuntimeApiInfo}; - use sp_runtime::RuntimeString; use sp_version::{create_apis_vec, RuntimeVersion}; use sp_wasm_interface::HostFunctions; use substrate_test_runtime::Block; #[derive(Encode)] pub struct OldRuntimeVersion { - pub spec_name: RuntimeString, - pub impl_name: RuntimeString, + pub spec_name: Cow<'static, str>, + pub impl_name: Cow<'static, str>, pub authoring_version: u32, pub spec_version: u32, pub impl_version: u32, diff --git a/substrate/frame/benchmarking/src/utils.rs b/substrate/frame/benchmarking/src/utils.rs index ca362f7aa7ef..fb55cee99e81 100644 --- a/substrate/frame/benchmarking/src/utils.rs +++ b/substrate/frame/benchmarking/src/utils.rs @@ -238,7 +238,7 @@ sp_api::decl_runtime_apis! { fn benchmark_metadata(extra: bool) -> (Vec, Vec); /// Dispatch the given benchmark. - fn dispatch_benchmark(config: BenchmarkConfig) -> Result, sp_runtime::RuntimeString>; + fn dispatch_benchmark(config: BenchmarkConfig) -> Result, alloc::string::String>; } } diff --git a/substrate/frame/benchmarking/src/v1.rs b/substrate/frame/benchmarking/src/v1.rs index d687f9fdfa10..e73ed1f4382f 100644 --- a/substrate/frame/benchmarking/src/v1.rs +++ b/substrate/frame/benchmarking/src/v1.rs @@ -1734,8 +1734,8 @@ pub fn show_benchmark_debug_info( components: &[(BenchmarkParameter, u32)], verify: &bool, error_message: &str, -) -> sp_runtime::RuntimeString { - sp_runtime::format_runtime_string!( +) -> alloc::string::String { + alloc::format!( "\n* Pallet: {}\n\ * Benchmark: {}\n\ * Components: {:?}\n\ diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index 9b360c7de712..d4c3440a3ea7 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -190,7 +190,7 @@ impl<'a, Address: Decode, Signature: Decode, E: EthExtra> serde::Deserialize<'a> { let r = sp_core::bytes::deserialize(de)?; Decode::decode(&mut &r[..]) - .map_err(|e| serde::de::Error::custom(sp_runtime::format!("Decode error: {}", e))) + .map_err(|e| serde::de::Error::custom(alloc::format!("Decode error: {}", e))) } } diff --git a/substrate/frame/src/lib.rs b/substrate/frame/src/lib.rs index a8d2c0b3fc56..0ca36ca8545a 100644 --- a/substrate/frame/src/lib.rs +++ b/substrate/frame/src/lib.rs @@ -373,7 +373,10 @@ pub mod runtime { }; /// Types to define your runtime version. - pub use sp_version::{create_runtime_str, runtime_version, RuntimeVersion}; + // TODO: Remove deprecation suppression once + #[allow(deprecated)] + pub use sp_version::create_runtime_str; + pub use sp_version::{runtime_version, RuntimeVersion}; #[cfg(feature = "std")] pub use sp_version::NativeVersion; diff --git a/substrate/frame/support/src/genesis_builder_helper.rs b/substrate/frame/support/src/genesis_builder_helper.rs index 662ea2cb1862..38b339eb9329 100644 --- a/substrate/frame/support/src/genesis_builder_helper.rs +++ b/substrate/frame/support/src/genesis_builder_helper.rs @@ -21,16 +21,15 @@ extern crate alloc; -use alloc::vec::Vec; +use alloc::{format, vec::Vec}; use frame_support::traits::BuildGenesisConfig; use sp_genesis_builder::{PresetId, Result as BuildResult}; -use sp_runtime::format_runtime_string; /// Build `GenesisConfig` from a JSON blob not using any defaults and store it in the storage. For /// more info refer to [`sp_genesis_builder::GenesisBuilder::build_state`]. pub fn build_state(json: Vec) -> BuildResult { - let gc = serde_json::from_slice::(&json) - .map_err(|e| format_runtime_string!("Invalid JSON blob: {}", e))?; + let gc = + serde_json::from_slice::(&json).map_err(|e| format!("Invalid JSON blob: {}", e))?; ::build(&gc); Ok(()) } @@ -41,7 +40,7 @@ pub fn build_state(json: Vec) -> BuildResult { /// to [`sp_genesis_builder::GenesisBuilder::get_preset`]. pub fn get_preset( name: &Option, - preset_for_name: impl FnOnce(&sp_genesis_builder::PresetId) -> Option>, + preset_for_name: impl FnOnce(&PresetId) -> Option>, ) -> Option> where GC: BuildGenesisConfig + Default, diff --git a/substrate/frame/support/test/compile_pass/src/lib.rs b/substrate/frame/support/test/compile_pass/src/lib.rs index 677ef4e94c89..31f3126b8dd5 100644 --- a/substrate/frame/support/test/compile_pass/src/lib.rs +++ b/substrate/frame/support/test/compile_pass/src/lib.rs @@ -21,20 +21,22 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use frame_support::{ construct_runtime, derive_impl, parameter_types, traits::{ConstU16, ConstU32, ConstU64, Everything}, }; use sp_core::{sr25519, H256}; use sp_runtime::{ - create_runtime_str, generic, + generic, traits::{BlakeTwo256, IdentityLookup, Verify}, }; use sp_version::RuntimeVersion; pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("frame-support-test-compile-pass"), - impl_name: create_runtime_str!("substrate-frame-support-test-compile-pass-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("frame-support-test-compile-pass"), + impl_name: alloc::borrow::Cow::Borrowed("substrate-frame-support-test-compile-pass-runtime"), authoring_version: 0, spec_version: 0, impl_version: 0, diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 02d61921741c..ff682c82ce9d 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -99,7 +99,7 @@ extern crate alloc; -use alloc::{boxed::Box, vec, vec::Vec}; +use alloc::{borrow::Cow, boxed::Box, vec, vec::Vec}; use core::{fmt::Debug, marker::PhantomData}; use pallet_prelude::{BlockNumberFor, HeaderFor}; #[cfg(feature = "std")] @@ -1159,24 +1159,24 @@ pub struct AccountInfo { /// Stores the `spec_version` and `spec_name` of when the last runtime upgrade /// happened. -#[derive(sp_runtime::RuntimeDebug, Encode, Decode, TypeInfo)] +#[derive(RuntimeDebug, Encode, Decode, TypeInfo)] #[cfg_attr(feature = "std", derive(PartialEq))] pub struct LastRuntimeUpgradeInfo { pub spec_version: codec::Compact, - pub spec_name: sp_runtime::RuntimeString, + pub spec_name: Cow<'static, str>, } impl LastRuntimeUpgradeInfo { /// Returns if the runtime was upgraded in comparison of `self` and `current`. /// /// Checks if either the `spec_version` increased or the `spec_name` changed. - pub fn was_upgraded(&self, current: &sp_version::RuntimeVersion) -> bool { + pub fn was_upgraded(&self, current: &RuntimeVersion) -> bool { current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name } } -impl From for LastRuntimeUpgradeInfo { - fn from(version: sp_version::RuntimeVersion) -> Self { +impl From for LastRuntimeUpgradeInfo { + fn from(version: RuntimeVersion) -> Self { Self { spec_version: version.spec_version.into(), spec_name: version.spec_name } } } diff --git a/substrate/frame/system/src/mock.rs b/substrate/frame/system/src/mock.rs index f43ffe3c87ee..80bc75973d19 100644 --- a/substrate/frame/system/src/mock.rs +++ b/substrate/frame/system/src/mock.rs @@ -33,8 +33,8 @@ const MAX_BLOCK_WEIGHT: Weight = Weight::from_parts(1024, u64::MAX); parameter_types! { pub Version: RuntimeVersion = RuntimeVersion { - spec_name: sp_version::create_runtime_str!("test"), - impl_name: sp_version::create_runtime_str!("system-test"), + spec_name: alloc::borrow::Cow::Borrowed("test"), + impl_name: alloc::borrow::Cow::Borrowed("system-test"), authoring_version: 1, spec_version: 1, impl_version: 1, diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 700e212688c8..b412d4b52fed 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -105,7 +105,7 @@ pub mod __private { generic::BlockId, traits::{Block as BlockT, Hash as HashT, HashingFor, Header as HeaderT, NumberFor}, transaction_validity::TransactionValidity, - ExtrinsicInclusionMode, RuntimeString, TransactionOutcome, + ExtrinsicInclusionMode, TransactionOutcome, }; pub use sp_version::{create_apis_vec, ApiId, ApisVec, RuntimeVersion}; @@ -286,7 +286,7 @@ pub use sp_api_proc_macro::decl_runtime_apis; /// # Example /// /// ```rust -/// use sp_version::create_runtime_str; +/// extern crate alloc; /// # /// # use sp_runtime::{ExtrinsicInclusionMode, traits::Block as BlockT}; /// # use sp_test_primitives::Block; @@ -338,8 +338,8 @@ pub use sp_api_proc_macro::decl_runtime_apis; /// /// /// Runtime version. This needs to be declared for each runtime. /// pub const VERSION: sp_version::RuntimeVersion = sp_version::RuntimeVersion { -/// spec_name: create_runtime_str!("node"), -/// impl_name: create_runtime_str!("test-node"), +/// spec_name: alloc::borrow::Cow::Borrowed("node"), +/// impl_name: alloc::borrow::Cow::Borrowed("test-node"), /// authoring_version: 1, /// spec_version: 1, /// impl_version: 0, diff --git a/substrate/primitives/genesis-builder/src/lib.rs b/substrate/primitives/genesis-builder/src/lib.rs index 4763aa06341e..9abc27868864 100644 --- a/substrate/primitives/genesis-builder/src/lib.rs +++ b/substrate/primitives/genesis-builder/src/lib.rs @@ -73,13 +73,13 @@ //! which is the foundation for genesis block. extern crate alloc; -use alloc::vec::Vec; +use alloc::{string::String, vec::Vec}; /// The result type alias, used in build methods. `Err` contains formatted error message. -pub type Result = core::result::Result<(), sp_runtime::RuntimeString>; +pub type Result = core::result::Result<(), String>; /// The type representing preset ID. -pub type PresetId = sp_runtime::RuntimeString; +pub type PresetId = String; /// The default `development` preset used to communicate with the runtime via /// [`GenesisBuilder`] interface. diff --git a/substrate/primitives/runtime/src/lib.rs b/substrate/primitives/runtime/src/lib.rs index 6eed57656a6d..f0c8e50f1ba1 100644 --- a/substrate/primitives/runtime/src/lib.rs +++ b/substrate/primitives/runtime/src/lib.rs @@ -49,7 +49,7 @@ extern crate alloc; #[doc(hidden)] -pub use alloc::{format, vec::Vec}; +pub use alloc::vec::Vec; #[doc(hidden)] pub use codec; #[doc(hidden)] @@ -90,15 +90,12 @@ mod multiaddress; pub mod offchain; pub mod proving_trie; pub mod runtime_logger; -mod runtime_string; #[cfg(feature = "std")] pub mod testing; pub mod traits; pub mod transaction_validity; pub mod type_with_default; -pub use crate::runtime_string::*; - // Re-export Multiaddress pub use multiaddress::MultiAddress; @@ -953,7 +950,7 @@ impl<'a> ::serde::Deserialize<'a> for OpaqueExtrinsic { { let r = ::sp_core::bytes::deserialize(de)?; Decode::decode(&mut &r[..]) - .map_err(|e| ::serde::de::Error::custom(format!("Decode error: {}", e))) + .map_err(|e| ::serde::de::Error::custom(alloc::format!("Decode error: {}", e))) } } @@ -1037,6 +1034,23 @@ impl OpaqueValue { } } +// TODO: Remove in future versions and clean up `parse_str_literal` in `sp-version-proc-macro` +/// Deprecated `Cow::Borrowed()` wrapper. +#[macro_export] +#[deprecated = "Use Cow::Borrowed() instead of create_runtime_str!()"] +macro_rules! create_runtime_str { + ( $y:expr ) => {{ + $crate::Cow::Borrowed($y) + }}; +} +// TODO: Re-export for ^ macro `create_runtime_str`, should be removed once macro is gone +#[doc(hidden)] +pub use alloc::borrow::Cow; +// TODO: Remove in future versions +/// Deprecated alias to improve upgrade experience +#[deprecated = "Use String or Cow<'static, str> instead"] +pub type RuntimeString = alloc::string::String; + #[cfg(test)] mod tests { use crate::traits::BlakeTwo256; diff --git a/substrate/primitives/runtime/src/runtime_string.rs b/substrate/primitives/runtime/src/runtime_string.rs deleted file mode 100644 index bb0347badcbb..000000000000 --- a/substrate/primitives/runtime/src/runtime_string.rs +++ /dev/null @@ -1,168 +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 alloc::vec::Vec; -use codec::{Decode, Encode}; -use sp_core::RuntimeDebug; - -/// A string that wraps a `&'static str` in the runtime and `String`/`Vec` on decode. -#[derive(Eq, RuntimeDebug, Clone)] -pub enum RuntimeString { - /// The borrowed mode that wraps a `&'static str`. - Borrowed(&'static str), - /// The owned mode that wraps a `String`. - #[cfg(feature = "std")] - Owned(String), - /// The owned mode that wraps a `Vec`. - #[cfg(not(feature = "std"))] - Owned(Vec), -} - -impl scale_info::TypeInfo for RuntimeString { - type Identity = str; - - fn type_info() -> scale_info::Type { - Self::Identity::type_info() - } -} - -/// Convenience macro to use the format! interface to get a `RuntimeString::Owned` -#[macro_export] -macro_rules! format_runtime_string { - ($($args:tt)*) => {{ - #[cfg(feature = "std")] - { - sp_runtime::RuntimeString::Owned(format!($($args)*)) - } - #[cfg(not(feature = "std"))] - { - sp_runtime::RuntimeString::Owned($crate::format!($($args)*).as_bytes().to_vec()) - } - }}; -} - -impl From<&'static str> for RuntimeString { - fn from(data: &'static str) -> Self { - Self::Borrowed(data) - } -} - -impl<'a> TryFrom<&'a RuntimeString> for &'a str { - type Error = core::str::Utf8Error; - fn try_from(from: &'a RuntimeString) -> core::result::Result<&'a str, Self::Error> { - match from { - #[cfg(feature = "std")] - RuntimeString::Owned(string) => Ok(string.as_str()), - #[cfg(not(feature = "std"))] - RuntimeString::Owned(vec) => core::str::from_utf8(&vec), - RuntimeString::Borrowed(str) => Ok(str), - } - } -} - -#[cfg(feature = "std")] -impl From for String { - fn from(string: RuntimeString) -> Self { - match string { - RuntimeString::Borrowed(data) => data.to_owned(), - RuntimeString::Owned(data) => data, - } - } -} - -impl Default for RuntimeString { - fn default() -> Self { - Self::Borrowed(Default::default()) - } -} - -impl PartialEq for RuntimeString { - fn eq(&self, other: &Self) -> bool { - self.as_ref() == other.as_ref() - } -} - -impl AsRef<[u8]> for RuntimeString { - fn as_ref(&self) -> &[u8] { - match self { - Self::Borrowed(val) => val.as_ref(), - Self::Owned(val) => val.as_ref(), - } - } -} - -#[cfg(feature = "std")] -impl std::ops::Deref for RuntimeString { - type Target = str; - - fn deref(&self) -> &str { - match self { - Self::Borrowed(val) => val, - Self::Owned(val) => val, - } - } -} - -impl Encode for RuntimeString { - fn encode(&self) -> Vec { - match self { - Self::Borrowed(val) => val.encode(), - Self::Owned(val) => val.encode(), - } - } -} - -impl Decode for RuntimeString { - fn decode(value: &mut I) -> Result { - Decode::decode(value).map(Self::Owned) - } -} - -#[cfg(feature = "std")] -impl std::fmt::Display for RuntimeString { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - Self::Borrowed(val) => write!(f, "{}", val), - Self::Owned(val) => write!(f, "{}", val), - } - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for RuntimeString { - fn serialize(&self, serializer: S) -> Result { - match self { - Self::Borrowed(val) => val.serialize(serializer), - Self::Owned(val) => val.serialize(serializer), - } - } -} - -#[cfg(feature = "serde")] -impl<'de> serde::Deserialize<'de> for RuntimeString { - fn deserialize>(de: D) -> Result { - Ok(Self::Owned(serde::Deserialize::deserialize(de)?)) - } -} - -/// Create a const [`RuntimeString`]. -#[macro_export] -macro_rules! create_runtime_str { - ( $y:expr ) => {{ - $crate::RuntimeString::Borrowed($y) - }}; -} diff --git a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs index b4f749c90f59..ac6d501b927d 100644 --- a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs +++ b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs @@ -182,21 +182,47 @@ impl ParseRuntimeVersion { } fn parse_str_literal(expr: &Expr) -> Result { - let mac = match *expr { - Expr::Macro(syn::ExprMacro { ref mac, .. }) => mac, - _ => return Err(Error::new(expr.span(), "a macro expression is expected here")), - }; + match expr { + // TODO: Remove this branch when `sp_runtime::create_runtime_str` is removed + Expr::Macro(syn::ExprMacro { mac, .. }) => { + let lit: ExprLit = mac.parse_body().map_err(|e| { + Error::new( + e.span(), + format!( + "a single literal argument is expected, but parsing is failed: {}", + e + ), + ) + })?; - let lit: ExprLit = mac.parse_body().map_err(|e| { - Error::new( - e.span(), - format!("a single literal argument is expected, but parsing is failed: {}", e), - ) - })?; + match &lit.lit { + Lit::Str(lit) => Ok(lit.value()), + _ => Err(Error::new(lit.span(), "only string literals are supported here")), + } + }, + Expr::Call(call) => { + if call.args.len() != 1 { + return Err(Error::new( + expr.span(), + "a single literal argument is expected, but parsing is failed", + )); + } + let Expr::Lit(lit) = call.args.first().expect("Length checked above; qed") else { + return Err(Error::new( + expr.span(), + "a single literal argument is expected, but parsing is failed", + )); + }; - match lit.lit { - Lit::Str(ref lit) => Ok(lit.value()), - _ => Err(Error::new(lit.span(), "only string literals are supported here")), + match &lit.lit { + Lit::Str(lit) => Ok(lit.value()), + _ => Err(Error::new(lit.span(), "only string literals are supported here")), + } + }, + _ => Err(Error::new( + expr.span(), + format!("a function call is expected here, instead of: {expr:?}"), + )), } } diff --git a/substrate/primitives/version/src/lib.rs b/substrate/primitives/version/src/lib.rs index a9f1c2373069..2e1464646647 100644 --- a/substrate/primitives/version/src/lib.rs +++ b/substrate/primitives/version/src/lib.rs @@ -46,7 +46,7 @@ use std::collections::HashSet; pub use alloc::borrow::Cow; use codec::{Decode, Encode, Input}; use scale_info::TypeInfo; -use sp_runtime::RuntimeString; +#[allow(deprecated)] pub use sp_runtime::{create_runtime_str, StateVersion}; #[doc(hidden)] pub use sp_std; @@ -72,12 +72,15 @@ pub mod embed; /// This macro accepts a const item like the following: /// /// ```rust -/// use sp_version::{create_runtime_str, RuntimeVersion}; +/// extern crate alloc; +/// +/// use alloc::borrow::Cow; +/// use sp_version::RuntimeVersion; /// /// #[sp_version::runtime_version] /// pub const VERSION: RuntimeVersion = RuntimeVersion { -/// spec_name: create_runtime_str!("test"), -/// impl_name: create_runtime_str!("test"), +/// spec_name: Cow::Borrowed("test"), +/// impl_name: Cow::Borrowed("test"), /// authoring_version: 10, /// spec_version: 265, /// impl_version: 1, @@ -164,14 +167,14 @@ pub struct RuntimeVersion { /// Identifies the different Substrate runtimes. There'll be at least polkadot and node. /// A different on-chain spec_name to that of the native runtime would normally result /// in node not attempting to sync or author blocks. - pub spec_name: RuntimeString, + pub spec_name: Cow<'static, str>, /// Name of the implementation of the spec. This is of little consequence for the node /// and serves only to differentiate code of different implementation teams. For this /// codebase, it will be parity-polkadot. If there were a non-Rust implementation of the /// Polkadot runtime (e.g. C++), then it would identify itself with an accordingly different /// `impl_name`. - pub impl_name: RuntimeString, + pub impl_name: Cow<'static, str>, /// `authoring_version` is the version of the authorship interface. An authoring node /// will not attempt to author blocks unless this is equal to its native runtime. @@ -472,8 +475,8 @@ impl<'de> serde::Deserialize<'de> for RuntimeVersion { where A: serde::de::MapAccess<'de>, { - let mut spec_name: Option = None; - let mut impl_name: Option = None; + let mut spec_name: Option> = None; + let mut impl_name: Option> = None; let mut authoring_version: Option = None; let mut spec_version: Option = None; let mut impl_version: Option = None; diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index a4a0d348a390..1314d9d6dd45 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -63,7 +63,7 @@ pub use sp_core::hash::H256; use sp_genesis_builder::PresetId; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ - create_runtime_str, impl_opaque_keys, impl_tx_ext_default, + impl_opaque_keys, impl_tx_ext_default, traits::{BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, NumberFor, Verify}, transaction_validity::{ TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction, @@ -114,8 +114,8 @@ pub fn wasm_binary_logging_disabled_unwrap() -> &'static [u8] { /// Test runtime version. #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("test"), - impl_name: create_runtime_str!("parity-test"), + spec_name: alloc::borrow::Cow::Borrowed("test"), + impl_name: alloc::borrow::Cow::Borrowed("parity-test"), authoring_version: 1, spec_version: 2, impl_version: 2, @@ -727,8 +727,8 @@ impl_runtime_apis! { fn get_preset(name: &Option) -> Option> { get_preset::(name, |name| { - let patch = match name.try_into() { - Ok("staging") => { + let patch = match name.as_ref() { + "staging" => { let endowed_accounts: Vec = vec![ AccountKeyring::Bob.public().into(), AccountKeyring::Charlie.public().into(), @@ -746,7 +746,7 @@ impl_runtime_apis! { } }) }, - Ok("foobar") => json!({"foo":"bar"}), + "foobar" => json!({"foo":"bar"}), _ => return None, }; Some(serde_json::to_string(&patch) @@ -1392,10 +1392,8 @@ mod tests { let r = BuildResult::decode(&mut &r[..]).unwrap(); log::info!("result: {:#?}", r); assert_eq!(r, Err( - sp_runtime::RuntimeString::Owned( - "Invalid JSON blob: unknown field `renamed_authorities`, expected `authorities` or `epochConfig` at line 4 column 25".to_string(), - )) - ); + "Invalid JSON blob: unknown field `renamed_authorities`, expected `authorities` or `epochConfig` at line 4 column 25".to_string(), + )); } #[test] @@ -1406,10 +1404,8 @@ mod tests { let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap(); let r = BuildResult::decode(&mut &r[..]).unwrap(); assert_eq!(r, Err( - sp_runtime::RuntimeString::Owned( - "Invalid JSON blob: unknown field `babex`, expected one of `system`, `babe`, `substrateTest`, `balances` at line 3 column 9".to_string(), - )) - ); + "Invalid JSON blob: unknown field `babex`, expected one of `system`, `babe`, `substrateTest`, `balances` at line 3 column 9".to_string(), + )); } #[test] @@ -1419,14 +1415,11 @@ mod tests { let mut t = BasicExternalities::new_empty(); let r = executor_call(&mut t, "GenesisBuilder_build_state", &j.encode()).unwrap(); - let r = - core::result::Result::<(), sp_runtime::RuntimeString>::decode(&mut &r[..]).unwrap(); + let r = core::result::Result::<(), String>::decode(&mut &r[..]).unwrap(); assert_eq!( r, - Err(sp_runtime::RuntimeString::Owned( - "Invalid JSON blob: missing field `authorities` at line 11 column 3" - .to_string() - )) + Err("Invalid JSON blob: missing field `authorities` at line 11 column 3" + .to_string()) ); } diff --git a/templates/minimal/runtime/src/lib.rs b/templates/minimal/runtime/src/lib.rs index 304e50af2508..ecdba739c50e 100644 --- a/templates/minimal/runtime/src/lib.rs +++ b/templates/minimal/runtime/src/lib.rs @@ -66,8 +66,8 @@ pub mod genesis_config_presets { /// Get the set of the available genesis config presets. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => development_config_genesis(), + let patch = match id.as_ref() { + sp_genesis_builder::DEV_RUNTIME_PRESET => development_config_genesis(), _ => return None, }; Some( @@ -86,8 +86,8 @@ pub mod genesis_config_presets { /// The runtime version. #[runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("minimal-template-runtime"), - impl_name: create_runtime_str!("minimal-template-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("minimal-template-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("minimal-template-runtime"), authoring_version: 1, spec_version: 0, impl_version: 1, diff --git a/templates/parachain/runtime/src/apis.rs b/templates/parachain/runtime/src/apis.rs index eba9293a67ba..05a508ca655f 100644 --- a/templates/parachain/runtime/src/apis.rs +++ b/templates/parachain/runtime/src/apis.rs @@ -261,7 +261,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; use super::*; diff --git a/templates/parachain/runtime/src/genesis_config_presets.rs b/templates/parachain/runtime/src/genesis_config_presets.rs index 9091db357005..77ae85c0b174 100644 --- a/templates/parachain/runtime/src/genesis_config_presets.rs +++ b/templates/parachain/runtime/src/genesis_config_presets.rs @@ -97,9 +97,9 @@ fn development_config_genesis() -> Value { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => local_testnet_genesis(), - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => development_config_genesis(), + let patch = match id.as_ref() { + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => local_testnet_genesis(), + sp_genesis_builder::DEV_RUNTIME_PRESET => development_config_genesis(), _ => return None, }; Some( diff --git a/templates/parachain/runtime/src/lib.rs b/templates/parachain/runtime/src/lib.rs index 78dc38ef427f..43e76dba0591 100644 --- a/templates/parachain/runtime/src/lib.rs +++ b/templates/parachain/runtime/src/lib.rs @@ -20,7 +20,7 @@ use smallvec::smallvec; use polkadot_sdk::{staging_parachain_info as parachain_info, *}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, IdentifyAccount, Verify}, MultiSignature, }; @@ -164,8 +164,8 @@ impl_opaque_keys! { #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("parachain-template-runtime"), - impl_name: create_runtime_str!("parachain-template-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("parachain-template-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("parachain-template-runtime"), authoring_version: 1, spec_version: 1, impl_version: 0, diff --git a/templates/solochain/runtime/src/apis.rs b/templates/solochain/runtime/src/apis.rs index f21eaa344431..06c645fa0c53 100644 --- a/templates/solochain/runtime/src/apis.rs +++ b/templates/solochain/runtime/src/apis.rs @@ -237,7 +237,7 @@ impl_runtime_apis! { fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { + ) -> Result, alloc::string::String> { use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch}; use sp_storage::TrackedStorageKey; use frame_system_benchmarking::Pallet as SystemBench; diff --git a/templates/solochain/runtime/src/genesis_config_presets.rs b/templates/solochain/runtime/src/genesis_config_presets.rs index 693ae5c2221f..7c444456a600 100644 --- a/templates/solochain/runtime/src/genesis_config_presets.rs +++ b/templates/solochain/runtime/src/genesis_config_presets.rs @@ -91,9 +91,9 @@ pub fn local_config_genesis() -> Value { /// Provides the JSON representation of predefined genesis config for given `id`. pub fn get_preset(id: &PresetId) -> Option> { - let patch = match id.try_into() { - Ok(sp_genesis_builder::DEV_RUNTIME_PRESET) => development_config_genesis(), - Ok(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET) => local_config_genesis(), + let patch = match id.as_ref() { + sp_genesis_builder::DEV_RUNTIME_PRESET => development_config_genesis(), + sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => local_config_genesis(), _ => return None, }; Some( diff --git a/templates/solochain/runtime/src/lib.rs b/templates/solochain/runtime/src/lib.rs index f2eb49592be9..ae0ea16ae42e 100644 --- a/templates/solochain/runtime/src/lib.rs +++ b/templates/solochain/runtime/src/lib.rs @@ -11,7 +11,7 @@ pub mod configs; extern crate alloc; use alloc::vec::Vec; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, + generic, impl_opaque_keys, traits::{BlakeTwo256, IdentifyAccount, Verify}, MultiAddress, MultiSignature, }; @@ -61,8 +61,8 @@ impl_opaque_keys! { // https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("solochain-template-runtime"), - impl_name: create_runtime_str!("solochain-template-runtime"), + spec_name: alloc::borrow::Cow::Borrowed("solochain-template-runtime"), + impl_name: alloc::borrow::Cow::Borrowed("solochain-template-runtime"), authoring_version: 1, // The version of the runtime specification. A full node will not attempt to use its native // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, From b667c279b6dc108ffa75fd56004b835906104ca4 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Tue, 5 Nov 2024 23:21:09 +0100 Subject: [PATCH 038/166] `chain-spec-builder`: info about patch/full files added (#6373) There was no good example of what is patch and full genesis config file. Some explanation and example were added to the `chain-spec-builder` doc. --------- Co-authored-by: GitHub Action Co-authored-by: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> --- prdoc/pr_6373.prdoc | 8 ++++ .../utils/chain-spec-builder/README.docify.md | 44 +++++++++++++++++++ .../bin/utils/chain-spec-builder/README.md | 44 +++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 prdoc/pr_6373.prdoc diff --git a/prdoc/pr_6373.prdoc b/prdoc/pr_6373.prdoc new file mode 100644 index 000000000000..04758d9dd41f --- /dev/null +++ b/prdoc/pr_6373.prdoc @@ -0,0 +1,8 @@ +title: '`chain-spec-builder`: info about patch/full files added' +doc: +- audience: Runtime User + description: There was no good example of what is patch and full genesis config + file. Some explanation and example were added to the `chain-spec-builder` doc. +crates: +- name: staging-chain-spec-builder + bump: patch diff --git a/substrate/bin/utils/chain-spec-builder/README.docify.md b/substrate/bin/utils/chain-spec-builder/README.docify.md index bb4db4c666e0..75d05bccfe0d 100644 --- a/substrate/bin/utils/chain-spec-builder/README.docify.md +++ b/substrate/bin/utils/chain-spec-builder/README.docify.md @@ -73,6 +73,8 @@ storage (`-s`) version of chain spec: +Refer to [*patch file*](#patch-file) for some details on the patch file format. + _Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) and [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) @@ -84,6 +86,8 @@ Build the chain spec using provided full genesis config json file. No defaults w +Refer to [*full config file*](#full-genesis-config-file) for some details on the full file format. + _Note_: [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) runtime function is called. @@ -91,10 +95,50 @@ runtime function is called. +Refer to [*patch file*](#patch-file) for some details on the patch file format. + ### Generate human readable chain spec using provided full genesis config +Refer to [*full config file*](#full-genesis-config-file) for some details on the full file format. + + +## Patch and full genesis config files +This section provides details on the files that can be used with `create patch` or `create full` subcommands. + +### Patch file +The patch file for genesis config contains the key-value pairs valid for given runtime, that needs to be customized, + e.g: +```ignore +{ + "balances": { + "balances": [ + [ + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + 1000000000000000 + ], + [ + "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", + 1000000000000000 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 5000000000000000 + ] + ] + }, + "sudo": { + "key": "5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo" + } +} +``` +The rest of genesis config keys will be initialized with default values. + +### Full genesis config file +The full genesis config file must contain values for *all* the keys present in the genesis config for given runtime. The +format of the file is similar to patch format. Example is not provided here as it heavily depends on the runtime. + ### Extra tools The `chain-spec-builder` provides also some extra utilities: [`VerifyCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.VerifyCmd.html), diff --git a/substrate/bin/utils/chain-spec-builder/README.md b/substrate/bin/utils/chain-spec-builder/README.md index e03c710ce1b3..a85b37826139 100644 --- a/substrate/bin/utils/chain-spec-builder/README.md +++ b/substrate/bin/utils/chain-spec-builder/README.md @@ -99,6 +99,8 @@ bash!( ) ``` +Refer to [*patch file*](#patch-file) for some details on the patch file format. + _Note:_ [`GenesisBuilder::get_preset`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.get_preset) and [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) @@ -114,6 +116,8 @@ bash!( ) ``` +Refer to [*full config file*](#full-genesis-config-file) for some details on the full file format. + _Note_: [`GenesisBuilder::build_state`](https://docs.rs/sp-genesis-builder/latest/sp_genesis_builder/trait.GenesisBuilder.html#method.build_state) runtime function is called. @@ -125,6 +129,8 @@ bash!( ) ``` +Refer to [*patch file*](#patch-file) for some details on the patch file format. + ### Generate human readable chain spec using provided full genesis config ```rust,ignore @@ -133,6 +139,44 @@ bash!( ) ``` +Refer to [*full config file*](#full-genesis-config-file) for some details on the full file format. + + +## Patch and full genesis config files +This section provides details on the files that can be used with `create patch` or `create full` subcommands. + +### Patch file +The patch file for genesis config contains the key-value pairs valid for given runtime, that needs to be customized, + e.g: +```ignore +{ + "balances": { + "balances": [ + [ + "5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty", + 1000000000000000 + ], + [ + "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y", + 1000000000000000 + ], + [ + "5CcjiSgG2KLuKAsqkE2Nak1S2FbAcMr5SxRASUuwR3zSNV2b", + 5000000000000000 + ] + ] + }, + "sudo": { + "key": "5Ff3iXP75ruzroPWRP2FYBHWnmGGBSb63857BgnzCoXNxfPo" + } +} +``` +The rest of genesis config keys will be initialized with default values. + +### Full genesis config file +The full genesis config file must contain values for *all* the keys present in the genesis config for given runtime. The +format of the file is similar to patch format. Example is not provided here as it heavily depends on the runtime. + ### Extra tools The `chain-spec-builder` provides also some extra utilities: [`VerifyCmd`](https://docs.rs/staging-chain-spec-builder/latest/staging_chain_spec_builder/struct.VerifyCmd.html), From a4791617241732f4fecafe21e12c16b7fe42f73e Mon Sep 17 00:00:00 2001 From: davidk-pt Date: Wed, 6 Nov 2024 03:27:48 +0200 Subject: [PATCH 039/166] pallet-child-bounties index child bounty by parent bounty (#6255) Resolves https://github.com/paritytech/polkadot-sdk/issues/5929 Migrates `ChildBountyDescriptions` to be indexed instead of unique child bounty id unique per all child bounties in the pallet to be unique per every parent bounty. Migrates `(ParentBounty, ChildBounty)` keys inside `ChildBounties` storage item to use new `ChildBounty` ids starting from `0`. @paritytech/frame-coders --------- Signed-off-by: Oliver Tale-Yazdi Co-authored-by: DavidK Co-authored-by: muharem Co-authored-by: Oliver Tale-Yazdi --- polkadot/runtime/rococo/src/lib.rs | 2 + prdoc/pr_6255.prdoc | 34 + substrate/frame/bounties/src/lib.rs | 10 +- .../frame/child-bounties/src/benchmarking.rs | 8 +- substrate/frame/child-bounties/src/lib.rs | 105 +++- .../frame/child-bounties/src/migration.rs | 229 +++++++ substrate/frame/child-bounties/src/tests.rs | 592 ++++++++++++------ substrate/primitives/core/src/crypto.rs | 4 +- 8 files changed, 759 insertions(+), 225 deletions(-) create mode 100644 prdoc/pr_6255.prdoc create mode 100644 substrate/frame/child-bounties/src/migration.rs diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 88e738cc980d..f8f8573bc900 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1661,6 +1661,7 @@ pub mod migrations { pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect"; /// Weight for balance unreservations pub BalanceUnreserveWeight: Weight = weights::pallet_balances_balances::WeightInfo::::force_unreserve(); + pub BalanceTransferAllowDeath: Weight = weights::pallet_balances_balances::WeightInfo::::transfer_allow_death(); } // Special Config for Gov V1 pallets, allowing us to run migrations for them without @@ -1710,6 +1711,7 @@ pub mod migrations { paras_registrar::migration::MigrateToV1, pallet_referenda::migration::v1::MigrateV0ToV1, pallet_referenda::migration::v1::MigrateV0ToV1, + pallet_child_bounties::migration::MigrateV0ToV1, // Unlock & unreserve Gov1 funds diff --git a/prdoc/pr_6255.prdoc b/prdoc/pr_6255.prdoc new file mode 100644 index 000000000000..7b69717b5c2d --- /dev/null +++ b/prdoc/pr_6255.prdoc @@ -0,0 +1,34 @@ +title: '[pallet-child-bounties] Index child bounties by parent bounty' +doc: +- audience: Runtime Dev + description: | + Index child bounties by their parent bounty, ensuring that their indexes are independent of + child bounties from other parent bounties. This will allow for predictable indexes and the + ability to batch creation and approval calls together. + + ### Migration for Runtime Pallet Instance + Use `migration::v1::MigrateToV1Impl` storage migration type to translate ids for the active + child bounties and migrate the state to the new schema. + + ### Migration for Clients + - Use new `ParentTotalChildBounties` storage item to iterate over child bounties for a certain + parent bounty; + - Use new `ChildBountyDescriptionsV1` storage item to get the bounty description instead of + removed `ChildBountyDescriptions`; + - Use `V0ToV1ChildBountyIds` storage item to look up the new child bounty id for a given + old child bounty id; + - Update the child bounty account id derivation from `PalletId + "cb" + child_id` to + `PalletId + "cb" + bounty_id + child_id`. + + ### Additional Notes + - The `ChildBountyCount` storage item is deprecated and will be remove in May 2025. + +crates: +- name: pallet-child-bounties + bump: major +- name: pallet-bounties + bump: major +- name: rococo-runtime + bump: major +- name: sp-core + bump: minor diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 06b0e76cfc7e..3ed408a19120 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -188,8 +188,11 @@ pub trait ChildBountyManager { /// Get the active child bounties for a parent bounty. fn child_bounties_count(bounty_id: BountyIndex) -> BountyIndex; - /// Get total curator fees of children-bounty curators. + /// Take total curator fees of children-bounty curators. fn children_curator_fees(bounty_id: BountyIndex) -> Balance; + + /// Hook called when a parent bounty is removed. + fn bounty_removed(bounty_id: BountyIndex); } #[frame_support::pallet] @@ -679,6 +682,7 @@ pub mod pallet { *maybe_bounty = None; BountyDescriptions::::remove(bounty_id); + T::ChildBountyManager::bounty_removed(bounty_id); Self::deposit_event(Event::::BountyClaimed { index: bounty_id, @@ -776,7 +780,9 @@ pub mod pallet { AllowDeath, ); // should not fail debug_assert!(res.is_ok()); + *maybe_bounty = None; + T::ChildBountyManager::bounty_removed(bounty_id); Self::deposit_event(Event::::BountyCanceled { index: bounty_id }); Ok(Some(>::WeightInfo::close_bounty_active()).into()) @@ -1054,4 +1060,6 @@ impl ChildBountyManager for () { fn children_curator_fees(_bounty_id: BountyIndex) -> Balance { Zero::zero() } + + fn bounty_removed(_bounty_id: BountyIndex) {} } diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index 68e99e21a456..67074f90cbf6 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -151,7 +151,7 @@ fn activate_child_bounty( bounty_setup.reason.clone(), )?; - bounty_setup.child_bounty_id = ChildBountyCount::::get() - 1; + bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; ChildBounties::::propose_curator( RawOrigin::Signed(bounty_setup.curator.clone()).into(), @@ -205,7 +205,7 @@ benchmarks! { bounty_setup.child_bounty_value, bounty_setup.reason.clone(), )?; - let child_bounty_id = ChildBountyCount::::get() - 1; + let child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; }: _(RawOrigin::Signed(bounty_setup.curator), bounty_setup.bounty_id, child_bounty_id, child_curator_lookup, bounty_setup.child_bounty_fee) @@ -221,7 +221,7 @@ benchmarks! { bounty_setup.child_bounty_value, bounty_setup.reason.clone(), )?; - bounty_setup.child_bounty_id = ChildBountyCount::::get() - 1; + bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; ChildBounties::::propose_curator( RawOrigin::Signed(bounty_setup.curator.clone()).into(), @@ -296,7 +296,7 @@ benchmarks! { bounty_setup.child_bounty_value, bounty_setup.reason.clone(), )?; - bounty_setup.child_bounty_id = ChildBountyCount::::get() - 1; + bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id) diff --git a/substrate/frame/child-bounties/src/lib.rs b/substrate/frame/child-bounties/src/lib.rs index 1e970b6ae67c..ea1d9547d465 100644 --- a/substrate/frame/child-bounties/src/lib.rs +++ b/substrate/frame/child-bounties/src/lib.rs @@ -53,11 +53,15 @@ #![cfg_attr(not(feature = "std"), no_std)] mod benchmarking; +pub mod migration; mod tests; pub mod weights; extern crate alloc; +/// The log target for this pallet. +const LOG_TARGET: &str = "runtime::child-bounties"; + use alloc::vec::Vec; use frame_support::traits::{ @@ -134,7 +138,11 @@ pub mod pallet { use super::*; + /// The in-code storage version. + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + #[pallet::pallet] + #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(_); #[pallet::config] @@ -184,16 +192,22 @@ pub mod pallet { Canceled { index: BountyIndex, child_index: BountyIndex }, } - /// Number of total child bounties. + /// DEPRECATED: Replaced with `ParentTotalChildBounties` storage item keeping dedicated counts + /// for each parent bounty. Number of total child bounties. Will be removed in May 2025. #[pallet::storage] pub type ChildBountyCount = StorageValue<_, BountyIndex, ValueQuery>; - /// Number of child bounties per parent bounty. + /// Number of active child bounties per parent bounty. /// Map of parent bounty index to number of child bounties. #[pallet::storage] pub type ParentChildBounties = StorageMap<_, Twox64Concat, BountyIndex, u32, ValueQuery>; + /// Number of total child bounties per parent bounty, including completed bounties. + #[pallet::storage] + pub type ParentTotalChildBounties = + StorageMap<_, Twox64Concat, BountyIndex, u32, ValueQuery>; + /// Child bounties that have been added. #[pallet::storage] pub type ChildBounties = StorageDoubleMap< @@ -205,10 +219,27 @@ pub mod pallet { ChildBounty, BlockNumberFor>, >; - /// The description of each child-bounty. + /// The description of each child-bounty. Indexed by `(parent_id, child_id)`. + /// + /// This item replaces the `ChildBountyDescriptions` storage item from the V0 storage version. + #[pallet::storage] + pub type ChildBountyDescriptionsV1 = StorageDoubleMap< + _, + Twox64Concat, + BountyIndex, + Twox64Concat, + BountyIndex, + BoundedVec, + >; + + /// The mapping of the child bounty ids from storage version `V0` to the new `V1` version. + /// + /// The `V0` ids based on total child bounty count [`ChildBountyCount`]`. The `V1` version ids + /// based on the child bounty count per parent bounty [`ParentTotalChildBounties`]. + /// The item intended solely for client convenience and not used in the pallet's core logic. #[pallet::storage] - pub type ChildBountyDescriptions = - StorageMap<_, Twox64Concat, BountyIndex, BoundedVec>; + pub type V0ToV1ChildBountyIds = + StorageMap<_, Twox64Concat, BountyIndex, (BountyIndex, BountyIndex)>; /// The cumulative child-bounty curator fee for each parent bounty. #[pallet::storage] @@ -276,15 +307,19 @@ pub mod pallet { )?; // Get child-bounty ID. - let child_bounty_id = ChildBountyCount::::get(); - let child_bounty_account = Self::child_bounty_account_id(child_bounty_id); + let child_bounty_id = ParentTotalChildBounties::::get(parent_bounty_id); + let child_bounty_account = + Self::child_bounty_account_id(parent_bounty_id, child_bounty_id); // Transfer funds from parent bounty to child-bounty. T::Currency::transfer(&parent_bounty_account, &child_bounty_account, value, KeepAlive)?; // Increment the active child-bounty count. ParentChildBounties::::mutate(parent_bounty_id, |count| count.saturating_inc()); - ChildBountyCount::::put(child_bounty_id.saturating_add(1)); + ParentTotalChildBounties::::insert( + parent_bounty_id, + child_bounty_id.saturating_add(1), + ); // Create child-bounty instance. Self::create_child_bounty( @@ -672,7 +707,8 @@ pub mod pallet { ); // Make curator fee payment. - let child_bounty_account = Self::child_bounty_account_id(child_bounty_id); + let child_bounty_account = + Self::child_bounty_account_id(parent_bounty_id, child_bounty_id); let balance = T::Currency::free_balance(&child_bounty_account); let curator_fee = child_bounty.fee.min(balance); let payout = balance.saturating_sub(curator_fee); @@ -716,7 +752,7 @@ pub mod pallet { }); // Remove the child-bounty description. - ChildBountyDescriptions::::remove(child_bounty_id); + ChildBountyDescriptionsV1::::remove(parent_bounty_id, child_bounty_id); // Remove the child-bounty instance from the state. *maybe_child_bounty = None; @@ -772,6 +808,19 @@ pub mod pallet { Ok(()) } } + + #[pallet::hooks] + impl Hooks> for Pallet { + fn integrity_test() { + let parent_bounty_id: BountyIndex = 1; + let child_bounty_id: BountyIndex = 2; + let _: T::AccountId = T::PalletId::get() + .try_into_sub_account(("cb", parent_bounty_id, child_bounty_id)) + .expect( + "The `AccountId` type must be large enough to fit the child bounty account ID.", + ); + } + } } impl Pallet { @@ -797,11 +846,14 @@ impl Pallet { } /// The account ID of a child-bounty account. - pub fn child_bounty_account_id(id: BountyIndex) -> T::AccountId { + pub fn child_bounty_account_id( + parent_bounty_id: BountyIndex, + child_bounty_id: BountyIndex, + ) -> T::AccountId { // This function is taken from the parent (bounties) pallet, but the // prefix is changed to have different AccountId when the index of // parent and child is same. - T::PalletId::get().into_sub_account_truncating(("cb", id)) + T::PalletId::get().into_sub_account_truncating(("cb", parent_bounty_id, child_bounty_id)) } fn create_child_bounty( @@ -818,7 +870,7 @@ impl Pallet { status: ChildBountyStatus::Added, }; ChildBounties::::insert(parent_bounty_id, child_bounty_id, &child_bounty); - ChildBountyDescriptions::::insert(child_bounty_id, description); + ChildBountyDescriptionsV1::::insert(parent_bounty_id, child_bounty_id, description); Self::deposit_event(Event::Added { index: parent_bounty_id, child_index: child_bounty_id }); } @@ -877,7 +929,8 @@ impl Pallet { // Transfer fund from child-bounty to parent bounty. let parent_bounty_account = pallet_bounties::Pallet::::bounty_account_id(parent_bounty_id); - let child_bounty_account = Self::child_bounty_account_id(child_bounty_id); + let child_bounty_account = + Self::child_bounty_account_id(parent_bounty_id, child_bounty_id); let balance = T::Currency::free_balance(&child_bounty_account); let transfer_result = T::Currency::transfer( &child_bounty_account, @@ -888,7 +941,7 @@ impl Pallet { debug_assert!(transfer_result.is_ok()); // Remove the child-bounty description. - ChildBountyDescriptions::::remove(child_bounty_id); + ChildBountyDescriptionsV1::::remove(parent_bounty_id, child_bounty_id); *maybe_child_bounty = None; @@ -902,16 +955,22 @@ impl Pallet { } } -// Implement ChildBountyManager to connect with the bounties pallet. This is -// where we pass the active child bounties and child curator fees to the parent -// bounty. +/// Implement ChildBountyManager to connect with the bounties pallet. This is +/// where we pass the active child bounties and child curator fees to the parent +/// bounty. +/// +/// Function `children_curator_fees` not only returns the fee but also removes cumulative curator +/// fees during call. impl pallet_bounties::ChildBountyManager> for Pallet { + /// Returns number of active child bounties for `bounty_id` fn child_bounties_count( bounty_id: pallet_bounties::BountyIndex, ) -> pallet_bounties::BountyIndex { ParentChildBounties::::get(bounty_id) } + /// Returns cumulative child bounty curator fees for `bounty_id` also removing the associated + /// storage item. This function is assumed to be called when parent bounty is claimed. fn children_curator_fees(bounty_id: pallet_bounties::BountyIndex) -> BalanceOf { // This is asked for when the parent bounty is being claimed. No use of // keeping it in state after that. Hence removing. @@ -919,4 +978,14 @@ impl pallet_bounties::ChildBountyManager> for Pallet ChildrenCuratorFees::::remove(bounty_id); children_fee_total } + + /// Clean up the storage on a parent bounty removal. + fn bounty_removed(bounty_id: BountyIndex) { + debug_assert!(ParentChildBounties::::get(bounty_id).is_zero()); + debug_assert!(ChildrenCuratorFees::::get(bounty_id).is_zero()); + debug_assert!(ChildBounties::::iter_key_prefix(bounty_id).count().is_zero()); + debug_assert!(ChildBountyDescriptionsV1::::iter_key_prefix(bounty_id).count().is_zero()); + ParentChildBounties::::remove(bounty_id); + ParentTotalChildBounties::::remove(bounty_id); + } } diff --git a/substrate/frame/child-bounties/src/migration.rs b/substrate/frame/child-bounties/src/migration.rs new file mode 100644 index 000000000000..52232a5a7f2f --- /dev/null +++ b/substrate/frame/child-bounties/src/migration.rs @@ -0,0 +1,229 @@ +// 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 super::*; +use core::marker::PhantomData; +use frame_support::{ + storage_alias, + traits::{Get, UncheckedOnRuntimeUpgrade}, +}; + +use alloc::collections::BTreeSet; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] +use frame_support::ensure; + +pub mod v1 { + use super::*; + + /// Creates a new ids for the child balances based on the child bounty count per parent bounty + /// instead of the total child bounty count. Translates the existing child bounties to the new + /// ids. Creates the `V0ToV1ChildBountyIds` map from `old_child_id` to new (`parent_id`, + /// `new_child_id`). + /// + /// `TransferWeight` returns `Weight` of `T::Currency::transfer` and `T::Currency::free_balance` + /// operation which is performed during this migration. + pub struct MigrateToV1Impl(PhantomData<(T, TransferWeight)>); + + #[storage_alias] + type ChildBountyDescriptions = StorageMap< + Pallet, + Twox64Concat, + BountyIndex, + BoundedVec::MaximumReasonLength>, + >; + + impl> UncheckedOnRuntimeUpgrade + for MigrateToV1Impl + { + fn on_runtime_upgrade() -> frame_support::weights::Weight { + // increment reads/writes after the action + let mut reads = 0u64; + let mut writes = 0u64; + let mut transfer_weights: Weight = Weight::zero(); + + // keep ids order roughly the same with the old order + let mut old_bounty_ids = BTreeSet::new(); + // first iteration collect all existing ids not to mutate map as we iterate it + for (parent_bounty_id, old_child_bounty_id) in ChildBounties::::iter_keys() { + reads += 1; + old_bounty_ids.insert((parent_bounty_id, old_child_bounty_id)); + } + + log::info!( + target: LOG_TARGET, + "Migrating {} child bounties", + old_bounty_ids.len(), + ); + + for (parent_bounty_id, old_child_bounty_id) in old_bounty_ids { + // assign new child bounty id + let new_child_bounty_id = ParentTotalChildBounties::::get(parent_bounty_id); + reads += 1; + ParentTotalChildBounties::::insert( + parent_bounty_id, + new_child_bounty_id.saturating_add(1), + ); + writes += 1; + + V0ToV1ChildBountyIds::::insert( + old_child_bounty_id, + (parent_bounty_id, new_child_bounty_id), + ); + writes += 1; + + let old_child_bounty_account = + Self::old_child_bounty_account_id(old_child_bounty_id); + let new_child_bounty_account = + Pallet::::child_bounty_account_id(parent_bounty_id, new_child_bounty_id); + let old_balance = T::Currency::free_balance(&old_child_bounty_account); + log::info!( + "Transferring {:?} funds from old child bounty account {:?} to new child bounty account {:?}", + old_balance, old_child_bounty_account, new_child_bounty_account + ); + if let Err(err) = T::Currency::transfer( + &old_child_bounty_account, + &new_child_bounty_account, + old_balance, + AllowDeath, + ) { + log::error!( + target: LOG_TARGET, + "Error transferring funds: {:?}", + err + ); + } + transfer_weights += TransferWeight::get(); + + log::info!( + target: LOG_TARGET, + "Remapped parent bounty {} child bounty id {}->{}", + parent_bounty_id, + old_child_bounty_id, + new_child_bounty_id, + ); + + let bounty_description = ChildBountyDescriptions::::take(old_child_bounty_id); + writes += 1; + let child_bounty = ChildBounties::::take(parent_bounty_id, old_child_bounty_id); + writes += 1; + + // should always be some + if let Some(taken) = child_bounty { + ChildBounties::::insert(parent_bounty_id, new_child_bounty_id, taken); + writes += 1; + } else { + log::error!( + "child bounty with old id {} not found, should be impossible", + old_child_bounty_id + ); + } + if let Some(bounty_description) = bounty_description { + super::super::ChildBountyDescriptionsV1::::insert( + parent_bounty_id, + new_child_bounty_id, + bounty_description, + ); + writes += 1; + } else { + log::error!( + "child bounty description with old id {} not found, should be impossible", + old_child_bounty_id + ); + } + } + + log::info!( + target: LOG_TARGET, + "Migration done, reads: {}, writes: {}, transfer weights: {}", + reads, writes, transfer_weights + ); + + T::DbWeight::get().reads_writes(reads, writes) + transfer_weights + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + let old_child_bounty_count = ChildBounties::::iter_keys().count() as u32; + let old_child_bounty_descriptions = + v1::ChildBountyDescriptions::::iter_keys().count() as u32; + let old_child_bounty_ids = ChildBounties::::iter_keys().collect::>(); + Ok((old_child_bounty_count, old_child_bounty_descriptions, old_child_bounty_ids) + .encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + type StateType = (u32, u32, Vec<(u32, u32)>); + let (old_child_bounty_count, old_child_bounty_descriptions, old_child_bounty_ids) = + StateType::decode(&mut &state[..]).expect("Can't decode previous state"); + let new_child_bounty_count = ChildBounties::::iter_keys().count() as u32; + let new_child_bounty_descriptions = + super::super::ChildBountyDescriptionsV1::::iter_keys().count() as u32; + + ensure!( + old_child_bounty_count == new_child_bounty_count, + "child bounty count doesn't match" + ); + ensure!( + old_child_bounty_descriptions == new_child_bounty_descriptions, + "child bounty descriptions count doesn't match" + ); + + let old_child_bounty_descriptions_storage = + v1::ChildBountyDescriptions::::iter_keys().count(); + log::info!("old child bounty descriptions: {}", old_child_bounty_descriptions_storage); + ensure!( + old_child_bounty_descriptions_storage == 0, + "Old bounty descriptions should have been drained." + ); + + for (_, old_child_bounty_id) in old_child_bounty_ids { + let old_account_id = Self::old_child_bounty_account_id(old_child_bounty_id); + let balance = T::Currency::total_balance(&old_account_id); + if !balance.is_zero() { + log::error!( + "Old child bounty id {} still has balance {:?}", + old_child_bounty_id, + balance + ); + } + } + + Ok(()) + } + } + + impl> MigrateToV1Impl { + fn old_child_bounty_account_id(id: BountyIndex) -> T::AccountId { + // This function is taken from the parent (bounties) pallet, but the + // prefix is changed to have different AccountId when the index of + // parent and child is same. + T::PalletId::get().into_sub_account_truncating(("cb", id)) + } + } +} + +/// Migrate the pallet storage from `0` to `1`. +pub type MigrateV0ToV1 = frame_support::migrations::VersionedMigration< + 0, + 1, + v1::MigrateToV1Impl, + Pallet, + ::DbWeight, +>; diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 0e58f7c91780..939983054f66 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -66,10 +66,16 @@ parameter_types! { } type Balance = u64; +// must be at least 20 bytes long because of child-bounty account derivation. +type AccountId = sp_core::U256; + +fn account_id(id: u8) -> AccountId { + sp_core::U256::from(id) +} #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Test { - type AccountId = u128; + type AccountId = AccountId; type Lookup = IdentityLookup; type Block = Block; type AccountData = pallet_balances::AccountData; @@ -82,14 +88,14 @@ impl pallet_balances::Config for Test { parameter_types! { pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); - pub TreasuryAccount: u128 = Treasury::account_id(); + pub TreasuryAccount: AccountId = Treasury::account_id(); pub const SpendLimit: Balance = u64::MAX; } impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type RejectOrigin = frame_system::EnsureRoot; + type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; type SpendPeriod = ConstU64<2>; type Burn = Burn; @@ -141,7 +147,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_balances::GenesisConfig:: { // Total issuance will be 200 with treasury account initialized at ED. - balances: vec![(0, 100), (1, 98), (2, 1)], + balances: vec![(account_id(0), 100), (account_id(1), 98), (account_id(2), 1)], } .assimilate_storage(&mut t) .unwrap(); @@ -195,52 +201,71 @@ fn add_child_bounty() { go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); let fee = 8; - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), fee)); - Balances::make_free_balance_be(&4, 10); + Balances::make_free_balance_be(&account_id(4), 10); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // This verifies that the accept curator logic took a deposit. let expected_deposit = CuratorDepositMultiplier::get() * fee; - assert_eq!(Balances::reserved_balance(&4), expected_deposit); - assert_eq!(Balances::free_balance(&4), 10 - expected_deposit); + assert_eq!(Balances::reserved_balance(&account_id(4)), expected_deposit); + assert_eq!(Balances::free_balance(&account_id(4)), 10 - expected_deposit); // Add child-bounty. // Acc-4 is the parent curator. // Call from invalid origin & check for error "RequireCurator". assert_noop!( - ChildBounties::add_child_bounty(RuntimeOrigin::signed(0), 0, 10, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty( + RuntimeOrigin::signed(account_id(0)), + 0, + 10, + b"12345-p1".to_vec() + ), BountiesError::RequireCurator, ); // Update the parent curator balance. - Balances::make_free_balance_be(&4, 101); + Balances::make_free_balance_be(&account_id(4), 101); // parent curator fee is reserved on parent bounty account. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 50); assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); assert_noop!( - ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 50, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty( + RuntimeOrigin::signed(account_id(4)), + 0, + 50, + b"12345-p1".to_vec() + ), TokenError::NotExpendable, ); assert_noop!( - ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 100, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty( + RuntimeOrigin::signed(account_id(4)), + 0, + 100, + b"12345-p1".to_vec() + ), Error::::InsufficientBountyBalance, ); // Add child-bounty with valid value, which can be funded by parent bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -249,8 +274,8 @@ fn add_child_bounty() { // Check for the event child-bounty added. assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); - assert_eq!(Balances::free_balance(4), 101); - assert_eq!(Balances::reserved_balance(4), expected_deposit); + assert_eq!(Balances::free_balance(account_id(4)), 101); + assert_eq!(Balances::reserved_balance(account_id(4)), expected_deposit); // DB check. // Check the child-bounty status. @@ -270,7 +295,7 @@ fn add_child_bounty() { // Check the child-bounty description status. assert_eq!( - pallet_child_bounties::ChildBountyDescriptions::::get(0).unwrap(), + pallet_child_bounties::ChildBountyDescriptionsV1::::get(0, 0).unwrap(), b"12345-p1".to_vec(), ); }); @@ -287,18 +312,22 @@ fn child_bounty_assign_curator() { // Make the parent bounty. go_to_block(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); - Balances::make_free_balance_be(&4, 101); - Balances::make_free_balance_be(&8, 101); + Balances::make_free_balance_be(&account_id(4), 101); + Balances::make_free_balance_be(&account_id(8), 101); - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); let fee = 4; - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, fee)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Bounty account status before adding child-bounty. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 50); @@ -307,13 +336,13 @@ fn child_bounty_assign_curator() { // Check the balance of parent curator. // Curator deposit is reserved for parent curator on parent bounty. let expected_deposit = Bounties::calculate_curator_deposit(&fee); - assert_eq!(Balances::free_balance(4), 101 - expected_deposit); - assert_eq!(Balances::reserved_balance(4), expected_deposit); + assert_eq!(Balances::free_balance(account_id(4)), 101 - expected_deposit); + assert_eq!(Balances::reserved_balance(account_id(4)), expected_deposit); // Add child-bounty. // Acc-4 is the parent curator & make sure enough deposit. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -326,11 +355,17 @@ fn child_bounty_assign_curator() { assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); // Child-bounty account status. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 10); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 10); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); let fee = 6u64; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + fee + )); assert_eq!( pallet_child_bounties::ChildBounties::::get(0, 0).unwrap(), @@ -339,20 +374,20 @@ fn child_bounty_assign_curator() { value: 10, fee, curator_deposit: 0, - status: ChildBountyStatus::CuratorProposed { curator: 8 }, + status: ChildBountyStatus::CuratorProposed { curator: account_id(8) }, } ); // Check the balance of parent curator. - assert_eq!(Balances::free_balance(4), 101 - expected_deposit); - assert_eq!(Balances::reserved_balance(4), expected_deposit); + assert_eq!(Balances::free_balance(account_id(4)), 101 - expected_deposit); + assert_eq!(Balances::reserved_balance(account_id(4)), expected_deposit); assert_noop!( - ChildBounties::accept_curator(RuntimeOrigin::signed(3), 0, 0), + ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(3)), 0, 0), BountiesError::RequireCurator, ); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; @@ -363,21 +398,21 @@ fn child_bounty_assign_curator() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 8 }, + status: ChildBountyStatus::Active { curator: account_id(8) }, } ); // Deposit for child-bounty curator deposit is reserved. - assert_eq!(Balances::free_balance(8), 101 - expected_child_deposit); - assert_eq!(Balances::reserved_balance(8), expected_child_deposit); + assert_eq!(Balances::free_balance(account_id(8)), 101 - expected_child_deposit); + assert_eq!(Balances::reserved_balance(account_id(8)), expected_child_deposit); // Bounty account status at exit. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 40); assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); // Child-bounty account status at exit. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 10); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 10); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); // Treasury account status at exit. assert_eq!(Balances::free_balance(Treasury::account_id()), 26); @@ -395,21 +430,25 @@ fn award_claim_child_bounty() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -419,17 +458,33 @@ fn award_claim_child_bounty() { // Propose and accept curator for child-bounty. let fee = 8; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); // Award child-bounty. // Test for non child-bounty curator. assert_noop!( - ChildBounties::award_child_bounty(RuntimeOrigin::signed(3), 0, 0, 7), + ChildBounties::award_child_bounty( + RuntimeOrigin::signed(account_id(3)), + 0, + 0, + account_id(7) + ), BountiesError::RequireCurator, ); - assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty( + RuntimeOrigin::signed(account_id(8)), + 0, + 0, + account_id(7) + )); let expected_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -440,8 +495,8 @@ fn award_claim_child_bounty() { fee, curator_deposit: expected_deposit, status: ChildBountyStatus::PendingPayout { - curator: 8, - beneficiary: 7, + curator: account_id(8), + beneficiary: account_id(7), unlock_at: 5 }, } @@ -450,25 +505,25 @@ fn award_claim_child_bounty() { // Claim child-bounty. // Test for Premature condition. assert_noop!( - ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0), + ChildBounties::claim_child_bounty(RuntimeOrigin::signed(account_id(7)), 0, 0), BountiesError::Premature ); go_to_block(9); - assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); + assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(account_id(7)), 0, 0)); // Ensure child-bounty curator is paid with curator fee & deposit refund. - assert_eq!(Balances::free_balance(8), 101 + fee); - assert_eq!(Balances::reserved_balance(8), 0); + assert_eq!(Balances::free_balance(account_id(8)), 101 + fee); + assert_eq!(Balances::reserved_balance(account_id(8)), 0); // Ensure executor is paid with beneficiary amount. - assert_eq!(Balances::free_balance(7), 10 - fee); - assert_eq!(Balances::reserved_balance(7), 0); + assert_eq!(Balances::free_balance(account_id(7)), 10 - fee); + assert_eq!(Balances::reserved_balance(account_id(7)), 0); // Child-bounty account status. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 0); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); // Check the child-bounty count. assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 0); @@ -485,22 +540,26 @@ fn close_child_bounty_added() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -512,11 +571,17 @@ fn close_child_bounty_added() { // Close child-bounty. // Wrong origin. - assert_noop!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(7), 0, 0), BadOrigin); - assert_noop!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(8), 0, 0), BadOrigin); + assert_noop!( + ChildBounties::close_child_bounty(RuntimeOrigin::signed(account_id(7)), 0, 0), + BadOrigin + ); + assert_noop!( + ChildBounties::close_child_bounty(RuntimeOrigin::signed(account_id(8)), 0, 0), + BadOrigin + ); // Correct origin - parent curator. - assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); + assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(account_id(4)), 0, 0)); // Check the child-bounty count. assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 0); @@ -526,8 +591,8 @@ fn close_child_bounty_added() { assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); // Child-bounty account status. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 0); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); }); } @@ -541,22 +606,26 @@ fn close_child_bounty_active() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -565,26 +634,32 @@ fn close_child_bounty_active() { assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose and accept curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, 2)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + 2 + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); // Close child-bounty in active state. - assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0)); + assert_ok!(ChildBounties::close_child_bounty(RuntimeOrigin::signed(account_id(4)), 0, 0)); // Check the child-bounty count. assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 0); // Ensure child-bounty curator balance is unreserved. - assert_eq!(Balances::free_balance(8), 101); - assert_eq!(Balances::reserved_balance(8), 0); + assert_eq!(Balances::free_balance(account_id(8)), 101); + assert_eq!(Balances::reserved_balance(account_id(8)), 0); // Parent-bounty account status. assert_eq!(Balances::free_balance(Bounties::bounty_account_id(0)), 50); assert_eq!(Balances::reserved_balance(Bounties::bounty_account_id(0)), 0); // Child-bounty account status. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 0); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); }); } @@ -598,22 +673,26 @@ fn close_child_bounty_pending() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); let parent_fee = 6; - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, parent_fee)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), parent_fee)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -623,15 +702,26 @@ fn close_child_bounty_pending() { // Propose and accept curator for child-bounty. let child_fee = 4; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, child_fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + child_fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); - assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty( + RuntimeOrigin::signed(account_id(8)), + 0, + 0, + account_id(7) + )); // Close child-bounty in pending_payout state. assert_noop!( - ChildBounties::close_child_bounty(RuntimeOrigin::signed(4), 0, 0), + ChildBounties::close_child_bounty(RuntimeOrigin::signed(account_id(4)), 0, 0), BountiesError::PendingPayout ); @@ -639,12 +729,12 @@ fn close_child_bounty_pending() { assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 1); // Ensure no changes in child-bounty curator balance. - assert_eq!(Balances::reserved_balance(8), expected_child_deposit); - assert_eq!(Balances::free_balance(8), 101 - expected_child_deposit); + assert_eq!(Balances::reserved_balance(account_id(8)), expected_child_deposit); + assert_eq!(Balances::free_balance(account_id(8)), 101 - expected_child_deposit); // Child-bounty account status. - assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0)), 10); - assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0)), 0); + assert_eq!(Balances::free_balance(ChildBounties::child_bounty_account_id(0, 0)), 10); + assert_eq!(Balances::reserved_balance(ChildBounties::child_bounty_account_id(0, 0)), 0); }); } @@ -658,22 +748,26 @@ fn child_bounty_added_unassign_curator() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -683,7 +777,7 @@ fn child_bounty_added_unassign_curator() { // Unassign curator in added state. assert_noop!( - ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(4)), 0, 0), BountiesError::UnexpectedStatus ); }); @@ -699,22 +793,26 @@ fn child_bounty_curator_proposed_unassign_curator() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -723,7 +821,13 @@ fn child_bounty_curator_proposed_unassign_curator() { assert_eq!(last_event(), ChildBountiesEvent::Added { index: 0, child_index: 0 }); // Propose curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, 2)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + 2 + )); assert_eq!( pallet_child_bounties::ChildBounties::::get(0, 0).unwrap(), @@ -732,15 +836,18 @@ fn child_bounty_curator_proposed_unassign_curator() { value: 10, fee: 2, curator_deposit: 0, - status: ChildBountyStatus::CuratorProposed { curator: 8 }, + status: ChildBountyStatus::CuratorProposed { curator: account_id(8) }, } ); // Random account cannot unassign the curator when in proposed state. - assert_noop!(ChildBounties::unassign_curator(RuntimeOrigin::signed(99), 0, 0), BadOrigin); + assert_noop!( + ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(99)), 0, 0), + BadOrigin + ); // Unassign curator. - assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(4)), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -773,23 +880,27 @@ fn child_bounty_active_unassign_curator() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&6, 101); // Child-bounty curator 1. - Balances::make_free_balance_be(&7, 101); // Child-bounty curator 2. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator 3. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(6), 101); // Child-bounty curator 1. + Balances::make_free_balance_be(&account_id(7), 101); // Child-bounty curator 2. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator 3. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Create Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -800,8 +911,14 @@ fn child_bounty_active_unassign_curator() { // Propose and accept curator for child-bounty. let fee = 6; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -811,7 +928,7 @@ fn child_bounty_active_unassign_curator() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 8 }, + status: ChildBountyStatus::Active { curator: account_id(8) }, } ); @@ -833,13 +950,19 @@ fn child_bounty_active_unassign_curator() { ); // Ensure child-bounty curator was slashed. - assert_eq!(Balances::free_balance(8), 101 - expected_child_deposit); - assert_eq!(Balances::reserved_balance(8), 0); // slashed + assert_eq!(Balances::free_balance(account_id(8)), 101 - expected_child_deposit); + assert_eq!(Balances::reserved_balance(account_id(8)), 0); // slashed // Propose and accept curator for child-bounty again. let fee = 2; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 7, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(7), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(7), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(7)), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( @@ -849,14 +972,14 @@ fn child_bounty_active_unassign_curator() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 7 }, + status: ChildBountyStatus::Active { curator: account_id(7) }, } ); go_to_block(5); // Unassign curator again - from parent curator. - assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(4), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(4)), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -871,12 +994,18 @@ fn child_bounty_active_unassign_curator() { ); // Ensure child-bounty curator was slashed. - assert_eq!(Balances::free_balance(7), 101 - expected_child_deposit); - assert_eq!(Balances::reserved_balance(7), 0); // slashed + assert_eq!(Balances::free_balance(account_id(7)), 101 - expected_child_deposit); + assert_eq!(Balances::reserved_balance(account_id(7)), 0); // slashed // Propose and accept curator for child-bounty again. - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 6, 2)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(6), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(6), + 2 + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(6)), 0, 0)); assert_eq!( pallet_child_bounties::ChildBounties::::get(0, 0).unwrap(), @@ -885,14 +1014,14 @@ fn child_bounty_active_unassign_curator() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 6 }, + status: ChildBountyStatus::Active { curator: account_id(6) }, } ); go_to_block(6); // Unassign curator again - from child-bounty curator. - assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(6), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(6)), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -907,13 +1036,19 @@ fn child_bounty_active_unassign_curator() { ); // Ensure child-bounty curator was **not** slashed. - assert_eq!(Balances::free_balance(6), 101); // not slashed - assert_eq!(Balances::reserved_balance(6), 0); + assert_eq!(Balances::free_balance(account_id(6)), 101); // not slashed + assert_eq!(Balances::reserved_balance(account_id(6)), 0); // Propose and accept curator for child-bounty one last time. let fee = 2; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 6, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(6), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(6), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(6)), 0, 0)); let expected_child_deposit = CuratorDepositMin::get(); assert_eq!( @@ -923,7 +1058,7 @@ fn child_bounty_active_unassign_curator() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 6 }, + status: ChildBountyStatus::Active { curator: account_id(6) }, } ); @@ -932,14 +1067,14 @@ fn child_bounty_active_unassign_curator() { // Unassign curator again - from non curator; non reject origin; some random guy. // Bounty update period is not yet complete. assert_noop!( - ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(3)), 0, 0), BountiesError::Premature ); go_to_block(20); // Unassign child curator from random account after inactivity. - assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(3)), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -954,8 +1089,8 @@ fn child_bounty_active_unassign_curator() { ); // Ensure child-bounty curator was slashed. - assert_eq!(Balances::free_balance(6), 101 - expected_child_deposit); // slashed - assert_eq!(Balances::reserved_balance(6), 0); + assert_eq!(Balances::free_balance(account_id(6)), 101 - expected_child_deposit); // slashed + assert_eq!(Balances::reserved_balance(account_id(6)), 0); }); } @@ -971,23 +1106,27 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator 1. - Balances::make_free_balance_be(&5, 101); // Parent-bounty curator 2. - Balances::make_free_balance_be(&6, 101); // Child-bounty curator 1. - Balances::make_free_balance_be(&7, 101); // Child-bounty curator 2. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator 3. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator 1. + Balances::make_free_balance_be(&account_id(5), 101); // Parent-bounty curator 2. + Balances::make_free_balance_be(&account_id(6), 101); // Child-bounty curator 1. + Balances::make_free_balance_be(&account_id(7), 101); // Child-bounty curator 2. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator 3. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Create Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -998,8 +1137,14 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Propose and accept curator for child-bounty. let fee = 8; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; assert_eq!( @@ -1009,7 +1154,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { value: 10, fee, curator_deposit: expected_child_deposit, - status: ChildBountyStatus::Active { curator: 8 }, + status: ChildBountyStatus::Active { curator: account_id(8) }, } ); @@ -1023,7 +1168,7 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { // Try unassign child-bounty curator - from non curator; non reject // origin; some random guy. Bounty update period is not yet complete. assert_noop!( - ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(3)), 0, 0), Error::::ParentBountyNotActive ); @@ -1043,21 +1188,27 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { ); // Ensure child-bounty curator was slashed. - assert_eq!(Balances::free_balance(8), 101 - expected_child_deposit); - assert_eq!(Balances::reserved_balance(8), 0); // slashed + assert_eq!(Balances::free_balance(account_id(8)), 101 - expected_child_deposit); + assert_eq!(Balances::reserved_balance(account_id(8)), 0); // slashed go_to_block(6); // Propose and accept curator for parent-bounty again. - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 5, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(5), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(5), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(5)), 0)); go_to_block(7); // Propose and accept curator for child-bounty again. let fee = 2; - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(5), 0, 0, 7, fee)); - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(7), 0, 0)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(5)), + 0, + 0, + account_id(7), + fee + )); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(7)), 0, 0)); let expected_deposit = CuratorDepositMin::get(); assert_eq!( @@ -1067,24 +1218,24 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { value: 10, fee, curator_deposit: expected_deposit, - status: ChildBountyStatus::Active { curator: 7 }, + status: ChildBountyStatus::Active { curator: account_id(7) }, } ); go_to_block(8); assert_noop!( - ChildBounties::unassign_curator(RuntimeOrigin::signed(3), 0, 0), + ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(3)), 0, 0), BountiesError::Premature ); // Unassign parent bounty curator again. - assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(5), 0)); + assert_ok!(Bounties::unassign_curator(RuntimeOrigin::signed(account_id(5)), 0)); go_to_block(9); // Unassign curator again - from parent curator. - assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(7), 0, 0)); + assert_ok!(ChildBounties::unassign_curator(RuntimeOrigin::signed(account_id(7)), 0, 0)); // Verify updated child-bounty status. assert_eq!( @@ -1099,8 +1250,8 @@ fn parent_bounty_inactive_unassign_curator_child_bounty() { ); // Ensure child-bounty curator was not slashed. - assert_eq!(Balances::free_balance(7), 101); - assert_eq!(Balances::reserved_balance(7), 0); // slashed + assert_eq!(Balances::free_balance(account_id(7)), 101); + assert_eq!(Balances::reserved_balance(account_id(7)), 0); // slashed }); } @@ -1114,27 +1265,36 @@ fn close_parent_with_child_bounty() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); // Try add child-bounty. // Should fail, parent bounty not active yet. assert_noop!( - ChildBounties::add_child_bounty(RuntimeOrigin::signed(4), 0, 10, b"12345-p1".to_vec()), + ChildBounties::add_child_bounty( + RuntimeOrigin::signed(account_id(4)), + 0, + 10, + b"12345-p1".to_vec() + ), Error::::ParentBountyNotActive ); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -1155,10 +1315,14 @@ fn close_parent_with_child_bounty() { // Check the child-bounty count. assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 0); + assert_eq!(pallet_child_bounties::ParentTotalChildBounties::::get(0), 1); // Try close parent-bounty again. // Should pass this time. assert_ok!(Bounties::close_bounty(RuntimeOrigin::root(), 0)); + + // Check the total count is removed after the parent bounty removal. + assert_eq!(pallet_child_bounties::ParentTotalChildBounties::::get(0), 0); }); } @@ -1174,20 +1338,24 @@ fn children_curator_fee_calculation_test() { assert_eq!(Balances::reserved_balance(Treasury::account_id()), 0); // Bounty curator initial balance. - Balances::make_free_balance_be(&4, 101); // Parent-bounty curator. - Balances::make_free_balance_be(&8, 101); // Child-bounty curator. + Balances::make_free_balance_be(&account_id(4), 101); // Parent-bounty curator. + Balances::make_free_balance_be(&account_id(8), 101); // Child-bounty curator. - assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); + assert_ok!(Bounties::propose_bounty( + RuntimeOrigin::signed(account_id(0)), + 50, + b"12345".to_vec() + )); assert_ok!(Bounties::approve_bounty(RuntimeOrigin::root(), 0)); go_to_block(2); - assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, 4, 6)); - assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(4), 0)); + assert_ok!(Bounties::propose_curator(RuntimeOrigin::root(), 0, account_id(4), 6)); + assert_ok!(Bounties::accept_curator(RuntimeOrigin::signed(account_id(4)), 0)); // Child-bounty. assert_ok!(ChildBounties::add_child_bounty( - RuntimeOrigin::signed(4), + RuntimeOrigin::signed(account_id(4)), 0, 10, b"12345-p1".to_vec() @@ -1199,13 +1367,24 @@ fn children_curator_fee_calculation_test() { let fee = 6; // Propose curator for child-bounty. - assert_ok!(ChildBounties::propose_curator(RuntimeOrigin::signed(4), 0, 0, 8, fee)); + assert_ok!(ChildBounties::propose_curator( + RuntimeOrigin::signed(account_id(4)), + 0, + 0, + account_id(8), + fee + )); // Check curator fee added to the sum. assert_eq!(pallet_child_bounties::ChildrenCuratorFees::::get(0), fee); // Accept curator for child-bounty. - assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(8), 0, 0)); + assert_ok!(ChildBounties::accept_curator(RuntimeOrigin::signed(account_id(8)), 0, 0)); // Award child-bounty. - assert_ok!(ChildBounties::award_child_bounty(RuntimeOrigin::signed(8), 0, 0, 7)); + assert_ok!(ChildBounties::award_child_bounty( + RuntimeOrigin::signed(account_id(8)), + 0, + 0, + account_id(7) + )); let expected_child_deposit = CuratorDepositMultiplier::get() * fee; @@ -1217,8 +1396,8 @@ fn children_curator_fee_calculation_test() { fee, curator_deposit: expected_child_deposit, status: ChildBountyStatus::PendingPayout { - curator: 8, - beneficiary: 7, + curator: account_id(8), + beneficiary: account_id(7), unlock_at: 7 }, } @@ -1227,26 +1406,32 @@ fn children_curator_fee_calculation_test() { go_to_block(9); // Claim child-bounty. - assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(7), 0, 0)); + assert_ok!(ChildBounties::claim_child_bounty(RuntimeOrigin::signed(account_id(7)), 0, 0)); // Check the child-bounty count. assert_eq!(pallet_child_bounties::ParentChildBounties::::get(0), 0); // Award the parent bounty. - assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(4), 0, 9)); + assert_ok!(Bounties::award_bounty(RuntimeOrigin::signed(account_id(4)), 0, account_id(9))); go_to_block(15); + // Check the total count. + assert_eq!(pallet_child_bounties::ParentTotalChildBounties::::get(0), 1); + // Claim the parent bounty. - assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(9), 0)); + assert_ok!(Bounties::claim_bounty(RuntimeOrigin::signed(account_id(9)), 0)); + + // Check the total count after the parent bounty removal. + assert_eq!(pallet_child_bounties::ParentTotalChildBounties::::get(0), 0); // Ensure parent-bounty curator received correctly reduced fee. - assert_eq!(Balances::free_balance(4), 101 + 6 - fee); // 101 + 6 - 2 - assert_eq!(Balances::reserved_balance(4), 0); + assert_eq!(Balances::free_balance(account_id(4)), 101 + 6 - fee); // 101 + 6 - 2 + assert_eq!(Balances::reserved_balance(account_id(4)), 0); // Verify parent-bounty beneficiary balance. - assert_eq!(Balances::free_balance(9), 34); - assert_eq!(Balances::reserved_balance(9), 0); + assert_eq!(Balances::free_balance(account_id(9)), 34); + assert_eq!(Balances::reserved_balance(account_id(9)), 0); }); } @@ -1256,7 +1441,7 @@ fn accept_curator_handles_different_deposit_calculations() { // in a different curator deposit, and if the child curator matches the parent curator. new_test_ext().execute_with(|| { // Setup a parent bounty. - let parent_curator = 0; + let parent_curator = account_id(0); let parent_index = 0; let parent_value = 1_000_000; let parent_fee = 10_000; @@ -1285,7 +1470,7 @@ fn accept_curator_handles_different_deposit_calculations() { // Case 1: Parent and child curator are not the same. let child_index = 0; - let child_curator = 1; + let child_curator = account_id(1); let child_value = 1_000; let child_fee = 100; let starting_balance = 100 * child_fee + child_value; @@ -1352,7 +1537,7 @@ fn accept_curator_handles_different_deposit_calculations() { // Case 3: Upper Limit let child_index = 2; - let child_curator = 2; + let child_curator = account_id(2); let child_value = 10_000; let child_fee = 5_000; @@ -1387,7 +1572,7 @@ fn accept_curator_handles_different_deposit_calculations() { // Case 4: Lower Limit let child_index = 3; - let child_curator = 3; + let child_curator = account_id(3); let child_value = 10_000; let child_fee = 0; @@ -1417,3 +1602,10 @@ fn accept_curator_handles_different_deposit_calculations() { assert_eq!(Balances::reserved_balance(child_curator), expected_deposit); }); } + +#[test] +fn integrity_test() { + new_test_ext().execute_with(|| { + ChildBounties::integrity_test(); + }); +} diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index b04d94e2bf40..cf24861e233c 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -17,7 +17,7 @@ //! Cryptographic utilities. -use crate::{ed25519, sr25519}; +use crate::{ed25519, sr25519, U256}; use alloc::{format, str, vec::Vec}; #[cfg(all(not(feature = "std"), feature = "serde"))] use alloc::{string::String, vec}; @@ -1191,7 +1191,7 @@ macro_rules! impl_from_entropy_base { } } -impl_from_entropy_base!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128); +impl_from_entropy_base!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, U256); #[cfg(test)] mod tests { From ccb2a889be7a9ca21f5e4a2b555129383d92ff7b Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Wed, 6 Nov 2024 11:57:12 +0200 Subject: [PATCH 040/166] litep2p/peerset: Do not disconnect all peers on `SetReservedPeers` command (#6016) Previously, when receiving the `SetReservedPeers { reserved }` all peers not in the `reserved` set were removed. This is incorrect, the intention of `SetReservedPeers` is to change the active set of reserved peers and disconnect previously reserved peers not in the new set. While at it, have added a few other improvements to make the peerset more robust: - `SetReservedPeers`: does not disconnect all peers - `SetReservedPeers`: if a reserved peer is no longer reserved, the peerset tries to move the peers to the regular set if the slots allow this move. This ensures the (now regular) peer counts towards slot allocation. - every 1 seconds: If we don't have enough connect peers, add the reserved peers to the list that the peerstore ignores. Reserved peers are already connected and the peerstore might return otherwise a reserved peer ### Next Steps - [x] More testing cc @paritytech/networking --------- Signed-off-by: Alexandru Vasile Co-authored-by: Dmitry Markin Co-authored-by: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> --- prdoc/pr_6016.prdoc | 15 + .../src/litep2p/shim/notification/peerset.rs | 300 +++++++++--------- .../shim/notification/tests/peerset.rs | 256 ++++++++++++++- 3 files changed, 414 insertions(+), 157 deletions(-) create mode 100644 prdoc/pr_6016.prdoc diff --git a/prdoc/pr_6016.prdoc b/prdoc/pr_6016.prdoc new file mode 100644 index 000000000000..967c3a766068 --- /dev/null +++ b/prdoc/pr_6016.prdoc @@ -0,0 +1,15 @@ +title: Litep2p network backend do not disconnect all peers on SetReservedPeers command + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + Previously, when the `SetReservedPeers` was received, all peers except the new + reserved peers were disconnected. + This PR ensures that previously reserved nodes are kept connected as regular nodes if + enough slots are available. + While at it, this PR excludes reserved peers from the candidates of peers obtained from + the peerstore. + +crates: + - name: sc-network + bump: patch diff --git a/substrate/client/network/src/litep2p/shim/notification/peerset.rs b/substrate/client/network/src/litep2p/shim/notification/peerset.rs index 2fd7920909e3..fb822794ccf0 100644 --- a/substrate/client/network/src/litep2p/shim/notification/peerset.rs +++ b/substrate/client/network/src/litep2p/shim/notification/peerset.rs @@ -88,6 +88,8 @@ const DISCONNECT_ADJUSTMENT: Reputation = Reputation::new(-256, "Peer disconnect const OPEN_FAILURE_ADJUSTMENT: Reputation = Reputation::new(-1024, "Open failure"); /// Is the peer reserved? +/// +/// Regular peers count towards slot allocation. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum Reserved { Yes, @@ -118,6 +120,15 @@ pub enum Direction { Outbound(Reserved), } +impl Direction { + fn set_reserved(&mut self, new_reserved: Reserved) { + match self { + Direction::Inbound(ref mut reserved) | Direction::Outbound(ref mut reserved) => + *reserved = new_reserved, + } + } +} + impl From for traits::Direction { fn from(direction: Direction) -> traits::Direction { match direction { @@ -784,7 +795,9 @@ impl Peerset { } /// Calculate how many of the connected peers were counted as normal inbound/outbound peers - /// which is needed to adjust slot counts when new reserved peers are added + /// which is needed to adjust slot counts when new reserved peers are added. + /// + /// If the peer is not already in the [`Peerset`], it is added as a disconnected peer. fn calculate_slot_adjustment<'a>( &'a mut self, peers: impl Iterator, @@ -819,6 +832,26 @@ impl Peerset { }) } + /// Checks if the peer should be disconnected based on the current state of the [`Peerset`] + /// and the provided direction. + /// + /// Note: The role of the peer is not checked. + fn should_disconnect(&self, direction: Direction) -> bool { + match direction { + Direction::Inbound(_) => self.num_in >= self.max_in, + Direction::Outbound(_) => self.num_out >= self.max_out, + } + } + + /// Increment the slot count for given peer. + fn increment_slot(&mut self, direction: Direction) { + match direction { + Direction::Inbound(Reserved::No) => self.num_in += 1, + Direction::Outbound(Reserved::No) => self.num_out += 1, + _ => {}, + } + } + /// Get the number of inbound peers. #[cfg(test)] pub fn num_in(&self) -> usize { @@ -949,8 +982,9 @@ impl Stream for Peerset { }, // set new reserved peers for the protocol // - // current reserved peers not in the new set are disconnected and the new reserved - // peers are scheduled for outbound substreams + // Current reserved peers not in the new set are moved to the regular set of peers + // or disconnected (if there are no slots available). The new reserved peers are + // scheduled for outbound substreams PeersetCommand::SetReservedPeers { peers } => { log::debug!(target: LOG_TARGET, "{}: set reserved peers {peers:?}", self.protocol); @@ -960,39 +994,58 @@ impl Stream for Peerset { // // calculate how many of the previously connected peers were counted as regular // peers and substract these counts from `num_out`/`num_in` + // + // If a reserved peer is not already tracked, it is added as disconnected by + // `calculate_slot_adjustment`. This ensures at the next slot allocation (1sec) + // that we'll try to establish a connection with the reserved peer. let (in_peers, out_peers) = self.calculate_slot_adjustment(peers.iter()); self.num_out -= out_peers; self.num_in -= in_peers; - // add all unknown peers to `self.peers` - peers.iter().for_each(|peer| { - if !self.peers.contains_key(peer) { - self.peers.insert(*peer, PeerState::Disconnected); - } - }); - - // collect all peers who are not in the new reserved set - let peers_to_remove = self - .peers - .iter() - .filter_map(|(peer, _)| (!peers.contains(peer)).then_some(*peer)) - .collect::>(); + // collect all *reserved* peers who are not in the new reserved set + let reserved_peers_maybe_remove = + self.reserved_peers.difference(&peers).cloned().collect::>(); self.reserved_peers = peers; - let peers = peers_to_remove + let peers_to_remove = reserved_peers_maybe_remove .into_iter() .filter(|peer| { match self.peers.remove(&peer) { - Some(PeerState::Connected { direction }) => { - log::trace!( - target: LOG_TARGET, - "{}: close connection to {peer:?}, direction {direction:?}", - self.protocol, - ); - - self.peers.insert(*peer, PeerState::Closing { direction }); - true + Some(PeerState::Connected { mut direction }) => { + // The direction contains a `Reserved::Yes` flag, because this + // is a reserve peer that we want to close. + // The `Reserved::Yes` ensures we don't adjust the slot count + // when the substream is closed. + + let disconnect = + self.reserved_only || self.should_disconnect(direction); + + if disconnect { + log::trace!( + target: LOG_TARGET, + "{}: close connection to previously reserved {peer:?}, direction {direction:?}", + self.protocol, + ); + + self.peers.insert(*peer, PeerState::Closing { direction }); + true + } else { + log::trace!( + target: LOG_TARGET, + "{}: {peer:?} is no longer reserved, move to regular peers, direction {direction:?}", + self.protocol, + ); + + // The peer is kept connected as non-reserved. This will + // further count towards the slot count. + direction.set_reserved(Reserved::No); + self.increment_slot(direction); + + self.peers + .insert(*peer, PeerState::Connected { direction }); + false + } }, // substream might have been opening but not yet fully open when // the protocol request the reserved set to be changed @@ -1021,11 +1074,13 @@ impl Stream for Peerset { log::trace!( target: LOG_TARGET, - "{}: close substreams to {peers:?}", + "{}: close substreams to {peers_to_remove:?}", self.protocol, ); - return Poll::Ready(Some(PeersetNotificationCommand::CloseSubstream { peers })) + return Poll::Ready(Some(PeersetNotificationCommand::CloseSubstream { + peers: peers_to_remove, + })) }, PeersetCommand::AddReservedPeers { peers } => { log::debug!(target: LOG_TARGET, "{}: add reserved peers {peers:?}", self.protocol); @@ -1102,6 +1157,7 @@ impl Stream for Peerset { self.peers.insert(*peer, PeerState::Backoff); None }, + // if there is a rapid change in substream state, the peer may // be canceled when the substream is asked to be closed. // @@ -1122,6 +1178,7 @@ impl Stream for Peerset { self.peers.insert(*peer, PeerState::Canceled { direction }); None }, + // substream to the peer might have failed to open which caused // the peer to be backed off // @@ -1138,6 +1195,7 @@ impl Stream for Peerset { self.peers.insert(*peer, PeerState::Disconnected); None }, + // if a node disconnects, it's put into `PeerState::Closing` // which indicates that `Peerset` wants the substream closed and // has asked litep2p to close it but it hasn't yet received a @@ -1167,125 +1225,70 @@ impl Stream for Peerset { // if there are enough slots, the peer is just converted to // a regular peer and the used slot count is increased and if the // peer cannot be accepted, litep2p is asked to close the substream. - PeerState::Connected { direction } => match direction { - Direction::Inbound(_) => match self.num_in < self.max_in { - true => { - log::trace!( - target: LOG_TARGET, - "{}: {peer:?} converted to regular inbound peer (inbound open)", - self.protocol, - ); - - self.num_in += 1; - self.peers.insert( - *peer, - PeerState::Connected { - direction: Direction::Inbound(Reserved::No), - }, - ); - - None - }, - false => { - self.peers.insert( - *peer, - PeerState::Closing { - direction: Direction::Inbound(Reserved::Yes), - }, - ); - - Some(*peer) - }, - }, - Direction::Outbound(_) => match self.num_out < self.max_out { - true => { - log::trace!( - target: LOG_TARGET, - "{}: {peer:?} converted to regular outbound peer (outbound open)", - self.protocol, - ); - - self.num_out += 1; - self.peers.insert( - *peer, - PeerState::Connected { - direction: Direction::Outbound(Reserved::No), - }, - ); - - None - }, - false => { - self.peers.insert( - *peer, - PeerState::Closing { - direction: Direction::Outbound(Reserved::Yes), - }, - ); - - Some(*peer) - }, - }, + PeerState::Connected { mut direction } => { + let disconnect = self.should_disconnect(direction); + + if disconnect { + log::trace!( + target: LOG_TARGET, + "{}: close connection to removed reserved {peer:?}, direction {direction:?}", + self.protocol, + ); + + self.peers.insert(*peer, PeerState::Closing { direction }); + Some(*peer) + } else { + log::trace!( + target: LOG_TARGET, + "{}: {peer:?} converted to regular peer {peer:?} direction {direction:?}", + self.protocol, + ); + + // The peer is kept connected as non-reserved. This will + // further count towards the slot count. + direction.set_reserved(Reserved::No); + self.increment_slot(direction); + + self.peers + .insert(*peer, PeerState::Connected { direction }); + + None + } }, - PeerState::Opening { direction } => match direction { - Direction::Inbound(_) => match self.num_in < self.max_in { - true => { - log::trace!( - target: LOG_TARGET, - "{}: {peer:?} converted to regular inbound peer (inbound opening)", - self.protocol, - ); - - self.num_in += 1; - self.peers.insert( - *peer, - PeerState::Opening { - direction: Direction::Inbound(Reserved::No), - }, - ); - - None - }, - false => { - self.peers.insert( - *peer, - PeerState::Canceled { - direction: Direction::Inbound(Reserved::Yes), - }, - ); - - None - }, - }, - Direction::Outbound(_) => match self.num_out < self.max_out { - true => { - log::trace!( - target: LOG_TARGET, - "{}: {peer:?} converted to regular outbound peer (outbound opening)", - self.protocol, - ); - - self.num_out += 1; - self.peers.insert( - *peer, - PeerState::Opening { - direction: Direction::Outbound(Reserved::No), - }, - ); - - None - }, - false => { - self.peers.insert( - *peer, - PeerState::Canceled { - direction: Direction::Outbound(Reserved::Yes), - }, - ); - - None - }, - }, + + PeerState::Opening { mut direction } => { + let disconnect = self.should_disconnect(direction); + + if disconnect { + log::trace!( + target: LOG_TARGET, + "{}: cancel substream to disconnect removed reserved peer {peer:?}, direction {direction:?}", + self.protocol, + ); + + self.peers.insert( + *peer, + PeerState::Canceled { + direction + }, + ); + } else { + log::trace!( + target: LOG_TARGET, + "{}: {peer:?} converted to regular peer {peer:?} direction {direction:?}", + self.protocol, + ); + + // The peer is kept connected as non-reserved. This will + // further count towards the slot count. + direction.set_reserved(Reserved::No); + self.increment_slot(direction); + + self.peers + .insert(*peer, PeerState::Opening { direction }); + } + + None }, } }) @@ -1373,12 +1376,17 @@ impl Stream for Peerset { // if the number of outbound peers is lower than the desired amount of outbound peers, // query `PeerStore` and try to get a new outbound candidated. if self.num_out < self.max_out && !self.reserved_only { + // From the candidates offered by the peerstore we need to ignore: + // - all peers that are not in the `PeerState::Disconnected` state (ie they are + // connected / closing) + // - reserved peers since we initiated a connection to them in the previous step let ignore: HashSet = self .peers .iter() .filter_map(|(peer, state)| { (!std::matches!(state, PeerState::Disconnected)).then_some(*peer) }) + .chain(self.reserved_peers.iter().cloned()) .collect(); let peers: Vec<_> = diff --git a/substrate/client/network/src/litep2p/shim/notification/tests/peerset.rs b/substrate/client/network/src/litep2p/shim/notification/tests/peerset.rs index 4f7bfffaa1fc..295a5b441b3e 100644 --- a/substrate/client/network/src/litep2p/shim/notification/tests/peerset.rs +++ b/substrate/client/network/src/litep2p/shim/notification/tests/peerset.rs @@ -794,8 +794,6 @@ async fn set_reserved_peers_but_available_slots() { // when `Peerset` is polled (along with two random peers) and later on `SetReservedPeers` // is called with the common peer and with two new random peers let common_peer = *known_peers.iter().next().unwrap(); - let disconnected_peers = known_peers.iter().skip(1).copied().collect::>(); - assert_eq!(disconnected_peers.len(), 2); let (mut peerset, to_peerset) = Peerset::new( ProtocolName::from("/notif/1"), @@ -809,6 +807,8 @@ async fn set_reserved_peers_but_available_slots() { assert_eq!(peerset.num_in(), 0usize); assert_eq!(peerset.num_out(), 0usize); + // We have less than 25 outbound peers connected. At the next slot allocation we + // query the `peerstore_handle` for more peers to connect to. match peerset.next().await { Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => { assert_eq!(out_peers.len(), 3); @@ -845,29 +845,167 @@ async fn set_reserved_peers_but_available_slots() { .unbounded_send(PeersetCommand::SetReservedPeers { peers: reserved_peers.clone() }) .unwrap(); + // The command `SetReservedPeers` might evict currently reserved peers if + // we don't have enough slot capacity to move them to regular nodes. + // In this case, we did not have previously any reserved peers. match peerset.next().await { - Some(PeersetNotificationCommand::CloseSubstream { peers: out_peers }) => { - assert_eq!(out_peers.len(), 2); + Some(PeersetNotificationCommand::CloseSubstream { peers }) => { + // This ensures we don't disconnect peers when receiving `SetReservedPeers`. + assert_eq!(peers.len(), 0); + }, + event => panic!("invalid event: {event:?}"), + } - for peer in &out_peers { - assert!(disconnected_peers.contains(peer)); + // verify that `Peerset` is aware of five peers, with two of them as outbound. + assert_eq!(peerset.peers().len(), 5); + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 2usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); + + match peerset.next().await { + Some(PeersetNotificationCommand::OpenSubstream { peers }) => { + assert_eq!(peers.len(), 2); + assert!(!peers.contains(&common_peer)); + + for peer in &peers { + assert!(reserved_peers.contains(peer)); + assert!(peerset.reserved_peers().contains(peer)); assert_eq!( peerset.peers().get(peer), - Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::No) }), + Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }), + ); + } + }, + event => panic!("invalid event: {event:?}"), + } + + assert_eq!(peerset.peers().len(), 5); + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 2usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); +} + +#[tokio::test] +async fn set_reserved_peers_move_previously_reserved() { + sp_tracing::try_init_simple(); + + let peerstore_handle = Arc::new(peerstore_handle_test()); + let known_peers = (0..3) + .map(|_| { + let peer = PeerId::random(); + peerstore_handle.add_known_peer(peer); + peer + }) + .collect::>(); + + // We'll keep this peer as reserved and move the the others to regular nodes. + let common_peer = *known_peers.iter().next().unwrap(); + let moved_peers = known_peers.iter().skip(1).copied().collect::>(); + let known_peers = known_peers.into_iter().collect::>(); + assert_eq!(moved_peers.len(), 2); + + let (mut peerset, to_peerset) = Peerset::new( + ProtocolName::from("/notif/1"), + 25, + 25, + false, + known_peers.clone(), + Default::default(), + peerstore_handle, + ); + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 0usize); + + // We are not connected to the reserved peers. + match peerset.next().await { + Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => { + assert_eq!(out_peers.len(), 3); + + for peer in &out_peers { + assert_eq!( + peerset.peers().get(&peer), + Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) ); } }, event => panic!("invalid event: {event:?}"), } - // verify that `Peerset` is aware of five peers, with two of them as outbound - // (the two disconnected peers) + // verify all three peers are marked as reserved peers and they don't count towards + // slot allocation. + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 0usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); + + // report that all substreams were opened + for peer in &known_peers { + assert!(std::matches!( + peerset.report_substream_opened(*peer, traits::Direction::Outbound), + OpenResult::Accept { .. } + )); + assert_eq!( + peerset.peers().get(peer), + Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) }) + ); + } + + // set reserved peers with `common_peer` being one of them + let reserved_peers = HashSet::from_iter([common_peer, PeerId::random(), PeerId::random()]); + to_peerset + .unbounded_send(PeersetCommand::SetReservedPeers { peers: reserved_peers.clone() }) + .unwrap(); + + // The command `SetReservedPeers` might evict currently reserved peers if + // we don't have enough slot capacity to move them to regular nodes. + // In this case, we have enough capacity. + match peerset.next().await { + Some(PeersetNotificationCommand::CloseSubstream { peers }) => { + // This ensures we don't disconnect peers when receiving `SetReservedPeers`. + assert_eq!(peers.len(), 0); + }, + event => panic!("invalid event: {event:?}"), + } + + // verify that `Peerset` is aware of five peers. + // 2 of the previously reserved peers are moved as outbound regular peers and + // count towards slot allocation. assert_eq!(peerset.peers().len(), 5); assert_eq!(peerset.num_in(), 0usize); assert_eq!(peerset.num_out(), 2usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); + + // Ensure the previously reserved are not regular nodes. + for (peer, state) in peerset.peers() { + // This peer was previously reserved and remained reserved after `SetReservedPeers`. + if peer == &common_peer { + assert_eq!( + state, + &PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) } + ); + continue + } + + // Part of the new reserved nodes. + if reserved_peers.contains(peer) { + assert_eq!(state, &PeerState::Disconnected); + continue + } + + // Previously reserved, but remained connected. + if moved_peers.contains(peer) { + // This was previously `Reseved::Yes` but moved to regular nodes. + assert_eq!( + state, + &PeerState::Connected { direction: Direction::Outbound(Reserved::No) } + ); + continue + } + panic!("Invalid state peer={peer:?} state={state:?}"); + } match peerset.next().await { Some(PeersetNotificationCommand::OpenSubstream { peers }) => { + // Open desires with newly reserved. assert_eq!(peers.len(), 2); assert!(!peers.contains(&common_peer)); @@ -885,7 +1023,103 @@ async fn set_reserved_peers_but_available_slots() { assert_eq!(peerset.peers().len(), 5); assert_eq!(peerset.num_in(), 0usize); - - // two substreams are closing still closing assert_eq!(peerset.num_out(), 2usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); +} + +#[tokio::test] +async fn set_reserved_peers_cannot_move_previously_reserved() { + sp_tracing::try_init_simple(); + + let peerstore_handle = Arc::new(peerstore_handle_test()); + let known_peers = (0..3) + .map(|_| { + let peer = PeerId::random(); + peerstore_handle.add_known_peer(peer); + peer + }) + .collect::>(); + + // We'll keep this peer as reserved and move the the others to regular nodes. + let common_peer = *known_peers.iter().next().unwrap(); + let moved_peers = known_peers.iter().skip(1).copied().collect::>(); + let known_peers = known_peers.into_iter().collect::>(); + assert_eq!(moved_peers.len(), 2); + + // We don't have capacity to move peers. + let (mut peerset, to_peerset) = Peerset::new( + ProtocolName::from("/notif/1"), + 0, + 0, + false, + known_peers.clone(), + Default::default(), + peerstore_handle, + ); + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 0usize); + + // We are not connected to the reserved peers. + match peerset.next().await { + Some(PeersetNotificationCommand::OpenSubstream { peers: out_peers }) => { + assert_eq!(out_peers.len(), 3); + + for peer in &out_peers { + assert_eq!( + peerset.peers().get(&peer), + Some(&PeerState::Opening { direction: Direction::Outbound(Reserved::Yes) }) + ); + } + }, + event => panic!("invalid event: {event:?}"), + } + + // verify all three peers are marked as reserved peers and they don't count towards + // slot allocation. + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 0usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); + + // report that all substreams were opened + for peer in &known_peers { + assert!(std::matches!( + peerset.report_substream_opened(*peer, traits::Direction::Outbound), + OpenResult::Accept { .. } + )); + assert_eq!( + peerset.peers().get(peer), + Some(&PeerState::Connected { direction: Direction::Outbound(Reserved::Yes) }) + ); + } + + // set reserved peers with `common_peer` being one of them + let reserved_peers = HashSet::from_iter([common_peer, PeerId::random(), PeerId::random()]); + to_peerset + .unbounded_send(PeersetCommand::SetReservedPeers { peers: reserved_peers.clone() }) + .unwrap(); + + // The command `SetReservedPeers` might evict currently reserved peers if + // we don't have enough slot capacity to move them to regular nodes. + // In this case, we don't have enough capacity. + match peerset.next().await { + Some(PeersetNotificationCommand::CloseSubstream { peers }) => { + // This ensures we don't disconnect peers when receiving `SetReservedPeers`. + assert_eq!(peers.len(), 2); + + for peer in peers { + // Ensure common peer is not disconnected. + assert_ne!(common_peer, peer); + + assert_eq!( + peerset.peers().get(&peer), + Some(&PeerState::Closing { direction: Direction::Outbound(Reserved::Yes) }) + ); + } + }, + event => panic!("invalid event: {event:?}"), + } + + assert_eq!(peerset.num_in(), 0usize); + assert_eq!(peerset.num_out(), 0usize); + assert_eq!(peerset.reserved_peers().len(), 3usize); } From d1620f06b53572fe10fe22208f5a29a2879d2587 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Wed, 6 Nov 2024 11:53:20 +0100 Subject: [PATCH 041/166] polkadot-service: Fix flaky tests (#6376) The tests used the same paths. When run on CI, each test is run in its own process and thus, this "serial_test" crate wasn't used. The tests are now using their own thread local tempdir, which ensures that the tests are working when running in parallel in the same program or when being run individually. --- Cargo.lock | 26 ------------ Cargo.toml | 1 - polkadot/node/service/Cargo.toml | 1 - polkadot/node/service/src/workers.rs | 59 +++++++++++----------------- 4 files changed, 23 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a8e7d7d4cdda..a824faedd6b3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15992,7 +15992,6 @@ dependencies = [ "sc-transaction-pool-api", "serde", "serde_json", - "serial_test", "sp-api 26.0.0", "sp-authority-discovery", "sp-block-builder", @@ -20641,31 +20640,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serial_test" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e56dd856803e253c8f298af3f4d7eb0ae5e23a737252cd90bb4f3b435033b2d" -dependencies = [ - "dashmap", - "futures", - "lazy_static", - "log", - "parking_lot 0.12.3", - "serial_test_derive", -] - -[[package]] -name = "serial_test_derive" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" -dependencies = [ - "proc-macro2 1.0.86", - "quote 1.0.37", - "syn 2.0.87", -] - [[package]] name = "sha-1" version = "0.9.8" diff --git a/Cargo.toml b/Cargo.toml index edfea7b8efa9..b12469987ed6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1210,7 +1210,6 @@ serde-big-array = { version = "0.3.2" } serde_derive = { version = "1.0.117" } serde_json = { version = "1.0.132", default-features = false } serde_yaml = { version = "0.9" } -serial_test = { version = "2.0.0" } sha1 = { version = "0.10.6" } sha2 = { version = "0.10.7", default-features = false } sha3 = { version = "0.10.0", default-features = false } diff --git a/polkadot/node/service/Cargo.toml b/polkadot/node/service/Cargo.toml index 3edb3f4dadbe..6e8eade21a43 100644 --- a/polkadot/node/service/Cargo.toml +++ b/polkadot/node/service/Cargo.toml @@ -140,7 +140,6 @@ polkadot-node-subsystem-test-helpers = { workspace = true } polkadot-primitives-test-helpers = { workspace = true } sp-tracing = { workspace = true } assert_matches = { workspace = true } -serial_test = { workspace = true } tempfile = { workspace = true } [features] diff --git a/polkadot/node/service/src/workers.rs b/polkadot/node/service/src/workers.rs index b35bb8302fdc..73c3aa466608 100644 --- a/polkadot/node/service/src/workers.rs +++ b/polkadot/node/service/src/workers.rs @@ -21,19 +21,20 @@ use is_executable::IsExecutable; use std::path::PathBuf; #[cfg(test)] -use std::sync::{Mutex, OnceLock}; +thread_local! { + static TMP_DIR: std::cell::RefCell> = std::cell::RefCell::new(None); +} /// Override the workers polkadot binary directory path, used for testing. #[cfg(test)] -fn workers_exe_path_override() -> &'static Mutex> { - static OVERRIDE: OnceLock>> = OnceLock::new(); - OVERRIDE.get_or_init(|| Mutex::new(None)) +fn workers_exe_path_override() -> Option { + TMP_DIR.with_borrow(|t| t.as_ref().map(|t| t.path().join("usr/bin"))) } + /// Override the workers lib directory path, used for testing. #[cfg(test)] -fn workers_lib_path_override() -> &'static Mutex> { - static OVERRIDE: OnceLock>> = OnceLock::new(); - OVERRIDE.get_or_init(|| Mutex::new(None)) +fn workers_lib_path_override() -> Option { + TMP_DIR.with_borrow(|t| t.as_ref().map(|t| t.path().join("usr/lib/polkadot"))) } /// Determines the final set of paths to use for the PVF workers. @@ -147,12 +148,9 @@ fn list_workers_paths( // Consider the /usr/lib/polkadot/ directory. { - #[allow(unused_mut)] - let mut lib_path = PathBuf::from("/usr/lib/polkadot"); + let lib_path = PathBuf::from("/usr/lib/polkadot"); #[cfg(test)] - if let Some(ref path_override) = *workers_lib_path_override().lock().unwrap() { - lib_path = path_override.clone(); - } + let lib_path = if let Some(o) = workers_lib_path_override() { o } else { lib_path }; let (prep_worker, exec_worker) = build_worker_paths(lib_path, workers_names); @@ -175,9 +173,10 @@ fn get_exe_path() -> Result { let mut exe_path = std::env::current_exe()?; let _ = exe_path.pop(); // executable file will always have a parent directory. #[cfg(test)] - if let Some(ref path_override) = *workers_exe_path_override().lock().unwrap() { - exe_path = path_override.clone(); + if let Some(o) = workers_exe_path_override() { + exe_path = o; } + Ok(exe_path) } @@ -205,8 +204,7 @@ mod tests { use super::*; use assert_matches::assert_matches; - use serial_test::serial; - use std::{env::temp_dir, fs, os::unix::fs::PermissionsExt, path::Path}; + use std::{fs, os::unix::fs::PermissionsExt, path::Path}; const TEST_NODE_VERSION: &'static str = "v0.1.2"; @@ -228,7 +226,7 @@ mod tests { fn get_program(version: &str) -> String { format!( - "#!/bin/bash + "#!/usr/bin/env bash if [[ $# -ne 1 ]] ; then echo \"unexpected number of arguments: $#\" @@ -253,27 +251,21 @@ echo {} ) -> Result<(), Box> { // Set up /usr/lib/polkadot and /usr/bin, both empty. - let tempdir = temp_dir(); - let lib_path = tempdir.join("usr/lib/polkadot"); - let _ = fs::remove_dir_all(&lib_path); - fs::create_dir_all(&lib_path)?; - *workers_lib_path_override().lock()? = Some(lib_path); + let tempdir = tempfile::tempdir().unwrap(); + let tmp_dir = tempdir.path().to_path_buf(); + TMP_DIR.with_borrow_mut(|t| *t = Some(tempdir)); - let exe_path = tempdir.join("usr/bin"); - let _ = fs::remove_dir_all(&exe_path); - fs::create_dir_all(&exe_path)?; - *workers_exe_path_override().lock()? = Some(exe_path.clone()); + fs::create_dir_all(workers_lib_path_override().unwrap()).unwrap(); + fs::create_dir_all(workers_exe_path_override().unwrap()).unwrap(); + let custom_path = tmp_dir.join("usr/local/bin"); // Set up custom path at /usr/local/bin. - let custom_path = tempdir.join("usr/local/bin"); - let _ = fs::remove_dir_all(&custom_path); - fs::create_dir_all(&custom_path)?; + fs::create_dir_all(&custom_path).unwrap(); - f(tempdir, exe_path) + f(tmp_dir, workers_exe_path_override().unwrap()) } #[test] - #[serial] fn test_given_worker_path() { with_temp_dir_structure(|tempdir, exe_path| { let given_workers_path = tempdir.join("usr/local/bin"); @@ -318,7 +310,6 @@ echo {} } #[test] - #[serial] fn missing_workers_paths_throws_error() { with_temp_dir_structure(|tempdir, exe_path| { // Try with both binaries missing. @@ -368,7 +359,6 @@ echo {} } #[test] - #[serial] fn should_find_workers_at_all_locations() { with_temp_dir_structure(|tempdir, _| { let prepare_worker_bin_path = tempdir.join("usr/bin/polkadot-prepare-worker"); @@ -394,7 +384,6 @@ echo {} } #[test] - #[serial] fn should_find_workers_with_custom_names_at_all_locations() { with_temp_dir_structure(|tempdir, _| { let (prep_worker_name, exec_worker_name) = ("test-prepare", "test-execute"); @@ -422,7 +411,6 @@ echo {} } #[test] - #[serial] fn workers_version_mismatch_throws_error() { let bad_version = "v9.9.9.9"; @@ -474,7 +462,6 @@ echo {} } #[test] - #[serial] fn should_find_valid_workers() { // Test bin location. with_temp_dir_structure(|tempdir, _| { From c81569ef341305a4b61f501cc000471645974b19 Mon Sep 17 00:00:00 2001 From: James Wilson Date: Wed, 6 Nov 2024 11:05:31 +0000 Subject: [PATCH 042/166] Don't expose metadata for Runtime APIs that haven't been implemented (#6337) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Prior to this PR, the metadata for runtime APIs was entirely based on that generated by `decl_runtime_apis`. It therefore didn't take into account that `impl_runtime_apis` might implement older versions of APIs than what has been declared. This PR filters the returned runtime API metadata to only include methods actually implemented, and also avoids including methods labelled with `changed_in` (which the previous code was atempting to do already but not successfully, owing to the attr being removed prior to the check). We also change all version related things to be `u32`s (rather than VERSION being `u32` and `api_version`s being `u64`) for consistency / ease of comparison. A test is added which works with both the `enable-staging-api` feature in api/tests enabled or disabled, to check all of this. --------- Co-authored-by: Bastian Köcher Co-authored-by: GitHub Action --- prdoc/pr_6337.prdoc | 17 +++ .../support/test/tests/runtime_metadata.rs | 2 +- .../api/proc-macro/src/decl_runtime_apis.rs | 26 ++--- .../api/proc-macro/src/impl_runtime_apis.rs | 100 ++---------------- .../api/proc-macro/src/runtime_metadata.rs | 91 +++++++++++----- .../primitives/api/proc-macro/src/utils.rs | 93 +++++++++++++++- .../api/test/tests/decl_and_impl.rs | 61 ++++++++++- .../primitives/consensus/babe/src/lib.rs | 2 +- 8 files changed, 250 insertions(+), 142 deletions(-) create mode 100644 prdoc/pr_6337.prdoc diff --git a/prdoc/pr_6337.prdoc b/prdoc/pr_6337.prdoc new file mode 100644 index 000000000000..aeab61cdf933 --- /dev/null +++ b/prdoc/pr_6337.prdoc @@ -0,0 +1,17 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Don't expose metadata for Runtime APIs that haven't been implemented + +doc: + - audience: Runtime User + description: | + Prior to this PR, the metadata for runtime APIs would contain all methods for the + latest version of each API, regardless of which version a runtime implements. This + PR fixes that, so that the runtime API metadata reflects what is actually implemented. + +crates: + - name: sp-api-proc-macro + bump: major + - name: sp-consensus-babe + bump: patch \ No newline at end of file diff --git a/substrate/frame/support/test/tests/runtime_metadata.rs b/substrate/frame/support/test/tests/runtime_metadata.rs index 81377210eb43..7523a415d458 100644 --- a/substrate/frame/support/test/tests/runtime_metadata.rs +++ b/substrate/frame/support/test/tests/runtime_metadata.rs @@ -178,7 +178,7 @@ fn runtime_metadata() { RuntimeApiMethodMetadataIR { name: "wild_card", inputs: vec![RuntimeApiMethodParamMetadataIR:: { - name: "_", + name: "__runtime_api_generated_name_0__", ty: meta_type::(), }], output: meta_type::<()>(), diff --git a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs index cb213f2fd627..ddca1095a192 100644 --- a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -32,6 +32,7 @@ use proc_macro2::{Span, TokenStream}; use quote::quote; +use std::collections::{BTreeMap, HashMap}; use syn::{ fold::{self, Fold}, parse::{Error, Parse, ParseStream, Result}, @@ -43,8 +44,6 @@ use syn::{ TraitItem, TraitItemFn, }; -use std::collections::{BTreeMap, HashMap}; - /// The structure used for parsing the runtime api declarations. struct RuntimeApiDecls { decls: Vec, @@ -133,7 +132,7 @@ fn remove_supported_attributes(attrs: &mut Vec) -> HashMap<&'static s /// ``` fn generate_versioned_api_traits( api: ItemTrait, - methods: BTreeMap>, + methods: BTreeMap>, ) -> Vec { let mut result = Vec::::new(); for (version, _) in &methods { @@ -189,15 +188,12 @@ fn generate_runtime_decls(decls: &[ItemTrait]) -> Result { extend_generics_with_block(&mut decl.generics); let mod_name = generate_runtime_mod_name_for_trait(&decl.ident); let found_attributes = remove_supported_attributes(&mut decl.attrs); - let api_version = - get_api_version(&found_attributes).map(|v| generate_runtime_api_version(v as u32))?; + let api_version = get_api_version(&found_attributes).map(generate_runtime_api_version)?; let id = generate_runtime_api_id(&decl.ident.to_string()); - let metadata = crate::runtime_metadata::generate_decl_runtime_metadata(&decl); - let trait_api_version = get_api_version(&found_attributes)?; - let mut methods_by_version: BTreeMap> = BTreeMap::new(); + let mut methods_by_version: BTreeMap> = BTreeMap::new(); // Process the items in the declaration. The filter_map function below does a lot of stuff // because the method attributes are stripped at this point @@ -255,6 +251,12 @@ fn generate_runtime_decls(decls: &[ItemTrait]) -> Result { _ => (), }); + let versioned_methods_iter = methods_by_version + .iter() + .flat_map(|(&version, methods)| methods.iter().map(move |method| (method, version))); + let metadata = + crate::runtime_metadata::generate_decl_runtime_metadata(&decl, versioned_methods_iter); + let versioned_api_traits = generate_versioned_api_traits(decl.clone(), methods_by_version); let main_api_ident = decl.ident.clone(); @@ -505,7 +507,7 @@ fn generate_runtime_api_version(version: u32) -> TokenStream { } /// Generates the implementation of `RuntimeApiInfo` for the given trait. -fn generate_runtime_info_impl(trait_: &ItemTrait, version: u64) -> TokenStream { +fn generate_runtime_info_impl(trait_: &ItemTrait, version: u32) -> TokenStream { let trait_name = &trait_.ident; let crate_ = generate_crate_access(); let id = generate_runtime_api_id(&trait_name.to_string()); @@ -537,7 +539,7 @@ fn generate_runtime_info_impl(trait_: &ItemTrait, version: u64) -> TokenStream { } /// Get changed in version from the user given attribute or `Ok(None)`, if no attribute was given. -fn get_changed_in(found_attributes: &HashMap<&'static str, Attribute>) -> Result> { +fn get_changed_in(found_attributes: &HashMap<&'static str, Attribute>) -> Result> { found_attributes .get(&CHANGED_IN_ATTRIBUTE) .map(|v| parse_runtime_api_version(v).map(Some)) @@ -545,7 +547,7 @@ fn get_changed_in(found_attributes: &HashMap<&'static str, Attribute>) -> Result } /// Get the api version from the user given attribute or `Ok(1)`, if no attribute was given. -fn get_api_version(found_attributes: &HashMap<&'static str, Attribute>) -> Result { +fn get_api_version(found_attributes: &HashMap<&'static str, Attribute>) -> Result { found_attributes .get(&API_VERSION_ATTRIBUTE) .map(parse_runtime_api_version) @@ -610,7 +612,7 @@ impl CheckTraitDecl { /// /// Any error is stored in `self.errors`. fn check_method_declarations<'a>(&mut self, methods: impl Iterator) { - let mut method_to_signature_changed = HashMap::>>::new(); + let mut method_to_signature_changed = HashMap::>>::new(); methods.into_iter().for_each(|method| { let attributes = remove_supported_attributes(&mut method.attrs.clone()); diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index de922e3253e4..89d0665f28cf 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -15,14 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{ - common::API_VERSION_ATTRIBUTE, - utils::{ - extract_block_type_from_trait_path, extract_impl_trait, - extract_parameter_names_types_and_borrows, generate_crate_access, - generate_runtime_mod_name_for_trait, parse_runtime_api_version, prefix_function_with_trait, - versioned_trait_name, AllowSelfRefInParameters, RequireQualifiedTraitPath, - }, +use crate::utils::{ + extract_api_version, extract_block_type_from_trait_path, extract_impl_trait, + extract_parameter_names_types_and_borrows, generate_crate_access, + generate_runtime_mod_name_for_trait, prefix_function_with_trait, versioned_trait_name, + AllowSelfRefInParameters, ApiVersion, RequireQualifiedTraitPath, }; use proc_macro2::{Span, TokenStream}; @@ -31,11 +28,10 @@ use quote::quote; use syn::{ fold::{self, Fold}, - parenthesized, parse::{Error, Parse, ParseStream, Result}, parse_macro_input, parse_quote, spanned::Spanned, - Attribute, Ident, ImplItem, ItemImpl, LitInt, LitStr, Path, Signature, Type, TypePath, + Attribute, Ident, ImplItem, ItemImpl, Path, Signature, Type, TypePath, }; use std::collections::HashMap; @@ -466,7 +462,7 @@ fn extend_with_runtime_decl_path(mut trait_: Path) -> Path { trait_ } -fn extend_with_api_version(mut trait_: Path, version: Option) -> Path { +fn extend_with_api_version(mut trait_: Path, version: Option) -> Path { let version = if let Some(v) = version { v } else { @@ -841,88 +837,6 @@ fn filter_cfg_attrs(attrs: &[Attribute]) -> Vec { attrs.iter().filter(|a| a.path().is_ident("cfg")).cloned().collect() } -/// Parse feature flagged api_version. -/// E.g. `#[cfg_attr(feature = "enable-staging-api", api_version(99))]` -fn extract_cfg_api_version(attrs: &Vec, span: Span) -> Result> { - let cfg_attrs = attrs.iter().filter(|a| a.path().is_ident("cfg_attr")).collect::>(); - - let mut cfg_api_version_attr = Vec::new(); - for cfg_attr in cfg_attrs { - let mut feature_name = None; - let mut api_version = None; - cfg_attr.parse_nested_meta(|m| { - if m.path.is_ident("feature") { - let a = m.value()?; - let b: LitStr = a.parse()?; - feature_name = Some(b.value()); - } else if m.path.is_ident(API_VERSION_ATTRIBUTE) { - let content; - parenthesized!(content in m.input); - let ver: LitInt = content.parse()?; - api_version = Some(ver.base10_parse::()?); - } - Ok(()) - })?; - - // If there is a cfg attribute containing api_version - save if for processing - if let (Some(feature_name), Some(api_version)) = (feature_name, api_version) { - cfg_api_version_attr.push((feature_name, api_version, cfg_attr.span())); - } - } - - if cfg_api_version_attr.len() > 1 { - let mut err = Error::new(span, format!("Found multiple feature gated api versions (cfg attribute with nested `{}` attribute). This is not supported.", API_VERSION_ATTRIBUTE)); - for (_, _, attr_span) in cfg_api_version_attr { - err.combine(Error::new(attr_span, format!("`{}` found here", API_VERSION_ATTRIBUTE))); - } - - return Err(err); - } - - Ok(cfg_api_version_attr - .into_iter() - .next() - .map(|(feature, name, _)| (feature, name))) -} - -/// Represents an API version. -struct ApiVersion { - /// Corresponds to `#[api_version(X)]` attribute. - pub custom: Option, - /// Corresponds to `#[cfg_attr(feature = "enable-staging-api", api_version(99))]` - /// attribute. `String` is the feature name, `u64` the staging api version. - pub feature_gated: Option<(String, u64)>, -} - -// Extracts the value of `API_VERSION_ATTRIBUTE` and handles errors. -// Returns: -// - Err if the version is malformed -// - `ApiVersion` on success. If a version is set or not is determined by the fields of `ApiVersion` -fn extract_api_version(attrs: &Vec, span: Span) -> Result { - // First fetch all `API_VERSION_ATTRIBUTE` values (should be only one) - let api_ver = attrs - .iter() - .filter(|a| a.path().is_ident(API_VERSION_ATTRIBUTE)) - .collect::>(); - - if api_ver.len() > 1 { - return Err(Error::new( - span, - format!( - "Found multiple #[{}] attributes for an API implementation. \ - Each runtime API can have only one version.", - API_VERSION_ATTRIBUTE - ), - )); - } - - // Parse the runtime version if there exists one. - Ok(ApiVersion { - custom: api_ver.first().map(|v| parse_runtime_api_version(v)).transpose()?, - feature_gated: extract_cfg_api_version(attrs, span)?, - }) -} - #[cfg(test)] mod tests { use super::*; diff --git a/substrate/primitives/api/proc-macro/src/runtime_metadata.rs b/substrate/primitives/api/proc-macro/src/runtime_metadata.rs index 4cba524dbe25..6be396339259 100644 --- a/substrate/primitives/api/proc-macro/src/runtime_metadata.rs +++ b/substrate/primitives/api/proc-macro/src/runtime_metadata.rs @@ -17,14 +17,11 @@ use proc_macro2::TokenStream as TokenStream2; use quote::quote; -use syn::{parse_quote, ItemImpl, ItemTrait, Result}; - -use crate::{ - common::CHANGED_IN_ATTRIBUTE, - utils::{ - extract_impl_trait, filter_cfg_attributes, generate_crate_access, - generate_runtime_mod_name_for_trait, get_doc_literals, RequireQualifiedTraitPath, - }, +use syn::{parse_quote, spanned::Spanned, ItemImpl, ItemTrait, Result}; + +use crate::utils::{ + extract_api_version, extract_impl_trait, filter_cfg_attributes, generate_crate_access, + generate_runtime_mod_name_for_trait, get_doc_literals, RequireQualifiedTraitPath, }; /// Get the type parameter argument without lifetime or mutability @@ -72,7 +69,10 @@ fn collect_docs(attrs: &[syn::Attribute], crate_: &TokenStream2) -> TokenStream2 /// /// The metadata is exposed as a generic function on the hidden module /// of the trait generated by the `decl_runtime_apis`. -pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { +pub fn generate_decl_runtime_metadata<'a>( + decl: &ItemTrait, + versioned_methods_iter: impl Iterator, +) -> TokenStream2 { let crate_ = generate_crate_access(); let mut methods = Vec::new(); @@ -86,17 +86,7 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { // This restricts the bounds at the metadata level, without needing to modify the `BlockT` // itself, since the concrete implementations are already satisfying `TypeInfo`. let mut where_clause = Vec::new(); - for item in &decl.items { - // Collect metadata for methods only. - let syn::TraitItem::Fn(method) = item else { continue }; - - // Collect metadata only for the latest methods. - let is_changed_in = - method.attrs.iter().any(|attr| attr.path().is_ident(CHANGED_IN_ATTRIBUTE)); - if is_changed_in { - continue; - } - + for (method, version) in versioned_methods_iter { let mut inputs = Vec::new(); let signature = &method.sig; for input in &signature.inputs { @@ -135,14 +125,21 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { Ok(deprecation) => deprecation, Err(e) => return e.into_compile_error(), }; + + // Methods are filtered so that only those whose version is <= the `impl_version` passed to + // `runtime_metadata` are kept in the metadata we hand back. methods.push(quote!( #( #attrs )* - #crate_::metadata_ir::RuntimeApiMethodMetadataIR { - name: #method_name, - inputs: #crate_::vec![ #( #inputs, )* ], - output: #output, - docs: #docs, - deprecation_info: #deprecation, + if #version <= impl_version { + Some(#crate_::metadata_ir::RuntimeApiMethodMetadataIR { + name: #method_name, + inputs: #crate_::vec![ #( #inputs, )* ], + output: #output, + docs: #docs, + deprecation_info: #deprecation, + }) + } else { + None } )); } @@ -176,12 +173,15 @@ pub fn generate_decl_runtime_metadata(decl: &ItemTrait) -> TokenStream2 { #crate_::frame_metadata_enabled! { #( #attrs )* #[inline(always)] - pub fn runtime_metadata #impl_generics () -> #crate_::metadata_ir::RuntimeApiMetadataIR + pub fn runtime_metadata #impl_generics (impl_version: u32) -> #crate_::metadata_ir::RuntimeApiMetadataIR #where_clause { #crate_::metadata_ir::RuntimeApiMetadataIR { name: #trait_name, - methods: #crate_::vec![ #( #methods, )* ], + methods: [ #( #methods, )* ] + .into_iter() + .filter_map(|maybe_m| maybe_m) + .collect(), docs: #docs, deprecation_info: #deprecation, } @@ -242,10 +242,43 @@ pub fn generate_impl_runtime_metadata(impls: &[ItemImpl]) -> Result Result { +pub fn parse_runtime_api_version(version: &Attribute) -> Result { let version = version.parse_args::().map_err(|_| { Error::new( version.span(), @@ -231,7 +231,7 @@ pub fn parse_runtime_api_version(version: &Attribute) -> Result { } /// Each versioned trait is named 'ApiNameVN' where N is the specific version. E.g. ParachainHostV2 -pub fn versioned_trait_name(trait_ident: &Ident, version: u64) -> Ident { +pub fn versioned_trait_name(trait_ident: &Ident, version: u32) -> Ident { format_ident!("{}V{}", trait_ident, version) } @@ -334,6 +334,89 @@ pub fn get_deprecation(crate_: &TokenStream, attrs: &[syn::Attribute]) -> Result .unwrap_or_else(|| Ok(quote! {#crate_::metadata_ir::DeprecationStatusIR::NotDeprecated})) } +/// Represents an API version. +pub struct ApiVersion { + /// Corresponds to `#[api_version(X)]` attribute. + pub custom: Option, + /// Corresponds to `#[cfg_attr(feature = "enable-staging-api", api_version(99))]` + /// attribute. `String` is the feature name, `u32` the staging api version. + pub feature_gated: Option<(String, u32)>, +} + +/// Extracts the value of `API_VERSION_ATTRIBUTE` and handles errors. +/// Returns: +/// - Err if the version is malformed +/// - `ApiVersion` on success. If a version is set or not is determined by the fields of +/// `ApiVersion` +pub fn extract_api_version(attrs: &[Attribute], span: Span) -> Result { + // First fetch all `API_VERSION_ATTRIBUTE` values (should be only one) + let api_ver = attrs + .iter() + .filter(|a| a.path().is_ident(API_VERSION_ATTRIBUTE)) + .collect::>(); + + if api_ver.len() > 1 { + return Err(Error::new( + span, + format!( + "Found multiple #[{}] attributes for an API implementation. \ + Each runtime API can have only one version.", + API_VERSION_ATTRIBUTE + ), + )); + } + + // Parse the runtime version if there exists one. + Ok(ApiVersion { + custom: api_ver.first().map(|v| parse_runtime_api_version(v)).transpose()?, + feature_gated: extract_cfg_api_version(attrs, span)?, + }) +} + +/// Parse feature flagged api_version. +/// E.g. `#[cfg_attr(feature = "enable-staging-api", api_version(99))]` +fn extract_cfg_api_version(attrs: &[Attribute], span: Span) -> Result> { + let cfg_attrs = attrs.iter().filter(|a| a.path().is_ident("cfg_attr")).collect::>(); + + let mut cfg_api_version_attr = Vec::new(); + for cfg_attr in cfg_attrs { + let mut feature_name = None; + let mut api_version = None; + cfg_attr.parse_nested_meta(|m| { + if m.path.is_ident("feature") { + let a = m.value()?; + let b: LitStr = a.parse()?; + feature_name = Some(b.value()); + } else if m.path.is_ident(API_VERSION_ATTRIBUTE) { + let content; + parenthesized!(content in m.input); + let ver: LitInt = content.parse()?; + api_version = Some(ver.base10_parse::()?); + } + Ok(()) + })?; + + // If there is a cfg attribute containing api_version - save if for processing + if let (Some(feature_name), Some(api_version)) = (feature_name, api_version) { + cfg_api_version_attr.push((feature_name, api_version, cfg_attr.span())); + } + } + + if cfg_api_version_attr.len() > 1 { + let mut err = Error::new(span, format!("Found multiple feature gated api versions (cfg attribute with nested `{}` attribute). This is not supported.", API_VERSION_ATTRIBUTE)); + for (_, _, attr_span) in cfg_api_version_attr { + err.combine(Error::new(attr_span, format!("`{}` found here", API_VERSION_ATTRIBUTE))); + } + + return Err(err); + } + + Ok(cfg_api_version_attr + .into_iter() + .next() + .map(|(feature, name, _)| (feature, name))) +} + #[cfg(test)] mod tests { use assert_matches::assert_matches; diff --git a/substrate/primitives/api/test/tests/decl_and_impl.rs b/substrate/primitives/api/test/tests/decl_and_impl.rs index 211a08561fd4..890cf6eccdbc 100644 --- a/substrate/primitives/api/test/tests/decl_and_impl.rs +++ b/substrate/primitives/api/test/tests/decl_and_impl.rs @@ -24,7 +24,7 @@ use substrate_test_runtime_client::runtime::{Block, Hash}; /// The declaration of the `Runtime` type is done by the `construct_runtime!` macro in a real /// runtime. -pub enum Runtime {} +pub struct Runtime {} decl_runtime_apis! { pub trait Api { @@ -306,3 +306,62 @@ fn mock_runtime_api_works_with_advanced() { mock.wild_card(Hash::repeat_byte(0x01), 1).unwrap_err().to_string(), ); } + +#[test] +fn runtime_api_metadata_matches_version_implemented() { + let rt = Runtime {}; + let runtime_metadata = rt.runtime_metadata(); + + // Check that the metadata for some runtime API matches expectation. + let assert_has_api_with_methods = |api_name: &str, api_methods: &[&str]| { + let Some(api) = runtime_metadata.iter().find(|api| api.name == api_name) else { + panic!("Can't find runtime API '{api_name}'"); + }; + if api.methods.len() != api_methods.len() { + panic!( + "Wrong number of methods in '{api_name}'; expected {} methods but got {}: {:?}", + api_methods.len(), + api.methods.len(), + api.methods + ); + } + for expected_name in api_methods { + if !api.methods.iter().any(|method| &method.name == expected_name) { + panic!("Can't find API method '{expected_name}' in '{api_name}'"); + } + } + }; + + assert_has_api_with_methods("ApiWithCustomVersion", &["same_name"]); + + assert_has_api_with_methods("ApiWithMultipleVersions", &["stable_one", "new_one"]); + + assert_has_api_with_methods( + "ApiWithStagingMethod", + &[ + "stable_one", + #[cfg(feature = "enable-staging-api")] + "staging_one", + ], + ); + + assert_has_api_with_methods( + "ApiWithStagingAndVersionedMethods", + &[ + "stable_one", + "new_one", + #[cfg(feature = "enable-staging-api")] + "staging_one", + ], + ); + + assert_has_api_with_methods( + "ApiWithStagingAndChangedBase", + &[ + "stable_one", + "new_one", + #[cfg(feature = "enable-staging-api")] + "staging_one", + ], + ); +} diff --git a/substrate/primitives/consensus/babe/src/lib.rs b/substrate/primitives/consensus/babe/src/lib.rs index ee07da6829f5..163fbafa8dd4 100644 --- a/substrate/primitives/consensus/babe/src/lib.rs +++ b/substrate/primitives/consensus/babe/src/lib.rs @@ -134,7 +134,7 @@ pub enum ConsensusLog { } /// Configuration data used by the BABE consensus engine. -#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] +#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] pub struct BabeConfigurationV1 { /// The slot duration in milliseconds for BABE. Currently, only /// the value provided by this type at genesis will be used. From 6170c37f5703617f18fe93d4f87a2ac05ef8dfd4 Mon Sep 17 00:00:00 2001 From: Egor_P Date: Wed, 6 Nov 2024 14:12:57 +0100 Subject: [PATCH 043/166] [Release|CI/CD] Fix GH_TOKEN owner (#6381) A quick fix to the step that generates a temporary token used in the pipeline --- .github/workflows/release-10_rc-automation.yml | 2 +- .github/workflows/release-branchoff-stable.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-10_rc-automation.yml b/.github/workflows/release-10_rc-automation.yml index 4ec4c05252b3..0be671185c70 100644 --- a/.github/workflows/release-10_rc-automation.yml +++ b/.github/workflows/release-10_rc-automation.yml @@ -42,7 +42,7 @@ jobs: with: app-id: ${{ vars.RELEASE_AUTOMATION_APP_ID }} private-key: ${{ secrets.RELEASE_AUTOMATION_APP_PRIVATE_KEY }} - owner: paritytech-release + owner: paritytech - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 diff --git a/.github/workflows/release-branchoff-stable.yml b/.github/workflows/release-branchoff-stable.yml index 4249a274ffd7..adce1b261b71 100644 --- a/.github/workflows/release-branchoff-stable.yml +++ b/.github/workflows/release-branchoff-stable.yml @@ -58,7 +58,7 @@ jobs: with: app-id: ${{ vars.RELEASE_AUTOMATION_APP_ID }} private-key: ${{ secrets.RELEASE_AUTOMATION_APP_PRIVATE_KEY }} - owner: paritytech-release + owner: paritytech - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 From 67394cd160809d205a63879effa14b738a698096 Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Wed, 6 Nov 2024 15:39:33 +0200 Subject: [PATCH 044/166] collator protocol: validate descriptor version on the validator side (#6011) Part of https://github.com/paritytech/polkadot-sdk/issues/5047 TODO: - [x] prdoc - [x] fix/add tests --------- Signed-off-by: Andrei Sandu Co-authored-by: Andrei Sandu Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com> --- .../network/collator-protocol/src/error.rs | 25 +- .../src/validator_side/collation.rs | 25 +- .../src/validator_side/mod.rs | 159 +++++++---- .../src/validator_side/tests/mod.rs | 133 +++++---- .../tests/prospective_parachains.rs | 265 ++++++++++++++++-- prdoc/pr_6011.prdoc | 12 + 6 files changed, 481 insertions(+), 138 deletions(-) create mode 100644 prdoc/pr_6011.prdoc diff --git a/polkadot/node/network/collator-protocol/src/error.rs b/polkadot/node/network/collator-protocol/src/error.rs index 0f5e0699d85c..ae7f9a8c1fbc 100644 --- a/polkadot/node/network/collator-protocol/src/error.rs +++ b/polkadot/node/network/collator-protocol/src/error.rs @@ -23,6 +23,7 @@ use polkadot_node_network_protocol::request_response::incoming; use polkadot_node_primitives::UncheckedSignedFullStatement; use polkadot_node_subsystem::{errors::SubsystemError, RuntimeApiError}; use polkadot_node_subsystem_util::{backing_implicit_view, runtime}; +use polkadot_primitives::vstaging::CandidateDescriptorVersion; use crate::LOG_TARGET; @@ -63,6 +64,12 @@ pub enum Error { #[error("CollationSeconded contained statement with invalid signature")] InvalidStatementSignature(UncheckedSignedFullStatement), + + #[error("Response receiver for session index request cancelled")] + CancelledSessionIndex(oneshot::Canceled), + + #[error("Response receiver for claim queue request cancelled")] + CancelledClaimQueue(oneshot::Canceled), } /// An error happened on the validator side of the protocol when attempting @@ -87,11 +94,23 @@ pub enum SecondingError { #[error("Candidate hash doesn't match the advertisement")] CandidateHashMismatch, + #[error("Relay parent hash doesn't match the advertisement")] + RelayParentMismatch, + #[error("Received duplicate collation from the peer")] Duplicate, #[error("The provided parent head data does not match the hash")] ParentHeadDataMismatch, + + #[error("Core index {0} present in descriptor is different than the assigned core {1}")] + InvalidCoreIndex(u32, u32), + + #[error("Session index {0} present in descriptor is different than the expected one {1}")] + InvalidSessionIndex(u32, u32), + + #[error("Invalid candidate receipt version {0:?}")] + InvalidReceiptVersion(CandidateDescriptorVersion), } impl SecondingError { @@ -102,7 +121,11 @@ impl SecondingError { self, PersistedValidationDataMismatch | CandidateHashMismatch | - Duplicate | ParentHeadDataMismatch + RelayParentMismatch | + Duplicate | ParentHeadDataMismatch | + InvalidCoreIndex(_, _) | + InvalidSessionIndex(_, _) | + InvalidReceiptVersion(_) ) } } diff --git a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs index 0b3e9f4b3431..cc0de1cb70f6 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs @@ -129,9 +129,6 @@ pub struct BlockedCollationId { } /// Performs a sanity check between advertised and fetched collations. -/// -/// Since the persisted validation data is constructed using the advertised -/// parent head data hash, the latter doesn't require an additional check. pub fn fetched_collation_sanity_check( advertised: &PendingCollation, fetched: &CandidateReceipt, @@ -139,17 +136,25 @@ pub fn fetched_collation_sanity_check( maybe_parent_head_and_hash: Option<(HeadData, Hash)>, ) -> Result<(), SecondingError> { if persisted_validation_data.hash() != fetched.descriptor().persisted_validation_data_hash() { - Err(SecondingError::PersistedValidationDataMismatch) - } else if advertised + return Err(SecondingError::PersistedValidationDataMismatch) + } + + if advertised .prospective_candidate .map_or(false, |pc| pc.candidate_hash() != fetched.hash()) { - Err(SecondingError::CandidateHashMismatch) - } else if maybe_parent_head_and_hash.map_or(false, |(head, hash)| head.hash() != hash) { - Err(SecondingError::ParentHeadDataMismatch) - } else { - Ok(()) + return Err(SecondingError::CandidateHashMismatch) + } + + if advertised.relay_parent != fetched.descriptor.relay_parent() { + return Err(SecondingError::RelayParentMismatch) } + + if maybe_parent_head_and_hash.map_or(false, |(head, hash)| head.hash() != hash) { + return Err(SecondingError::ParentHeadDataMismatch) + } + + Ok(()) } /// Identifier for a requested collation and the respective collator that advertised it. diff --git a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs index 51e987d59ce8..86358f503d04 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs @@ -49,11 +49,14 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_util::{ backing_implicit_view::View as ImplicitView, reputation::{ReputationAggregator, REPUTATION_CHANGE_INTERVAL}, - runtime::{fetch_claim_queue, prospective_parachains_mode, ProspectiveParachainsMode}, + request_claim_queue, request_session_index_for_child, + runtime::{prospective_parachains_mode, request_node_features, ProspectiveParachainsMode}, }; use polkadot_primitives::{ - vstaging::CoreState, CandidateHash, CollatorId, Hash, HeadData, Id as ParaId, - OccupiedCoreAssumption, PersistedValidationData, + node_features, + vstaging::{CandidateDescriptorV2, CandidateDescriptorVersion, CoreState}, + CandidateHash, CollatorId, CoreIndex, Hash, HeadData, Id as ParaId, OccupiedCoreAssumption, + PersistedValidationData, SessionIndex, }; use crate::error::{Error, FetchError, Result, SecondingError}; @@ -369,16 +372,9 @@ struct PerRelayParent { prospective_parachains_mode: ProspectiveParachainsMode, assignment: GroupAssignments, collations: Collations, -} - -impl PerRelayParent { - fn new(mode: ProspectiveParachainsMode) -> Self { - Self { - prospective_parachains_mode: mode, - assignment: GroupAssignments { current: vec![] }, - collations: Collations::default(), - } - } + v2_receipts: bool, + current_core: CoreIndex, + session_index: SessionIndex, } /// All state relevant for the validator side of the protocol lives here. @@ -460,14 +456,15 @@ fn is_relay_parent_in_implicit_view( } } -async fn assign_incoming( +async fn construct_per_relay_parent( sender: &mut Sender, - group_assignment: &mut GroupAssignments, current_assignments: &mut HashMap, keystore: &KeystorePtr, relay_parent: Hash, relay_parent_mode: ProspectiveParachainsMode, -) -> Result<()> + v2_receipts: bool, + session_index: SessionIndex, +) -> Result> where Sender: CollatorProtocolSenderTrait, { @@ -494,25 +491,25 @@ where rotation_info.core_for_group(group, cores.len()) } else { gum::trace!(target: LOG_TARGET, ?relay_parent, "Not a validator"); - return Ok(()) + return Ok(None) }; - let paras_now = match fetch_claim_queue(sender, relay_parent).await.map_err(Error::Runtime)? { - // Runtime supports claim queue - use it - // - // `relay_parent_mode` is not examined here because if the runtime supports claim queue - // then it supports async backing params too (`ASYNC_BACKING_STATE_RUNTIME_REQUIREMENT` - // < `CLAIM_QUEUE_RUNTIME_REQUIREMENT`). - Some(mut claim_queue) => claim_queue.0.remove(&core_now), - // Claim queue is not supported by the runtime - use availability cores instead. - None => cores.get(core_now.0 as usize).and_then(|c| match c { - CoreState::Occupied(core) if relay_parent_mode.is_enabled() => - core.next_up_on_available.as_ref().map(|c| [c.para_id].into_iter().collect()), - CoreState::Scheduled(core) => Some([core.para_id].into_iter().collect()), - CoreState::Occupied(_) | CoreState::Free => None, - }), - } - .unwrap_or_else(|| VecDeque::new()); + let claim_queue = request_claim_queue(relay_parent, sender) + .await + .await + .map_err(Error::CancelledClaimQueue)??; + + let paras_now = cores + .get(core_now.0 as usize) + .and_then(|c| match (c, relay_parent_mode) { + (CoreState::Occupied(_), ProspectiveParachainsMode::Disabled) => None, + ( + CoreState::Occupied(_), + ProspectiveParachainsMode::Enabled { max_candidate_depth: 0, .. }, + ) => None, + _ => claim_queue.get(&core_now).cloned(), + }) + .unwrap_or_else(|| VecDeque::new()); for para_id in paras_now.iter() { let entry = current_assignments.entry(*para_id).or_default(); @@ -527,9 +524,14 @@ where } } - *group_assignment = GroupAssignments { current: paras_now.into_iter().collect() }; - - Ok(()) + Ok(Some(PerRelayParent { + prospective_parachains_mode: relay_parent_mode, + assignment: GroupAssignments { current: paras_now.into_iter().collect() }, + collations: Collations::default(), + v2_receipts, + session_index, + current_core: core_now, + })) } fn remove_outgoing( @@ -1249,18 +1251,31 @@ where let added = view.iter().filter(|h| !current_leaves.contains_key(h)); for leaf in added { + let session_index = request_session_index_for_child(*leaf, sender) + .await + .await + .map_err(Error::CancelledSessionIndex)??; let mode = prospective_parachains_mode(sender, *leaf).await?; - - let mut per_relay_parent = PerRelayParent::new(mode); - assign_incoming( + let v2_receipts = request_node_features(*leaf, session_index, sender) + .await? + .unwrap_or_default() + .get(node_features::FeatureIndex::CandidateReceiptV2 as usize) + .map(|b| *b) + .unwrap_or(false); + + let Some(per_relay_parent) = construct_per_relay_parent( sender, - &mut per_relay_parent.assignment, &mut state.current_assignments, keystore, *leaf, mode, + v2_receipts, + session_index, ) - .await?; + .await? + else { + continue + }; state.active_leaves.insert(*leaf, mode); state.per_relay_parent.insert(*leaf, per_relay_parent); @@ -1279,18 +1294,21 @@ where .unwrap_or_default(); for block_hash in allowed_ancestry { if let Entry::Vacant(entry) = state.per_relay_parent.entry(*block_hash) { - let mut per_relay_parent = PerRelayParent::new(mode); - assign_incoming( + // Safe to use the same v2 receipts config for the allowed relay parents as well + // as the same session index since they must be in the same session. + if let Some(per_relay_parent) = construct_per_relay_parent( sender, - &mut per_relay_parent.assignment, &mut state.current_assignments, keystore, *block_hash, mode, + v2_receipts, + session_index, ) - .await?; - - entry.insert(per_relay_parent); + .await? + { + entry.insert(per_relay_parent); + } } } } @@ -1621,11 +1639,10 @@ async fn run_inner( Ok(FromOrchestra::Signal(OverseerSignal::Conclude)) | Err(_) => break, Ok(FromOrchestra::Signal(_)) => continue, } - } + }, _ = next_inactivity_stream.next() => { disconnect_inactive_peers(ctx.sender(), &eviction_policy, &state.peer_data).await; - } - + }, resp = state.collation_requests.select_next_some() => { let res = match handle_collation_fetch_response( &mut state, @@ -1684,7 +1701,7 @@ async fn run_inner( } Ok(true) => {} } - } + }, res = state.collation_fetch_timeouts.select_next_some() => { let (collator_id, maybe_candidate_hash, relay_parent) = res; gum::debug!( @@ -1814,6 +1831,10 @@ async fn kick_off_seconding( return Ok(false) }, }; + + // Sanity check of the candidate receipt version. + descriptor_version_sanity_check(candidate_receipt.descriptor(), per_relay_parent)?; + let collations = &mut per_relay_parent.collations; let fetched_collation = FetchedCollation::from(&candidate_receipt); @@ -2024,7 +2045,9 @@ async fn handle_collation_fetch_response( }, Ok( request_v1::CollationFetchingResponse::Collation(receipt, _) | - request_v1::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. }, + request_v2::CollationFetchingResponse::Collation(receipt, _) | + request_v1::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. } | + request_v2::CollationFetchingResponse::CollationWithParentHeadData { receipt, .. }, ) if receipt.descriptor().para_id() != pending_collation.para_id => { gum::debug!( target: LOG_TARGET, @@ -2086,3 +2109,35 @@ async fn handle_collation_fetch_response( state.metrics.on_request(metrics_result); result } + +// Sanity check the candidate descriptor version. +fn descriptor_version_sanity_check( + descriptor: &CandidateDescriptorV2, + per_relay_parent: &PerRelayParent, +) -> std::result::Result<(), SecondingError> { + match descriptor.version() { + CandidateDescriptorVersion::V1 => Ok(()), + CandidateDescriptorVersion::V2 if per_relay_parent.v2_receipts => { + if let Some(core_index) = descriptor.core_index() { + if core_index != per_relay_parent.current_core { + return Err(SecondingError::InvalidCoreIndex( + core_index.0, + per_relay_parent.current_core.0, + )) + } + } + + if let Some(session_index) = descriptor.session_index() { + if session_index != per_relay_parent.session_index { + return Err(SecondingError::InvalidSessionIndex( + session_index, + per_relay_parent.session_index, + )) + } + } + + Ok(()) + }, + descriptor_version => Err(SecondingError::InvalidReceiptVersion(descriptor_version)), + } +} diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs index 290c4db901d5..7bc61dd4ebec 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs @@ -42,9 +42,10 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::{reputation::add_reputation, TimeoutExt}; use polkadot_primitives::{ + node_features, vstaging::{CandidateReceiptV2 as CandidateReceipt, CoreState, OccupiedCore}, - CollatorPair, CoreIndex, GroupIndex, GroupRotationInfo, HeadData, PersistedValidationData, - ScheduledCore, ValidatorId, ValidatorIndex, + CollatorPair, CoreIndex, GroupIndex, GroupRotationInfo, HeadData, NodeFeatures, + PersistedValidationData, ScheduledCore, ValidatorId, ValidatorIndex, }; use polkadot_primitives_test_helpers::{ dummy_candidate_descriptor, dummy_candidate_receipt_bad_sig, dummy_hash, @@ -78,6 +79,8 @@ struct TestState { group_rotation_info: GroupRotationInfo, cores: Vec, claim_queue: BTreeMap>, + node_features: NodeFeatures, + session_index: SessionIndex, } impl Default for TestState { @@ -132,6 +135,10 @@ impl Default for TestState { claim_queue.insert(CoreIndex(1), VecDeque::new()); claim_queue.insert(CoreIndex(2), [chain_ids[1]].into_iter().collect()); + let mut node_features = NodeFeatures::EMPTY; + node_features.resize(node_features::FeatureIndex::CandidateReceiptV2 as usize + 1, false); + node_features.set(node_features::FeatureIndex::CandidateReceiptV2 as u8 as usize, true); + Self { chain_ids, relay_parent, @@ -141,6 +148,8 @@ impl Default for TestState { group_rotation_info, cores, claim_queue, + node_features, + session_index: 1, } } } @@ -237,10 +246,44 @@ async fn overseer_signal(overseer: &mut VirtualOverseer, signal: OverseerSignal) .expect(&format!("{:?} is more than enough for sending signals.", TIMEOUT)); } -async fn respond_to_core_info_queries( +async fn respond_to_runtime_api_queries( virtual_overseer: &mut VirtualOverseer, test_state: &TestState, + hash: Hash, ) { + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + rp, + RuntimeApiRequest::SessionIndexForChild(tx) + )) => { + assert_eq!(rp, hash); + tx.send(Ok(test_state.session_index)).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + rp, + RuntimeApiRequest::AsyncBackingParams(tx) + )) => { + assert_eq!(rp, hash); + tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + rp, + RuntimeApiRequest::NodeFeatures(_, tx) + )) => { + assert_eq!(rp, hash); + tx.send(Ok(test_state.node_features.clone())).unwrap(); + } + ); + assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( @@ -254,9 +297,10 @@ async fn respond_to_core_info_queries( assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, + rp, RuntimeApiRequest::ValidatorGroups(tx), )) => { + assert_eq!(rp, hash); let _ = tx.send(Ok(( test_state.validator_groups.clone(), test_state.group_rotation_info.clone(), @@ -267,9 +311,10 @@ async fn respond_to_core_info_queries( assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, + rp, RuntimeApiRequest::AvailabilityCores(tx), )) => { + assert_eq!(rp, hash); let _ = tx.send(Ok(test_state.cores.clone())); } ); @@ -277,19 +322,10 @@ async fn respond_to_core_info_queries( assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::Version(tx), - )) => { - let _ = tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)); - } - ); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, + rp, RuntimeApiRequest::ClaimQueue(tx), )) => { + assert_eq!(rp, hash); let _ = tx.send(Ok(test_state.claim_queue.clone())); } ); @@ -470,19 +506,6 @@ async fn advertise_collation( .await; } -async fn assert_async_backing_params_request(virtual_overseer: &mut VirtualOverseer, hash: Hash) { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - relay_parent, - RuntimeApiRequest::AsyncBackingParams(tx) - )) => { - assert_eq!(relay_parent, hash); - tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); - } - ); -} - // As we receive a relevant advertisement act on it and issue a collation request. #[test] fn act_on_advertisement() { @@ -502,8 +525,8 @@ fn act_on_advertisement() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -550,8 +573,8 @@ fn act_on_advertisement_v2() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -631,9 +654,8 @@ fn collator_reporting_works() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); let peer_c = PeerId::random(); @@ -748,8 +770,7 @@ fn fetch_one_collation_at_a_time() { // Iter over view since the order may change due to sorted invariant. for hash in our_view.iter() { - assert_async_backing_params_request(&mut virtual_overseer, *hash).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, *hash).await; } let peer_b = PeerId::random(); @@ -847,8 +868,7 @@ fn fetches_next_collation() { .await; for hash in our_view.iter() { - assert_async_backing_params_request(&mut virtual_overseer, *hash).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, *hash).await; } let peer_b = PeerId::random(); @@ -972,8 +992,8 @@ fn reject_connection_to_next_group() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1024,8 +1044,7 @@ fn fetch_next_collation_on_invalid_collation() { .await; for hash in our_view.iter() { - assert_async_backing_params_request(&mut virtual_overseer, *hash).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, *hash).await; } let peer_b = PeerId::random(); @@ -1135,8 +1154,8 @@ fn inactive_disconnected() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, hash_a).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1189,8 +1208,7 @@ fn activity_extends_life() { .await; for hash in our_view.iter() { - assert_async_backing_params_request(&mut virtual_overseer, *hash).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, *hash).await; } let peer_b = PeerId::random(); @@ -1263,8 +1281,8 @@ fn disconnect_if_no_declare() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1302,8 +1320,8 @@ fn disconnect_if_wrong_declare() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1364,8 +1382,8 @@ fn delay_reputation_change() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1450,8 +1468,8 @@ fn view_change_clears_old_collators() { ) .await; - assert_async_backing_params_request(&mut virtual_overseer, test_state.relay_parent).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) + .await; let peer_b = PeerId::random(); @@ -1475,8 +1493,7 @@ fn view_change_clears_old_collators() { .await; test_state.group_rotation_info = test_state.group_rotation_info.bump_rotation(); - assert_async_backing_params_request(&mut virtual_overseer, hash_b).await; - respond_to_core_info_queries(&mut virtual_overseer, &test_state).await; + respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, hash_b).await; assert_collator_disconnect(&mut virtual_overseer, peer_b).await; diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs index e040163cd905..eda26e8539a1 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs @@ -20,9 +20,10 @@ use super::*; use polkadot_node_subsystem::messages::ChainApiMessage; use polkadot_primitives::{ - vstaging::CommittedCandidateReceiptV2 as CommittedCandidateReceipt, AsyncBackingParams, - BlockNumber, CandidateCommitments, Header, SigningContext, ValidatorId, + vstaging::{CommittedCandidateReceiptV2 as CommittedCandidateReceipt, MutateDescriptorV2}, + AsyncBackingParams, BlockNumber, CandidateCommitments, Header, SigningContext, ValidatorId, }; +use polkadot_primitives_test_helpers::dummy_committed_candidate_receipt_v2; use rstest::rstest; const ASYNC_BACKING_PARAMETERS: AsyncBackingParams = @@ -32,7 +33,7 @@ fn get_parent_hash(hash: Hash) -> Hash { Hash::from_low_u64_be(hash.to_low_u64_be() + 1) } -async fn assert_assign_incoming( +async fn assert_construct_per_relay_parent( virtual_overseer: &mut VirtualOverseer, test_state: &TestState, hash: Hash, @@ -73,16 +74,6 @@ async fn assert_assign_incoming( } ); - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::Version(tx), - )) if parent == hash => { - let _ = tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)); - } - ); - assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( @@ -117,14 +108,34 @@ pub(super) async fn update_view( overseer_recv(virtual_overseer).await, AllMessages::RuntimeApi(RuntimeApiMessage::Request( parent, + RuntimeApiRequest::SessionIndexForChild(tx) + )) => { + tx.send(Ok(test_state.session_index)).unwrap(); + (parent, new_view.get(&parent).copied().expect("Unknown parent requested")) + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, RuntimeApiRequest::AsyncBackingParams(tx), )) => { tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap(); - (parent, new_view.get(&parent).copied().expect("Unknown parent requested")) } ); - assert_assign_incoming( + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::NodeFeatures(_, tx) + )) => { + tx.send(Ok(test_state.node_features.clone())).unwrap(); + } + ); + + assert_construct_per_relay_parent( virtual_overseer, test_state, leaf_hash, @@ -193,7 +204,7 @@ pub(super) async fn update_view( // Skip the leaf. for (hash, number) in ancestry_iter.skip(1).take(requested_len.saturating_sub(1)) { - assert_assign_incoming( + assert_construct_per_relay_parent( virtual_overseer, test_state, hash, @@ -406,7 +417,7 @@ fn v1_advertisement_accepted_and_seconded() { } #[test] -fn v1_advertisement_rejected_on_non_active_leave() { +fn v1_advertisement_rejected_on_non_active_leaf() { let test_state = TestState::default(); test_harness(ReputationAggregator::new(|_| true), |test_harness| async move { @@ -1314,3 +1325,223 @@ fn child_blocked_from_seconding_by_parent(#[case] valid_parent: bool) { virtual_overseer }); } + +#[rstest] +#[case(true)] +#[case(false)] +fn v2_descriptor(#[case] v2_feature_enabled: bool) { + let mut test_state = TestState::default(); + + if !v2_feature_enabled { + test_state.node_features = NodeFeatures::EMPTY; + } + + test_harness(ReputationAggregator::new(|_| true), |test_harness| async move { + let TestHarness { mut virtual_overseer, keystore } = test_harness; + + let pair_a = CollatorPair::generate().0; + + let head_b = Hash::from_low_u64_be(128); + let head_b_num: u32 = 0; + + update_view(&mut virtual_overseer, &test_state, vec![(head_b, head_b_num)], 1).await; + + let peer_a = PeerId::random(); + + connect_and_declare_collator( + &mut virtual_overseer, + peer_a, + pair_a.clone(), + test_state.chain_ids[0], + CollationVersion::V2, + ) + .await; + + let mut committed_candidate = dummy_committed_candidate_receipt_v2(head_b); + committed_candidate.descriptor.set_para_id(test_state.chain_ids[0]); + committed_candidate + .descriptor + .set_persisted_validation_data_hash(dummy_pvd().hash()); + // First para is assigned to core 0. + committed_candidate.descriptor.set_core_index(CoreIndex(0)); + committed_candidate.descriptor.set_session_index(test_state.session_index); + + let candidate: CandidateReceipt = committed_candidate.clone().to_plain(); + let pov = PoV { block_data: BlockData(vec![1]) }; + + let candidate_hash = candidate.hash(); + let parent_head_data_hash = Hash::zero(); + + advertise_collation( + &mut virtual_overseer, + peer_a, + head_b, + Some((candidate_hash, parent_head_data_hash)), + ) + .await; + + assert_matches!( + overseer_recv(&mut virtual_overseer).await, + AllMessages::CandidateBacking( + CandidateBackingMessage::CanSecond(request, tx), + ) => { + assert_eq!(request.candidate_hash, candidate_hash); + assert_eq!(request.candidate_para_id, test_state.chain_ids[0]); + assert_eq!(request.parent_head_data_hash, parent_head_data_hash); + tx.send(true).expect("receiving side should be alive"); + } + ); + + let response_channel = assert_fetch_collation_request( + &mut virtual_overseer, + head_b, + test_state.chain_ids[0], + Some(candidate_hash), + ) + .await; + + response_channel + .send(Ok(( + request_v2::CollationFetchingResponse::Collation(candidate.clone(), pov.clone()) + .encode(), + ProtocolName::from(""), + ))) + .expect("Sending response should succeed"); + + if v2_feature_enabled { + assert_candidate_backing_second( + &mut virtual_overseer, + head_b, + test_state.chain_ids[0], + &pov, + CollationVersion::V2, + ) + .await; + + send_seconded_statement(&mut virtual_overseer, keystore.clone(), &committed_candidate) + .await; + + assert_collation_seconded(&mut virtual_overseer, head_b, peer_a, CollationVersion::V2) + .await; + } else { + // Reported malicious. Used v2 descriptor without the feature being enabled + assert_matches!( + overseer_recv(&mut virtual_overseer).await, + AllMessages::NetworkBridgeTx( + NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(peer_id, rep)), + ) => { + assert_eq!(peer_a, peer_id); + assert_eq!(rep.value, COST_REPORT_BAD.cost_or_benefit()); + } + ); + } + + virtual_overseer + }); +} + +#[test] +fn invalid_v2_descriptor() { + let test_state = TestState::default(); + + test_harness(ReputationAggregator::new(|_| true), |test_harness| async move { + let TestHarness { mut virtual_overseer, .. } = test_harness; + + let pair_a = CollatorPair::generate().0; + + let head_b = Hash::from_low_u64_be(128); + let head_b_num: u32 = 0; + + update_view(&mut virtual_overseer, &test_state, vec![(head_b, head_b_num)], 1).await; + + let peer_a = PeerId::random(); + + connect_and_declare_collator( + &mut virtual_overseer, + peer_a, + pair_a.clone(), + test_state.chain_ids[0], + CollationVersion::V2, + ) + .await; + + let mut candidates = vec![]; + + let mut committed_candidate = dummy_committed_candidate_receipt_v2(head_b); + committed_candidate.descriptor.set_para_id(test_state.chain_ids[0]); + committed_candidate + .descriptor + .set_persisted_validation_data_hash(dummy_pvd().hash()); + // First para is assigned to core 0, set an invalid core index. + committed_candidate.descriptor.set_core_index(CoreIndex(10)); + committed_candidate.descriptor.set_session_index(test_state.session_index); + + candidates.push(committed_candidate.clone()); + + // Invalid session index. + committed_candidate.descriptor.set_core_index(CoreIndex(0)); + committed_candidate.descriptor.set_session_index(10); + + candidates.push(committed_candidate); + + for committed_candidate in candidates { + let candidate: CandidateReceipt = committed_candidate.clone().to_plain(); + let pov = PoV { block_data: BlockData(vec![1]) }; + + let candidate_hash = candidate.hash(); + let parent_head_data_hash = Hash::zero(); + + advertise_collation( + &mut virtual_overseer, + peer_a, + head_b, + Some((candidate_hash, parent_head_data_hash)), + ) + .await; + + assert_matches!( + overseer_recv(&mut virtual_overseer).await, + AllMessages::CandidateBacking( + CandidateBackingMessage::CanSecond(request, tx), + ) => { + assert_eq!(request.candidate_hash, candidate_hash); + assert_eq!(request.candidate_para_id, test_state.chain_ids[0]); + assert_eq!(request.parent_head_data_hash, parent_head_data_hash); + tx.send(true).expect("receiving side should be alive"); + } + ); + + let response_channel = assert_fetch_collation_request( + &mut virtual_overseer, + head_b, + test_state.chain_ids[0], + Some(candidate_hash), + ) + .await; + + response_channel + .send(Ok(( + request_v2::CollationFetchingResponse::Collation( + candidate.clone(), + pov.clone(), + ) + .encode(), + ProtocolName::from(""), + ))) + .expect("Sending response should succeed"); + + // Reported malicious. Invalid core index + assert_matches!( + overseer_recv(&mut virtual_overseer).await, + AllMessages::NetworkBridgeTx( + NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(peer_id, rep)), + ) => { + assert_eq!(peer_a, peer_id); + assert_eq!(rep.value, COST_REPORT_BAD.cost_or_benefit()); + } + ); + } + + virtual_overseer + }); +} diff --git a/prdoc/pr_6011.prdoc b/prdoc/pr_6011.prdoc new file mode 100644 index 000000000000..e053b607085f --- /dev/null +++ b/prdoc/pr_6011.prdoc @@ -0,0 +1,12 @@ +title: "collator protocol: validate descriptor version on the validator side" + +doc: + - audience: Node Dev + description: | + Implement checks needed for RFC 103 https://github.com/polkadot-fellows/rfcs/pull/103 in the validator + side of the collator protocol. + + +crates: + - name: polkadot-collator-protocol + bump: major From a1aa71ea36d8b7293557d13d614d73af52f57a32 Mon Sep 17 00:00:00 2001 From: Dastan <88332432+dastansam@users.noreply.github.com> Date: Wed, 6 Nov 2024 19:39:55 +0600 Subject: [PATCH 045/166] sp-api: `impl_runtime_apis!` replace the use of `Self` as a type argument (#4012) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes #1890 ### Overview Introduces similar checker struct to `CheckTraitDecls` in `decl_runtime_apis!` - `CheckTraitImpls`. Overrides `visit::visit_type_path` to detect usage of `Self` as a type argument within the scope of `impl_runtime_apis!`. **Note**: only prevents the usage of `Self` as a type argument in an angle bracket `<>`, as it is the only use case that fails to compile. For example, the code [below](https://github.com/paritytech/polkadot-sdk/blob/master/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs#L1002) compiles fine: ```rs impl BridgeMessagesConfig for Runtime { fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool { let bench_lane_id = >::bench_lane_id(); // ... ``` ### Result Given a block of code like this: ```rs impl_runtime_apis! { impl apis::Core for Runtime { fn initialize_block(header: &HeaderFor) -> ExtrinsicInclusionMode { let _: HeaderFor = header.clone(); RuntimeExecutive::initialize_block(header) } // ... } // ... ```
Output: ```bash $ cargo build --release -p minimal-template-node error: `Self` can not be used as type argument in the scope of `impl_runtime_apis!`. Use `Runtime` instead. --> /polkadot-sdk/templates/minimal/runtime/src/lib.rs:133:11 | 133 | let _: HeaderFor = header.clone(); | ^^^^^^^^^^^^^^^ error: `Self` can not be used as type argument in the scope of `impl_runtime_apis!`. Use `Runtime` instead. --> /polkadot-sdk/templates/minimal/runtime/src/lib.rs:132:32 | 132 | fn initialize_block(header: &HeaderFor) -> ExtrinsicInclusionMode { ```
--------- Co-authored-by: Pavlo Khrystenko Co-authored-by: Pavlo Khrystenko <45178695+pkhry@users.noreply.github.com> Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Co-authored-by: Bastian Köcher --- prdoc/pr_4012.prdoc | 37 +++++ .../primitives/api/proc-macro/Cargo.toml | 2 +- .../api/proc-macro/src/impl_runtime_apis.rs | 138 +++++++++++++----- 3 files changed, 139 insertions(+), 38 deletions(-) create mode 100644 prdoc/pr_4012.prdoc diff --git a/prdoc/pr_4012.prdoc b/prdoc/pr_4012.prdoc new file mode 100644 index 000000000000..3a53e31a7fc6 --- /dev/null +++ b/prdoc/pr_4012.prdoc @@ -0,0 +1,37 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "`impl_runtime_apis!`: replace the use of `Self` with `Runtime`" + +doc: + - audience: Runtime Dev + description: | + Currently, if there is a type alias similar to `type HeaderFor` in the scope, it makes sense to expect that + `HeaderFor` and `HeaderFor` are equivalent. However, this is not the case. It currently leads to + a compilation error that `Self is not in scope`, which is confusing. This PR introduces a visitor, similar to + `CheckTraitDecl` in `decl_runtime_apis!`, `ReplaceSelfImpl`. It identifies usage of `Self` as a type argument in + `impl_runtime_apis!` and replaces `Self` with an explicit `Runtime` type. + + For example, the following example code will be transformed before expansion: + ```rust + impl apis::Core for Runtime { + fn initialize_block(header: &HeaderFor) -> ExtrinsicInclusionMode { + let _: HeaderFor = header.clone(); + RuntimeExecutive::initialize_block(header) + } + } + ``` + Instead, it will be passed to macro as: + ```rust + impl apis::Core for Runtime { + fn initialize_block(header: &HeaderFor) -> ExtrinsicInclusionMode { + let _: HeaderFor = header.clone(); + RuntimeExecutive::initialize_block(header) + } + } + ``` +crates: + - name: sp-api + bump: none + - name: sp-api-proc-macro + bump: none \ No newline at end of file diff --git a/substrate/primitives/api/proc-macro/Cargo.toml b/substrate/primitives/api/proc-macro/Cargo.toml index 659307e7b0f8..191578f432ad 100644 --- a/substrate/primitives/api/proc-macro/Cargo.toml +++ b/substrate/primitives/api/proc-macro/Cargo.toml @@ -20,7 +20,7 @@ proc-macro = true [dependencies] quote = { workspace = true } -syn = { features = ["extra-traits", "fold", "full", "visit"], workspace = true } +syn = { features = ["extra-traits", "fold", "full", "visit", "visit-mut"], workspace = true } proc-macro2 = { workspace = true } blake2 = { workspace = true } proc-macro-crate = { workspace = true } diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index 89d0665f28cf..5c9448da2bc7 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -31,6 +31,7 @@ use syn::{ parse::{Error, Parse, ParseStream, Result}, parse_macro_input, parse_quote, spanned::Spanned, + visit_mut::{self, VisitMut}, Attribute, Ident, ImplItem, ItemImpl, Path, Signature, Type, TypePath, }; @@ -223,34 +224,34 @@ fn generate_wasm_interface(impls: &[ItemImpl]) -> Result { let c = generate_crate_access(); let impl_calls = - generate_impl_calls(impls, &input)? - .into_iter() - .map(|(trait_, fn_name, impl_, attrs)| { - let fn_name = - Ident::new(&prefix_function_with_trait(&trait_, &fn_name), Span::call_site()); - - quote!( - #c::std_disabled! { - #( #attrs )* - #[no_mangle] - #[cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), #c::__private::polkavm_export(abi = #c::__private::polkavm_abi))] - pub unsafe extern fn #fn_name(input_data: *mut u8, input_len: usize) -> u64 { - let mut #input = if input_len == 0 { - &[0u8; 0] - } else { - unsafe { - ::core::slice::from_raw_parts(input_data, input_len) - } - }; - - #c::init_runtime_logger(); - - let output = (move || { #impl_ })(); - #c::to_substrate_wasm_fn_return_value(&output) - } - } - ) - }); + generate_impl_calls(impls, &input)? + .into_iter() + .map(|(trait_, fn_name, impl_, attrs)| { + let fn_name = + Ident::new(&prefix_function_with_trait(&trait_, &fn_name), Span::call_site()); + + quote!( + #c::std_disabled! { + #( #attrs )* + #[no_mangle] + #[cfg_attr(any(target_arch = "riscv32", target_arch = "riscv64"), #c::__private::polkavm_export(abi = #c::__private::polkavm_abi))] + pub unsafe extern fn #fn_name(input_data: *mut u8, input_len: usize) -> u64 { + let mut #input = if input_len == 0 { + &[0u8; 0] + } else { + unsafe { + ::core::slice::from_raw_parts(input_data, input_len) + } + }; + + #c::init_runtime_logger(); + + let output = (move || { #impl_ })(); + #c::to_substrate_wasm_fn_return_value(&output) + } + } + ) + }); Ok(quote!( #( #impl_calls )* )) } @@ -392,10 +393,10 @@ fn generate_runtime_api_base_structures() -> Result { impl> RuntimeApiImpl { fn commit_or_rollback_transaction(&self, commit: bool) { let proof = "\ - We only close a transaction when we opened one ourself. - Other parts of the runtime that make use of transactions (state-machine) - also balance their transactions. The runtime cannot close client initiated - transactions; qed"; + We only close a transaction when we opened one ourself. + Other parts of the runtime that make use of transactions (state-machine) + also balance their transactions. The runtime cannot close client initiated + transactions; qed"; let res = if commit { let res = if let Some(recorder) = &self.recorder { @@ -736,8 +737,8 @@ fn generate_runtime_api_versions(impls: &[ItemImpl]) -> Result { let mut error = Error::new( span, "Two traits with the same name detected! \ - The trait name is used to generate its ID. \ - Please rename one trait at the declaration!", + The trait name is used to generate its ID. \ + Please rename one trait at the declaration!", ); error.combine(Error::new(other_span, "First trait implementation.")); @@ -783,17 +784,50 @@ fn generate_runtime_api_versions(impls: &[ItemImpl]) -> Result { )) } +/// replaces `Self` with explicit `ItemImpl.self_ty`. +struct ReplaceSelfImpl { + self_ty: Box, +} + +impl ReplaceSelfImpl { + /// Replace `Self` with `ItemImpl.self_ty` + fn replace(&mut self, trait_: &mut ItemImpl) { + visit_mut::visit_item_impl_mut(self, trait_) + } +} + +impl VisitMut for ReplaceSelfImpl { + fn visit_type_mut(&mut self, ty: &mut syn::Type) { + match ty { + Type::Path(p) if p.path.is_ident("Self") => { + *ty = *self.self_ty.clone(); + }, + ty => syn::visit_mut::visit_type_mut(self, ty), + } + } +} + +/// Rename `Self` to `ItemImpl.self_ty` in all items. +fn rename_self_in_trait_impls(impls: &mut [ItemImpl]) { + impls.iter_mut().for_each(|i| { + let mut checker = ReplaceSelfImpl { self_ty: i.self_ty.clone() }; + checker.replace(i); + }); +} + /// The implementation of the `impl_runtime_apis!` macro. pub fn impl_runtime_apis_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream { // Parse all impl blocks - let RuntimeApiImpls { impls: api_impls } = parse_macro_input!(input as RuntimeApiImpls); + let RuntimeApiImpls { impls: mut api_impls } = parse_macro_input!(input as RuntimeApiImpls); - impl_runtime_apis_impl_inner(&api_impls) + impl_runtime_apis_impl_inner(&mut api_impls) .unwrap_or_else(|e| e.to_compile_error()) .into() } -fn impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result { +fn impl_runtime_apis_impl_inner(api_impls: &mut [ItemImpl]) -> Result { + rename_self_in_trait_impls(api_impls); + let dispatch_impl = generate_dispatch_function(api_impls)?; let api_impls_for_runtime = generate_api_impl_for_runtime(api_impls)?; let base_runtime_api = generate_runtime_api_base_structures()?; @@ -859,4 +893,34 @@ mod tests { assert_eq!(cfg_std, filtered[0]); assert_eq!(cfg_benchmarks, filtered[1]); } + + #[test] + fn impl_trait_rename_self_param() { + let code = quote::quote! { + impl client::Core for Runtime { + fn initialize_block(header: &HeaderFor) -> Output { + let _: HeaderFor = header.clone(); + example_fn::(header) + } + } + }; + let expected = quote::quote! { + impl client::Core for Runtime { + fn initialize_block(header: &HeaderFor) -> Output { + let _: HeaderFor = header.clone(); + example_fn::(header) + } + } + }; + + // Parse the items + let RuntimeApiImpls { impls: mut api_impls } = + syn::parse2::(code).unwrap(); + + // Run the renamer which is being run first in the `impl_runtime_apis!` macro. + rename_self_in_trait_impls(&mut api_impls); + let result: TokenStream = quote::quote! { #(#api_impls)* }; + + assert_eq!(result.to_string(), expected.to_string()); + } } From 86e1e3864f57ae0077d363873837adeefaaa2c56 Mon Sep 17 00:00:00 2001 From: eskimor Date: Wed, 6 Nov 2024 14:43:41 +0100 Subject: [PATCH 046/166] Fix #6102 (#6384) Relax requirements for `assign_core` so that it accepts updates for the last scheduled entry. Fixes #6102 --------- Co-authored-by: eskimor Co-authored-by: GitHub Action --- .../parachains/src/assigner_coretime/mod.rs | 97 ++++++++----------- .../parachains/src/assigner_coretime/tests.rs | 86 ++++++---------- prdoc/pr_6384.prdoc | 12 +++ 3 files changed, 79 insertions(+), 116 deletions(-) create mode 100644 prdoc/pr_6384.prdoc diff --git a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs index 33a36a1bb2ea..866d52dc9848 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs @@ -236,17 +236,9 @@ pub mod pallet { #[pallet::error] pub enum Error { AssignmentsEmpty, - /// Assignments together exceeded 57600. - OverScheduled, - /// Assignments together less than 57600 - UnderScheduled, /// assign_core is only allowed to append new assignments at the end of already existing - /// ones. + /// ones or update the last entry. DisallowedInsert, - /// Tried to insert a schedule for the same core and block number as an existing schedule - DuplicateInsert, - /// Tried to add an unsorted set of assignments - AssignmentsNotSorted, } } @@ -387,67 +379,56 @@ impl Pallet { /// Append another assignment for a core. /// - /// Important only appending is allowed. Meaning, all already existing assignments must have a - /// begin smaller than the one passed here. This restriction exists, because it makes the - /// insertion O(1) and the author could not think of a reason, why this restriction should be - /// causing any problems. Inserting arbitrarily causes a `DispatchError::DisallowedInsert` - /// error. This restriction could easily be lifted if need be and in fact an implementation is - /// available - /// [here](https://github.com/paritytech/polkadot-sdk/pull/1694/commits/c0c23b01fd2830910cde92c11960dad12cdff398#diff-0c85a46e448de79a5452395829986ee8747e17a857c27ab624304987d2dde8baR386). - /// The problem is that insertion complexity then depends on the size of the existing queue, - /// which makes determining weights hard and could lead to issues like overweight blocks (at - /// least in theory). + /// Important: Only appending is allowed or insertion into the last item. Meaning, + /// all already existing assignments must have a `begin` smaller or equal than the one passed + /// here. + /// Updating the last entry is supported to allow for making a core assignment multiple calls to + /// assign_core. Thus if you have too much interlacing for e.g. a single UMP message you can + /// split that up into multiple messages, each triggering a call to `assign_core`, together + /// forming the total assignment. + /// + /// Inserting arbitrarily causes a `DispatchError::DisallowedInsert` error. + // With this restriction this function allows for O(1) complexity. It could easily be lifted, if + // need be and in fact an implementation is available + // [here](https://github.com/paritytech/polkadot-sdk/pull/1694/commits/c0c23b01fd2830910cde92c11960dad12cdff398#diff-0c85a46e448de79a5452395829986ee8747e17a857c27ab624304987d2dde8baR386). + // The problem is that insertion complexity then depends on the size of the existing queue, + // which makes determining weights hard and could lead to issues like overweight blocks (at + // least in theory). pub fn assign_core( core_idx: CoreIndex, begin: BlockNumberFor, - assignments: Vec<(CoreAssignment, PartsOf57600)>, + mut assignments: Vec<(CoreAssignment, PartsOf57600)>, end_hint: Option>, ) -> Result<(), DispatchError> { // There should be at least one assignment. ensure!(!assignments.is_empty(), Error::::AssignmentsEmpty); - // Checking for sort and unique manually, since we don't have access to iterator tools. - // This way of checking uniqueness only works since we also check sortedness. - assignments.iter().map(|x| &x.0).try_fold(None, |prev, cur| { - if prev.map_or(false, |p| p >= cur) { - Err(Error::::AssignmentsNotSorted) - } else { - Ok(Some(cur)) - } - })?; - - // Check that the total parts between all assignments are equal to 57600 - let parts_sum = assignments - .iter() - .map(|assignment| assignment.1) - .try_fold(PartsOf57600::ZERO, |sum, parts| { - sum.checked_add(parts).ok_or(Error::::OverScheduled) - })?; - ensure!(parts_sum.is_full(), Error::::UnderScheduled); - CoreDescriptors::::mutate(core_idx, |core_descriptor| { let new_queue = match core_descriptor.queue { Some(queue) => { - ensure!(begin > queue.last, Error::::DisallowedInsert); - - CoreSchedules::::try_mutate((queue.last, core_idx), |schedule| { - if let Some(schedule) = schedule.as_mut() { - debug_assert!(schedule.next_schedule.is_none(), "queue.end was supposed to be the end, so the next item must be `None`!"); - schedule.next_schedule = Some(begin); + ensure!(begin >= queue.last, Error::::DisallowedInsert); + + // Update queue if we are appending: + if begin > queue.last { + CoreSchedules::::mutate((queue.last, core_idx), |schedule| { + if let Some(schedule) = schedule.as_mut() { + debug_assert!(schedule.next_schedule.is_none(), "queue.end was supposed to be the end, so the next item must be `None`!"); + schedule.next_schedule = Some(begin); + } else { + defensive!("Queue end entry does not exist?"); + } + }); + } + + CoreSchedules::::mutate((begin, core_idx), |schedule| { + let assignments = if let Some(mut old_schedule) = schedule.take() { + old_schedule.assignments.append(&mut assignments); + old_schedule.assignments } else { - defensive!("Queue end entry does not exist?"); - } - CoreSchedules::::try_mutate((begin, core_idx), |schedule| { - // It should already be impossible to overwrite an existing schedule due - // to strictly increasing block number. But we check here for safety and - // in case the design changes. - ensure!(schedule.is_none(), Error::::DuplicateInsert); - *schedule = - Some(Schedule { assignments, end_hint, next_schedule: None }); - Ok::<(), DispatchError>(()) - })?; - Ok::<(), DispatchError>(()) - })?; + assignments + }; + *schedule = Some(Schedule { assignments, end_hint, next_schedule: None }); + }); QueueDescriptor { first: queue.first, last: begin } }, diff --git a/polkadot/runtime/parachains/src/assigner_coretime/tests.rs b/polkadot/runtime/parachains/src/assigner_coretime/tests.rs index 25007f0eed6a..ab011bfc4ae1 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/tests.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/tests.rs @@ -235,10 +235,7 @@ fn assign_core_works_with_prior_schedule() { } #[test] -// Invariants: We assume that CoreSchedules is append only and consumed. In other words new -// schedules inserted for a core must have a higher block number than all of the already existing -// schedules. -fn assign_core_enforces_higher_block_number() { +fn assign_core_enforces_higher_or_equal_block_number() { let core_idx = CoreIndex(0); new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| { @@ -255,7 +252,7 @@ fn assign_core_enforces_higher_block_number() { assert_ok!(CoretimeAssigner::assign_core( core_idx, BlockNumberFor::::from(15u32), - default_test_assignments(), + vec![(CoreAssignment::Idle, PartsOf57600(28800))], None, )); @@ -281,32 +278,27 @@ fn assign_core_enforces_higher_block_number() { ), Error::::DisallowedInsert ); + // Call assign core again on last entry should work: + assert_eq!( + CoretimeAssigner::assign_core( + core_idx, + BlockNumberFor::::from(15u32), + vec![(CoreAssignment::Pool, PartsOf57600(28800))], + None, + ), + Ok(()) + ); }); } #[test] fn assign_core_enforces_well_formed_schedule() { - let para_id = ParaId::from(1u32); let core_idx = CoreIndex(0); new_test_ext(GenesisConfigBuilder::default().build()).execute_with(|| { run_to_block(1, |n| if n == 1 { Some(Default::default()) } else { None }); let empty_assignments: Vec<(CoreAssignment, PartsOf57600)> = vec![]; - let overscheduled = vec![ - (CoreAssignment::Pool, PartsOf57600::FULL), - (CoreAssignment::Task(para_id.into()), PartsOf57600::FULL), - ]; - let underscheduled = vec![(CoreAssignment::Pool, PartsOf57600(30000))]; - let not_unique = vec![ - (CoreAssignment::Pool, PartsOf57600::FULL / 2), - (CoreAssignment::Pool, PartsOf57600::FULL / 2), - ]; - let not_sorted = vec![ - (CoreAssignment::Task(para_id.into()), PartsOf57600(19200)), - (CoreAssignment::Pool, PartsOf57600(19200)), - (CoreAssignment::Idle, PartsOf57600(19200)), - ]; // Attempting assign_core with malformed assignments such that all error cases // are tested @@ -319,42 +311,6 @@ fn assign_core_enforces_well_formed_schedule() { ), Error::::AssignmentsEmpty ); - assert_noop!( - CoretimeAssigner::assign_core( - core_idx, - BlockNumberFor::::from(11u32), - overscheduled, - None, - ), - Error::::OverScheduled - ); - assert_noop!( - CoretimeAssigner::assign_core( - core_idx, - BlockNumberFor::::from(11u32), - underscheduled, - None, - ), - Error::::UnderScheduled - ); - assert_noop!( - CoretimeAssigner::assign_core( - core_idx, - BlockNumberFor::::from(11u32), - not_unique, - None, - ), - Error::::AssignmentsNotSorted - ); - assert_noop!( - CoretimeAssigner::assign_core( - core_idx, - BlockNumberFor::::from(11u32), - not_sorted, - None, - ), - Error::::AssignmentsNotSorted - ); }); } @@ -374,7 +330,14 @@ fn next_schedule_always_points_to_next_work_plan_item() { Schedule { next_schedule: Some(start_4), ..default_test_schedule() }; let expected_schedule_4 = Schedule { next_schedule: Some(start_5), ..default_test_schedule() }; - let expected_schedule_5 = default_test_schedule(); + let expected_schedule_5 = Schedule { + next_schedule: None, + end_hint: None, + assignments: vec![ + (CoreAssignment::Pool, PartsOf57600(28800)), + (CoreAssignment::Idle, PartsOf57600(28800)), + ], + }; // Call assign_core for each of five schedules assert_ok!(CoretimeAssigner::assign_core( @@ -408,7 +371,14 @@ fn next_schedule_always_points_to_next_work_plan_item() { assert_ok!(CoretimeAssigner::assign_core( core_idx, BlockNumberFor::::from(start_5), - default_test_assignments(), + vec![(CoreAssignment::Pool, PartsOf57600(28800))], + None, + )); + // Test updating last entry once more: + assert_ok!(CoretimeAssigner::assign_core( + core_idx, + BlockNumberFor::::from(start_5), + vec![(CoreAssignment::Idle, PartsOf57600(28800))], None, )); diff --git a/prdoc/pr_6384.prdoc b/prdoc/pr_6384.prdoc new file mode 100644 index 000000000000..2ea0bc1043c3 --- /dev/null +++ b/prdoc/pr_6384.prdoc @@ -0,0 +1,12 @@ +title: Relax requirements on `assign_core`. +doc: +- audience: Runtime Dev + description: |- + Relax requirements for `assign_core` so that it accepts updates for the last scheduled entry. + This will allow the coretime chain to split up assignments into multiple + messages, which allows for interlacing down to single block granularity. + + Fixes: https://github.com/paritytech/polkadot-sdk/issues/6102 +crates: +- name: polkadot-runtime-parachains + bump: major From c1238b64431b4c74d88c082099caed36177b5b11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Wed, 6 Nov 2024 15:12:25 +0100 Subject: [PATCH 047/166] pallet-revive: The fixtures are only required for benchmarking (#6385) --- substrate/frame/revive/Cargo.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index 67bc1809cad7..81fbbc8cf38e 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -40,7 +40,7 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } pallet-balances = { optional = true, workspace = true } -pallet-revive-fixtures = { workspace = true, default-features = false } +pallet-revive-fixtures = { workspace = true, default-features = false, optional = true } pallet-revive-uapi = { workspace = true, default-features = true } pallet-revive-proc-macro = { workspace = true, default-features = true } pallet-transaction-payment = { workspace = true } @@ -91,7 +91,7 @@ std = [ "log/std", "pallet-balances?/std", "pallet-proxy/std", - "pallet-revive-fixtures/std", + "pallet-revive-fixtures?/std", "pallet-timestamp/std", "pallet-transaction-payment/std", "pallet-utility/std", @@ -121,6 +121,7 @@ runtime-benchmarks = [ "pallet-balances/runtime-benchmarks", "pallet-message-queue/runtime-benchmarks", "pallet-proxy/runtime-benchmarks", + "pallet-revive-fixtures", "pallet-timestamp/runtime-benchmarks", "pallet-transaction-payment/runtime-benchmarks", "pallet-utility/runtime-benchmarks", From 85521e873f4b3023e7611711439e2e1b7d5fde41 Mon Sep 17 00:00:00 2001 From: Francisco Aguirre Date: Wed, 6 Nov 2024 17:46:28 -0300 Subject: [PATCH 048/166] XCM v5 (#4826) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Context This PR aims to introduce XCMv5, for now it's in progress and will be updated over time. This branch will serve as a milestone branch for merging in all features we want to add to XCM, roughly outlined [here](https://github.com/polkadot-fellows/xcm-format/issues/60). More features could be added. ## TODO - [x] Migrate foreign assets from v3 to v4 - [x] Setup v5 skeleton - [x] Remove XCMv2 - [x] https://github.com/paritytech/polkadot-sdk/pull/5390 - [x] https://github.com/paritytech/polkadot-sdk/pull/5585 - [x] https://github.com/paritytech/polkadot-sdk/pull/5420 - [x] https://github.com/paritytech/polkadot-sdk/pull/5876 - [x] https://github.com/paritytech/polkadot-sdk/pull/5971 - [x] https://github.com/paritytech/polkadot-sdk/pull/6148 - [x] https://github.com/paritytech/polkadot-sdk/pull/6228 Fixes #3434 Fixes https://github.com/paritytech/polkadot-sdk/issues/4190 Fixes https://github.com/paritytech/polkadot-sdk/issues/5209 Fixes https://github.com/paritytech/polkadot-sdk/issues/5241 Fixes https://github.com/paritytech/polkadot-sdk/issues/4284 --------- Signed-off-by: Adrian Catangiu Co-authored-by: Adrian Catangiu Co-authored-by: Andrii Co-authored-by: Branislav Kontur Co-authored-by: Joseph Zhao <65984904+programskillforverification@users.noreply.github.com> Co-authored-by: Nazar Mokrynskyi Co-authored-by: Bastian Köcher Co-authored-by: Shawn Tabrizi Co-authored-by: command-bot <> Co-authored-by: GitHub Action Co-authored-by: Serban Iorga --- Cargo.lock | 3 + .../modules/xcm-bridge-hub-router/src/mock.rs | 4 +- bridges/modules/xcm-bridge-hub/src/mock.rs | 4 +- bridges/primitives/xcm-bridge-hub/src/lib.rs | 3 +- .../pallets/inbound-queue/src/mock.rs | 9 +- .../pallets/inbound-queue/src/test.rs | 4 +- .../pallets/system/src/benchmarking.rs | 2 +- bridges/snowbridge/pallets/system/src/lib.rs | 4 +- .../primitives/core/src/location.rs | 50 +- .../primitives/router/src/inbound/mod.rs | 3 +- .../primitives/router/src/outbound/tests.rs | 15 +- .../snowbridge/runtime/test-common/src/lib.rs | 9 +- cumulus/pallets/xcmp-queue/src/lib.rs | 2 +- cumulus/pallets/xcmp-queue/src/tests.rs | 23 +- .../assets/asset-hub-rococo/src/genesis.rs | 18 +- .../assets/asset-hub-rococo/src/lib.rs | 2 +- .../assets/asset-hub-westend/src/genesis.rs | 12 +- .../assets/asset-hub-westend/src/lib.rs | 2 +- .../bridges/bridge-hub-rococo/src/genesis.rs | 4 +- .../bridges/bridge-hub-westend/src/genesis.rs | 7 +- .../bridges/bridge-hub-westend/src/lib.rs | 2 +- .../parachains/testing/penpal/src/lib.rs | 7 +- .../emulated/common/src/lib.rs | 25 +- .../emulated/common/src/macros.rs | 226 ++- .../emulated/common/src/xcm_helpers.rs | 6 +- .../tests/assets/asset-hub-rococo/src/lib.rs | 2 +- .../src/tests/claim_assets.rs | 8 +- .../src/tests/hybrid_transfers.rs | 14 +- .../src/tests/reserve_transfer.rs | 2 +- .../assets/asset-hub-rococo/src/tests/send.rs | 4 +- .../src/tests/set_xcm_versions.rs | 2 +- .../asset-hub-rococo/src/tests/teleport.rs | 2 +- .../asset-hub-rococo/src/tests/treasury.rs | 35 +- .../src/tests/xcm_fee_estimation.rs | 55 +- .../tests/assets/asset-hub-westend/Cargo.toml | 1 + .../tests/assets/asset-hub-westend/src/lib.rs | 11 +- .../src/tests/claim_assets.rs | 8 +- .../src/tests/fellowship_treasury.rs | 7 +- .../src/tests/hybrid_transfers.rs | 99 +- .../assets/asset-hub-westend/src/tests/mod.rs | 78 + .../src/tests/reserve_transfer.rs | 298 +--- .../asset-hub-westend/src/tests/send.rs | 4 +- .../src/tests/set_asset_claimer.rs | 154 ++ .../src/tests/set_xcm_versions.rs | 5 +- .../asset-hub-westend/src/tests/teleport.rs | 123 +- .../asset-hub-westend/src/tests/transact.rs | 246 +++ .../asset-hub-westend/src/tests/treasury.rs | 9 +- .../src/tests/xcm_fee_estimation.rs | 51 +- .../bridges/bridge-hub-rococo/src/lib.rs | 3 +- .../src/tests/asset_transfers.rs | 14 +- .../src/tests/claim_assets.rs | 8 +- .../bridge-hub-rococo/src/tests/mod.rs | 49 +- .../src/tests/register_bridged_assets.rs | 4 +- .../bridge-hub-rococo/src/tests/send_xcm.rs | 19 +- .../bridge-hub-rococo/src/tests/snowbridge.rs | 42 +- .../bridges/bridge-hub-westend/src/lib.rs | 10 +- .../src/tests/asset_transfers.rs | 323 +++- .../src/tests/claim_assets.rs | 8 +- .../bridge-hub-westend/src/tests/mod.rs | 161 +- .../src/tests/register_bridged_assets.rs | 4 +- .../bridge-hub-westend/src/tests/send_xcm.rs | 19 +- .../src/tests/snowbridge.rs | 46 +- .../bridge-hub-westend/src/tests/transact.rs | 248 +++ .../src/tests/fellowship.rs | 1 - .../src/tests/fellowship_treasury.rs | 31 +- .../tests/coretime/coretime-rococo/src/lib.rs | 2 +- .../coretime-rococo/src/tests/claim_assets.rs | 8 +- .../coretime/coretime-westend/src/lib.rs | 2 +- .../src/tests/claim_assets.rs | 8 +- .../tests/people/people-rococo/src/lib.rs | 2 +- .../people-rococo/src/tests/claim_assets.rs | 8 +- .../tests/people/people-westend/src/lib.rs | 2 +- .../people-westend/src/tests/claim_assets.rs | 8 +- cumulus/parachains/pallets/ping/src/lib.rs | 2 - .../assets/asset-hub-rococo/src/lib.rs | 47 +- .../asset-hub-rococo/src/weights/xcm/mod.rs | 40 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 65 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 139 +- .../assets/asset-hub-rococo/src/xcm_config.rs | 56 +- .../assets/asset-hub-rococo/tests/tests.rs | 17 +- .../assets/asset-hub-westend/src/lib.rs | 49 +- .../asset-hub-westend/src/weights/xcm/mod.rs | 40 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 65 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 141 +- .../asset-hub-westend/src/xcm_config.rs | 56 +- .../assets/asset-hub-westend/tests/tests.rs | 75 +- .../runtimes/assets/common/src/lib.rs | 32 +- .../runtimes/assets/common/src/matching.rs | 23 +- .../assets/test-utils/src/test_cases.rs | 24 +- .../test-utils/src/test_cases_over_bridge.rs | 6 +- .../src/bridge_to_bulletin_config.rs | 5 +- .../src/bridge_to_westend_config.rs | 12 +- .../src/genesis_config_presets.rs | 3 +- .../bridge-hubs/bridge-hub-rococo/src/lib.rs | 7 +- .../bridge-hub-rococo/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 61 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 142 +- .../bridge-hub-rococo/src/xcm_config.rs | 6 +- .../bridge-hub-rococo/tests/tests.rs | 10 +- .../src/bridge_to_ethereum_config.rs | 45 + .../src/bridge_to_rococo_config.rs | 25 +- .../src/genesis_config_presets.rs | 6 +- .../bridge-hubs/bridge-hub-westend/src/lib.rs | 13 +- .../bridge-hub-westend/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 61 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 142 +- .../bridge-hub-westend/src/xcm_config.rs | 6 +- .../bridge-hub-westend/tests/tests.rs | 6 +- .../bridge-hubs/common/src/message_queue.rs | 4 +- .../test-utils/src/test_cases/mod.rs | 10 +- .../collectives-westend/src/xcm_config.rs | 4 +- .../contracts-rococo/src/xcm_config.rs | 4 +- .../coretime/coretime-rococo/src/coretime.rs | 4 - .../coretime-rococo/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 59 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 130 +- .../coretime-rococo/src/xcm_config.rs | 4 +- .../coretime/coretime-westend/src/coretime.rs | 16 - .../coretime-westend/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 59 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 130 +- .../coretime-westend/src/xcm_config.rs | 4 +- .../glutton/glutton-westend/src/xcm_config.rs | 4 +- .../people-rococo/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 59 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 128 +- .../people/people-rococo/src/xcm_config.rs | 4 +- .../people-westend/src/weights/xcm/mod.rs | 37 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 59 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 130 +- .../people/people-westend/src/xcm_config.rs | 4 +- .../parachains/runtimes/test-utils/src/lib.rs | 14 +- .../runtimes/test-utils/src/test_cases.rs | 27 +- .../runtimes/testing/penpal/Cargo.toml | 3 + .../runtimes/testing/penpal/src/lib.rs | 8 +- .../runtimes/testing/penpal/src/xcm_config.rs | 25 +- .../testing/rococo-parachain/src/lib.rs | 4 +- cumulus/xcm/xcm-emulator/src/lib.rs | 29 +- polkadot/runtime/common/src/impls.rs | 97 +- polkadot/runtime/common/src/xcm_sender.rs | 2 +- .../parachains/src/coretime/migration.rs | 29 +- .../runtime/parachains/src/coretime/mod.rs | 25 +- polkadot/runtime/parachains/src/mock.rs | 10 +- polkadot/runtime/rococo/src/impls.rs | 18 +- polkadot/runtime/rococo/src/lib.rs | 2 - .../runtime/rococo/src/weights/xcm/mod.rs | 33 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 55 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 337 ++-- polkadot/runtime/rococo/src/xcm_config.rs | 4 +- polkadot/runtime/test-runtime/src/lib.rs | 6 +- polkadot/runtime/westend/src/impls.rs | 18 +- polkadot/runtime/westend/src/lib.rs | 2 - .../runtime/westend/src/weights/xcm/mod.rs | 35 +- .../xcm/pallet_xcm_benchmarks_fungible.rs | 55 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 316 ++-- polkadot/runtime/westend/src/xcm_config.rs | 4 +- polkadot/xcm/Cargo.toml | 4 +- .../parachain/xcm_config.rs | 2 +- .../relay_token_transactor/relay_chain/mod.rs | 2 +- .../relay_chain/xcm_config.rs | 2 +- .../cookbook/relay_token_transactor/tests.rs | 12 +- .../src/fungible/benchmarking.rs | 29 +- .../src/generic/benchmarking.rs | 33 +- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 4 +- polkadot/xcm/pallet-xcm/src/lib.rs | 4 +- polkadot/xcm/pallet-xcm/src/tests/mod.rs | 13 +- .../xcm/procedural/src/builder_pattern.rs | 104 +- polkadot/xcm/procedural/src/lib.rs | 30 +- polkadot/xcm/procedural/src/v2.rs | 226 --- polkadot/xcm/procedural/src/v3.rs | 30 - polkadot/xcm/procedural/src/v4.rs | 41 + polkadot/xcm/procedural/src/v5.rs | 198 ++ .../badly_formatted_attribute.stderr | 2 +- .../buy_execution_named_fields.rs | 30 - .../buy_execution_named_fields.stderr | 5 - .../builder_pattern/no_buy_execution.stderr | 6 - .../builder_pattern/unexpected_attribute.rs | 32 - .../unexpected_attribute.stderr | 5 - polkadot/xcm/src/lib.rs | 326 ++-- polkadot/xcm/src/tests.rs | 167 +- polkadot/xcm/src/v2/junction.rs | 123 -- polkadot/xcm/src/v2/mod.rs | 1222 ------------- polkadot/xcm/src/v2/multiasset.rs | 626 ------- polkadot/xcm/src/v2/multilocation.rs | 1105 ------------ polkadot/xcm/src/v2/traits.rs | 363 ---- polkadot/xcm/src/v3/junction.rs | 125 -- polkadot/xcm/src/v3/mod.rs | 202 +-- polkadot/xcm/src/v3/multiasset.rs | 136 +- polkadot/xcm/src/v3/multilocation.rs | 44 +- polkadot/xcm/src/v3/traits.rs | 48 +- polkadot/xcm/src/v4/asset.rs | 103 +- polkadot/xcm/src/v4/junction.rs | 47 +- polkadot/xcm/src/v4/location.rs | 16 +- polkadot/xcm/src/v4/mod.rs | 237 ++- polkadot/xcm/src/v5/asset.rs | 1155 ++++++++++++ polkadot/xcm/src/v5/junction.rs | 321 ++++ polkadot/xcm/src/v5/junctions.rs | 723 ++++++++ polkadot/xcm/src/v5/location.rs | 755 ++++++++ polkadot/xcm/src/v5/mod.rs | 1585 +++++++++++++++++ polkadot/xcm/src/v5/traits.rs | 525 ++++++ polkadot/xcm/xcm-builder/src/barriers.rs | 1 + polkadot/xcm/xcm-builder/src/lib.rs | 2 +- .../xcm/xcm-builder/src/origin_aliases.rs | 33 +- .../xcm-builder/src/process_xcm_message.rs | 24 +- polkadot/xcm/xcm-builder/src/tests/aliases.rs | 161 ++ .../xcm/xcm-builder/src/tests/transacting.rs | 16 +- polkadot/xcm/xcm-builder/src/weight.rs | 30 +- .../xcm-executor/integration-tests/src/lib.rs | 10 +- polkadot/xcm/xcm-executor/src/lib.rs | 559 ++++-- .../src/tests/initiate_transfer.rs | 106 ++ polkadot/xcm/xcm-executor/src/tests/mock.rs | 279 +++ .../src/tests/mod.rs} | 23 +- .../xcm/xcm-executor/src/tests/pay_fees.rs | 257 +++ .../src/tests/set_asset_claimer.rs | 138 ++ .../xcm-executor/src/traits/fee_manager.rs | 2 + .../xcm/xcm-executor/src/traits/weight.rs | 2 +- polkadot/xcm/xcm-runtime-apis/tests/mock.rs | 2 +- .../xcm/xcm-simulator/example/src/tests.rs | 4 - prdoc/pr_4826.prdoc | 69 + prdoc/pr_5390.prdoc | 55 + prdoc/pr_5420.prdoc | 62 + prdoc/pr_5585.prdoc | 47 + prdoc/pr_5876.prdoc | 99 + prdoc/pr_5971.prdoc | 66 + prdoc/pr_6228.prdoc | 50 + .../src/migrations/v1/weights.rs | 2 +- substrate/frame/system/src/lib.rs | 4 +- 227 files changed, 12140 insertions(+), 7048 deletions(-) create mode 100644 cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_asset_claimer.rs create mode 100644 cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/transact.rs create mode 100644 cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/transact.rs delete mode 100644 polkadot/xcm/procedural/src/v2.rs create mode 100644 polkadot/xcm/procedural/src/v5.rs delete mode 100644 polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.rs delete mode 100644 polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.stderr delete mode 100644 polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.stderr delete mode 100644 polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.rs delete mode 100644 polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.stderr delete mode 100644 polkadot/xcm/src/v2/junction.rs delete mode 100644 polkadot/xcm/src/v2/mod.rs delete mode 100644 polkadot/xcm/src/v2/multiasset.rs delete mode 100644 polkadot/xcm/src/v2/multilocation.rs delete mode 100644 polkadot/xcm/src/v2/traits.rs create mode 100644 polkadot/xcm/src/v5/asset.rs create mode 100644 polkadot/xcm/src/v5/junction.rs create mode 100644 polkadot/xcm/src/v5/junctions.rs create mode 100644 polkadot/xcm/src/v5/location.rs create mode 100644 polkadot/xcm/src/v5/mod.rs create mode 100644 polkadot/xcm/src/v5/traits.rs create mode 100644 polkadot/xcm/xcm-executor/src/tests/initiate_transfer.rs create mode 100644 polkadot/xcm/xcm-executor/src/tests/mock.rs rename polkadot/xcm/{procedural/tests/ui/builder_pattern/no_buy_execution.rs => xcm-executor/src/tests/mod.rs} (70%) create mode 100644 polkadot/xcm/xcm-executor/src/tests/pay_fees.rs create mode 100644 polkadot/xcm/xcm-executor/src/tests/set_asset_claimer.rs create mode 100644 prdoc/pr_4826.prdoc create mode 100644 prdoc/pr_5390.prdoc create mode 100644 prdoc/pr_5420.prdoc create mode 100644 prdoc/pr_5585.prdoc create mode 100644 prdoc/pr_5876.prdoc create mode 100644 prdoc/pr_5971.prdoc create mode 100644 prdoc/pr_6228.prdoc diff --git a/Cargo.lock b/Cargo.lock index a824faedd6b3..03350ff38f5d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -973,6 +973,7 @@ dependencies = [ "sp-core 28.0.0", "sp-runtime 31.0.1", "staging-xcm", + "staging-xcm-builder", "staging-xcm-executor", "westend-system-emulated-network", "xcm-runtime-apis", @@ -13642,6 +13643,7 @@ dependencies = [ "primitive-types 0.12.2", "scale-info", "smallvec", + "snowbridge-router-primitives", "sp-api 26.0.0", "sp-block-builder", "sp-consensus-aura", @@ -23628,6 +23630,7 @@ dependencies = [ "bounded-collections", "derivative", "environmental", + "frame-support", "hex", "hex-literal", "impl-trait-for-tuples", diff --git a/bridges/modules/xcm-bridge-hub-router/src/mock.rs b/bridges/modules/xcm-bridge-hub-router/src/mock.rs index bb265e1925a2..095572883920 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/mock.rs @@ -141,8 +141,8 @@ impl InspectMessageQueues for TestToBridgeHubSender { .iter() .map(|(location, message)| { ( - VersionedLocation::V4(location.clone()), - vec![VersionedXcm::V4(message.clone())], + VersionedLocation::from(location.clone()), + vec![VersionedXcm::from(message.clone())], ) }) .collect() diff --git a/bridges/modules/xcm-bridge-hub/src/mock.rs b/bridges/modules/xcm-bridge-hub/src/mock.rs index 6511b9fc5b04..9f06b99ef6d5 100644 --- a/bridges/modules/xcm-bridge-hub/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub/src/mock.rs @@ -38,7 +38,7 @@ use sp_runtime::{ AccountId32, BuildStorage, StateVersion, }; use sp_std::cell::RefCell; -use xcm::prelude::*; +use xcm::{latest::ROCOCO_GENESIS_HASH, prelude::*}; use xcm_builder::{ AllowUnpaidExecutionFrom, DispatchBlob, DispatchBlobError, FixedWeightBounds, InspectMessageQueues, NetworkExportTable, NetworkExportTableItem, ParentIsPreset, @@ -160,7 +160,7 @@ parameter_types! { pub BridgedRelayNetworkLocation: Location = (Parent, GlobalConsensus(BridgedRelayNetwork::get())).into(); pub BridgedRelativeDestination: InteriorLocation = [Parachain(BRIDGED_ASSET_HUB_ID)].into(); pub BridgedUniversalDestination: InteriorLocation = [GlobalConsensus(BridgedRelayNetwork::get()), Parachain(BRIDGED_ASSET_HUB_ID)].into(); - pub const NonBridgedRelayNetwork: NetworkId = NetworkId::Rococo; + pub const NonBridgedRelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub const BridgeDeposit: Balance = 100_000; diff --git a/bridges/primitives/xcm-bridge-hub/src/lib.rs b/bridges/primitives/xcm-bridge-hub/src/lib.rs index 061e7a275063..63beb1bc3041 100644 --- a/bridges/primitives/xcm-bridge-hub/src/lib.rs +++ b/bridges/primitives/xcm-bridge-hub/src/lib.rs @@ -359,10 +359,11 @@ impl BridgeLocations { #[cfg(test)] mod tests { use super::*; + use xcm::latest::ROCOCO_GENESIS_HASH; const LOCAL_NETWORK: NetworkId = Kusama; const REMOTE_NETWORK: NetworkId = Polkadot; - const UNREACHABLE_NETWORK: NetworkId = Rococo; + const UNREACHABLE_NETWORK: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); const SIBLING_PARACHAIN: u32 = 1000; const LOCAL_BRIDGE_HUB: u32 = 1001; const REMOTE_PARACHAIN: u32 = 2000; diff --git a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs index 3e67d5ab738b..675d4b691593 100644 --- a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs +++ b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs @@ -19,7 +19,10 @@ use sp_runtime::{ BuildStorage, FixedU128, MultiSignature, }; use sp_std::{convert::From, default::Default}; -use xcm::{latest::SendXcm, prelude::*}; +use xcm::{ + latest::{SendXcm, WESTEND_GENESIS_HASH}, + prelude::*, +}; use xcm_executor::AssetsInHolding; use crate::{self as inbound_queue}; @@ -113,8 +116,8 @@ parameter_types! { pub const InitialFund: u128 = 1_000_000_000_000; pub const InboundQueuePalletInstance: u8 = 80; pub UniversalLocation: InteriorLocation = - [GlobalConsensus(Westend), Parachain(1002)].into(); - pub AssetHubFromEthereum: Location = Location::new(1,[GlobalConsensus(Westend),Parachain(1000)]); + [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1002)].into(); + pub AssetHubFromEthereum: Location = Location::new(1,[GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)),Parachain(1000)]); } #[cfg(feature = "runtime-benchmarks")] diff --git a/bridges/snowbridge/pallets/inbound-queue/src/test.rs b/bridges/snowbridge/pallets/inbound-queue/src/test.rs index 41c38460aabf..76d0b98e9eb4 100644 --- a/bridges/snowbridge/pallets/inbound-queue/src/test.rs +++ b/bridges/snowbridge/pallets/inbound-queue/src/test.rs @@ -40,8 +40,8 @@ fn test_submit_happy_path() { .into(), nonce: 1, message_id: [ - 255, 125, 48, 71, 174, 185, 100, 26, 159, 43, 108, 6, 116, 218, 55, 155, 223, 143, - 141, 22, 124, 110, 241, 18, 122, 217, 130, 29, 139, 76, 97, 201, + 11, 25, 133, 51, 23, 68, 111, 211, 132, 94, 254, 17, 194, 252, 198, 233, 10, 193, + 156, 93, 72, 140, 65, 69, 79, 155, 154, 28, 141, 166, 171, 255, ], fee_burned: 110000000000, } diff --git a/bridges/snowbridge/pallets/system/src/benchmarking.rs b/bridges/snowbridge/pallets/system/src/benchmarking.rs index 20798b7c3493..939de9d40d13 100644 --- a/bridges/snowbridge/pallets/system/src/benchmarking.rs +++ b/bridges/snowbridge/pallets/system/src/benchmarking.rs @@ -169,7 +169,7 @@ mod benchmarks { T::Token::mint_into(&caller, amount)?; let relay_token_asset_id: Location = Location::parent(); - let asset = Box::new(VersionedLocation::V4(relay_token_asset_id)); + let asset = Box::new(VersionedLocation::from(relay_token_asset_id)); let asset_metadata = AssetMetadata { name: "wnd".as_bytes().to_vec().try_into().unwrap(), symbol: "wnd".as_bytes().to_vec().try_into().unwrap(), diff --git a/bridges/snowbridge/pallets/system/src/lib.rs b/bridges/snowbridge/pallets/system/src/lib.rs index 1e8a788b7a5a..eb3da095fe85 100644 --- a/bridges/snowbridge/pallets/system/src/lib.rs +++ b/bridges/snowbridge/pallets/system/src/lib.rs @@ -269,12 +269,12 @@ pub mod pallet { /// Lookup table for foreign token ID to native location relative to ethereum #[pallet::storage] pub type ForeignToNativeId = - StorageMap<_, Blake2_128Concat, TokenId, xcm::v4::Location, OptionQuery>; + StorageMap<_, Blake2_128Concat, TokenId, xcm::v5::Location, OptionQuery>; /// Lookup table for native location relative to ethereum to foreign token ID #[pallet::storage] pub type NativeToForeignId = - StorageMap<_, Blake2_128Concat, xcm::v4::Location, TokenId, OptionQuery>; + StorageMap<_, Blake2_128Concat, xcm::v5::Location, TokenId, OptionQuery>; #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] diff --git a/bridges/snowbridge/primitives/core/src/location.rs b/bridges/snowbridge/primitives/core/src/location.rs index aad1c9ece05c..f49a245c4126 100644 --- a/bridges/snowbridge/primitives/core/src/location.rs +++ b/bridges/snowbridge/primitives/core/src/location.rs @@ -97,9 +97,12 @@ impl DescribeLocation for DescribeTokenTerminal { #[cfg(test)] mod tests { use crate::TokenIdOf; - use xcm::prelude::{ - GeneralIndex, GeneralKey, GlobalConsensus, Junction::*, Location, NetworkId::*, - PalletInstance, Parachain, + use xcm::{ + latest::WESTEND_GENESIS_HASH, + prelude::{ + GeneralIndex, GeneralKey, GlobalConsensus, Junction::*, Location, NetworkId::ByGenesis, + PalletInstance, Parachain, + }, }; use xcm_executor::traits::ConvertLocation; @@ -108,17 +111,24 @@ mod tests { let token_locations = [ // Relay Chain cases // Relay Chain relative to Ethereum - Location::new(1, [GlobalConsensus(Westend)]), + Location::new(1, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]), // Parachain cases // Parachain relative to Ethereum - Location::new(1, [GlobalConsensus(Westend), Parachain(2000)]), + Location::new(1, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000)]), // Parachain general index - Location::new(1, [GlobalConsensus(Westend), Parachain(2000), GeneralIndex(1)]), + Location::new( + 1, + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(2000), + GeneralIndex(1), + ], + ), // Parachain general key Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), GeneralKey { length: 32, data: [0; 32] }, ], @@ -127,7 +137,7 @@ mod tests { Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), AccountKey20 { network: None, key: [0; 20] }, ], @@ -136,24 +146,36 @@ mod tests { Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), AccountId32 { network: None, id: [0; 32] }, ], ), // Parchain Pallet instance cases // Parachain pallet instance - Location::new(1, [GlobalConsensus(Westend), Parachain(2000), PalletInstance(8)]), + Location::new( + 1, + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(2000), + PalletInstance(8), + ], + ), // Parachain Pallet general index Location::new( 1, - [GlobalConsensus(Westend), Parachain(2000), PalletInstance(8), GeneralIndex(1)], + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(2000), + PalletInstance(8), + GeneralIndex(1), + ], ), // Parachain Pallet general key Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), PalletInstance(8), GeneralKey { length: 32, data: [0; 32] }, @@ -163,7 +185,7 @@ mod tests { Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), PalletInstance(8), AccountKey20 { network: None, key: [0; 20] }, @@ -173,7 +195,7 @@ mod tests { Location::new( 1, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2000), PalletInstance(8), AccountId32 { network: None, id: [0; 32] }, diff --git a/bridges/snowbridge/primitives/router/src/inbound/mod.rs b/bridges/snowbridge/primitives/router/src/inbound/mod.rs index 357f77f831cc..e03560f66e24 100644 --- a/bridges/snowbridge/primitives/router/src/inbound/mod.rs +++ b/bridges/snowbridge/primitives/router/src/inbound/mod.rs @@ -7,7 +7,7 @@ mod tests; use codec::{Decode, Encode}; use core::marker::PhantomData; -use frame_support::{traits::tokens::Balance as BalanceT, weights::Weight, PalletError}; +use frame_support::{traits::tokens::Balance as BalanceT, PalletError}; use scale_info::TypeInfo; use snowbridge_core::TokenId; use sp_core::{Get, RuntimeDebug, H160, H256}; @@ -279,7 +279,6 @@ where // Call create_asset on foreign assets pallet. Transact { origin_kind: OriginKind::Xcm, - require_weight_at_most: Weight::from_parts(400_000_000, 8_000), call: ( create_call_index, asset_id, diff --git a/bridges/snowbridge/primitives/router/src/outbound/tests.rs b/bridges/snowbridge/primitives/router/src/outbound/tests.rs index 8bd3fa24df5b..44f81ce31b3a 100644 --- a/bridges/snowbridge/primitives/router/src/outbound/tests.rs +++ b/bridges/snowbridge/primitives/router/src/outbound/tests.rs @@ -5,7 +5,10 @@ use snowbridge_core::{ AgentIdOf, }; use sp_std::default::Default; -use xcm::prelude::SendError as XcmSendError; +use xcm::{ + latest::{ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}, + prelude::SendError as XcmSendError, +}; use super::*; @@ -61,7 +64,7 @@ impl SendMessageFeeProvider for MockErrOutboundQueue { pub struct MockTokenIdConvert; impl MaybeEquivalence for MockTokenIdConvert { fn convert(_id: &TokenId) -> Option { - Some(Location::new(1, [GlobalConsensus(Westend)])) + Some(Location::new(1, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))])) } fn convert_back(_loc: &Location) -> Option { None @@ -1109,7 +1112,7 @@ fn xcm_converter_transfer_native_token_success() { let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); let amount = 1000000; - let asset_location = Location::new(1, [GlobalConsensus(Westend)]); + let asset_location = Location::new(1, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]); let token_id = TokenIdOf::convert_location(&asset_location).unwrap(); let assets: Assets = vec![Asset { id: AssetId(asset_location), fun: Fungible(amount) }].into(); @@ -1142,7 +1145,8 @@ fn xcm_converter_transfer_native_token_with_invalid_location_will_fail() { let amount = 1000000; // Invalid asset location from a different consensus - let asset_location = Location { parents: 2, interior: [GlobalConsensus(Rococo)].into() }; + let asset_location = + Location { parents: 2, interior: [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))].into() }; let assets: Assets = vec![Asset { id: AssetId(asset_location), fun: Fungible(amount) }].into(); let filter: AssetFilter = assets.clone().into(); @@ -1221,7 +1225,8 @@ fn exporter_validate_with_invalid_universal_source_does_not_alter_universal_sour let network = BridgedNetwork::get(); let destination: InteriorLocation = Here.into(); - let universal_source: InteriorLocation = [GlobalConsensus(Westend), Parachain(1000)].into(); + let universal_source: InteriorLocation = + [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1000)].into(); let token_address: [u8; 20] = hex!("1000000000000000000000000000000000000000"); let beneficiary_address: [u8; 20] = hex!("2000000000000000000000000000000000000000"); diff --git a/bridges/snowbridge/runtime/test-common/src/lib.rs b/bridges/snowbridge/runtime/test-common/src/lib.rs index b157ad4356bd..dca5062ab310 100644 --- a/bridges/snowbridge/runtime/test-common/src/lib.rs +++ b/bridges/snowbridge/runtime/test-common/src/lib.rs @@ -15,10 +15,7 @@ use snowbridge_pallet_ethereum_client_fixtures::*; use sp_core::{Get, H160, U256}; use sp_keyring::AccountKeyring::*; use sp_runtime::{traits::Header, AccountId32, DigestItem, SaturatedConversion, Saturating}; -use xcm::{ - latest::prelude::*, - v3::Error::{self, Barrier}, -}; +use xcm::latest::prelude::*; use xcm_executor::XcmExecutor; type RuntimeHelper = @@ -374,7 +371,7 @@ pub fn send_unpaid_transfer_token_message( Weight::zero(), ); // check error is barrier - assert_err!(outcome.ensure_complete(), Barrier); + assert_err!(outcome.ensure_complete(), XcmError::Barrier); }); } @@ -388,7 +385,7 @@ pub fn send_transfer_token_message_failure( weth_contract_address: H160, destination_address: H160, fee_amount: u128, - expected_error: Error, + expected_error: XcmError, ) where Runtime: frame_system::Config + pallet_balances::Config diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 6bb7395f6553..91f71558b54a 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -1036,7 +1036,7 @@ impl InspectMessageQueues for Pallet { } ( - VersionedLocation::V4((Parent, Parachain(para_id.into())).into()), + VersionedLocation::from(Location::new(1, Parachain(para_id.into()))), decoded_messages, ) }) diff --git a/cumulus/pallets/xcmp-queue/src/tests.rs b/cumulus/pallets/xcmp-queue/src/tests.rs index 5b02baf2310a..bf042f15ccc0 100644 --- a/cumulus/pallets/xcmp-queue/src/tests.rs +++ b/cumulus/pallets/xcmp-queue/src/tests.rs @@ -456,7 +456,7 @@ fn send_xcm_nested_works() { XcmpQueue::take_outbound_messages(usize::MAX), vec![( HRMP_PARA_ID.into(), - (XcmpMessageFormat::ConcatenatedVersionedXcm, VersionedXcm::V4(good.clone())) + (XcmpMessageFormat::ConcatenatedVersionedXcm, VersionedXcm::from(good.clone())) .encode(), )] ); @@ -512,7 +512,7 @@ fn hrmp_signals_are_prioritized() { // Without a signal we get the messages in order: let mut expected_msg = XcmpMessageFormat::ConcatenatedVersionedXcm.encode(); for _ in 0..31 { - expected_msg.extend(VersionedXcm::V4(message.clone()).encode()); + expected_msg.extend(VersionedXcm::from(message.clone()).encode()); } hypothetically!({ @@ -539,6 +539,7 @@ fn maybe_double_encoded_versioned_xcm_works() { // pre conditions assert_eq!(VersionedXcm::<()>::V3(Default::default()).encode(), &[3, 0]); assert_eq!(VersionedXcm::<()>::V4(Default::default()).encode(), &[4, 0]); + assert_eq!(VersionedXcm::<()>::V5(Default::default()).encode(), &[5, 0]); } // Now also testing a page instead of just concat messages. @@ -597,7 +598,7 @@ fn take_first_concatenated_xcm_good_recursion_depth_works() { for _ in 0..MAX_XCM_DECODE_DEPTH - 1 { good = Xcm(vec![SetAppendix(good)]); } - let good = VersionedXcm::V4(good); + let good = VersionedXcm::from(good); let page = good.encode(); assert_ok!(XcmpQueue::take_first_concatenated_xcm(&mut &page[..], &mut WeightMeter::new())); @@ -610,7 +611,7 @@ fn take_first_concatenated_xcm_good_bad_depth_errors() { for _ in 0..MAX_XCM_DECODE_DEPTH { bad = Xcm(vec![SetAppendix(bad)]); } - let bad = VersionedXcm::V4(bad); + let bad = VersionedXcm::from(bad); let page = bad.encode(); assert_err!( @@ -872,18 +873,18 @@ fn get_messages_works() { queued_messages, vec![ ( - VersionedLocation::V4(other_destination), + VersionedLocation::from(other_destination), vec![ - VersionedXcm::V4(Xcm(vec![ClearOrigin])), - VersionedXcm::V4(Xcm(vec![ClearOrigin])), + VersionedXcm::from(Xcm(vec![ClearOrigin])), + VersionedXcm::from(Xcm(vec![ClearOrigin])), ], ), ( - VersionedLocation::V4(destination), + VersionedLocation::from(destination), vec![ - VersionedXcm::V4(Xcm(vec![ClearOrigin])), - VersionedXcm::V4(Xcm(vec![ClearOrigin])), - VersionedXcm::V4(Xcm(vec![ClearOrigin])), + VersionedXcm::from(Xcm(vec![ClearOrigin])), + VersionedXcm::from(Xcm(vec![ClearOrigin])), + VersionedXcm::from(Xcm(vec![ClearOrigin])), ], ), ], diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/genesis.rs index 606d04060b6b..3ffb9a704b46 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/genesis.rs @@ -20,8 +20,9 @@ use sp_keyring::Sr25519Keyring as Keyring; // Cumulus use emulated_integration_tests_common::{ - accounts, build_genesis_storage, collators, PenpalSiblingSovereignAccount, - PenpalTeleportableAssetLocation, RESERVABLE_ASSET_ID, SAFE_XCM_VERSION, USDT_ID, + accounts, build_genesis_storage, collators, PenpalASiblingSovereignAccount, + PenpalATeleportableAssetLocation, PenpalBSiblingSovereignAccount, + PenpalBTeleportableAssetLocation, RESERVABLE_ASSET_ID, SAFE_XCM_VERSION, USDT_ID, }; use parachains_common::{AccountId, Balance}; @@ -77,10 +78,17 @@ pub fn genesis() -> Storage { }, foreign_assets: asset_hub_rococo_runtime::ForeignAssetsConfig { assets: vec![ - // Penpal's teleportable asset representation + // PenpalA's teleportable asset representation ( - PenpalTeleportableAssetLocation::get(), - PenpalSiblingSovereignAccount::get(), + PenpalATeleportableAssetLocation::get(), + PenpalASiblingSovereignAccount::get(), + false, + ED, + ), + // PenpalB's teleportable asset representation + ( + PenpalBTeleportableAssetLocation::get(), + PenpalBSiblingSovereignAccount::get(), false, ED, ), diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs index 75b61d6a4cd7..1a075b9fe6be 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs @@ -59,7 +59,7 @@ impl_accounts_helpers_for_parachain!(AssetHubRococo); impl_assert_events_helpers_for_parachain!(AssetHubRococo); impl_assets_helpers_for_system_parachain!(AssetHubRococo, Rococo); impl_assets_helpers_for_parachain!(AssetHubRococo); -impl_foreign_assets_helpers_for_parachain!(AssetHubRococo, xcm::v4::Location); +impl_foreign_assets_helpers_for_parachain!(AssetHubRococo, xcm::v5::Location); impl_xcm_helpers_for_parachain!(AssetHubRococo); impl_bridge_helpers_for_chain!( AssetHubRococo, diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/genesis.rs index 30e7279a383f..ef7997322da7 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/genesis.rs @@ -20,9 +20,9 @@ use sp_keyring::Sr25519Keyring as Keyring; // Cumulus use emulated_integration_tests_common::{ - accounts, build_genesis_storage, collators, PenpalBSiblingSovereignAccount, - PenpalBTeleportableAssetLocation, PenpalSiblingSovereignAccount, - PenpalTeleportableAssetLocation, RESERVABLE_ASSET_ID, SAFE_XCM_VERSION, USDT_ID, + accounts, build_genesis_storage, collators, PenpalASiblingSovereignAccount, + PenpalATeleportableAssetLocation, PenpalBSiblingSovereignAccount, + PenpalBTeleportableAssetLocation, RESERVABLE_ASSET_ID, SAFE_XCM_VERSION, USDT_ID, }; use parachains_common::{AccountId, Balance}; @@ -75,10 +75,10 @@ pub fn genesis() -> Storage { }, foreign_assets: asset_hub_westend_runtime::ForeignAssetsConfig { assets: vec![ - // Penpal's teleportable asset representation + // PenpalA's teleportable asset representation ( - PenpalTeleportableAssetLocation::get(), - PenpalSiblingSovereignAccount::get(), + PenpalATeleportableAssetLocation::get(), + PenpalASiblingSovereignAccount::get(), false, ED, ), diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs index c44f4b010c0a..3e240ed67482 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs @@ -59,7 +59,7 @@ impl_accounts_helpers_for_parachain!(AssetHubWestend); impl_assert_events_helpers_for_parachain!(AssetHubWestend); impl_assets_helpers_for_system_parachain!(AssetHubWestend, Westend); impl_assets_helpers_for_parachain!(AssetHubWestend); -impl_foreign_assets_helpers_for_parachain!(AssetHubWestend, xcm::v4::Location); +impl_foreign_assets_helpers_for_parachain!(AssetHubWestend, xcm::v5::Location); impl_xcm_helpers_for_parachain!(AssetHubWestend); impl_bridge_helpers_for_chain!( AssetHubWestend, diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/genesis.rs index 0268a6a7a1b3..575017f88bb5 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/genesis.rs @@ -22,7 +22,7 @@ use emulated_integration_tests_common::{ accounts, build_genesis_storage, collators, SAFE_XCM_VERSION, }; use parachains_common::Balance; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; pub const ASSETHUB_PARA_ID: u32 = 1000; pub const PARA_ID: u32 = 1013; @@ -73,7 +73,7 @@ pub fn genesis() -> Storage { // open AHR -> AHW bridge ( Location::new(1, [Parachain(1000)]), - Junctions::from([Westend.into(), Parachain(1000)]), + Junctions::from([ByGenesis(WESTEND_GENESIS_HASH).into(), Parachain(1000)]), Some(bp_messages::LegacyLaneId([0, 0, 0, 2])), ), ], diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/genesis.rs index f72eaa30026d..eb4623084f85 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/genesis.rs @@ -22,7 +22,7 @@ use emulated_integration_tests_common::{ accounts, build_genesis_storage, collators, SAFE_XCM_VERSION, }; use parachains_common::Balance; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; pub const PARA_ID: u32 = 1002; pub const ASSETHUB_PARA_ID: u32 = 1000; @@ -73,7 +73,10 @@ pub fn genesis() -> Storage { // open AHW -> AHR bridge ( Location::new(1, [Parachain(1000)]), - Junctions::from([Rococo.into(), Parachain(1000)]), + Junctions::from([ + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH).into(), + Parachain(1000), + ]), Some(bp_messages::LegacyLaneId([0, 0, 0, 2])), ), ], diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs index e7a28ebf4a46..b548e3b7e64c 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs @@ -16,7 +16,7 @@ pub mod genesis; pub use bridge_hub_westend_runtime::{ - xcm_config::XcmConfig as BridgeHubWestendXcmConfig, + self, xcm_config::XcmConfig as BridgeHubWestendXcmConfig, ExistentialDeposit as BridgeHubWestendExistentialDeposit, }; diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs index 92dfa30f2e83..f5642dbb0daa 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs @@ -31,6 +31,9 @@ use emulated_integration_tests_common::{ xcm_emulator::decl_test_parachains, }; +// Polkadot +use xcm::latest::{ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}; + // Penpal Parachain declaration decl_test_parachains! { pub struct PenpalA { @@ -39,7 +42,7 @@ decl_test_parachains! { penpal_runtime::AuraExt::on_initialize(1); frame_support::assert_ok!(penpal_runtime::System::set_storage( penpal_runtime::RuntimeOrigin::root(), - vec![(PenpalRelayNetworkId::key().to_vec(), NetworkId::Rococo.encode())], + vec![(PenpalRelayNetworkId::key().to_vec(), NetworkId::ByGenesis(ROCOCO_GENESIS_HASH).encode())], )); }, runtime = penpal_runtime, @@ -63,7 +66,7 @@ decl_test_parachains! { penpal_runtime::AuraExt::on_initialize(1); frame_support::assert_ok!(penpal_runtime::System::set_storage( penpal_runtime::RuntimeOrigin::root(), - vec![(PenpalRelayNetworkId::key().to_vec(), NetworkId::Westend.encode())], + vec![(PenpalRelayNetworkId::key().to_vec(), NetworkId::ByGenesis(WESTEND_GENESIS_HASH).encode())], )); }, runtime = penpal_runtime, diff --git a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs index 07fde111d3dc..e2757f8b9a35 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs @@ -41,6 +41,7 @@ use polkadot_primitives::{AssignmentId, ValidatorId}; pub const XCM_V2: u32 = 2; pub const XCM_V3: u32 = 3; pub const XCM_V4: u32 = 4; +pub const XCM_V5: u32 = 5; pub const REF_TIME_THRESHOLD: u64 = 33; pub const PROOF_SIZE_THRESHOLD: u64 = 33; @@ -55,26 +56,26 @@ pub const TELEPORTABLE_ASSET_ID: u32 = 2; // USDT registered on AH as (trust-backed) Asset and reserve-transferred between Parachain and AH pub const USDT_ID: u32 = 1984; -pub const PENPAL_ID: u32 = 2000; +pub const PENPAL_A_ID: u32 = 2000; pub const PENPAL_B_ID: u32 = 2001; pub const ASSETS_PALLET_ID: u8 = 50; parameter_types! { - pub PenpalTeleportableAssetLocation: xcm::v4::Location - = xcm::v4::Location::new(1, [ - xcm::v4::Junction::Parachain(PENPAL_ID), - xcm::v4::Junction::PalletInstance(ASSETS_PALLET_ID), - xcm::v4::Junction::GeneralIndex(TELEPORTABLE_ASSET_ID.into()), + pub PenpalATeleportableAssetLocation: xcm::v5::Location + = xcm::v5::Location::new(1, [ + xcm::v5::Junction::Parachain(PENPAL_A_ID), + xcm::v5::Junction::PalletInstance(ASSETS_PALLET_ID), + xcm::v5::Junction::GeneralIndex(TELEPORTABLE_ASSET_ID.into()), ] ); - pub PenpalSiblingSovereignAccount: AccountId = Sibling::from(PENPAL_ID).into_account_truncating(); - pub PenpalBTeleportableAssetLocation: xcm::v4::Location - = xcm::v4::Location::new(1, [ - xcm::v4::Junction::Parachain(PENPAL_B_ID), - xcm::v4::Junction::PalletInstance(ASSETS_PALLET_ID), - xcm::v4::Junction::GeneralIndex(TELEPORTABLE_ASSET_ID.into()), + pub PenpalBTeleportableAssetLocation: xcm::v5::Location + = xcm::v5::Location::new(1, [ + xcm::v5::Junction::Parachain(PENPAL_B_ID), + xcm::v5::Junction::PalletInstance(ASSETS_PALLET_ID), + xcm::v5::Junction::GeneralIndex(TELEPORTABLE_ASSET_ID.into()), ] ); + pub PenpalASiblingSovereignAccount: AccountId = Sibling::from(PENPAL_A_ID).into_account_truncating(); pub PenpalBSiblingSovereignAccount: AccountId = Sibling::from(PENPAL_B_ID).into_account_truncating(); } diff --git a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs index 3ff5ed388a39..b776cafb2545 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs @@ -404,6 +404,230 @@ macro_rules! test_chain_can_claim_assets { }; } +#[macro_export] +macro_rules! test_can_estimate_and_pay_exact_fees { + ( $sender_para:ty, $asset_hub:ty, $receiver_para:ty, ($asset_id:expr, $amount:expr), $owner_prefix:ty ) => { + $crate::macros::paste::paste! { + // We first define the call we'll use throughout the test. + fn get_call( + estimated_local_fees: impl Into, + estimated_intermediate_fees: impl Into, + estimated_remote_fees: impl Into, + ) -> <$sender_para as Chain>::RuntimeCall { + type RuntimeCall = <$sender_para as Chain>::RuntimeCall; + + let beneficiary = [<$receiver_para Receiver>]::get(); + let xcm_in_destination = Xcm::<()>::builder_unsafe() + .pay_fees(estimated_remote_fees) + .deposit_asset(AllCounted(1), beneficiary) + .build(); + let ah_to_receiver = $asset_hub::sibling_location_of($receiver_para::para_id()); + let xcm_in_reserve = Xcm::<()>::builder_unsafe() + .pay_fees(estimated_intermediate_fees) + .deposit_reserve_asset( + AllCounted(1), + ah_to_receiver, + xcm_in_destination, + ) + .build(); + let sender_to_ah = $sender_para::sibling_location_of($asset_hub::para_id()); + let local_xcm = Xcm::<<$sender_para as Chain>::RuntimeCall>::builder() + .withdraw_asset(($asset_id, $amount)) + .pay_fees(estimated_local_fees) + .initiate_reserve_withdraw(AllCounted(1), sender_to_ah, xcm_in_reserve) + .build(); + + RuntimeCall::PolkadotXcm(pallet_xcm::Call::execute { + message: bx!(VersionedXcm::from(local_xcm)), + max_weight: Weight::from_parts(10_000_000_000, 500_000), + }) + } + + let destination = $sender_para::sibling_location_of($receiver_para::para_id()); + let sender = [<$sender_para Sender>]::get(); + let sender_as_seen_by_ah = $asset_hub::sibling_location_of($sender_para::para_id()); + let sov_of_sender_on_ah = $asset_hub::sovereign_account_id_of(sender_as_seen_by_ah.clone()); + let asset_owner = [<$owner_prefix AssetOwner>]::get(); + + // Fund parachain's sender account. + $sender_para::mint_foreign_asset( + <$sender_para as Chain>::RuntimeOrigin::signed(asset_owner.clone()), + $asset_id.clone().into(), + sender.clone(), + $amount * 2, + ); + + // Fund the parachain origin's SA on Asset Hub with the native tokens. + $asset_hub::fund_accounts(vec![(sov_of_sender_on_ah.clone(), $amount * 2)]); + + let beneficiary_id = [<$receiver_para Receiver>]::get(); + + let test_args = TestContext { + sender: sender.clone(), + receiver: beneficiary_id.clone(), + args: TestArgs::new_para( + destination, + beneficiary_id.clone(), + $amount, + ($asset_id, $amount).into(), + None, + 0, + ), + }; + let mut test = ParaToParaThroughAHTest::new(test_args); + + // We get these from the closure. + let mut local_execution_fees = 0; + let mut local_delivery_fees = 0; + let mut remote_message = VersionedXcm::from(Xcm::<()>(Vec::new())); + <$sender_para as TestExt>::execute_with(|| { + type Runtime = <$sender_para as Chain>::Runtime; + type OriginCaller = <$sender_para as Chain>::OriginCaller; + + let call = get_call( + (Parent, 100_000_000_000u128), + (Parent, 100_000_000_000u128), + (Parent, 100_000_000_000u128), + ); + let origin = OriginCaller::system(RawOrigin::Signed(sender.clone())); + let result = Runtime::dry_run_call(origin, call).unwrap(); + let local_xcm = result.local_xcm.unwrap().clone(); + let local_xcm_weight = Runtime::query_xcm_weight(local_xcm).unwrap(); + local_execution_fees = Runtime::query_weight_to_asset_fee( + local_xcm_weight, + VersionedAssetId::from(AssetId(Location::parent())), + ) + .unwrap(); + // We filter the result to get only the messages we are interested in. + let (destination_to_query, messages_to_query) = &result + .forwarded_xcms + .iter() + .find(|(destination, _)| { + *destination == VersionedLocation::from(Location::new(1, [Parachain(1000)])) + }) + .unwrap(); + assert_eq!(messages_to_query.len(), 1); + remote_message = messages_to_query[0].clone(); + let delivery_fees = + Runtime::query_delivery_fees(destination_to_query.clone(), remote_message.clone()) + .unwrap(); + local_delivery_fees = $crate::xcm_helpers::get_amount_from_versioned_assets(delivery_fees); + }); + + // These are set in the AssetHub closure. + let mut intermediate_execution_fees = 0; + let mut intermediate_delivery_fees = 0; + let mut intermediate_remote_message = VersionedXcm::from(Xcm::<()>(Vec::new())); + <$asset_hub as TestExt>::execute_with(|| { + type Runtime = <$asset_hub as Chain>::Runtime; + type RuntimeCall = <$asset_hub as Chain>::RuntimeCall; + + // First we get the execution fees. + let weight = Runtime::query_xcm_weight(remote_message.clone()).unwrap(); + intermediate_execution_fees = Runtime::query_weight_to_asset_fee( + weight, + VersionedAssetId::from(AssetId(Location::new(1, []))), + ) + .unwrap(); + + // We have to do this to turn `VersionedXcm<()>` into `VersionedXcm`. + let xcm_program = + VersionedXcm::from(Xcm::::from(remote_message.clone().try_into().unwrap())); + + // Now we get the delivery fees to the final destination. + let result = + Runtime::dry_run_xcm(sender_as_seen_by_ah.clone().into(), xcm_program).unwrap(); + let (destination_to_query, messages_to_query) = &result + .forwarded_xcms + .iter() + .find(|(destination, _)| { + *destination == VersionedLocation::from(Location::new(1, [Parachain(2001)])) + }) + .unwrap(); + // There's actually two messages here. + // One created when the message we sent from `$sender_para` arrived and was executed. + // The second one when we dry-run the xcm. + // We could've gotten the message from the queue without having to dry-run, but + // offchain applications would have to dry-run, so we do it here as well. + intermediate_remote_message = messages_to_query[0].clone(); + let delivery_fees = Runtime::query_delivery_fees( + destination_to_query.clone(), + intermediate_remote_message.clone(), + ) + .unwrap(); + intermediate_delivery_fees = $crate::xcm_helpers::get_amount_from_versioned_assets(delivery_fees); + }); + + // Get the final execution fees in the destination. + let mut final_execution_fees = 0; + <$receiver_para as TestExt>::execute_with(|| { + type Runtime = <$sender_para as Chain>::Runtime; + + let weight = Runtime::query_xcm_weight(intermediate_remote_message.clone()).unwrap(); + final_execution_fees = + Runtime::query_weight_to_asset_fee(weight, VersionedAssetId::from(AssetId(Location::parent()))) + .unwrap(); + }); + + // Dry-running is done. + $sender_para::reset_ext(); + $asset_hub::reset_ext(); + $receiver_para::reset_ext(); + + // Fund accounts again. + $sender_para::mint_foreign_asset( + <$sender_para as Chain>::RuntimeOrigin::signed(asset_owner), + $asset_id.clone().into(), + sender.clone(), + $amount * 2, + ); + $asset_hub::fund_accounts(vec![(sov_of_sender_on_ah, $amount * 2)]); + + // Actually run the extrinsic. + let sender_assets_before = $sender_para::execute_with(|| { + type ForeignAssets = <$sender_para as [<$sender_para Pallet>]>::ForeignAssets; + >::balance($asset_id.clone().into(), &sender) + }); + let receiver_assets_before = $receiver_para::execute_with(|| { + type ForeignAssets = <$receiver_para as [<$receiver_para Pallet>]>::ForeignAssets; + >::balance($asset_id.clone().into(), &beneficiary_id) + }); + + test.set_assertion::<$sender_para>(sender_assertions); + test.set_assertion::<$asset_hub>(hop_assertions); + test.set_assertion::<$receiver_para>(receiver_assertions); + let call = get_call( + (Parent, local_execution_fees + local_delivery_fees), + (Parent, intermediate_execution_fees + intermediate_delivery_fees), + (Parent, final_execution_fees), + ); + test.set_call(call); + test.assert(); + + let sender_assets_after = $sender_para::execute_with(|| { + type ForeignAssets = <$sender_para as [<$sender_para Pallet>]>::ForeignAssets; + >::balance($asset_id.clone().into(), &sender) + }); + let receiver_assets_after = $receiver_para::execute_with(|| { + type ForeignAssets = <$receiver_para as [<$receiver_para Pallet>]>::ForeignAssets; + >::balance($asset_id.into(), &beneficiary_id) + }); + + // We know the exact fees on every hop. + assert_eq!(sender_assets_after, sender_assets_before - $amount); + assert_eq!( + receiver_assets_after, + receiver_assets_before + $amount - + local_execution_fees - + local_delivery_fees - + intermediate_execution_fees - + intermediate_delivery_fees - + final_execution_fees + ); + } + }; +} + #[macro_export] macro_rules! test_dry_run_transfer_across_pk_bridge { ( $sender_asset_hub:ty, $sender_bridge_hub:ty, $destination:expr ) => { @@ -474,7 +698,7 @@ macro_rules! test_xcm_fee_querying_apis_work_for_asset_hub { )); type Runtime = <$asset_hub as Chain>::Runtime; - let acceptable_payment_assets = Runtime::query_acceptable_payment_assets(4).unwrap(); + let acceptable_payment_assets = Runtime::query_acceptable_payment_assets(XCM_VERSION).unwrap(); assert_eq!(acceptable_payment_assets, vec![ VersionedAssetId::from(AssetId(wnd.clone())), VersionedAssetId::from(AssetId(usdt.clone())), diff --git a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs index 7a289a3f1ac6..9125c976525e 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs @@ -27,12 +27,11 @@ pub fn xcm_transact_paid_execution( beneficiary: AccountId, ) -> VersionedXcm<()> { let weight_limit = WeightLimit::Unlimited; - let require_weight_at_most = Weight::from_parts(1000000000, 200000); VersionedXcm::from(Xcm(vec![ WithdrawAsset(fees.clone().into()), BuyExecution { fees, weight_limit }, - Transact { require_weight_at_most, origin_kind, call }, + Transact { origin_kind, call }, RefundSurplus, DepositAsset { assets: All.into(), @@ -50,12 +49,11 @@ pub fn xcm_transact_unpaid_execution( origin_kind: OriginKind, ) -> VersionedXcm<()> { let weight_limit = WeightLimit::Unlimited; - let require_weight_at_most = Weight::from_parts(1000000000, 200000); let check_origin = None; VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit, check_origin }, - Transact { require_weight_at_most, origin_kind, call }, + Transact { origin_kind, call }, ])) } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs index 1184b5fd7c4a..f3a1b3f5bfa2 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs @@ -27,8 +27,8 @@ mod imports { // Polkadot pub use xcm::{ + latest::{ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}, prelude::{AccountId32 as AccountId32Junction, *}, - v3, }; pub use xcm_executor::traits::TransferType; diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs index 99b31aba4be0..52a20c00c277 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = AssetHubRococoExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(AssetHubRococo, RuntimeCall, NetworkId::Rococo, assets, amount); + test_chain_can_claim_assets!( + AssetHubRococo, + RuntimeCall, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/hybrid_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/hybrid_transfers.rs index 7bb25d7cec62..baec7d20f415 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/hybrid_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/hybrid_transfers.rs @@ -163,7 +163,7 @@ fn transfer_foreign_assets_from_asset_hub_to_para() { // Foreign asset used: bridged WND let foreign_amount_to_send = ASSET_HUB_ROCOCO_ED * 10_000_000; let wnd_at_rococo_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Westend)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH))]); // Configure destination chain to trust AH as reserve of WND PenpalA::execute_with(|| { @@ -171,7 +171,7 @@ fn transfer_foreign_assets_from_asset_hub_to_para() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Westend)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]).encode(), )], )); }); @@ -293,7 +293,7 @@ fn transfer_foreign_assets_from_para_to_asset_hub() { // Foreign asset used: bridged WND let foreign_amount_to_send = ASSET_HUB_ROCOCO_ED * 10_000_000; let wnd_at_rococo_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Westend)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH))]); // Configure destination chain to trust AH as reserve of WND PenpalA::execute_with(|| { @@ -301,7 +301,7 @@ fn transfer_foreign_assets_from_para_to_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Westend)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]).encode(), )], )); }); @@ -455,7 +455,7 @@ fn transfer_foreign_assets_from_para_to_para_through_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Westend)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]).encode(), )], )); }); @@ -464,14 +464,14 @@ fn transfer_foreign_assets_from_para_to_para_through_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Westend)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]).encode(), )], )); }); // Register WND as foreign asset and transfer it around the Rococo ecosystem let wnd_at_rococo_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Westend)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH))]); AssetHubRococo::force_create_foreign_asset( wnd_at_rococo_parachains.clone().try_into().unwrap(), assets_owner.clone(), diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs index 302f71f89f83..698ef2c9e792 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs @@ -1599,7 +1599,7 @@ fn reserve_withdraw_from_untrusted_reserve_fails() { ]); let result = ::PolkadotXcm::execute( signed_origin, - bx!(xcm::VersionedXcm::V4(xcm)), + bx!(xcm::VersionedXcm::from(xcm)), Weight::MAX, ); assert!(result.is_err()); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs index 29eaa9694643..ea8f6c1defba 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/send.rs @@ -24,7 +24,7 @@ fn send_transact_as_superuser_from_relay_to_asset_hub_works() { ASSET_MIN_BALANCE, true, AssetHubRococoSender::get().into(), - Some(Weight::from_parts(1_019_445_000, 200_000)), + Some(Weight::from_parts(144_933_000, 3675)), ) } @@ -121,7 +121,7 @@ fn send_xcm_from_para_to_asset_hub_paying_fee_with_sufficient_asset() { ASSET_MIN_BALANCE, true, para_sovereign_account.clone(), - Some(Weight::from_parts(1_019_445_000, 200_000)), + Some(Weight::from_parts(144_933_000, 3675)), ASSET_MIN_BALANCE * 1000000000, ); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs index 5662a78ab67f..8da1e56de219 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/set_xcm_versions.rs @@ -67,7 +67,7 @@ fn system_para_sets_relay_xcm_supported_version() { AssetHubRococo::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; - AssetHubRococo::assert_dmp_queue_complete(Some(Weight::from_parts(1_019_210_000, 200_000))); + AssetHubRococo::assert_dmp_queue_complete(Some(Weight::from_parts(115_294_000, 0))); assert_expected_events!( AssetHubRococo, diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs index 470b4d0f389e..7fde929c0dcb 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs @@ -574,7 +574,7 @@ fn teleport_to_untrusted_chain_fails() { ]); let result = ::PolkadotXcm::execute( signed_origin, - bx!(xcm::VersionedXcm::V4(xcm)), + bx!(xcm::VersionedXcm::from(xcm)), Weight::MAX, ); assert!(result.is_err()); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/treasury.rs index 3320392b495d..69111d38bcac 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/treasury.rs @@ -71,11 +71,12 @@ fn spend_roc_on_asset_hub() { let teleport_call = RuntimeCall::Utility(pallet_utility::Call::::dispatch_as { as_origin: bx!(RococoOriginCaller::system(RawOrigin::Signed(treasury_account))), call: bx!(RuntimeCall::XcmPallet(pallet_xcm::Call::::teleport_assets { - dest: bx!(VersionedLocation::V4(asset_hub_location.clone())), - beneficiary: bx!(VersionedLocation::V4(treasury_location)), - assets: bx!(VersionedAssets::V4( - Asset { id: native_asset.clone().into(), fun: treasury_balance.into() }.into() - )), + dest: bx!(VersionedLocation::from(asset_hub_location.clone())), + beneficiary: bx!(VersionedLocation::from(treasury_location)), + assets: bx!(VersionedAssets::from(Assets::from(Asset { + id: native_asset.clone().into(), + fun: treasury_balance.into() + }))), fee_asset_item: 0, })), }); @@ -110,12 +111,12 @@ fn spend_roc_on_asset_hub() { let native_asset = Location::parent(); let treasury_spend_call = RuntimeCall::Treasury(pallet_treasury::Call::::spend { - asset_kind: bx!(VersionedLocatableAsset::V4 { - location: asset_hub_location.clone(), - asset_id: native_asset.into(), - }), + asset_kind: bx!(VersionedLocatableAsset::from(( + asset_hub_location.clone(), + native_asset.into() + ))), amount: treasury_spend_balance, - beneficiary: bx!(VersionedLocation::V4(alice_location)), + beneficiary: bx!(VersionedLocation::from(alice_location)), valid_from: None, }); @@ -170,16 +171,12 @@ fn create_and_claim_treasury_spend_in_usdt() { // treasury account on a sibling parachain. let treasury_account = ahr_xcm_config::LocationToAccountId::convert_location(&treasury_location).unwrap(); - let asset_hub_location = - v3::Location::new(0, v3::Junction::Parachain(AssetHubRococo::para_id().into())); + let asset_hub_location = Location::new(0, Parachain(AssetHubRococo::para_id().into())); let root = ::RuntimeOrigin::root(); - // asset kind to be spend from the treasury. - let asset_kind = VersionedLocatableAsset::V3 { - location: asset_hub_location, - asset_id: v3::AssetId::Concrete( - (v3::Junction::PalletInstance(50), v3::Junction::GeneralIndex(USDT_ID.into())).into(), - ), - }; + // asset kind to be spent from the treasury. + let asset_kind: VersionedLocatableAsset = + (asset_hub_location, AssetId((PalletInstance(50), GeneralIndex(USDT_ID.into())).into())) + .into(); // treasury spend beneficiary. let alice: AccountId = Rococo::account_id_of(ALICE); let bob: AccountId = Rococo::account_id_of(BOB); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/xcm_fee_estimation.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/xcm_fee_estimation.rs index aa0e183ecdda..ea210d4f3b65 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/xcm_fee_estimation.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/xcm_fee_estimation.rs @@ -16,10 +16,8 @@ //! Tests for XCM fee estimation in the runtime. use crate::imports::*; -use frame_support::{ - dispatch::RawOrigin, - sp_runtime::{traits::Dispatchable, DispatchResult}, -}; +use emulated_integration_tests_common::test_can_estimate_and_pay_exact_fees; +use frame_support::dispatch::RawOrigin; use xcm_runtime_apis::{ dry_run::runtime_decl_for_dry_run_api::DryRunApiV1, fees::runtime_decl_for_xcm_payment_api::XcmPaymentApiV1, @@ -76,16 +74,6 @@ fn receiver_assertions(test: ParaToParaThroughAHTest) { ); } -fn transfer_assets_para_to_para_through_ah_dispatchable( - test: ParaToParaThroughAHTest, -) -> DispatchResult { - let call = transfer_assets_para_to_para_through_ah_call(test.clone()); - match call.dispatch(test.signed_origin) { - Ok(_) => Ok(()), - Err(error_with_post_info) => Err(error_with_post_info.error), - } -} - fn transfer_assets_para_to_para_through_ah_call( test: ParaToParaThroughAHTest, ) -> ::RuntimeCall { @@ -100,7 +88,7 @@ fn transfer_assets_para_to_para_through_ah_call( dest: bx!(test.args.dest.into()), assets: bx!(test.args.assets.clone().into()), assets_transfer_type: bx!(TransferType::RemoteReserve(asset_hub_location.clone().into())), - remote_fees_id: bx!(VersionedAssetId::V4(AssetId(Location::new(1, [])))), + remote_fees_id: bx!(VersionedAssetId::from(AssetId(Location::new(1, [])))), fees_transfer_type: bx!(TransferType::RemoteReserve(asset_hub_location.into())), custom_xcm_on_dest: bx!(VersionedXcm::from(custom_xcm_on_dest)), weight_limit: test.args.weight_limit, @@ -151,7 +139,7 @@ fn multi_hop_works() { // We get them from the PenpalA closure. let mut delivery_fees_amount = 0; - let mut remote_message = VersionedXcm::V4(Xcm(Vec::new())); + let mut remote_message = VersionedXcm::from(Xcm(Vec::new())); ::execute_with(|| { type Runtime = ::Runtime; type OriginCaller = ::OriginCaller; @@ -164,7 +152,7 @@ fn multi_hop_works() { .forwarded_xcms .iter() .find(|(destination, _)| { - *destination == VersionedLocation::V4(Location::new(1, [Parachain(1000)])) + *destination == VersionedLocation::from(Location::new(1, [Parachain(1000)])) }) .unwrap(); assert_eq!(messages_to_query.len(), 1); @@ -178,7 +166,7 @@ fn multi_hop_works() { // These are set in the AssetHub closure. let mut intermediate_execution_fees = 0; let mut intermediate_delivery_fees_amount = 0; - let mut intermediate_remote_message = VersionedXcm::V4(Xcm::<()>(Vec::new())); + let mut intermediate_remote_message = VersionedXcm::from(Xcm::<()>(Vec::new())); ::execute_with(|| { type Runtime = ::Runtime; type RuntimeCall = ::RuntimeCall; @@ -187,13 +175,14 @@ fn multi_hop_works() { let weight = Runtime::query_xcm_weight(remote_message.clone()).unwrap(); intermediate_execution_fees = Runtime::query_weight_to_asset_fee( weight, - VersionedAssetId::V4(Location::new(1, []).into()), + VersionedAssetId::from(AssetId(Location::new(1, []))), ) .unwrap(); // We have to do this to turn `VersionedXcm<()>` into `VersionedXcm`. - let xcm_program = - VersionedXcm::V4(Xcm::::from(remote_message.clone().try_into().unwrap())); + let xcm_program = VersionedXcm::from(Xcm::::from( + remote_message.clone().try_into().unwrap(), + )); // Now we get the delivery fees to the final destination. let result = @@ -202,7 +191,7 @@ fn multi_hop_works() { .forwarded_xcms .iter() .find(|(destination, _)| { - *destination == VersionedLocation::V4(Location::new(1, [Parachain(2001)])) + *destination == VersionedLocation::from(Location::new(1, [Parachain(2001)])) }) .unwrap(); // There's actually two messages here. @@ -225,9 +214,11 @@ fn multi_hop_works() { type Runtime = ::Runtime; let weight = Runtime::query_xcm_weight(intermediate_remote_message.clone()).unwrap(); - final_execution_fees = - Runtime::query_weight_to_asset_fee(weight, VersionedAssetId::V4(Parent.into())) - .unwrap(); + final_execution_fees = Runtime::query_weight_to_asset_fee( + weight, + VersionedAssetId::from(AssetId(Location::parent())), + ) + .unwrap(); }); // Dry-running is done. @@ -257,7 +248,8 @@ fn multi_hop_works() { test.set_assertion::(sender_assertions); test.set_assertion::(hop_assertions); test.set_assertion::(receiver_assertions); - test.set_dispatchable::(transfer_assets_para_to_para_through_ah_dispatchable); + let call = transfer_assets_para_to_para_through_ah_call(test.clone()); + test.set_call(call); test.assert(); let sender_assets_after = PenpalA::execute_with(|| { @@ -284,3 +276,14 @@ fn multi_hop_works() { final_execution_fees ); } + +#[test] +fn multi_hop_pay_fees_works() { + test_can_estimate_and_pay_exact_fees!( + PenpalA, + AssetHubRococo, + PenpalB, + (Parent, 1_000_000_000_000u128), + Penpal + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml index 872a8ffa6a8a..71e44e5cee7d 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml @@ -31,6 +31,7 @@ pallet-asset-tx-payment = { workspace = true } # Polkadot polkadot-runtime-common = { workspace = true, default-features = true } xcm = { workspace = true } +xcm-builder = { workspace = true } xcm-executor = { workspace = true } pallet-xcm = { workspace = true } xcm-runtime-apis = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs index 179a44e14aa1..3cca99fbfe5c 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs @@ -26,7 +26,10 @@ mod imports { }; // Polkadot - pub use xcm::prelude::{AccountId32 as AccountId32Junction, *}; + pub use xcm::{ + latest::{AssetTransferFilter, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}, + prelude::{AccountId32 as AccountId32Junction, *}, + }; pub use xcm_executor::traits::TransferType; // Cumulus @@ -42,7 +45,7 @@ mod imports { xcm_helpers::{ get_amount_from_versioned_assets, non_fee_asset, xcm_transact_paid_execution, }, - ASSETS_PALLET_ID, RESERVABLE_ASSET_ID, XCM_V3, + ASSETS_PALLET_ID, RESERVABLE_ASSET_ID, USDT_ID, XCM_V3, }; pub use parachains_common::{AccountId, Balance}; pub use westend_system_emulated_network::{ @@ -59,12 +62,16 @@ mod imports { genesis::{AssetHubWestendAssetOwner, ED as ASSET_HUB_WESTEND_ED}, AssetHubWestendParaPallet as AssetHubWestendPallet, }, + bridge_hub_westend_emulated_chain::bridge_hub_westend_runtime::xcm_config::{ + self as bhw_xcm_config, + }, collectives_westend_emulated_chain::CollectivesWestendParaPallet as CollectivesWestendPallet, penpal_emulated_chain::{ penpal_runtime::xcm_config::{ CustomizableAssetFromSystemAssetHub as PenpalCustomizableAssetFromSystemAssetHub, LocalReservableFromAssetHub as PenpalLocalReservableFromAssetHub, LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub, + UniversalLocation as PenpalUniversalLocation, UsdtFromAssetHub as PenpalUsdtFromAssetHub, }, PenpalAParaPallet as PenpalAPallet, PenpalAssetOwner, diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs index de58839634f1..90af907654f9 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = AssetHubWestendExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(AssetHubWestend, RuntimeCall, NetworkId::Westend, assets, amount); + test_chain_can_claim_assets!( + AssetHubWestend, + RuntimeCall, + NetworkId::ByGenesis(WESTEND_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs index 9520659712fc..124ec2ec1f66 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs @@ -34,10 +34,9 @@ fn create_and_claim_treasury_spend() { let asset_hub_location = Location::new(1, [Parachain(AssetHubWestend::para_id().into())]); let root = ::RuntimeOrigin::root(); // asset kind to be spent from the treasury. - let asset_kind = VersionedLocatableAsset::V4 { - location: asset_hub_location, - asset_id: AssetId((PalletInstance(50), GeneralIndex(USDT_ID.into())).into()), - }; + let asset_kind: VersionedLocatableAsset = + (asset_hub_location, AssetId((PalletInstance(50), GeneralIndex(USDT_ID.into())).into())) + .into(); // treasury spend beneficiary. let alice: AccountId = Westend::account_id_of(ALICE); let bob: AccountId = CollectivesWestend::account_id_of(BOB); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/hybrid_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/hybrid_transfers.rs index 4d6cdd9a94d6..a0fc82fba6ef 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/hybrid_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/hybrid_transfers.rs @@ -163,7 +163,7 @@ fn transfer_foreign_assets_from_asset_hub_to_para() { // Foreign asset used: bridged ROC let foreign_amount_to_send = ASSET_HUB_WESTEND_ED * 10_000_000; let roc_at_westend_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Rococo)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))]); // Configure destination chain to trust AH as reserve of ROC PenpalA::execute_with(|| { @@ -171,7 +171,7 @@ fn transfer_foreign_assets_from_asset_hub_to_para() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Rococo)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]).encode(), )], )); }); @@ -293,7 +293,7 @@ fn transfer_foreign_assets_from_para_to_asset_hub() { // Foreign asset used: bridged ROC let foreign_amount_to_send = ASSET_HUB_WESTEND_ED * 10_000_000; let roc_at_westend_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Rococo)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))]); // Configure destination chain to trust AH as reserve of ROC PenpalA::execute_with(|| { @@ -301,7 +301,7 @@ fn transfer_foreign_assets_from_para_to_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Rococo)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]).encode(), )], )); }); @@ -456,7 +456,7 @@ fn transfer_foreign_assets_from_para_to_para_through_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Rococo)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]).encode(), )], )); }); @@ -465,14 +465,14 @@ fn transfer_foreign_assets_from_para_to_para_through_asset_hub() { ::RuntimeOrigin::root(), vec![( PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), - Location::new(2, [GlobalConsensus(Rococo)]).encode(), + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]).encode(), )], )); }); // Register ROC as foreign asset and transfer it around the Westend ecosystem let roc_at_westend_parachains = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Rococo)]); + Location::new(2, [Junction::GlobalConsensus(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))]); AssetHubWestend::force_create_foreign_asset( roc_at_westend_parachains.clone().try_into().unwrap(), assets_owner.clone(), @@ -819,3 +819,88 @@ fn transfer_native_asset_from_relay_to_para_through_asset_hub() { // should be non-zero assert!(receiver_assets_after < receiver_assets_before + amount_to_send); } + +// ============================================================================================== +// ==== Bidirectional Transfer - Native + Teleportable Foreign Assets - Parachain<->AssetHub ==== +// ============================================================================================== +/// Transfers of native asset plus teleportable foreign asset from Parachain to AssetHub and back +/// with fees paid using native asset. +#[test] +fn bidirectional_transfer_multiple_assets_between_penpal_and_asset_hub() { + fn execute_xcm_penpal_to_asset_hub(t: ParaToSystemParaTest) -> DispatchResult { + let all_assets = t.args.assets.clone().into_inner(); + let mut assets = all_assets.clone(); + let mut fees = assets.remove(t.args.fee_asset_item as usize); + // TODO(https://github.com/paritytech/polkadot-sdk/issues/6197): dry-run to get exact fees. + // For now just use half the fees locally, half on dest + if let Fungible(fees_amount) = fees.fun { + fees.fun = Fungible(fees_amount / 2); + } + // xcm to be executed at dest + let xcm_on_dest = Xcm(vec![ + // since this is the last hop, we don't need to further use any assets previously + // reserved for fees (there are no further hops to cover transport fees for); we + // RefundSurplus to get back any unspent fees + RefundSurplus, + DepositAsset { assets: Wild(All), beneficiary: t.args.beneficiary }, + ]); + let xcm = Xcm::<()>(vec![ + WithdrawAsset(all_assets.into()), + PayFees { asset: fees.clone() }, + InitiateTransfer { + destination: t.args.dest, + remote_fees: Some(AssetTransferFilter::ReserveWithdraw(fees.into())), + preserve_origin: false, + assets: vec![AssetTransferFilter::Teleport(assets.into())], + remote_xcm: xcm_on_dest, + }, + ]); + ::PolkadotXcm::execute( + t.signed_origin, + bx!(xcm::VersionedXcm::from(xcm.into())), + Weight::MAX, + ) + .unwrap(); + Ok(()) + } + fn execute_xcm_asset_hub_to_penpal(t: SystemParaToParaTest) -> DispatchResult { + let all_assets = t.args.assets.clone().into_inner(); + let mut assets = all_assets.clone(); + let mut fees = assets.remove(t.args.fee_asset_item as usize); + // TODO(https://github.com/paritytech/polkadot-sdk/issues/6197): dry-run to get exact fees. + // For now just use half the fees locally, half on dest + if let Fungible(fees_amount) = fees.fun { + fees.fun = Fungible(fees_amount / 2); + } + // xcm to be executed at dest + let xcm_on_dest = Xcm(vec![ + // since this is the last hop, we don't need to further use any assets previously + // reserved for fees (there are no further hops to cover transport fees for); we + // RefundSurplus to get back any unspent fees + RefundSurplus, + DepositAsset { assets: Wild(All), beneficiary: t.args.beneficiary }, + ]); + let xcm = Xcm::<()>(vec![ + WithdrawAsset(all_assets.into()), + PayFees { asset: fees.clone() }, + InitiateTransfer { + destination: t.args.dest, + remote_fees: Some(AssetTransferFilter::ReserveDeposit(fees.into())), + preserve_origin: false, + assets: vec![AssetTransferFilter::Teleport(assets.into())], + remote_xcm: xcm_on_dest, + }, + ]); + ::PolkadotXcm::execute( + t.signed_origin, + bx!(xcm::VersionedXcm::from(xcm.into())), + Weight::MAX, + ) + .unwrap(); + Ok(()) + } + do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using_xt( + execute_xcm_penpal_to_asset_hub, + execute_xcm_asset_hub_to_penpal, + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs index 73b73b239a1b..0dfe7a85f4c2 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs @@ -18,8 +18,86 @@ mod fellowship_treasury; mod hybrid_transfers; mod reserve_transfer; mod send; +mod set_asset_claimer; mod set_xcm_versions; mod swap; mod teleport; +mod transact; mod treasury; mod xcm_fee_estimation; + +#[macro_export] +macro_rules! foreign_balance_on { + ( $chain:ident, $id:expr, $who:expr ) => { + emulated_integration_tests_common::impls::paste::paste! { + <$chain>::execute_with(|| { + type ForeignAssets = <$chain as [<$chain Pallet>]>::ForeignAssets; + >::balance($id, $who) + }) + } + }; +} + +#[macro_export] +macro_rules! create_pool_with_wnd_on { + ( $chain:ident, $asset_id:expr, $is_foreign:expr, $asset_owner:expr ) => { + emulated_integration_tests_common::impls::paste::paste! { + <$chain>::execute_with(|| { + type RuntimeEvent = <$chain as Chain>::RuntimeEvent; + let owner = $asset_owner; + let signed_owner = <$chain as Chain>::RuntimeOrigin::signed(owner.clone()); + let wnd_location: Location = Parent.into(); + if $is_foreign { + assert_ok!(<$chain as [<$chain Pallet>]>::ForeignAssets::mint( + signed_owner.clone(), + $asset_id.clone().into(), + owner.clone().into(), + 10_000_000_000_000, // For it to have more than enough. + )); + } else { + let asset_id = match $asset_id.interior.last() { + Some(GeneralIndex(id)) => *id as u32, + _ => unreachable!(), + }; + assert_ok!(<$chain as [<$chain Pallet>]>::Assets::mint( + signed_owner.clone(), + asset_id.into(), + owner.clone().into(), + 10_000_000_000_000, // For it to have more than enough. + )); + } + + assert_ok!(<$chain as [<$chain Pallet>]>::AssetConversion::create_pool( + signed_owner.clone(), + Box::new(wnd_location.clone()), + Box::new($asset_id.clone()), + )); + + assert_expected_events!( + $chain, + vec![ + RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, + ] + ); + + assert_ok!(<$chain as [<$chain Pallet>]>::AssetConversion::add_liquidity( + signed_owner, + Box::new(wnd_location), + Box::new($asset_id), + 1_000_000_000_000, + 2_000_000_000_000, // $asset_id is worth half of wnd + 0, + 0, + owner.into() + )); + + assert_expected_events!( + $chain, + vec![ + RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded { .. }) => {}, + ] + ); + }); + } + }; +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs index 10c27c338ec7..558eab13e5c7 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::imports::*; +use crate::{create_pool_with_wnd_on, foreign_balance_on, imports::*}; use sp_core::{crypto::get_public_from_string_or_panic, sr25519}; fn relay_to_para_sender_assertions(t: RelayToParaTest) { @@ -651,10 +651,8 @@ fn reserve_transfer_native_asset_from_relay_to_para() { // Query initial balances let sender_balance_before = test.sender.balance; - let receiver_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location.clone(), &receiver) - }); + let receiver_assets_before = + foreign_balance_on!(PenpalA, relay_native_asset_location.clone(), &receiver); // Set assertions and dispatchables test.set_assertion::(relay_to_para_sender_assertions); @@ -664,10 +662,8 @@ fn reserve_transfer_native_asset_from_relay_to_para() { // Query final balances let sender_balance_after = test.sender.balance; - let receiver_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location, &receiver) - }); + let receiver_assets_after = + foreign_balance_on!(PenpalA, relay_native_asset_location, &receiver); // Sender's balance is reduced by amount sent plus delivery fees assert!(sender_balance_after < sender_balance_before - amount_to_send); @@ -722,10 +718,8 @@ fn reserve_transfer_native_asset_from_para_to_relay() { let mut test = ParaToRelayTest::new(test_args); // Query initial balances - let sender_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location.clone(), &sender) - }); + let sender_assets_before = + foreign_balance_on!(PenpalA, relay_native_asset_location.clone(), &sender); let receiver_balance_before = test.receiver.balance; // Set assertions and dispatchables @@ -735,10 +729,7 @@ fn reserve_transfer_native_asset_from_para_to_relay() { test.assert(); // Query final balances - let sender_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location, &sender) - }); + let sender_assets_after = foreign_balance_on!(PenpalA, relay_native_asset_location, &sender); let receiver_balance_after = test.receiver.balance; // Sender's balance is reduced by amount sent plus delivery fees @@ -784,10 +775,8 @@ fn reserve_transfer_native_asset_from_asset_hub_to_para() { // Query initial balances let sender_balance_before = test.sender.balance; - let receiver_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location.clone(), &receiver) - }); + let receiver_assets_before = + foreign_balance_on!(PenpalA, system_para_native_asset_location.clone(), &receiver); // Set assertions and dispatchables test.set_assertion::(system_para_to_para_sender_assertions); @@ -797,10 +786,8 @@ fn reserve_transfer_native_asset_from_asset_hub_to_para() { // Query final balances let sender_balance_after = test.sender.balance; - let receiver_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location, &receiver) - }); + let receiver_assets_after = + foreign_balance_on!(PenpalA, system_para_native_asset_location, &receiver); // Sender's balance is reduced by amount sent plus delivery fees assert!(sender_balance_after < sender_balance_before - amount_to_send); @@ -856,10 +843,8 @@ fn reserve_transfer_native_asset_from_para_to_asset_hub() { let mut test = ParaToSystemParaTest::new(test_args); // Query initial balances - let sender_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location.clone(), &sender) - }); + let sender_assets_before = + foreign_balance_on!(PenpalA, system_para_native_asset_location.clone(), &sender); let receiver_balance_before = test.receiver.balance; // Set assertions and dispatchables @@ -869,10 +854,8 @@ fn reserve_transfer_native_asset_from_para_to_asset_hub() { test.assert(); // Query final balances - let sender_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location, &sender) - }); + let sender_assets_after = + foreign_balance_on!(PenpalA, system_para_native_asset_location, &sender); let receiver_balance_after = test.receiver.balance; // Sender's balance is reduced by amount sent plus delivery fees @@ -950,17 +933,10 @@ fn reserve_transfer_multiple_assets_from_asset_hub_to_para() { type Assets = ::Assets; >::balance(RESERVABLE_ASSET_ID, &sender) }); - let receiver_system_native_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location.clone(), &receiver) - }); - let receiver_foreign_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - system_para_foreign_asset_location.clone(), - &receiver, - ) - }); + let receiver_system_native_assets_before = + foreign_balance_on!(PenpalA, system_para_native_asset_location.clone(), &receiver); + let receiver_foreign_assets_before = + foreign_balance_on!(PenpalA, system_para_foreign_asset_location.clone(), &receiver); // Set assertions and dispatchables test.set_assertion::(system_para_to_para_assets_sender_assertions); @@ -974,14 +950,10 @@ fn reserve_transfer_multiple_assets_from_asset_hub_to_para() { type Assets = ::Assets; >::balance(RESERVABLE_ASSET_ID, &sender) }); - let receiver_system_native_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_native_asset_location, &receiver) - }); - let receiver_foreign_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_para_foreign_asset_location, &receiver) - }); + let receiver_system_native_assets_after = + foreign_balance_on!(PenpalA, system_para_native_asset_location, &receiver); + let receiver_foreign_assets_after = + foreign_balance_on!(PenpalA, system_para_foreign_asset_location.clone(), &receiver); // Sender's balance is reduced assert!(sender_balance_after < sender_balance_before); // Receiver's foreign asset balance is increased @@ -1082,14 +1054,10 @@ fn reserve_transfer_multiple_assets_from_para_to_asset_hub() { let mut test = ParaToSystemParaTest::new(para_test_args); // Query initial balances - let sender_system_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_asset_location_on_penpal.clone(), &sender) - }); - let sender_foreign_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(asset_location_on_penpal.clone(), &sender) - }); + let sender_system_assets_before = + foreign_balance_on!(PenpalA, system_asset_location_on_penpal.clone(), &sender); + let sender_foreign_assets_before = + foreign_balance_on!(PenpalA, asset_location_on_penpal.clone(), &sender); let receiver_balance_before = test.receiver.balance; let receiver_assets_before = AssetHubWestend::execute_with(|| { type Assets = ::Assets; @@ -1103,14 +1071,10 @@ fn reserve_transfer_multiple_assets_from_para_to_asset_hub() { test.assert(); // Query final balances - let sender_system_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(system_asset_location_on_penpal, &sender) - }); - let sender_foreign_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(asset_location_on_penpal, &sender) - }); + let sender_system_assets_after = + foreign_balance_on!(PenpalA, system_asset_location_on_penpal, &sender); + let sender_foreign_assets_after = + foreign_balance_on!(PenpalA, asset_location_on_penpal, &sender); let receiver_balance_after = test.receiver.balance; let receiver_assets_after = AssetHubWestend::execute_with(|| { type Assets = ::Assets; @@ -1171,14 +1135,10 @@ fn reserve_transfer_native_asset_from_para_to_para_through_relay() { let mut test = ParaToParaThroughRelayTest::new(test_args); // Query initial balances - let sender_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location.clone(), &sender) - }); - let receiver_assets_before = PenpalB::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location.clone(), &receiver) - }); + let sender_assets_before = + foreign_balance_on!(PenpalA, relay_native_asset_location.clone(), &sender); + let receiver_assets_before = + foreign_balance_on!(PenpalB, relay_native_asset_location.clone(), &receiver); // Set assertions and dispatchables test.set_assertion::(para_to_para_through_hop_sender_assertions); @@ -1188,14 +1148,10 @@ fn reserve_transfer_native_asset_from_para_to_para_through_relay() { test.assert(); // Query final balances - let sender_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location.clone(), &sender) - }); - let receiver_assets_after = PenpalB::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(relay_native_asset_location, &receiver) - }); + let sender_assets_after = + foreign_balance_on!(PenpalA, relay_native_asset_location.clone(), &sender); + let receiver_assets_after = + foreign_balance_on!(PenpalB, relay_native_asset_location, &receiver); // Sender's balance is reduced by amount sent plus delivery fees. assert!(sender_assets_after < sender_assets_before - amount_to_send); @@ -1231,55 +1187,11 @@ fn reserve_transfer_usdt_from_asset_hub_to_para() { )); }); - let relay_asset_penpal_pov = RelayLocation::get(); - let usdt_from_asset_hub = PenpalUsdtFromAssetHub::get(); - // Setup the pool between `relay_asset_penpal_pov` and `usdt_from_asset_hub` on PenpalA. // So we can swap the custom asset that comes from AssetHubWestend for native asset to pay for // fees. - PenpalA::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - - assert_ok!(::ForeignAssets::mint( - ::RuntimeOrigin::signed(PenpalAssetOwner::get()), - usdt_from_asset_hub.clone().into(), - PenpalASender::get().into(), - 10_000_000_000_000, // For it to have more than enough. - )); - - assert_ok!(::AssetConversion::create_pool( - ::RuntimeOrigin::signed(PenpalASender::get()), - Box::new(relay_asset_penpal_pov.clone()), - Box::new(usdt_from_asset_hub.clone()), - )); - - assert_expected_events!( - PenpalA, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, - ] - ); - - assert_ok!(::AssetConversion::add_liquidity( - ::RuntimeOrigin::signed(PenpalASender::get()), - Box::new(relay_asset_penpal_pov), - Box::new(usdt_from_asset_hub.clone()), - // `usdt_from_asset_hub` is worth a third of `relay_asset_penpal_pov` - 1_000_000_000_000, - 3_000_000_000_000, - 0, - 0, - PenpalASender::get().into() - )); - - assert_expected_events!( - PenpalA, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded { .. }) => {}, - ] - ); - }); + create_pool_with_wnd_on!(PenpalA, PenpalUsdtFromAssetHub::get(), true, PenpalAssetOwner::get()); let assets: Assets = vec![( [PalletInstance(ASSETS_PALLET_ID), GeneralIndex(usdt_id.into())], @@ -1310,10 +1222,8 @@ fn reserve_transfer_usdt_from_asset_hub_to_para() { type Balances = ::Balances; Balances::free_balance(&sender) }); - let receiver_initial_balance = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub.clone(), &receiver) - }); + let receiver_initial_balance = + foreign_balance_on!(PenpalA, usdt_from_asset_hub.clone(), &receiver); test.set_assertion::(system_para_to_para_sender_assertions); test.set_assertion::(system_para_to_para_receiver_assertions); @@ -1328,10 +1238,7 @@ fn reserve_transfer_usdt_from_asset_hub_to_para() { type Balances = ::Balances; Balances::free_balance(&sender) }); - let receiver_after_balance = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub, &receiver) - }); + let receiver_after_balance = foreign_balance_on!(PenpalA, usdt_from_asset_hub, &receiver); // TODO(https://github.com/paritytech/polkadot-sdk/issues/5160): When we allow payment with different assets locally, this should be the same, since // they aren't used for fees. @@ -1371,7 +1278,7 @@ fn reserve_transfer_usdt_from_para_to_para_through_asset_hub() { ]); // Give USDT to sov account of sender. - let usdt_id = 1984; + let usdt_id: u32 = 1984; AssetHubWestend::execute_with(|| { use frame_support::traits::tokens::fungibles::Mutate; type Assets = ::Assets; @@ -1383,101 +1290,15 @@ fn reserve_transfer_usdt_from_para_to_para_through_asset_hub() { }); // We create a pool between WND and USDT in AssetHub. - let native_asset: Location = Parent.into(); let usdt = Location::new( 0, [Junction::PalletInstance(ASSETS_PALLET_ID), Junction::GeneralIndex(usdt_id.into())], ); - - // set up pool with USDT <> native pair - AssetHubWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - - assert_ok!(::Assets::mint( - ::RuntimeOrigin::signed(AssetHubWestendSender::get()), - usdt_id.into(), - AssetHubWestendSender::get().into(), - 10_000_000_000_000, // For it to have more than enough. - )); - - assert_ok!(::AssetConversion::create_pool( - ::RuntimeOrigin::signed(AssetHubWestendSender::get()), - Box::new(native_asset.clone()), - Box::new(usdt.clone()), - )); - - assert_expected_events!( - AssetHubWestend, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, - ] - ); - - assert_ok!(::AssetConversion::add_liquidity( - ::RuntimeOrigin::signed(AssetHubWestendSender::get()), - Box::new(native_asset), - Box::new(usdt), - 1_000_000_000_000, - 2_000_000_000_000, // usdt is worth half of `native_asset` - 0, - 0, - AssetHubWestendSender::get().into() - )); - - assert_expected_events!( - AssetHubWestend, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded { .. }) => {}, - ] - ); - }); - - let usdt_from_asset_hub = PenpalUsdtFromAssetHub::get(); - + create_pool_with_wnd_on!(AssetHubWestend, usdt, false, AssetHubWestendSender::get()); // We also need a pool between WND and USDT on PenpalB. - PenpalB::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - let relay_asset = RelayLocation::get(); - - assert_ok!(::ForeignAssets::mint( - ::RuntimeOrigin::signed(PenpalAssetOwner::get()), - usdt_from_asset_hub.clone().into(), - PenpalBReceiver::get().into(), - 10_000_000_000_000, // For it to have more than enough. - )); - - assert_ok!(::AssetConversion::create_pool( - ::RuntimeOrigin::signed(PenpalBReceiver::get()), - Box::new(relay_asset.clone()), - Box::new(usdt_from_asset_hub.clone()), - )); - - assert_expected_events!( - PenpalB, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, - ] - ); - - assert_ok!(::AssetConversion::add_liquidity( - ::RuntimeOrigin::signed(PenpalBReceiver::get()), - Box::new(relay_asset), - Box::new(usdt_from_asset_hub.clone()), - 1_000_000_000_000, - 2_000_000_000_000, // `usdt_from_asset_hub` is worth half of `relay_asset` - 0, - 0, - PenpalBReceiver::get().into() - )); - - assert_expected_events!( - PenpalB, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded { .. }) => {}, - ] - ); - }); + create_pool_with_wnd_on!(PenpalB, PenpalUsdtFromAssetHub::get(), true, PenpalAssetOwner::get()); + let usdt_from_asset_hub = PenpalUsdtFromAssetHub::get(); PenpalA::execute_with(|| { use frame_support::traits::tokens::fungibles::Mutate; type ForeignAssets = ::ForeignAssets; @@ -1523,14 +1344,9 @@ fn reserve_transfer_usdt_from_para_to_para_through_asset_hub() { let mut test = ParaToParaThroughAHTest::new(test_args); // Query initial balances - let sender_assets_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub.clone(), &sender) - }); - let receiver_assets_before = PenpalB::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub.clone(), &receiver) - }); + let sender_assets_before = foreign_balance_on!(PenpalA, usdt_from_asset_hub.clone(), &sender); + let receiver_assets_before = + foreign_balance_on!(PenpalB, usdt_from_asset_hub.clone(), &receiver); test.set_assertion::(para_to_para_through_hop_sender_assertions); test.set_assertion::(para_to_para_asset_hub_hop_assertions); test.set_assertion::(para_to_para_through_hop_receiver_assertions); @@ -1540,14 +1356,8 @@ fn reserve_transfer_usdt_from_para_to_para_through_asset_hub() { test.assert(); // Query final balances - let sender_assets_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub.clone(), &sender) - }); - let receiver_assets_after = PenpalB::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance(usdt_from_asset_hub, &receiver) - }); + let sender_assets_after = foreign_balance_on!(PenpalA, usdt_from_asset_hub.clone(), &sender); + let receiver_assets_after = foreign_balance_on!(PenpalB, usdt_from_asset_hub, &receiver); // Sender's balance is reduced by amount assert!(sender_assets_after < sender_assets_before - asset_amount_to_send); @@ -1603,7 +1413,7 @@ fn reserve_withdraw_from_untrusted_reserve_fails() { ]); let result = ::PolkadotXcm::execute( signed_origin, - bx!(xcm::VersionedXcm::V4(xcm)), + bx!(xcm::VersionedXcm::from(xcm)), Weight::MAX, ); assert!(result.is_err()); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs index 761c7c12255c..d4f239df4877 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs @@ -24,7 +24,7 @@ fn send_transact_as_superuser_from_relay_to_asset_hub_works() { ASSET_MIN_BALANCE, true, AssetHubWestendSender::get().into(), - Some(Weight::from_parts(1_019_445_000, 200_000)), + Some(Weight::from_parts(144_759_000, 3675)), ) } @@ -121,7 +121,7 @@ fn send_xcm_from_para_to_asset_hub_paying_fee_with_sufficient_asset() { ASSET_MIN_BALANCE, true, para_sovereign_account.clone(), - Some(Weight::from_parts(1_019_445_000, 200_000)), + Some(Weight::from_parts(144_759_000, 3675)), ASSET_MIN_BALANCE * 1000000000, ); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_asset_claimer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_asset_claimer.rs new file mode 100644 index 000000000000..544b05360521 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_asset_claimer.rs @@ -0,0 +1,154 @@ +// 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. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::{bhw_xcm_config::LocationToAccountId, *}; +use emulated_integration_tests_common::{ + accounts::{ALICE, BOB}, + impls::AccountId32, +}; +use frame_support::{assert_ok, sp_runtime::traits::Dispatchable}; +use westend_system_emulated_network::{ + asset_hub_westend_emulated_chain::asset_hub_westend_runtime::RuntimeOrigin as AssetHubRuntimeOrigin, + bridge_hub_westend_emulated_chain::bridge_hub_westend_runtime::RuntimeOrigin as BridgeHubRuntimeOrigin, +}; +use xcm_executor::traits::ConvertLocation; + +#[test] +fn test_set_asset_claimer_within_a_chain() { + let (alice_account, _) = account_and_location(ALICE); + let (bob_account, bob_location) = account_and_location(BOB); + + let trap_amount = 16_000_000_000_000; + let assets: Assets = (Parent, trap_amount).into(); + + let alice_balance_before = + ::account_data_of(alice_account.clone()).free; + AssetHubWestend::fund_accounts(vec![(alice_account.clone(), trap_amount * 2)]); + let alice_balance_after = + ::account_data_of(alice_account.clone()).free; + assert_eq!(alice_balance_after - alice_balance_before, trap_amount * 2); + + type RuntimeCall = ::RuntimeCall; + let asset_trap_xcm = Xcm::::builder_unsafe() + .set_asset_claimer(bob_location.clone()) + .withdraw_asset(assets.clone()) + .clear_origin() + .build(); + + AssetHubWestend::execute_with(|| { + assert_ok!(RuntimeCall::PolkadotXcm(pallet_xcm::Call::execute { + message: bx!(VersionedXcm::from(asset_trap_xcm)), + max_weight: Weight::from_parts(4_000_000_000_000, 300_000), + }) + .dispatch(AssetHubRuntimeOrigin::signed(alice_account.clone()))); + }); + + let balance_after_trap = + ::account_data_of(alice_account.clone()).free; + assert_eq!(alice_balance_after - balance_after_trap, trap_amount); + + let bob_balance_before = ::account_data_of(bob_account.clone()).free; + let claim_xcm = Xcm::::builder_unsafe() + .claim_asset(assets.clone(), Here) + .deposit_asset(AllCounted(assets.len() as u32), bob_location.clone()) + .build(); + + AssetHubWestend::execute_with(|| { + assert_ok!(RuntimeCall::PolkadotXcm(pallet_xcm::Call::execute { + message: bx!(VersionedXcm::from(claim_xcm)), + max_weight: Weight::from_parts(4_000_000_000_000, 300_000), + }) + .dispatch(AssetHubRuntimeOrigin::signed(bob_account.clone()))); + }); + + let bob_balance_after = ::account_data_of(bob_account.clone()).free; + assert_eq!(bob_balance_after - bob_balance_before, trap_amount); +} + +fn account_and_location(account: &str) -> (AccountId32, Location) { + let account_id = AssetHubWestend::account_id_of(account); + let account_clone = account_id.clone(); + let location: Location = [Junction::AccountId32 { + network: Some(ByGenesis(WESTEND_GENESIS_HASH)), + id: account_id.into(), + }] + .into(); + (account_clone, location) +} + +// The test: +// 1. Funds Bob account on BridgeHub, withdraws the funds, sets asset claimer to +// sibling-account-of(AssetHub/Alice) and traps the funds. +// 2. Alice on AssetHub sends an XCM to BridgeHub to claim assets, pay fees and deposit +// remaining to her sibling account on BridgeHub. +#[test] +fn test_set_asset_claimer_between_the_chains() { + let alice = AssetHubWestend::account_id_of(ALICE); + let alice_bh_sibling = Location::new( + 1, + [ + Parachain(AssetHubWestend::para_id().into()), + Junction::AccountId32 { + network: Some(ByGenesis(WESTEND_GENESIS_HASH)), + id: alice.clone().into(), + }, + ], + ); + + let bob = BridgeHubWestend::account_id_of(BOB); + let trap_amount = 16_000_000_000_000u128; + BridgeHubWestend::fund_accounts(vec![(bob.clone(), trap_amount * 2)]); + + let assets: Assets = (Parent, trap_amount).into(); + type RuntimeCall = ::RuntimeCall; + let trap_xcm = Xcm::::builder_unsafe() + .set_asset_claimer(alice_bh_sibling.clone()) + .withdraw_asset(assets.clone()) + .clear_origin() + .build(); + + BridgeHubWestend::execute_with(|| { + assert_ok!(RuntimeCall::PolkadotXcm(pallet_xcm::Call::execute { + message: bx!(VersionedXcm::from(trap_xcm)), + max_weight: Weight::from_parts(4_000_000_000_000, 700_000), + }) + .dispatch(BridgeHubRuntimeOrigin::signed(bob.clone()))); + }); + + let alice_bh_acc = LocationToAccountId::convert_location(&alice_bh_sibling).unwrap(); + let balance = ::account_data_of(alice_bh_acc.clone()).free; + assert_eq!(balance, 0); + + let pay_fees = 6_000_000_000_000u128; + let xcm_on_bh = Xcm::<()>::builder_unsafe() + .claim_asset(assets.clone(), Here) + .pay_fees((Parent, pay_fees)) + .deposit_asset(All, alice_bh_sibling.clone()) + .build(); + let bh_on_ah = AssetHubWestend::sibling_location_of(BridgeHubWestend::para_id()).into(); + AssetHubWestend::execute_with(|| { + assert_ok!(::PolkadotXcm::send( + AssetHubRuntimeOrigin::signed(alice.clone()), + bx!(bh_on_ah), + bx!(VersionedXcm::from(xcm_on_bh)), + )); + }); + + let alice_bh_acc = LocationToAccountId::convert_location(&alice_bh_sibling).unwrap(); + let balance = ::account_data_of(alice_bh_acc).free; + assert_eq!(balance, trap_amount - pay_fees); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs index 474e9a86ccc2..4405ed2988a9 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/set_xcm_versions.rs @@ -67,10 +67,7 @@ fn system_para_sets_relay_xcm_supported_version() { AssetHubWestend::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; - AssetHubWestend::assert_dmp_queue_complete(Some(Weight::from_parts( - 1_019_210_000, - 200_000, - ))); + AssetHubWestend::assert_dmp_queue_complete(Some(Weight::from_parts(115_688_000, 0))); assert_expected_events!( AssetHubWestend, diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs index ee0f297792f8..0897c187e7cb 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::imports::*; +use crate::{foreign_balance_on, imports::*}; fn relay_dest_assertions_fail(_t: SystemParaToRelayTest) { Westend::assert_ump_queue_processed( @@ -112,16 +112,6 @@ fn ah_to_penpal_foreign_assets_sender_assertions(t: SystemParaToParaTest) { assert_expected_events!( AssetHubWestend, vec![ - // native asset used for fees is transferred to Parachain's Sovereign account as reserve - RuntimeEvent::Balances( - pallet_balances::Event::Transfer { from, to, amount } - ) => { - from: *from == t.sender.account_id, - to: *to == AssetHubWestend::sovereign_account_id_of( - t.args.dest.clone() - ), - amount: *amount == t.args.amount, - }, // foreign asset is burned locally as part of teleportation RuntimeEvent::ForeignAssets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { asset_id: *asset_id == expected_foreign_asset_id, @@ -283,13 +273,13 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using ah_to_para_dispatchable: fn(SystemParaToParaTest) -> DispatchResult, ) { // Init values for Parachain - let fee_amount_to_send: Balance = ASSET_HUB_WESTEND_ED * 100; + let fee_amount_to_send: Balance = ASSET_HUB_WESTEND_ED * 1000; let asset_location_on_penpal = PenpalLocalTeleportableToAssetHub::get(); let asset_id_on_penpal = match asset_location_on_penpal.last() { Some(Junction::GeneralIndex(id)) => *id as u32, _ => unreachable!(), }; - let asset_amount_to_send = ASSET_HUB_WESTEND_ED * 100; + let asset_amount_to_send = ASSET_HUB_WESTEND_ED * 1000; let asset_owner = PenpalAssetOwner::get(); let system_para_native_asset_location = RelayLocation::get(); let sender = PenpalASender::get(); @@ -318,7 +308,7 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using ::RuntimeOrigin::signed(asset_owner.clone()), asset_id_on_penpal, sender.clone(), - asset_amount_to_send, + asset_amount_to_send * 2, ); // fund Parachain's check account to be able to teleport PenpalA::fund_accounts(vec![( @@ -335,7 +325,7 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using )]); // Init values for System Parachain - let foreign_asset_at_asset_hub_westend = + let foreign_asset_at_asset_hub = Location::new(1, [Junction::Parachain(PenpalA::para_id().into())]) .appended_with(asset_location_on_penpal) .unwrap(); @@ -355,13 +345,11 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using ), }; let mut penpal_to_ah = ParaToSystemParaTest::new(penpal_to_ah_test_args); - let penpal_sender_balance_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - system_para_native_asset_location.clone(), - &PenpalASender::get(), - ) - }); + let penpal_sender_balance_before = foreign_balance_on!( + PenpalA, + system_para_native_asset_location.clone(), + &PenpalASender::get() + ); let ah_receiver_balance_before = penpal_to_ah.receiver.balance; @@ -369,26 +357,22 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using type Assets = ::Assets; >::balance(asset_id_on_penpal, &PenpalASender::get()) }); - let ah_receiver_assets_before = AssetHubWestend::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend.clone().try_into().unwrap(), - &AssetHubWestendReceiver::get(), - ) - }); + let ah_receiver_assets_before = foreign_balance_on!( + AssetHubWestend, + foreign_asset_at_asset_hub.clone(), + &AssetHubWestendReceiver::get() + ); penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_sender_assertions); penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_receiver_assertions); penpal_to_ah.set_dispatchable::(para_to_ah_dispatchable); penpal_to_ah.assert(); - let penpal_sender_balance_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - system_para_native_asset_location.clone(), - &PenpalASender::get(), - ) - }); + let penpal_sender_balance_after = foreign_balance_on!( + PenpalA, + system_para_native_asset_location.clone(), + &PenpalASender::get() + ); let ah_receiver_balance_after = penpal_to_ah.receiver.balance; @@ -396,13 +380,11 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using type Assets = ::Assets; >::balance(asset_id_on_penpal, &PenpalASender::get()) }); - let ah_receiver_assets_after = AssetHubWestend::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend.clone().try_into().unwrap(), - &AssetHubWestendReceiver::get(), - ) - }); + let ah_receiver_assets_after = foreign_balance_on!( + AssetHubWestend, + foreign_asset_at_asset_hub.clone(), + &AssetHubWestendReceiver::get() + ); // Sender's balance is reduced assert!(penpal_sender_balance_after < penpal_sender_balance_before); @@ -427,17 +409,21 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using type ForeignAssets = ::ForeignAssets; assert_ok!(ForeignAssets::transfer( ::RuntimeOrigin::signed(AssetHubWestendReceiver::get()), - foreign_asset_at_asset_hub_westend.clone().try_into().unwrap(), + foreign_asset_at_asset_hub.clone().try_into().unwrap(), AssetHubWestendSender::get().into(), asset_amount_to_send, )); }); + // Only send back half the amount. + let asset_amount_to_send = asset_amount_to_send / 2; + let fee_amount_to_send = fee_amount_to_send / 2; + let ah_to_penpal_beneficiary_id = PenpalAReceiver::get(); let penpal_as_seen_by_ah = AssetHubWestend::sibling_location_of(PenpalA::para_id()); let ah_assets: Assets = vec![ (Parent, fee_amount_to_send).into(), - (foreign_asset_at_asset_hub_westend.clone(), asset_amount_to_send).into(), + (foreign_asset_at_asset_hub.clone(), asset_amount_to_send).into(), ] .into(); let fee_asset_index = ah_assets @@ -462,21 +448,17 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using let mut ah_to_penpal = SystemParaToParaTest::new(ah_to_penpal_test_args); let ah_sender_balance_before = ah_to_penpal.sender.balance; - let penpal_receiver_balance_before = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - system_para_native_asset_location.clone(), - &PenpalAReceiver::get(), - ) - }); + let penpal_receiver_balance_before = foreign_balance_on!( + PenpalA, + system_para_native_asset_location.clone(), + &PenpalAReceiver::get() + ); - let ah_sender_assets_before = AssetHubWestend::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend.clone().try_into().unwrap(), - &AssetHubWestendSender::get(), - ) - }); + let ah_sender_assets_before = foreign_balance_on!( + AssetHubWestend, + foreign_asset_at_asset_hub.clone(), + &AssetHubWestendSender::get() + ); let penpal_receiver_assets_before = PenpalA::execute_with(|| { type Assets = ::Assets; >::balance(asset_id_on_penpal, &PenpalAReceiver::get()) @@ -488,21 +470,14 @@ pub fn do_bidirectional_teleport_foreign_assets_between_para_and_asset_hub_using ah_to_penpal.assert(); let ah_sender_balance_after = ah_to_penpal.sender.balance; - let penpal_receiver_balance_after = PenpalA::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - system_para_native_asset_location, - &PenpalAReceiver::get(), - ) - }); + let penpal_receiver_balance_after = + foreign_balance_on!(PenpalA, system_para_native_asset_location, &PenpalAReceiver::get()); - let ah_sender_assets_after = AssetHubWestend::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend.clone().try_into().unwrap(), - &AssetHubWestendSender::get(), - ) - }); + let ah_sender_assets_after = foreign_balance_on!( + AssetHubWestend, + foreign_asset_at_asset_hub.clone(), + &AssetHubWestendSender::get() + ); let penpal_receiver_assets_after = PenpalA::execute_with(|| { type Assets = ::Assets; >::balance(asset_id_on_penpal, &PenpalAReceiver::get()) @@ -577,7 +552,7 @@ fn teleport_to_untrusted_chain_fails() { ]); let result = ::PolkadotXcm::execute( signed_origin, - bx!(xcm::VersionedXcm::V4(xcm)), + bx!(xcm::VersionedXcm::from(xcm)), Weight::MAX, ); assert!(result.is_err()); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/transact.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/transact.rs new file mode 100644 index 000000000000..3c53cfb261be --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/transact.rs @@ -0,0 +1,246 @@ +// 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::{create_pool_with_wnd_on, foreign_balance_on, imports::*}; +use frame_support::traits::tokens::fungibles::Mutate; +use xcm_builder::{DescribeAllTerminal, DescribeFamily, HashedDescription}; +use xcm_executor::traits::ConvertLocation; + +/// PenpalA transacts on PenpalB, paying fees using USDT. XCM has to go through Asset Hub as the +/// reserve location of USDT. The original origin `PenpalA/PenpalASender` is proxied by Asset Hub. +fn transfer_and_transact_in_same_xcm( + destination: Location, + usdt: Asset, + beneficiary: Location, + call: xcm::DoubleEncoded<()>, +) { + let signed_origin = ::RuntimeOrigin::signed(PenpalASender::get().into()); + let context = PenpalUniversalLocation::get(); + let asset_hub_location = PenpalA::sibling_location_of(AssetHubWestend::para_id()); + + let Fungible(total_usdt) = usdt.fun else { unreachable!() }; + + // TODO(https://github.com/paritytech/polkadot-sdk/issues/6197): dry-run to get local fees, for now use hardcoded value. + let local_fees_amount = 80_000_000_000; // current exact value 69_200_786_622 + let ah_fees_amount = 90_000_000_000; // current exact value 79_948_099_299 + let usdt_to_ah_then_onward_amount = total_usdt - local_fees_amount - ah_fees_amount; + + let local_fees: Asset = (usdt.id.clone(), local_fees_amount).into(); + let fees_for_ah: Asset = (usdt.id.clone(), ah_fees_amount).into(); + let usdt_to_ah_then_onward: Asset = (usdt.id.clone(), usdt_to_ah_then_onward_amount).into(); + + // xcm to be executed at dest + let xcm_on_dest = Xcm(vec![ + Transact { origin_kind: OriginKind::Xcm, call }, + ExpectTransactStatus(MaybeErrorCode::Success), + // since this is the last hop, we don't need to further use any assets previously + // reserved for fees (there are no further hops to cover transport fees for); we + // RefundSurplus to get back any unspent fees + RefundSurplus, + DepositAsset { assets: Wild(All), beneficiary }, + ]); + let destination = destination.reanchored(&asset_hub_location, &context).unwrap(); + let xcm_on_ah = Xcm(vec![InitiateTransfer { + destination, + remote_fees: Some(AssetTransferFilter::ReserveDeposit(Wild(All))), + preserve_origin: true, + assets: vec![], + remote_xcm: xcm_on_dest, + }]); + let xcm = Xcm::<()>(vec![ + WithdrawAsset(usdt.into()), + PayFees { asset: local_fees }, + InitiateTransfer { + destination: asset_hub_location, + remote_fees: Some(AssetTransferFilter::ReserveWithdraw(fees_for_ah.into())), + preserve_origin: true, + assets: vec![AssetTransferFilter::ReserveWithdraw(usdt_to_ah_then_onward.into())], + remote_xcm: xcm_on_ah, + }, + ]); + ::PolkadotXcm::execute( + signed_origin, + bx!(xcm::VersionedXcm::from(xcm.into())), + Weight::MAX, + ) + .unwrap(); +} + +/// PenpalA transacts on PenpalB, paying fees using USDT. XCM has to go through Asset Hub as the +/// reserve location of USDT. The original origin `PenpalA/PenpalASender` is proxied by Asset Hub. +#[test] +fn transact_from_para_to_para_through_asset_hub() { + let destination = PenpalA::sibling_location_of(PenpalB::para_id()); + let sender = PenpalASender::get(); + let fee_amount_to_send: Balance = WESTEND_ED * 10000; + let sender_chain_as_seen_by_asset_hub = + AssetHubWestend::sibling_location_of(PenpalA::para_id()); + let sov_of_sender_on_asset_hub = + AssetHubWestend::sovereign_account_id_of(sender_chain_as_seen_by_asset_hub); + let receiver_as_seen_by_asset_hub = AssetHubWestend::sibling_location_of(PenpalB::para_id()); + let sov_of_receiver_on_asset_hub = + AssetHubWestend::sovereign_account_id_of(receiver_as_seen_by_asset_hub); + + // Create SA-of-Penpal-on-AHW with ED. + AssetHubWestend::fund_accounts(vec![ + (sov_of_sender_on_asset_hub.clone().into(), ASSET_HUB_WESTEND_ED), + (sov_of_receiver_on_asset_hub.clone().into(), ASSET_HUB_WESTEND_ED), + ]); + + // Prefund USDT to sov account of sender. + AssetHubWestend::execute_with(|| { + type Assets = ::Assets; + assert_ok!(>::mint_into( + USDT_ID, + &sov_of_sender_on_asset_hub.clone().into(), + fee_amount_to_send, + )); + }); + + // We create a pool between WND and USDT in AssetHub. + let usdt = Location::new(0, [PalletInstance(ASSETS_PALLET_ID), GeneralIndex(USDT_ID.into())]); + create_pool_with_wnd_on!(AssetHubWestend, usdt, false, AssetHubWestendSender::get()); + // We also need a pool between WND and USDT on PenpalA. + create_pool_with_wnd_on!(PenpalA, PenpalUsdtFromAssetHub::get(), true, PenpalAssetOwner::get()); + // We also need a pool between WND and USDT on PenpalB. + create_pool_with_wnd_on!(PenpalB, PenpalUsdtFromAssetHub::get(), true, PenpalAssetOwner::get()); + + let usdt_from_asset_hub = PenpalUsdtFromAssetHub::get(); + PenpalA::execute_with(|| { + type ForeignAssets = ::ForeignAssets; + assert_ok!(>::mint_into( + usdt_from_asset_hub.clone(), + &sender, + fee_amount_to_send, + )); + }); + + // Give the sender enough Relay tokens to pay for local delivery fees. + PenpalA::mint_foreign_asset( + ::RuntimeOrigin::signed(PenpalAssetOwner::get()), + RelayLocation::get(), + sender.clone(), + 10_000_000_000_000, // Large estimate to make sure it works. + ); + + // Init values for Parachain Destination + let receiver = PenpalBReceiver::get(); + + // Query initial balances + let sender_assets_before = foreign_balance_on!(PenpalA, usdt_from_asset_hub.clone(), &sender); + let receiver_assets_before = + foreign_balance_on!(PenpalB, usdt_from_asset_hub.clone(), &receiver); + + // Now register a new asset on PenpalB from PenpalA/sender account while paying fees using USDT + // (going through Asset Hub) + + let usdt_to_send: Asset = (usdt_from_asset_hub.clone(), fee_amount_to_send).into(); + let assets: Assets = usdt_to_send.clone().into(); + let asset_location_on_penpal_a = + Location::new(0, [PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())]); + let penpal_a_as_seen_by_penpal_b = PenpalB::sibling_location_of(PenpalA::para_id()); + let sender_as_seen_by_penpal_b = + penpal_a_as_seen_by_penpal_b.clone().appended_with(sender.clone()).unwrap(); + let foreign_asset_at_penpal_b = + penpal_a_as_seen_by_penpal_b.appended_with(asset_location_on_penpal_a).unwrap(); + // Encoded `create_asset` call to be executed in PenpalB + let call = PenpalB::create_foreign_asset_call( + foreign_asset_at_penpal_b.clone(), + ASSET_MIN_BALANCE, + receiver.clone(), + ); + PenpalA::execute_with(|| { + // initiate transaction + transfer_and_transact_in_same_xcm(destination, usdt_to_send, receiver.clone().into(), call); + + // verify expected events; + PenpalA::assert_xcm_pallet_attempted_complete(None); + }); + AssetHubWestend::execute_with(|| { + let sov_penpal_a_on_ah = AssetHubWestend::sovereign_account_id_of( + AssetHubWestend::sibling_location_of(PenpalA::para_id()), + ); + let sov_penpal_b_on_ah = AssetHubWestend::sovereign_account_id_of( + AssetHubWestend::sibling_location_of(PenpalB::para_id()), + ); + asset_hub_hop_assertions(&assets, sov_penpal_a_on_ah, sov_penpal_b_on_ah); + }); + PenpalB::execute_with(|| { + let expected_creator = + HashedDescription::>::convert_location( + &sender_as_seen_by_penpal_b, + ) + .unwrap(); + penpal_b_assertions(foreign_asset_at_penpal_b, expected_creator, receiver.clone()); + }); + + // Query final balances + let sender_assets_after = foreign_balance_on!(PenpalA, usdt_from_asset_hub.clone(), &sender); + let receiver_assets_after = foreign_balance_on!(PenpalB, usdt_from_asset_hub, &receiver); + + // Sender's balance is reduced by amount + assert_eq!(sender_assets_after, sender_assets_before - fee_amount_to_send); + // Receiver's balance is increased + assert!(receiver_assets_after > receiver_assets_before); +} + +fn asset_hub_hop_assertions(assets: &Assets, sender_sa: AccountId, receiver_sa: AccountId) { + type RuntimeEvent = ::RuntimeEvent; + for asset in assets.inner() { + let amount = if let Fungible(a) = asset.fun { a } else { unreachable!() }; + assert_expected_events!( + AssetHubWestend, + vec![ + // Withdrawn from sender parachain SA + RuntimeEvent::Assets( + pallet_assets::Event::Burned { owner, balance, .. } + ) => { + owner: *owner == sender_sa, + balance: *balance == amount, + }, + // Deposited to receiver parachain SA + RuntimeEvent::Assets( + pallet_assets::Event::Deposited { who, .. } + ) => { + who: *who == receiver_sa, + }, + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + } +} + +fn penpal_b_assertions( + expected_asset: Location, + expected_creator: AccountId, + expected_owner: AccountId, +) { + type RuntimeEvent = ::RuntimeEvent; + PenpalB::assert_xcmp_queue_success(None); + assert_expected_events!( + PenpalB, + vec![ + RuntimeEvent::ForeignAssets( + pallet_assets::Event::Created { asset_id, creator, owner } + ) => { + asset_id: *asset_id == expected_asset, + creator: *creator == expected_creator, + owner: *owner == expected_owner, + }, + ] + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs index b70967184387..c303e6411d33 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/treasury.rs @@ -32,11 +32,10 @@ fn create_and_claim_treasury_spend() { ahw_xcm_config::LocationToAccountId::convert_location(&treasury_location).unwrap(); let asset_hub_location = Location::new(0, Parachain(AssetHubWestend::para_id().into())); let root = ::RuntimeOrigin::root(); - // asset kind to be spend from the treasury. - let asset_kind = VersionedLocatableAsset::V4 { - location: asset_hub_location, - asset_id: AssetId([PalletInstance(50), GeneralIndex(USDT_ID.into())].into()), - }; + // asset kind to be spent from the treasury. + let asset_kind: VersionedLocatableAsset = + (asset_hub_location, AssetId([PalletInstance(50), GeneralIndex(USDT_ID.into())].into())) + .into(); // treasury spend beneficiary. let alice: AccountId = Westend::account_id_of(ALICE); let bob: AccountId = Westend::account_id_of(BOB); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs index 037d6604ea4d..ec05a074c5ac 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs @@ -17,10 +17,8 @@ use crate::imports::*; -use frame_support::{ - dispatch::RawOrigin, - sp_runtime::{traits::Dispatchable, DispatchResult}, -}; +use emulated_integration_tests_common::test_can_estimate_and_pay_exact_fees; +use frame_support::dispatch::RawOrigin; use xcm_runtime_apis::{ dry_run::runtime_decl_for_dry_run_api::DryRunApiV1, fees::runtime_decl_for_xcm_payment_api::XcmPaymentApiV1, @@ -77,22 +75,12 @@ fn receiver_assertions(test: ParaToParaThroughAHTest) { ); } -fn transfer_assets_para_to_para_through_ah_dispatchable( - test: ParaToParaThroughAHTest, -) -> DispatchResult { - let call = transfer_assets_para_to_para_through_ah_call(test.clone()); - match call.dispatch(test.signed_origin) { - Ok(_) => Ok(()), - Err(error_with_post_info) => Err(error_with_post_info.error), - } -} - fn transfer_assets_para_to_para_through_ah_call( test: ParaToParaThroughAHTest, ) -> ::RuntimeCall { type RuntimeCall = ::RuntimeCall; - let asset_hub_location: Location = PenpalB::sibling_location_of(AssetHubWestend::para_id()); + let asset_hub_location: Location = PenpalA::sibling_location_of(AssetHubWestend::para_id()); let custom_xcm_on_dest = Xcm::<()>(vec![DepositAsset { assets: Wild(AllCounted(test.args.assets.len() as u32)), beneficiary: test.args.beneficiary, @@ -101,7 +89,7 @@ fn transfer_assets_para_to_para_through_ah_call( dest: bx!(test.args.dest.into()), assets: bx!(test.args.assets.clone().into()), assets_transfer_type: bx!(TransferType::RemoteReserve(asset_hub_location.clone().into())), - remote_fees_id: bx!(VersionedAssetId::V4(AssetId(Location::new(1, [])))), + remote_fees_id: bx!(VersionedAssetId::from(AssetId(Location::parent()))), fees_transfer_type: bx!(TransferType::RemoteReserve(asset_hub_location.into())), custom_xcm_on_dest: bx!(VersionedXcm::from(custom_xcm_on_dest)), weight_limit: test.args.weight_limit, @@ -153,7 +141,7 @@ fn multi_hop_works() { // We get them from the PenpalA closure. let mut delivery_fees_amount = 0; - let mut remote_message = VersionedXcm::V4(Xcm(Vec::new())); + let mut remote_message = VersionedXcm::from(Xcm(Vec::new())); ::execute_with(|| { type Runtime = ::Runtime; type OriginCaller = ::OriginCaller; @@ -166,7 +154,7 @@ fn multi_hop_works() { .forwarded_xcms .iter() .find(|(destination, _)| { - *destination == VersionedLocation::V4(Location::new(1, [Parachain(1000)])) + *destination == VersionedLocation::from(Location::new(1, [Parachain(1000)])) }) .unwrap(); assert_eq!(messages_to_query.len(), 1); @@ -180,7 +168,7 @@ fn multi_hop_works() { // These are set in the AssetHub closure. let mut intermediate_execution_fees = 0; let mut intermediate_delivery_fees_amount = 0; - let mut intermediate_remote_message = VersionedXcm::V4(Xcm::<()>(Vec::new())); + let mut intermediate_remote_message = VersionedXcm::from(Xcm::<()>(Vec::new())); ::execute_with(|| { type Runtime = ::Runtime; type RuntimeCall = ::RuntimeCall; @@ -189,13 +177,14 @@ fn multi_hop_works() { let weight = Runtime::query_xcm_weight(remote_message.clone()).unwrap(); intermediate_execution_fees = Runtime::query_weight_to_asset_fee( weight, - VersionedAssetId::V4(Location::new(1, []).into()), + VersionedAssetId::from(AssetId(Location::new(1, []))), ) .unwrap(); // We have to do this to turn `VersionedXcm<()>` into `VersionedXcm`. - let xcm_program = - VersionedXcm::V4(Xcm::::from(remote_message.clone().try_into().unwrap())); + let xcm_program = VersionedXcm::from(Xcm::::from( + remote_message.clone().try_into().unwrap(), + )); // Now we get the delivery fees to the final destination. let result = @@ -204,7 +193,7 @@ fn multi_hop_works() { .forwarded_xcms .iter() .find(|(destination, _)| { - *destination == VersionedLocation::V4(Location::new(1, [Parachain(2001)])) + *destination == VersionedLocation::from(Location::new(1, [Parachain(2001)])) }) .unwrap(); // There's actually two messages here. @@ -228,7 +217,7 @@ fn multi_hop_works() { let weight = Runtime::query_xcm_weight(intermediate_remote_message.clone()).unwrap(); final_execution_fees = - Runtime::query_weight_to_asset_fee(weight, VersionedAssetId::V4(Parent.into())) + Runtime::query_weight_to_asset_fee(weight, VersionedAssetId::from(Location::parent())) .unwrap(); }); @@ -259,7 +248,8 @@ fn multi_hop_works() { test.set_assertion::(sender_assertions); test.set_assertion::(hop_assertions); test.set_assertion::(receiver_assertions); - test.set_dispatchable::(transfer_assets_para_to_para_through_ah_dispatchable); + let call = transfer_assets_para_to_para_through_ah_call(test.clone()); + test.set_call(call); test.assert(); let sender_assets_after = PenpalA::execute_with(|| { @@ -286,3 +276,14 @@ fn multi_hop_works() { final_execution_fees ); } + +#[test] +fn multi_hop_pay_fees_works() { + test_can_estimate_and_pay_exact_fees!( + PenpalA, + AssetHubWestend, + PenpalB, + (Parent, 1_000_000_000_000u128), + Penpal + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs index 77e4c8183e65..54bc395c86f0 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs @@ -22,9 +22,8 @@ mod imports { // Polkadot pub use xcm::{ - latest::ParentThen, + latest::{ParentThen, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}, prelude::{AccountId32 as AccountId32Junction, *}, - v4::{self, NetworkId::Westend as WestendId}, }; pub use xcm_executor::traits::TransferType; diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs index 0e1cfdd82aaf..33ab1e70b97b 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs @@ -39,7 +39,7 @@ fn send_assets_over_bridge(send_fn: F) { fn set_up_rocs_for_penpal_rococo_through_ahr_to_ahw( sender: &AccountId, amount: u128, -) -> (Location, v4::Location) { +) -> (Location, v5::Location) { let roc_at_rococo_parachains = roc_at_ah_rococo(); let roc_at_asset_hub_westend = bridged_roc_at_ah_westend(); create_foreign_on_ah_westend(roc_at_asset_hub_westend.clone(), true); @@ -70,7 +70,7 @@ fn send_assets_from_penpal_rococo_through_rococo_ah_to_westend_ah( ); let sov_ahw_on_ahr = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); // send message over bridge @@ -125,7 +125,7 @@ fn send_roc_from_asset_hub_rococo_to_asset_hub_westend() { set_up_pool_with_wnd_on_ah_westend(bridged_roc_at_asset_hub_westend.clone(), true); let sov_ahw_on_ahr = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); let rocs_in_reserve_on_ahr_before = @@ -199,7 +199,7 @@ fn send_back_wnds_usdt_and_weth_from_asset_hub_rococo_to_asset_hub_westend() { // fund the AHR's SA on AHW with the WND tokens held in reserve let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); AssetHubWestend::fund_accounts(vec![(sov_ahr_on_ahw.clone(), prefund_amount)]); @@ -271,7 +271,7 @@ fn send_back_wnds_usdt_and_weth_from_asset_hub_rococo_to_asset_hub_westend() { create_foreign_on_ah_westend(bridged_weth_at_ah.clone(), true); // prefund AHR's sovereign account on AHW to be able to withdraw USDT and wETH from reserves let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); AssetHubWestend::mint_asset( @@ -357,7 +357,7 @@ fn send_rocs_from_penpal_rococo_through_asset_hub_rococo_to_asset_hub_westend() set_up_rocs_for_penpal_rococo_through_ahr_to_ahw(&sender, amount); let sov_ahw_on_ahr = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); let rocs_in_reserve_on_ahr_before = @@ -463,7 +463,7 @@ fn send_back_wnds_from_penpal_rococo_through_asset_hub_rococo_to_asset_hub_weste // fund the AHR's SA on AHW with the WND tokens held in reserve let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - NetworkId::Rococo, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); AssetHubWestend::fund_accounts(vec![(sov_ahr_on_ahw.clone(), amount * 2)]); diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs index e61dc35bdf8a..e678cc40a3cb 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = BridgeHubRococoExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(AssetHubRococo, RuntimeCall, NetworkId::Rococo, assets, amount); + test_chain_can_claim_assets!( + AssetHubRococo, + RuntimeCall, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs index 767f74f6ad7f..8aff87755961 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs @@ -14,6 +14,7 @@ // limitations under the License. use crate::imports::*; +use xcm::opaque::v5; mod asset_transfers; mod claim_assets; @@ -23,10 +24,22 @@ mod snowbridge; mod teleport; pub(crate) fn asset_hub_westend_location() -> Location { - Location::new(2, [GlobalConsensus(Westend), Parachain(AssetHubWestend::para_id().into())]) + Location::new( + 2, + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(AssetHubWestend::para_id().into()), + ], + ) } pub(crate) fn bridge_hub_westend_location() -> Location { - Location::new(2, [GlobalConsensus(Westend), Parachain(BridgeHubWestend::para_id().into())]) + Location::new( + 2, + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(BridgeHubWestend::para_id().into()), + ], + ) } // ROC and wROC @@ -34,7 +47,7 @@ pub(crate) fn roc_at_ah_rococo() -> Location { Parent.into() } pub(crate) fn bridged_roc_at_ah_westend() -> Location { - Location::new(2, [GlobalConsensus(Rococo)]) + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) } // WND and wWND @@ -42,7 +55,7 @@ pub(crate) fn wnd_at_ah_westend() -> Location { Parent.into() } pub(crate) fn bridged_wnd_at_ah_rococo() -> Location { - Location::new(2, [GlobalConsensus(Westend)]) + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]) } // USDT and wUSDT @@ -53,7 +66,7 @@ pub(crate) fn bridged_usdt_at_ah_rococo() -> Location { Location::new( 2, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(AssetHubWestend::para_id().into()), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(USDT_ID.into()), @@ -73,7 +86,7 @@ pub(crate) fn weth_at_asset_hubs() -> Location { } pub(crate) fn create_foreign_on_ah_rococo( - id: v4::Location, + id: v5::Location, sufficient: bool, prefund_accounts: Vec<(AccountId, u128)>, ) { @@ -82,18 +95,18 @@ pub(crate) fn create_foreign_on_ah_rococo( AssetHubRococo::force_create_foreign_asset(id, owner, sufficient, min, prefund_accounts); } -pub(crate) fn create_foreign_on_ah_westend(id: v4::Location, sufficient: bool) { +pub(crate) fn create_foreign_on_ah_westend(id: v5::Location, sufficient: bool) { let owner = AssetHubWestend::account_id_of(ALICE); AssetHubWestend::force_create_foreign_asset(id, owner, sufficient, ASSET_MIN_BALANCE, vec![]); } -pub(crate) fn foreign_balance_on_ah_rococo(id: v4::Location, who: &AccountId) -> u128 { +pub(crate) fn foreign_balance_on_ah_rococo(id: v5::Location, who: &AccountId) -> u128 { AssetHubRococo::execute_with(|| { type Assets = ::ForeignAssets; >::balance(id, who) }) } -pub(crate) fn foreign_balance_on_ah_westend(id: v4::Location, who: &AccountId) -> u128 { +pub(crate) fn foreign_balance_on_ah_westend(id: v5::Location, who: &AccountId) -> u128 { AssetHubWestend::execute_with(|| { type Assets = ::ForeignAssets; >::balance(id, who) @@ -101,8 +114,8 @@ pub(crate) fn foreign_balance_on_ah_westend(id: v4::Location, who: &AccountId) - } // set up pool -pub(crate) fn set_up_pool_with_wnd_on_ah_westend(asset: v4::Location, is_foreign: bool) { - let wnd: v4::Location = v4::Parent.into(); +pub(crate) fn set_up_pool_with_wnd_on_ah_westend(asset: v5::Location, is_foreign: bool) { + let wnd: v5::Location = v5::Parent.into(); AssetHubWestend::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; let owner = AssetHubWestendSender::get(); @@ -117,7 +130,7 @@ pub(crate) fn set_up_pool_with_wnd_on_ah_westend(asset: v4::Location, is_foreign )); } else { let asset_id = match asset.interior.last() { - Some(v4::Junction::GeneralIndex(id)) => *id as u32, + Some(GeneralIndex(id)) => *id as u32, _ => unreachable!(), }; assert_ok!(::Assets::mint( @@ -237,7 +250,11 @@ pub(crate) fn open_bridge_between_asset_hub_rococo_and_asset_hub_westend() { BridgeHubRococo::fund_para_sovereign(AssetHubRococo::para_id(), ROC * 5); AssetHubRococo::open_bridge( AssetHubRococo::sibling_location_of(BridgeHubRococo::para_id()), - [GlobalConsensus(Westend), Parachain(AssetHubWestend::para_id().into())].into(), + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(AssetHubWestend::para_id().into()), + ] + .into(), Some(( (roc_at_ah_rococo(), ROC * 1).into(), BridgeHubRococo::sovereign_account_id_of(BridgeHubRococo::sibling_location_of( @@ -250,7 +267,11 @@ pub(crate) fn open_bridge_between_asset_hub_rococo_and_asset_hub_westend() { BridgeHubWestend::fund_para_sovereign(AssetHubWestend::para_id(), WND * 5); AssetHubWestend::open_bridge( AssetHubWestend::sibling_location_of(BridgeHubWestend::para_id()), - [GlobalConsensus(Rococo), Parachain(AssetHubRococo::para_id().into())].into(), + [ + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), + Parachain(AssetHubRococo::para_id().into()), + ] + .into(), Some(( (wnd_at_ah_westend(), WND * 1).into(), BridgeHubWestend::sovereign_account_id_of(BridgeHubWestend::sibling_location_of( diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/register_bridged_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/register_bridged_assets.rs index 44637670112b..1ae3a1b15805 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/register_bridged_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/register_bridged_assets.rs @@ -22,7 +22,7 @@ const XCM_FEE: u128 = 4_000_000_000_000; fn register_rococo_asset_on_wah_from_rah() { let sa_of_rah_on_wah = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); @@ -30,7 +30,7 @@ fn register_rococo_asset_on_wah_from_rah() { let bridged_asset_at_wah = Location::new( 2, [ - GlobalConsensus(Rococo), + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(AssetHubRococo::para_id().into()), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into()), diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs index 12f05742a080..931a3128f826 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs @@ -29,7 +29,7 @@ fn send_xcm_from_rococo_relay_to_westend_asset_hub_should_fail_on_not_applicable let xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit, check_origin }, ExportMessage { - network: WestendId, + network: ByGenesis(WESTEND_GENESIS_HASH), destination: [Parachain(AssetHubWestend::para_id().into())].into(), xcm: remote_xcm, }, @@ -60,15 +60,6 @@ fn send_xcm_from_rococo_relay_to_westend_asset_hub_should_fail_on_not_applicable #[test] fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { - // Initially set only default version on all runtimes - let newer_xcm_version = xcm::prelude::XCM_VERSION; - let older_xcm_version = newer_xcm_version - 1; - - AssetHubRococo::force_default_xcm_version(Some(older_xcm_version)); - BridgeHubRococo::force_default_xcm_version(Some(older_xcm_version)); - BridgeHubWestend::force_default_xcm_version(Some(older_xcm_version)); - AssetHubWestend::force_default_xcm_version(Some(older_xcm_version)); - // prepare data let destination = asset_hub_westend_location(); let native_token = Location::parent(); @@ -82,6 +73,14 @@ fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { // open bridge open_bridge_between_asset_hub_rococo_and_asset_hub_westend(); + // Initially set only default version on all runtimes + let newer_xcm_version = xcm::prelude::XCM_VERSION; + let older_xcm_version = newer_xcm_version - 1; + AssetHubRococo::force_default_xcm_version(Some(older_xcm_version)); + BridgeHubRococo::force_default_xcm_version(Some(older_xcm_version)); + BridgeHubWestend::force_default_xcm_version(Some(older_xcm_version)); + AssetHubWestend::force_default_xcm_version(Some(older_xcm_version)); + // send XCM from AssetHubRococo - fails - destination version not known assert_err!( send_assets_from_asset_hub_rococo( diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs index 912e74af6981..d59553574c26 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/snowbridge.rs @@ -84,11 +84,7 @@ fn create_agent() { let remote_xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, DescendOrigin(Parachain(origin_para).into()), - Transact { - require_weight_at_most: 3000000000.into(), - origin_kind: OriginKind::Xcm, - call: create_agent_call.encode().into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: create_agent_call.encode().into() }, ])); // Rococo Global Consensus @@ -142,11 +138,7 @@ fn create_channel() { let create_agent_xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, DescendOrigin(Parachain(origin_para).into()), - Transact { - require_weight_at_most: 3000000000.into(), - origin_kind: OriginKind::Xcm, - call: create_agent_call.encode().into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: create_agent_call.encode().into() }, ])); let create_channel_call = @@ -155,11 +147,7 @@ fn create_channel() { let create_channel_xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, DescendOrigin(Parachain(origin_para).into()), - Transact { - require_weight_at_most: 3000000000.into(), - origin_kind: OriginKind::Xcm, - call: create_channel_call.encode().into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: create_channel_call.encode().into() }, ])); // Rococo Global Consensus @@ -310,11 +298,13 @@ fn send_token_from_ethereum_to_penpal() { )); }); + let ethereum_network_v5: NetworkId = EthereumNetwork::get().into(); + // The Weth asset location, identified by the contract address on Ethereum let weth_asset_location: Location = - (Parent, Parent, EthereumNetwork::get(), AccountKey20 { network: None, key: WETH }).into(); + (Parent, Parent, ethereum_network_v5, AccountKey20 { network: None, key: WETH }).into(); - let origin_location = (Parent, Parent, EthereumNetwork::get()).into(); + let origin_location = (Parent, Parent, ethereum_network_v5).into(); // Fund ethereum sovereign on AssetHub let ethereum_sovereign: AccountId = @@ -323,10 +313,11 @@ fn send_token_from_ethereum_to_penpal() { // Create asset on the Penpal parachain. PenpalA::execute_with(|| { - assert_ok!(::ForeignAssets::create( - ::RuntimeOrigin::signed(PenpalASender::get()), + assert_ok!(::ForeignAssets::force_create( + ::RuntimeOrigin::root(), weth_asset_location.clone(), asset_hub_sovereign.into(), + false, 1000, )); @@ -447,14 +438,14 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { )), fun: Fungible(WETH_AMOUNT), }]; - let multi_assets = VersionedAssets::V4(Assets::from(assets)); + let multi_assets = VersionedAssets::from(Assets::from(assets)); - let destination = VersionedLocation::V4(Location::new( + let destination = VersionedLocation::from(Location::new( 2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })], )); - let beneficiary = VersionedLocation::V4(Location::new( + let beneficiary = VersionedLocation::from(Location::new( 0, [AccountKey20 { network: None, key: ETHEREUM_DESTINATION_ADDRESS.into() }], )); @@ -563,10 +554,9 @@ fn register_weth_token_in_asset_hub_fail_for_insufficient_fee() { } fn send_token_from_ethereum_to_asset_hub_with_fee(account_id: [u8; 32], fee: u128) { - let weth_asset_location: Location = Location::new( - 2, - [EthereumNetwork::get().into(), AccountKey20 { network: None, key: WETH }], - ); + let ethereum_network_v5: NetworkId = EthereumNetwork::get().into(); + let weth_asset_location: Location = + Location::new(2, [ethereum_network_v5.into(), AccountKey20 { network: None, key: WETH }]); // Fund asset hub sovereign on bridge hub let asset_hub_sovereign = BridgeHubRococo::sovereign_account_id_of(Location::new( 1, diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs index 76e8312921de..501ddb84d425 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs @@ -22,9 +22,9 @@ mod imports { // Polkadot pub use xcm::{ - latest::ParentThen, + latest::{ParentThen, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}, prelude::{AccountId32 as AccountId32Junction, *}, - v4::{self, NetworkId::Rococo as RococoId}, + v5, }; pub use xcm_executor::traits::TransferType; @@ -56,6 +56,7 @@ mod imports { penpal_emulated_chain::{ penpal_runtime::xcm_config::{ CustomizableAssetFromSystemAssetHub as PenpalCustomizableAssetFromSystemAssetHub, + LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub, UniversalLocation as PenpalUniversalLocation, }, PenpalAssetOwner, PenpalBParaPallet as PenpalBPallet, @@ -71,8 +72,9 @@ mod imports { BridgeHubWestendPara as BridgeHubWestend, BridgeHubWestendParaReceiver as BridgeHubWestendReceiver, BridgeHubWestendParaSender as BridgeHubWestendSender, PenpalBPara as PenpalB, - PenpalBParaSender as PenpalBSender, WestendRelay as Westend, - WestendRelayReceiver as WestendReceiver, WestendRelaySender as WestendSender, + PenpalBParaReceiver as PenpalBReceiver, PenpalBParaSender as PenpalBSender, + WestendRelay as Westend, WestendRelayReceiver as WestendReceiver, + WestendRelaySender as WestendSender, }; pub const ASSET_ID: u32 = 1; diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs index 0856c9526009..ab09517339db 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs @@ -12,7 +12,9 @@ // 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::tests::*; + +use crate::{create_pool_with_native_on, tests::*}; +use xcm::latest::AssetTransferFilter; fn send_assets_over_bridge(send_fn: F) { // fund the AHW's SA on BHW for paying bridge transport fees @@ -38,7 +40,7 @@ fn send_assets_over_bridge(send_fn: F) { fn set_up_wnds_for_penpal_westend_through_ahw_to_ahr( sender: &AccountId, amount: u128, -) -> (Location, v4::Location) { +) -> (Location, v5::Location) { let wnd_at_westend_parachains = wnd_at_ah_westend(); let wnd_at_asset_hub_rococo = bridged_wnd_at_ah_rococo(); create_foreign_on_ah_rococo(wnd_at_asset_hub_rococo.clone(), true); @@ -69,10 +71,9 @@ fn send_assets_from_penpal_westend_through_westend_ah_to_rococo_ah( ); let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); - // send message over bridge assert_ok!(PenpalB::execute_with(|| { let signed_origin = ::RuntimeOrigin::signed(PenpalBSender::get()); @@ -128,13 +129,18 @@ fn send_wnds_usdt_and_weth_from_asset_hub_westend_to_asset_hub_rococo() { let bridged_wnd_at_asset_hub_rococo = bridged_wnd_at_ah_rococo(); create_foreign_on_ah_rococo(bridged_wnd_at_asset_hub_rococo.clone(), true); - set_up_pool_with_roc_on_ah_rococo(bridged_wnd_at_asset_hub_rococo.clone(), true); + create_pool_with_native_on!( + AssetHubRococo, + bridged_wnd_at_asset_hub_rococo.clone(), + true, + AssetHubRococoSender::get() + ); //////////////////////////////////////////////////////////// // Let's first send over just some WNDs as a simple example //////////////////////////////////////////////////////////// let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); let wnds_in_reserve_on_ahw_before = @@ -206,7 +212,12 @@ fn send_wnds_usdt_and_weth_from_asset_hub_westend_to_asset_hub_rococo() { ); create_foreign_on_ah_rococo(bridged_weth_at_ah.clone(), true); create_foreign_on_ah_rococo(bridged_usdt_at_asset_hub_rococo.clone(), true); - set_up_pool_with_roc_on_ah_rococo(bridged_usdt_at_asset_hub_rococo.clone(), true); + create_pool_with_native_on!( + AssetHubRococo, + bridged_usdt_at_asset_hub_rococo.clone(), + true, + AssetHubRococoSender::get() + ); let receiver_usdts_before = foreign_balance_on_ah_rococo(bridged_usdt_at_asset_hub_rococo.clone(), &receiver); @@ -269,7 +280,7 @@ fn send_back_rocs_from_asset_hub_westend_to_asset_hub_rococo() { // fund the AHW's SA on AHR with the ROC tokens held in reserve let sov_ahw_on_ahr = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); AssetHubRococo::fund_accounts(vec![(sov_ahw_on_ahr.clone(), prefund_amount)]); @@ -339,7 +350,7 @@ fn send_wnds_from_penpal_westend_through_asset_hub_westend_to_asset_hub_rococo() set_up_wnds_for_penpal_westend_through_ahw_to_ahr(&sender, amount); let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), AssetHubRococo::para_id(), ); let wnds_in_reserve_on_ahw_before = @@ -445,7 +456,7 @@ fn send_back_rocs_from_penpal_westend_through_asset_hub_westend_to_asset_hub_roc // fund the AHW's SA on AHR with the ROC tokens held in reserve let sov_ahw_on_ahr = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); AssetHubRococo::fund_accounts(vec![(sov_ahw_on_ahr.clone(), amount * 2)]); @@ -543,3 +554,295 @@ fn dry_run_transfer_to_rococo_sends_xcm_to_bridge_hub() { asset_hub_rococo_location() ); } + +fn do_send_pens_and_wnds_from_penpal_westend_via_ahw_to_asset_hub_rococo( + wnds: (Location, u128), + pens: (Location, u128), +) { + let (wnds_id, wnds_amount) = wnds; + let (pens_id, pens_amount) = pens; + send_assets_over_bridge(|| { + let sov_penpal_on_ahw = AssetHubWestend::sovereign_account_id_of( + AssetHubWestend::sibling_location_of(PenpalB::para_id()), + ); + let sov_ahr_on_ahw = + AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( + ByGenesis(ROCOCO_GENESIS_HASH), + AssetHubRococo::para_id(), + ); + // send message over bridge + assert_ok!(PenpalB::execute_with(|| { + let destination = asset_hub_rococo_location(); + let local_asset_hub = PenpalB::sibling_location_of(AssetHubWestend::para_id()); + let signed_origin = ::RuntimeOrigin::signed(PenpalBSender::get()); + let beneficiary: Location = + AccountId32Junction { network: None, id: AssetHubRococoReceiver::get().into() } + .into(); + let wnds: Asset = (wnds_id.clone(), wnds_amount).into(); + let pens: Asset = (pens_id, pens_amount).into(); + let assets: Assets = vec![wnds.clone(), pens.clone()].into(); + + // TODO: dry-run to get exact fees, for now just some static value 100_000_000_000 + let penpal_fees_amount = 100_000_000_000; + // use 100_000_000_000 WNDs in fees on AHW + // (exec fees: 3_593_000_000, transpo fees: 69_021_561_290 = 72_614_561_290) + // TODO: make this exact once we have bridge dry-running + let ahw_fee_amount = 100_000_000_000; + + // XCM to be executed at dest (Rococo Asset Hub) + let xcm_on_dest = Xcm(vec![ + // since this is the last hop, we don't need to further use any assets previously + // reserved for fees (there are no further hops to cover transport fees for); we + // RefundSurplus to get back any unspent fees + RefundSurplus, + // deposit everything to final beneficiary + DepositAsset { assets: Wild(All), beneficiary: beneficiary.clone() }, + ]); + + // XCM to be executed at (intermediary) Westend Asset Hub + let context = PenpalUniversalLocation::get(); + let reanchored_dest = + destination.clone().reanchored(&local_asset_hub, &context).unwrap(); + let reanchored_pens = pens.clone().reanchored(&local_asset_hub, &context).unwrap(); + let mut onward_wnds = wnds.clone().reanchored(&local_asset_hub, &context).unwrap(); + onward_wnds.fun = Fungible(wnds_amount - ahw_fee_amount - penpal_fees_amount); + let xcm_on_ahw = Xcm(vec![ + // both WNDs and PENs are local-reserve transferred to Rococo Asset Hub + // initially, all WNDs are reserved for fees on destination, but at the end of the + // program we RefundSurplus to get back any unspent and deposit them to final + // beneficiary + InitiateTransfer { + destination: reanchored_dest, + remote_fees: Some(AssetTransferFilter::ReserveDeposit(onward_wnds.into())), + preserve_origin: false, + assets: vec![AssetTransferFilter::ReserveDeposit(reanchored_pens.into())], + remote_xcm: xcm_on_dest, + }, + ]); + + let penpal_fees = (wnds.id.clone(), Fungible(penpal_fees_amount)); + let ahw_fees: Asset = (wnds.id.clone(), Fungible(ahw_fee_amount)).into(); + let ahw_non_fees_wnds: Asset = + (wnds.id.clone(), Fungible(wnds_amount - ahw_fee_amount - penpal_fees_amount)) + .into(); + // XCM to be executed locally + let xcm = Xcm::<()>(vec![ + // Withdraw both WNDs and PENs from origin account + WithdrawAsset(assets.into()), + PayFees { asset: penpal_fees.into() }, + // Execute the transfers while paying remote fees with WNDs + InitiateTransfer { + destination: local_asset_hub, + // WNDs for fees are reserve-withdrawn at AHW and reserved for fees + remote_fees: Some(AssetTransferFilter::ReserveWithdraw(ahw_fees.into())), + preserve_origin: false, + // PENs are teleported to AHW, rest of non-fee WNDs are reserve-withdrawn at AHW + assets: vec![ + AssetTransferFilter::Teleport(pens.into()), + AssetTransferFilter::ReserveWithdraw(ahw_non_fees_wnds.into()), + ], + remote_xcm: xcm_on_ahw, + }, + ]); + + ::PolkadotXcm::execute( + signed_origin, + bx!(xcm::VersionedXcm::V5(xcm.into())), + Weight::MAX, + ) + })); + AssetHubWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + AssetHubWestend, + vec![ + // Amount to reserve transfer is withdrawn from Penpal's sovereign account + RuntimeEvent::Balances( + pallet_balances::Event::Burned { who, amount } + ) => { + who: *who == sov_penpal_on_ahw.clone().into(), + amount: *amount == wnds_amount, + }, + // Amount deposited in AHR's sovereign account + RuntimeEvent::Balances(pallet_balances::Event::Minted { who, .. }) => { + who: *who == sov_ahr_on_ahw.clone().into(), + }, + RuntimeEvent::XcmpQueue( + cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. } + ) => {}, + ] + ); + }); + }); +} + +/// Transfer "PEN"s plus "WND"s from PenpalWestend to AssetHubWestend, over bridge to +/// AssetHubRococo. PENs need to be teleported to AHW, while WNDs reserve-withdrawn, then both +/// reserve transferred further to AHR. (transfer 2 different assets with different transfer types +/// across 3 different chains) +#[test] +fn send_pens_and_wnds_from_penpal_westend_via_ahw_to_ahr() { + let penpal_check_account = ::PolkadotXcm::check_account(); + let owner: AccountId = AssetHubRococo::account_id_of(ALICE); + let sender = PenpalBSender::get(); + let amount = ASSET_HUB_WESTEND_ED * 10_000_000; + + let (wnd_at_westend_parachains, wnd_at_rococo_parachains) = + set_up_wnds_for_penpal_westend_through_ahw_to_ahr(&sender, amount); + + let pens_location_on_penpal = + Location::try_from(PenpalLocalTeleportableToAssetHub::get()).unwrap(); + let pens_id_on_penpal = match pens_location_on_penpal.last() { + Some(Junction::GeneralIndex(id)) => *id as u32, + _ => unreachable!(), + }; + + let penpal_parachain_junction = Junction::Parachain(PenpalB::para_id().into()); + let pens_at_ahw = Location::new( + 1, + pens_location_on_penpal + .interior() + .clone() + .pushed_front_with(penpal_parachain_junction) + .unwrap(), + ); + let pens_at_rococo_parachains = Location::new( + 2, + pens_at_ahw + .interior() + .clone() + .pushed_front_with(Junction::GlobalConsensus(NetworkId::ByGenesis( + WESTEND_GENESIS_HASH, + ))) + .unwrap(), + ); + let wnds_to_send = amount; + let pens_to_send = amount; + + // ---------- Set up Penpal Westend ---------- + // Fund Penpal's sender account. No need to create the asset (only mint), it exists in genesis. + PenpalB::mint_asset( + ::RuntimeOrigin::signed(owner.clone()), + pens_id_on_penpal, + sender.clone(), + pens_to_send * 2, + ); + // fund Penpal's check account to be able to teleport + PenpalB::fund_accounts(vec![(penpal_check_account.clone().into(), pens_to_send * 2)]); + + // ---------- Set up Asset Hub Rococo ---------- + // create PEN at AHR + AssetHubRococo::force_create_foreign_asset( + pens_at_rococo_parachains.clone(), + owner.clone(), + false, + ASSET_MIN_BALANCE, + vec![], + ); + + // account balances before + let sender_wnds_before = PenpalB::execute_with(|| { + type ForeignAssets = ::ForeignAssets; + >::balance( + wnd_at_westend_parachains.clone().into(), + &PenpalBSender::get(), + ) + }); + let sender_pens_before = PenpalB::execute_with(|| { + type Assets = ::Assets; + >::balance(pens_id_on_penpal, &PenpalBSender::get()) + }); + let sov_ahr_on_ahw = AssetHubWestend::sovereign_account_of_parachain_on_other_global_consensus( + ByGenesis(ROCOCO_GENESIS_HASH), + AssetHubRococo::para_id(), + ); + let wnds_in_reserve_on_ahw_before = + ::account_data_of(sov_ahr_on_ahw.clone()).free; + let pens_in_reserve_on_ahw_before = AssetHubWestend::execute_with(|| { + type ForeignAssets = ::ForeignAssets; + >::balance(pens_at_ahw.clone(), &sov_ahr_on_ahw) + }); + let receiver_wnds_before = AssetHubRococo::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance( + wnd_at_rococo_parachains.clone(), + &AssetHubRococoReceiver::get(), + ) + }); + let receiver_pens_before = AssetHubRococo::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance( + pens_at_rococo_parachains.clone(), + &AssetHubRococoReceiver::get(), + ) + }); + + // transfer assets + do_send_pens_and_wnds_from_penpal_westend_via_ahw_to_asset_hub_rococo( + (wnd_at_westend_parachains.clone(), wnds_to_send), + (pens_location_on_penpal.try_into().unwrap(), pens_to_send), + ); + + AssetHubRococo::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + AssetHubRococo, + vec![ + // issue WNDs on AHR + RuntimeEvent::ForeignAssets(pallet_assets::Event::Issued { asset_id, owner, .. }) => { + asset_id: *asset_id == wnd_at_westend_parachains.clone().try_into().unwrap(), + owner: *owner == AssetHubRococoReceiver::get(), + }, + // message processed successfully + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + }); + + // account balances after + let sender_wnds_after = PenpalB::execute_with(|| { + type ForeignAssets = ::ForeignAssets; + >::balance( + wnd_at_westend_parachains.into(), + &PenpalBSender::get(), + ) + }); + let sender_pens_after = PenpalB::execute_with(|| { + type Assets = ::Assets; + >::balance(pens_id_on_penpal, &PenpalBSender::get()) + }); + let wnds_in_reserve_on_ahw_after = + ::account_data_of(sov_ahr_on_ahw.clone()).free; + let pens_in_reserve_on_ahw_after = AssetHubWestend::execute_with(|| { + type ForeignAssets = ::ForeignAssets; + >::balance(pens_at_ahw, &sov_ahr_on_ahw) + }); + let receiver_wnds_after = AssetHubRococo::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance( + wnd_at_rococo_parachains.clone(), + &AssetHubRococoReceiver::get(), + ) + }); + let receiver_pens_after = AssetHubRococo::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance(pens_at_rococo_parachains, &AssetHubRococoReceiver::get()) + }); + + // Sender's balance is reduced + assert!(sender_wnds_after < sender_wnds_before); + // Receiver's balance is increased + assert!(receiver_wnds_after > receiver_wnds_before); + // Reserve balance is increased by sent amount (less fess) + assert!(wnds_in_reserve_on_ahw_after > wnds_in_reserve_on_ahw_before); + assert!(wnds_in_reserve_on_ahw_after <= wnds_in_reserve_on_ahw_before + wnds_to_send); + + // Sender's balance is reduced by sent amount + assert_eq!(sender_pens_after, sender_pens_before - pens_to_send); + // Reserve balance is increased by sent amount + assert_eq!(pens_in_reserve_on_ahw_after, pens_in_reserve_on_ahw_before + pens_to_send); + // Receiver's balance is increased by sent amount + assert_eq!(receiver_pens_after, receiver_pens_before + pens_to_send); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs index e62ce6843258..c111eb86501a 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = BridgeHubWestendExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(AssetHubWestend, RuntimeCall, NetworkId::Westend, assets, amount); + test_chain_can_claim_assets!( + AssetHubWestend, + RuntimeCall, + NetworkId::ByGenesis(WESTEND_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs index af11f0f7ba72..6c1cdb98e8b2 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs @@ -19,16 +19,28 @@ mod asset_transfers; mod claim_assets; mod register_bridged_assets; mod send_xcm; -mod teleport; - mod snowbridge; +mod teleport; +mod transact; pub(crate) fn asset_hub_rococo_location() -> Location { - Location::new(2, [GlobalConsensus(Rococo), Parachain(AssetHubRococo::para_id().into())]) + Location::new( + 2, + [ + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), + Parachain(AssetHubRococo::para_id().into()), + ], + ) } pub(crate) fn bridge_hub_rococo_location() -> Location { - Location::new(2, [GlobalConsensus(Rococo), Parachain(BridgeHubRococo::para_id().into())]) + Location::new( + 2, + [ + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), + Parachain(BridgeHubRococo::para_id().into()), + ], + ) } // WND and wWND @@ -36,7 +48,7 @@ pub(crate) fn wnd_at_ah_westend() -> Location { Parent.into() } pub(crate) fn bridged_wnd_at_ah_rococo() -> Location { - Location::new(2, [GlobalConsensus(Westend)]) + Location::new(2, [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))]) } // ROC and wROC @@ -44,7 +56,7 @@ pub(crate) fn roc_at_ah_rococo() -> Location { Parent.into() } pub(crate) fn bridged_roc_at_ah_westend() -> Location { - Location::new(2, [GlobalConsensus(Rococo)]) + Location::new(2, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) } // USDT and wUSDT @@ -55,7 +67,7 @@ pub(crate) fn bridged_usdt_at_ah_rococo() -> Location { Location::new( 2, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(AssetHubWestend::para_id().into()), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(USDT_ID.into()), @@ -74,13 +86,13 @@ pub(crate) fn weth_at_asset_hubs() -> Location { ) } -pub(crate) fn create_foreign_on_ah_rococo(id: v4::Location, sufficient: bool) { +pub(crate) fn create_foreign_on_ah_rococo(id: v5::Location, sufficient: bool) { let owner = AssetHubRococo::account_id_of(ALICE); AssetHubRococo::force_create_foreign_asset(id, owner, sufficient, ASSET_MIN_BALANCE, vec![]); } pub(crate) fn create_foreign_on_ah_westend( - id: v4::Location, + id: v5::Location, sufficient: bool, prefund_accounts: Vec<(AccountId, u128)>, ) { @@ -89,74 +101,83 @@ pub(crate) fn create_foreign_on_ah_westend( AssetHubWestend::force_create_foreign_asset(id, owner, sufficient, min, prefund_accounts); } -pub(crate) fn foreign_balance_on_ah_rococo(id: v4::Location, who: &AccountId) -> u128 { +pub(crate) fn foreign_balance_on_ah_rococo(id: v5::Location, who: &AccountId) -> u128 { AssetHubRococo::execute_with(|| { type Assets = ::ForeignAssets; >::balance(id, who) }) } -pub(crate) fn foreign_balance_on_ah_westend(id: v4::Location, who: &AccountId) -> u128 { +pub(crate) fn foreign_balance_on_ah_westend(id: v5::Location, who: &AccountId) -> u128 { AssetHubWestend::execute_with(|| { type Assets = ::ForeignAssets; >::balance(id, who) }) } -// set up pool -pub(crate) fn set_up_pool_with_roc_on_ah_rococo(asset: v4::Location, is_foreign: bool) { - let roc: v4::Location = v4::Parent.into(); - AssetHubRococo::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - let owner = AssetHubRococoSender::get(); - let signed_owner = ::RuntimeOrigin::signed(owner.clone()); +/// note: $asset needs to be prefunded outside this function +#[macro_export] +macro_rules! create_pool_with_native_on { + ( $chain:ident, $asset:expr, $is_foreign:expr, $asset_owner:expr ) => { + emulated_integration_tests_common::impls::paste::paste! { + <$chain>::execute_with(|| { + type RuntimeEvent = <$chain as Chain>::RuntimeEvent; + let owner = $asset_owner; + let signed_owner = <$chain as Chain>::RuntimeOrigin::signed(owner.clone()); + let native_asset: Location = Parent.into(); - if is_foreign { - assert_ok!(::ForeignAssets::mint( - signed_owner.clone(), - asset.clone().into(), - owner.clone().into(), - 3_000_000_000_000, - )); - } else { - let asset_id = match asset.interior.last() { - Some(v4::Junction::GeneralIndex(id)) => *id as u32, - _ => unreachable!(), - }; - assert_ok!(::Assets::mint( - signed_owner.clone(), - asset_id.into(), - owner.clone().into(), - 3_000_000_000_000, - )); + if $is_foreign { + assert_ok!(<$chain as [<$chain Pallet>]>::ForeignAssets::mint( + signed_owner.clone(), + $asset.clone().into(), + owner.clone().into(), + 10_000_000_000_000, // For it to have more than enough. + )); + } else { + let asset_id = match $asset.interior.last() { + Some(GeneralIndex(id)) => *id as u32, + _ => unreachable!(), + }; + assert_ok!(<$chain as [<$chain Pallet>]>::Assets::mint( + signed_owner.clone(), + asset_id.into(), + owner.clone().into(), + 10_000_000_000_000, // For it to have more than enough. + )); + } + + assert_ok!(<$chain as [<$chain Pallet>]>::AssetConversion::create_pool( + signed_owner.clone(), + Box::new(native_asset.clone()), + Box::new($asset.clone()), + )); + + assert_expected_events!( + $chain, + vec![ + RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, + ] + ); + + assert_ok!(<$chain as [<$chain Pallet>]>::AssetConversion::add_liquidity( + signed_owner, + Box::new(native_asset), + Box::new($asset), + 1_000_000_000_000, + 2_000_000_000_000, // $asset is worth half of native_asset + 0, + 0, + owner.into() + )); + + assert_expected_events!( + $chain, + vec![ + RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded { .. }) => {}, + ] + ); + }); } - assert_ok!(::AssetConversion::create_pool( - signed_owner.clone(), - Box::new(roc.clone()), - Box::new(asset.clone()), - )); - assert_expected_events!( - AssetHubRococo, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::PoolCreated { .. }) => {}, - ] - ); - assert_ok!(::AssetConversion::add_liquidity( - signed_owner.clone(), - Box::new(roc), - Box::new(asset), - 1_000_000_000_000, - 2_000_000_000_000, - 1, - 1, - owner.into() - )); - assert_expected_events!( - AssetHubRococo, - vec![ - RuntimeEvent::AssetConversion(pallet_asset_conversion::Event::LiquidityAdded {..}) => {}, - ] - ); - }); + }; } pub(crate) fn send_assets_from_asset_hub_westend( @@ -239,7 +260,11 @@ pub(crate) fn open_bridge_between_asset_hub_rococo_and_asset_hub_westend() { BridgeHubRococo::fund_para_sovereign(AssetHubRococo::para_id(), ROC * 5); AssetHubRococo::open_bridge( AssetHubRococo::sibling_location_of(BridgeHubRococo::para_id()), - [GlobalConsensus(Westend), Parachain(AssetHubWestend::para_id().into())].into(), + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(AssetHubWestend::para_id().into()), + ] + .into(), Some(( (roc_at_ah_rococo(), ROC * 1).into(), BridgeHubRococo::sovereign_account_id_of(BridgeHubRococo::sibling_location_of( @@ -252,7 +277,11 @@ pub(crate) fn open_bridge_between_asset_hub_rococo_and_asset_hub_westend() { BridgeHubWestend::fund_para_sovereign(AssetHubWestend::para_id(), WND * 5); AssetHubWestend::open_bridge( AssetHubWestend::sibling_location_of(BridgeHubWestend::para_id()), - [GlobalConsensus(Rococo), Parachain(AssetHubRococo::para_id().into())].into(), + [ + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), + Parachain(AssetHubRococo::para_id().into()), + ] + .into(), Some(( (wnd_at_ah_westend(), WND * 1).into(), BridgeHubWestend::sovereign_account_id_of(BridgeHubWestend::sibling_location_of( diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/register_bridged_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/register_bridged_assets.rs index 7a7ad6da2d55..424f1e55956b 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/register_bridged_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/register_bridged_assets.rs @@ -30,7 +30,7 @@ fn register_westend_asset_on_rah_from_wah() { let bridged_asset_at_rah = Location::new( 2, [ - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(AssetHubWestend::para_id().into()), PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into()), @@ -57,7 +57,7 @@ fn register_ethereum_asset_on_rah_from_wah() { fn register_asset_on_rah_from_wah(bridged_asset_at_rah: Location) { let sa_of_wah_on_rah = AssetHubRococo::sovereign_account_of_parachain_on_other_global_consensus( - Westend, + ByGenesis(WESTEND_GENESIS_HASH), AssetHubWestend::para_id(), ); diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs index ae05e4223b07..787d7dc842cb 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs @@ -29,7 +29,7 @@ fn send_xcm_from_westend_relay_to_rococo_asset_hub_should_fail_on_not_applicable let xcm = VersionedXcm::from(Xcm(vec![ UnpaidExecution { weight_limit, check_origin }, ExportMessage { - network: RococoId, + network: ByGenesis(ROCOCO_GENESIS_HASH), destination: [Parachain(AssetHubRococo::para_id().into())].into(), xcm: remote_xcm, }, @@ -60,15 +60,6 @@ fn send_xcm_from_westend_relay_to_rococo_asset_hub_should_fail_on_not_applicable #[test] fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { - // Initially set only default version on all runtimes - let newer_xcm_version = xcm::prelude::XCM_VERSION; - let older_xcm_version = newer_xcm_version - 1; - - AssetHubRococo::force_default_xcm_version(Some(older_xcm_version)); - BridgeHubRococo::force_default_xcm_version(Some(older_xcm_version)); - BridgeHubWestend::force_default_xcm_version(Some(older_xcm_version)); - AssetHubWestend::force_default_xcm_version(Some(older_xcm_version)); - // prepare data let destination = asset_hub_rococo_location(); let native_token = Location::parent(); @@ -82,6 +73,14 @@ fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { // open bridge open_bridge_between_asset_hub_rococo_and_asset_hub_westend(); + // Initially set only default version on all runtimes + let newer_xcm_version = xcm::prelude::XCM_VERSION; + let older_xcm_version = newer_xcm_version - 1; + AssetHubRococo::force_default_xcm_version(Some(older_xcm_version)); + BridgeHubRococo::force_default_xcm_version(Some(older_xcm_version)); + BridgeHubWestend::force_default_xcm_version(Some(older_xcm_version)); + AssetHubWestend::force_default_xcm_version(Some(older_xcm_version)); + // send XCM from AssetHubWestend - fails - destination version not known assert_err!( send_assets_from_asset_hub_westend( diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs index f1c27aedf164..ffa60a4f52e7 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/snowbridge.rs @@ -96,8 +96,10 @@ fn send_token_from_ethereum_to_asset_hub() { // Fund ethereum sovereign on AssetHub AssetHubWestend::fund_accounts(vec![(AssetHubWestendReceiver::get(), INITIAL_FUND)]); + let ethereum_network_v5: NetworkId = EthereumNetwork::get().into(); + let weth_asset_location: Location = - (Parent, Parent, EthereumNetwork::get(), AccountKey20 { network: None, key: WETH }).into(); + (Parent, Parent, ethereum_network_v5, AccountKey20 { network: None, key: WETH }).into(); AssetHubWestend::execute_with(|| { type RuntimeOrigin = ::RuntimeOrigin; @@ -156,8 +158,9 @@ fn send_token_from_ethereum_to_asset_hub() { fn send_weth_asset_from_asset_hub_to_ethereum() { let assethub_location = BridgeHubWestend::sibling_location_of(AssetHubWestend::para_id()); let assethub_sovereign = BridgeHubWestend::sovereign_account_id_of(assethub_location); + let ethereum_network_v5: NetworkId = EthereumNetwork::get().into(); let weth_asset_location: Location = - (Parent, Parent, EthereumNetwork::get(), AccountKey20 { network: None, key: WETH }).into(); + (Parent, Parent, ethereum_network_v5, AccountKey20 { network: None, key: WETH }).into(); BridgeHubWestend::fund_accounts(vec![(assethub_sovereign.clone(), INITIAL_FUND)]); @@ -218,14 +221,14 @@ fn send_weth_asset_from_asset_hub_to_ethereum() { )), fun: Fungible(TOKEN_AMOUNT), }]; - let versioned_assets = VersionedAssets::V4(Assets::from(assets)); + let versioned_assets = VersionedAssets::from(Assets::from(assets)); - let destination = VersionedLocation::V4(Location::new( + let destination = VersionedLocation::from(Location::new( 2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })], )); - let beneficiary = VersionedLocation::V4(Location::new( + let beneficiary = VersionedLocation::from(Location::new( 0, [AccountKey20 { network: None, key: ETHEREUM_DESTINATION_ADDRESS.into() }], )); @@ -291,8 +294,10 @@ fn transfer_relay_token() { BridgeHubWestend::fund_accounts(vec![(assethub_sovereign.clone(), INITIAL_FUND)]); let asset_id: Location = Location { parents: 1, interior: [].into() }; - let expected_asset_id: Location = - Location { parents: 1, interior: [GlobalConsensus(Westend)].into() }; + let expected_asset_id: Location = Location { + parents: 1, + interior: [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH))].into(), + }; let expected_token_id = TokenIdOf::convert_location(&expected_asset_id).unwrap(); @@ -317,7 +322,7 @@ fn transfer_relay_token() { assert_ok!(::EthereumSystem::register_token( RuntimeOrigin::root(), - Box::new(VersionedLocation::V4(asset_id.clone())), + Box::new(VersionedLocation::from(asset_id.clone())), AssetMetadata { name: "wnd".as_bytes().to_vec().try_into().unwrap(), symbol: "wnd".as_bytes().to_vec().try_into().unwrap(), @@ -337,14 +342,14 @@ fn transfer_relay_token() { type RuntimeEvent = ::RuntimeEvent; let assets = vec![Asset { id: AssetId(Location::parent()), fun: Fungible(TOKEN_AMOUNT) }]; - let versioned_assets = VersionedAssets::V4(Assets::from(assets)); + let versioned_assets = VersionedAssets::from(Assets::from(assets)); - let destination = VersionedLocation::V4(Location::new( + let destination = VersionedLocation::from(Location::new( 2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })], )); - let beneficiary = VersionedLocation::V4(Location::new( + let beneficiary = VersionedLocation::from(Location::new( 0, [AccountKey20 { network: None, key: ETHEREUM_DESTINATION_ADDRESS.into() }], )); @@ -462,10 +467,15 @@ fn transfer_ah_token() { ], ); - let asset_id_after_reanchored = - Location::new(1, [GlobalConsensus(Westend), Parachain(AssetHubWestend::para_id().into())]) - .appended_with(asset_id.clone().interior) - .unwrap(); + let asset_id_after_reanchored = Location::new( + 1, + [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(AssetHubWestend::para_id().into()), + ], + ) + .appended_with(asset_id.clone().interior) + .unwrap(); let token_id = TokenIdOf::convert_location(&asset_id_after_reanchored).unwrap(); @@ -475,7 +485,7 @@ fn transfer_ah_token() { assert_ok!(::EthereumSystem::register_token( RuntimeOrigin::root(), - Box::new(VersionedLocation::V4(asset_id_in_bh.clone())), + Box::new(VersionedLocation::from(asset_id_in_bh.clone())), AssetMetadata { name: "ah_asset".as_bytes().to_vec().try_into().unwrap(), symbol: "ah_asset".as_bytes().to_vec().try_into().unwrap(), @@ -500,9 +510,9 @@ fn transfer_ah_token() { // Send partial of the token, will fail if send all let assets = vec![Asset { id: AssetId(asset_id.clone()), fun: Fungible(TOKEN_AMOUNT / 10) }]; - let versioned_assets = VersionedAssets::V4(Assets::from(assets)); + let versioned_assets = VersionedAssets::from(Assets::from(assets)); - let beneficiary = VersionedLocation::V4(Location::new( + let beneficiary = VersionedLocation::from(Location::new( 0, [AccountKey20 { network: None, key: ETHEREUM_DESTINATION_ADDRESS.into() }], )); diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/transact.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/transact.rs new file mode 100644 index 000000000000..db42704dae61 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/transact.rs @@ -0,0 +1,248 @@ +// 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::{ + create_pool_with_native_on, + tests::{snowbridge::CHAIN_ID, *}, +}; +use sp_core::Get; +use xcm::latest::AssetTransferFilter; + +const ETHEREUM_BOB: [u8; 20] = hex_literal::hex!("11b0b11000011b0b11000011b0b11000011b0b11"); + +/// Bob on Ethereum transacts on PenpalB, paying fees using WETH. XCM has to go through Asset Hub +/// as the reserve location of WETH. The original origin `Ethereum/Bob` is proxied by Asset Hub. +/// +/// This particular test is not testing snowbridge, but only Bridge Hub, so the tested XCM flow from +/// Ethereum starts from Bridge Hub. +// TODO(https://github.com/paritytech/polkadot-sdk/issues/6243): Once Snowbridge supports Transact, start the flow from Ethereum and test completely e2e. +fn transfer_and_transact_in_same_xcm( + sender: Location, + weth: Asset, + destination: Location, + beneficiary: Location, + call: xcm::DoubleEncoded<()>, +) { + let signed_origin = ::RuntimeOrigin::root(); + let context: InteriorLocation = [ + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), + Parachain(::ParachainInfo::get().into()), + ] + .into(); + let asset_hub_location = BridgeHubWestend::sibling_location_of(AssetHubWestend::para_id()); + + // TODO(https://github.com/paritytech/polkadot-sdk/issues/6197): dry-run to get local fees, for now use hardcoded value. + let ah_fees_amount = 90_000_000_000u128; // current exact value 79_948_099_299 + let fees_for_ah: Asset = (weth.id.clone(), ah_fees_amount).into(); + + // xcm to be executed at dest + let xcm_on_dest = Xcm(vec![ + Transact { origin_kind: OriginKind::Xcm, call }, + ExpectTransactStatus(MaybeErrorCode::Success), + // since this is the last hop, we don't need to further use any assets previously + // reserved for fees (there are no further hops to cover transport fees for); we + // RefundSurplus to get back any unspent fees + RefundSurplus, + DepositAsset { assets: Wild(All), beneficiary }, + ]); + let destination = destination.reanchored(&asset_hub_location, &context).unwrap(); + let xcm_to_ah = Xcm::<()>(vec![ + UnpaidExecution { check_origin: None, weight_limit: Unlimited }, + DescendOrigin([PalletInstance(80)].into()), // snowbridge pallet + UniversalOrigin(GlobalConsensus(Ethereum { chain_id: CHAIN_ID })), + ReserveAssetDeposited(weth.clone().into()), + AliasOrigin(sender), + PayFees { asset: fees_for_ah }, + InitiateTransfer { + destination, + // on the last hop we can just put everything in fees and `RefundSurplus` to get any + // unused back + remote_fees: Some(AssetTransferFilter::ReserveDeposit(Wild(All))), + preserve_origin: true, + assets: vec![], + remote_xcm: xcm_on_dest, + }, + ]); + ::PolkadotXcm::send( + signed_origin, + bx!(asset_hub_location.into()), + bx!(xcm::VersionedXcm::from(xcm_to_ah.into())), + ) + .unwrap(); +} + +/// Bob on Ethereum transacts on PenpalB, paying fees using WETH. XCM has to go through Asset Hub +/// as the reserve location of WETH. The original origin `Ethereum/Bob` is proxied by Asset Hub. +/// +/// This particular test is not testing snowbridge, but only Bridge Hub, so the tested XCM flow from +/// Ethereum starts from Bridge Hub. +// TODO(https://github.com/paritytech/polkadot-sdk/issues/6243): Once Snowbridge supports Transact, start the flow from Ethereum and test completely e2e. +#[test] +fn transact_from_ethereum_to_penpalb_through_asset_hub() { + // Snowbridge doesn't support transact yet, we are emulating it by sending one from Bridge Hub + // as if it comes from Snowbridge. + let destination = BridgeHubWestend::sibling_location_of(PenpalB::para_id()); + let sender = Location::new( + 2, + [ + GlobalConsensus(Ethereum { chain_id: CHAIN_ID }), + AccountKey20 { network: None, key: ETHEREUM_BOB }, + ], + ); + + let bridged_weth = weth_at_asset_hubs(); + AssetHubWestend::force_create_foreign_asset( + bridged_weth.clone(), + PenpalAssetOwner::get(), + true, + ASSET_MIN_BALANCE, + vec![], + ); + PenpalB::force_create_foreign_asset( + bridged_weth.clone(), + PenpalAssetOwner::get(), + true, + ASSET_MIN_BALANCE, + vec![], + ); + // Configure source Penpal chain to trust local AH as reserve of bridged WETH + PenpalB::execute_with(|| { + assert_ok!(::System::set_storage( + ::RuntimeOrigin::root(), + vec![( + PenpalCustomizableAssetFromSystemAssetHub::key().to_vec(), + bridged_weth.encode(), + )], + )); + }); + + let fee_amount_to_send: parachains_common::Balance = ASSET_HUB_WESTEND_ED * 10000; + let sender_chain_as_seen_by_asset_hub = + Location::new(2, [GlobalConsensus(Ethereum { chain_id: CHAIN_ID })]); + + let sov_of_sender_on_asset_hub = AssetHubWestend::execute_with(|| { + AssetHubWestend::sovereign_account_id_of(sender_chain_as_seen_by_asset_hub) + }); + let receiver_as_seen_by_asset_hub = AssetHubWestend::sibling_location_of(PenpalB::para_id()); + let sov_of_receiver_on_asset_hub = AssetHubWestend::execute_with(|| { + AssetHubWestend::sovereign_account_id_of(receiver_as_seen_by_asset_hub) + }); + // Create SAs of sender and receiver on AHW with ED. + AssetHubWestend::fund_accounts(vec![ + (sov_of_sender_on_asset_hub.clone().into(), ASSET_HUB_WESTEND_ED), + (sov_of_receiver_on_asset_hub.clone().into(), ASSET_HUB_WESTEND_ED), + ]); + + // We create a pool between WND and WETH in AssetHub to support paying for fees with WETH. + let ahw_owner = AssetHubWestendSender::get(); + create_pool_with_native_on!(AssetHubWestend, bridged_weth.clone(), true, ahw_owner); + // We also need a pool between WND and WETH on PenpalB to support paying for fees with WETH. + create_pool_with_native_on!(PenpalB, bridged_weth.clone(), true, PenpalAssetOwner::get()); + + // Init values for Parachain Destination + let receiver = PenpalBReceiver::get(); + + // Query initial balances + let receiver_assets_before = PenpalB::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance(bridged_weth.clone(), &receiver) + }); + + // Now register a new asset on PenpalB from Ethereum/Bob account while paying fees using WETH + // (going through Asset Hub) + let weth_to_send: Asset = (bridged_weth.clone(), fee_amount_to_send).into(); + // Silly example of a Transact: Bob creates his own foreign assset on PenpalB based on his + // Ethereum address + let foreign_asset_at_penpal_b = Location::new( + 2, + [ + GlobalConsensus(Ethereum { chain_id: CHAIN_ID }), + AccountKey20 { network: None, key: ETHEREUM_BOB }, + ], + ); + // Encoded `create_asset` call to be executed in PenpalB + let call = PenpalB::create_foreign_asset_call( + foreign_asset_at_penpal_b.clone(), + ASSET_MIN_BALANCE, + receiver.clone(), + ); + BridgeHubWestend::execute_with(|| { + // initiate transaction + transfer_and_transact_in_same_xcm( + sender.clone(), + weth_to_send, + destination, + receiver.clone().into(), + call, + ); + }); + AssetHubWestend::execute_with(|| { + let sov_penpal_b_on_ah = AssetHubWestend::sovereign_account_id_of( + AssetHubWestend::sibling_location_of(PenpalB::para_id()), + ); + asset_hub_hop_assertions(sov_penpal_b_on_ah); + }); + PenpalB::execute_with(|| { + let expected_creator = PenpalB::sovereign_account_id_of(sender); + penpal_b_assertions(foreign_asset_at_penpal_b, expected_creator, receiver.clone()); + }); + + // Query final balances + let receiver_assets_after = PenpalB::execute_with(|| { + type Assets = ::ForeignAssets; + >::balance(bridged_weth, &receiver) + }); + // Receiver's balance is increased + assert!(receiver_assets_after > receiver_assets_before); +} + +fn asset_hub_hop_assertions(receiver_sa: AccountId) { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + AssetHubWestend, + vec![ + // Deposited to receiver parachain SA + RuntimeEvent::ForeignAssets( + pallet_assets::Event::Deposited { who, .. } + ) => { + who: *who == receiver_sa, + }, + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); +} + +fn penpal_b_assertions( + expected_asset: Location, + expected_creator: AccountId, + expected_owner: AccountId, +) { + type RuntimeEvent = ::RuntimeEvent; + PenpalB::assert_xcmp_queue_success(None); + assert_expected_events!( + PenpalB, + vec![ + RuntimeEvent::ForeignAssets( + pallet_assets::Event::Created { asset_id, creator, owner } + ) => { + asset_id: *asset_id == expected_asset, + creator: *creator == expected_creator, + owner: *owner == expected_owner, + }, + ] + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship.rs index f97599bda7f0..80b82e0c446f 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship.rs @@ -36,7 +36,6 @@ fn fellows_whitelist_call() { UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, - require_weight_at_most: Weight::from_parts(5_000_000_000, 500_000), call: WestendCall::Whitelist( pallet_whitelist::Call::::whitelist_call { call_hash } ) diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs index 943f8965540d..8418e3da3bba 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs @@ -64,11 +64,12 @@ fn fellowship_treasury_spend() { let teleport_call = RuntimeCall::Utility(pallet_utility::Call::::dispatch_as { as_origin: bx!(WestendOriginCaller::system(RawOrigin::Signed(treasury_account))), call: bx!(RuntimeCall::XcmPallet(pallet_xcm::Call::::teleport_assets { - dest: bx!(VersionedLocation::V4(asset_hub_location.clone())), - beneficiary: bx!(VersionedLocation::V4(treasury_location)), - assets: bx!(VersionedAssets::V4( - Asset { id: native_asset.clone().into(), fun: treasury_balance.into() }.into() - )), + dest: bx!(VersionedLocation::from(asset_hub_location.clone())), + beneficiary: bx!(VersionedLocation::from(treasury_location)), + assets: bx!(VersionedAssets::from(Assets::from(Asset { + id: native_asset.clone().into(), + fun: treasury_balance.into() + }))), fee_asset_item: 0, })), }); @@ -101,12 +102,12 @@ fn fellowship_treasury_spend() { let native_asset = Location::parent(); let treasury_spend_call = RuntimeCall::Treasury(pallet_treasury::Call::::spend { - asset_kind: bx!(VersionedLocatableAsset::V4 { - location: asset_hub_location.clone(), - asset_id: native_asset.into(), - }), + asset_kind: bx!(VersionedLocatableAsset::from(( + asset_hub_location.clone(), + native_asset.into() + ))), amount: fellowship_treasury_balance, - beneficiary: bx!(VersionedLocation::V4(fellowship_treasury_location)), + beneficiary: bx!(VersionedLocation::from(fellowship_treasury_location)), valid_from: None, }); @@ -179,12 +180,12 @@ fn fellowship_treasury_spend() { let fellowship_treasury_spend_call = RuntimeCall::FellowshipTreasury(pallet_treasury::Call::::spend { - asset_kind: bx!(VersionedLocatableAsset::V4 { - location: asset_hub_location, - asset_id: native_asset.into(), - }), + asset_kind: bx!(VersionedLocatableAsset::from(( + asset_hub_location, + native_asset.into() + ))), amount: fellowship_spend_balance, - beneficiary: bx!(VersionedLocation::V4(alice_location)), + beneficiary: bx!(VersionedLocation::from(alice_location)), valid_from: None, }); diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs index 055bd50d8298..d3fec4230368 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs @@ -20,7 +20,7 @@ mod imports { pub use frame_support::assert_ok; // Polkadot - pub use xcm::prelude::*; + pub use xcm::{latest::ROCOCO_GENESIS_HASH, prelude::*}; // Cumulus pub use emulated_integration_tests_common::xcm_emulator::{ diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs index e37b915174d3..bdab86f5cbf2 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = CoretimeRococoExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(CoretimeRococo, RuntimeCall, NetworkId::Rococo, assets, amount); + test_chain_can_claim_assets!( + CoretimeRococo, + RuntimeCall, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs index ac844e0f3284..4fb619aba3d3 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs @@ -20,7 +20,7 @@ mod imports { pub use frame_support::assert_ok; // Polkadot - pub use xcm::prelude::*; + pub use xcm::{latest::WESTEND_GENESIS_HASH, prelude::*}; // Cumulus pub use emulated_integration_tests_common::xcm_emulator::{ diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs index c8d853698444..3cabc3f8ac51 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = CoretimeWestendExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(CoretimeWestend, RuntimeCall, NetworkId::Westend, assets, amount); + test_chain_can_claim_assets!( + CoretimeWestend, + RuntimeCall, + NetworkId::ByGenesis(WESTEND_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs index 06b0b6ba6005..a95396d5070b 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs @@ -19,7 +19,7 @@ mod imports { pub use frame_support::{assert_ok, sp_runtime::DispatchResult, traits::fungibles::Inspect}; // Polkadot - pub use xcm::prelude::*; + pub use xcm::{latest::ROCOCO_GENESIS_HASH, prelude::*}; // Cumulus pub use asset_test_utils::xcm_helpers; diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs index 793200e1d06b..6795b1e7f397 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = PeopleRococoExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(PeopleRococo, RuntimeCall, NetworkId::Rococo, assets, amount); + test_chain_can_claim_assets!( + PeopleRococo, + RuntimeCall, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs index 418cfea07ddc..59d87e1ea3f0 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs @@ -19,7 +19,7 @@ mod imports { pub use frame_support::{assert_ok, sp_runtime::DispatchResult, traits::fungibles::Inspect}; // Polkadot - pub use xcm::prelude::*; + pub use xcm::{latest::WESTEND_GENESIS_HASH, prelude::*}; // Cumulus pub use asset_test_utils::xcm_helpers; diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs index 42ccc459286a..055c713abfd8 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs @@ -25,5 +25,11 @@ fn assets_can_be_claimed() { let amount = PeopleWestendExistentialDeposit::get(); let assets: Assets = (Parent, amount).into(); - test_chain_can_claim_assets!(PeopleWestend, RuntimeCall, NetworkId::Westend, assets, amount); + test_chain_can_claim_assets!( + PeopleWestend, + RuntimeCall, + NetworkId::ByGenesis(WESTEND_GENESIS_HASH), + assets, + amount + ); } diff --git a/cumulus/parachains/pallets/ping/src/lib.rs b/cumulus/parachains/pallets/ping/src/lib.rs index 729494cbd251..2cf32c891fc0 100644 --- a/cumulus/parachains/pallets/ping/src/lib.rs +++ b/cumulus/parachains/pallets/ping/src/lib.rs @@ -108,7 +108,6 @@ pub mod pallet { (Parent, Junction::Parachain(para.into())).into(), Xcm(vec![Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1_000, 1_000), call: ::RuntimeCall::from(Call::::ping { seq, payload: payload.clone().to_vec(), @@ -209,7 +208,6 @@ pub mod pallet { (Parent, Junction::Parachain(para.into())).into(), Xcm(vec![Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1_000, 1_000), call: ::RuntimeCall::from(Call::::pong { seq, payload: payload.clone(), diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index 474434448bb9..2f9d83bd9d0b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -330,11 +330,11 @@ pub type LocalAndForeignAssets = fungibles::UnionOf< Assets, ForeignAssets, LocalFromLeft< - AssetIdForTrustBackedAssetsConvert, + AssetIdForTrustBackedAssetsConvert, AssetIdForTrustBackedAssets, - xcm::v4::Location, + xcm::v5::Location, >, - xcm::v4::Location, + xcm::v5::Location, AccountId, >; @@ -342,21 +342,21 @@ pub type LocalAndForeignAssets = fungibles::UnionOf< pub type NativeAndAssets = fungible::UnionOf< Balances, LocalAndForeignAssets, - TargetFromLeft, - xcm::v4::Location, + TargetFromLeft, + xcm::v5::Location, AccountId, >; pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter< AssetConversionPalletId, - (xcm::v4::Location, xcm::v4::Location), + (xcm::v5::Location, xcm::v5::Location), >; impl pallet_asset_conversion::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type HigherPrecisionBalance = sp_core::U256; - type AssetKind = xcm::v4::Location; + type AssetKind = xcm::v5::Location; type Assets = NativeAndAssets; type PoolId = (Self::AssetKind, Self::AssetKind); type PoolLocator = pallet_asset_conversion::WithFirstAsset< @@ -381,7 +381,7 @@ impl pallet_asset_conversion::Config for Runtime { TokenLocation, parachain_info::Pallet, xcm_config::TrustBackedAssetsPalletIndex, - xcm::v4::Location, + xcm::v5::Location, >; } @@ -415,18 +415,18 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = xcm::v4::Location; - type AssetIdParameter = xcm::v4::Location; + type AssetId = xcm::v5::Location; + type AssetIdParameter = xcm::v5::Location; type Currency = Balances; type CreateOrigin = ForeignCreators< ( - FromSiblingParachain, xcm::v4::Location>, - FromNetwork, + FromSiblingParachain, xcm::v5::Location>, + FromNetwork, xcm_config::bridging::to_westend::WestendOrEthereumAssetFromAssetHubWestend, ), LocationToAccountId, AccountId, - xcm::v4::Location, + xcm::v5::Location, >; type ForceOrigin = AssetsForceOrigin; type AssetDeposit = ForeignAssetsAssetDeposit; @@ -813,7 +813,7 @@ parameter_types! { impl pallet_asset_conversion_tx_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type AssetId = xcm::v4::Location; + type AssetId = xcm::v5::Location; type OnChargeAssetTransaction = SwapAssetAdapter< TokenLocation, NativeAndAssets, @@ -1308,16 +1308,16 @@ impl_runtime_apis! { impl pallet_asset_conversion::AssetConversionApi< Block, Balance, - xcm::v4::Location, + xcm::v5::Location, > for Runtime { - fn quote_price_exact_tokens_for_tokens(asset1: xcm::v4::Location, asset2: xcm::v4::Location, amount: Balance, include_fee: bool) -> Option { + fn quote_price_exact_tokens_for_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option { AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) } - fn quote_price_tokens_for_exact_tokens(asset1: xcm::v4::Location, asset2: xcm::v4::Location, amount: Balance, include_fee: bool) -> Option { + fn quote_price_tokens_for_exact_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option { AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) } - fn get_reserves(asset1: xcm::v4::Location, asset2: xcm::v4::Location) -> Option<(Balance, Balance)> { + fn get_reserves(asset1: xcm::v5::Location, asset2: xcm::v5::Location) -> Option<(Balance, Balance)> { AssetConversion::get_reserves(asset1, asset2).ok() } } @@ -1414,7 +1414,7 @@ impl_runtime_apis! { // We also accept all assets in a pool with the native token. let assets_in_pool_with_native = assets_common::get_assets_in_pool_with::< Runtime, - xcm::v4::Location + xcm::v5::Location >(&native_token).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?.into_iter(); acceptable_assets.extend(assets_in_pool_with_native); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -1431,7 +1431,7 @@ impl_runtime_apis! { Ok(asset_id) => { let assets_in_pool_with_this_asset: Vec<_> = assets_common::get_assets_in_pool_with::< Runtime, - xcm::v4::Location + xcm::v5::Location >(&asset_id.0).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?; if assets_in_pool_with_this_asset .into_iter() @@ -1834,7 +1834,12 @@ impl_runtime_apis! { } fn alias_origin() -> Result<(Location, Location), BenchmarkError> { - Err(BenchmarkError::Skip) + // Any location can alias to an internal location. + // Here parachain 1001 aliases to an internal account. + Ok(( + Location::new(1, [Parachain(1001)]), + Location::new(1, [Parachain(1001), AccountId32 { id: [111u8; 32], network: None }]), + )) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs index 8c52ecd9f1b1..bf374fc415ce 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs @@ -22,7 +22,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -81,11 +84,7 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -132,12 +131,35 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -150,6 +172,9 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } @@ -223,8 +248,7 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { XcmGeneric::::clear_topic() } fn alias_origin(_: &Location) -> Weight { - // XCM Executor does not currently support alias origin operations - Weight::MAX + XcmGeneric::::alias_origin() } fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 7478ba8893c1..a2169e2ea04b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-25, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wmcgzesc-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 34_364_000 picoseconds. - Weight::from_parts(35_040_000, 3593) + // Minimum execution time: 33_878_000 picoseconds. + Weight::from_parts(34_766_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 42_755_000 picoseconds. - Weight::from_parts(43_650_000, 6196) + // Minimum execution time: 42_776_000 picoseconds. + Weight::from_parts(43_643_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -90,8 +90,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `8799` - // Minimum execution time: 103_037_000 picoseconds. - Weight::from_parts(105_732_000, 8799) + // Minimum execution time: 104_654_000 picoseconds. + Weight::from_parts(106_518_000, 8799) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -99,8 +99,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_095_000 picoseconds. - Weight::from_parts(1_220_000, 0) + // Minimum execution time: 1_183_000 picoseconds. + Weight::from_parts(1_309_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -122,8 +122,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 108_117_000 picoseconds. - Weight::from_parts(110_416_000, 6196) + // Minimum execution time: 112_272_000 picoseconds. + Weight::from_parts(114_853_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -131,8 +131,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_907_000 picoseconds. - Weight::from_parts(3_050_000, 0) + // Minimum execution time: 2_769_000 picoseconds. + Weight::from_parts(2_916_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -140,8 +140,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 24_965_000 picoseconds. - Weight::from_parts(25_687_000, 3593) + // Minimum execution time: 26_145_000 picoseconds. + Weight::from_parts(26_589_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -165,8 +165,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `6196` - // Minimum execution time: 83_312_000 picoseconds. - Weight::from_parts(85_463_000, 6196) + // Minimum execution time: 85_446_000 picoseconds. + Weight::from_parts(88_146_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -190,9 +190,34 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 49_874_000 picoseconds. - Weight::from_parts(51_165_000, 3610) + // Minimum execution time: 55_060_000 picoseconds. + Weight::from_parts(56_120_000, 3610) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + // Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `6196` + // Minimum execution time: 90_870_000 picoseconds. + Weight::from_parts(93_455_000, 6196) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) + } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index f6a883c03e9d..ef08b432e5c7 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-25, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wmcgzesc-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 99_552_000 picoseconds. - Weight::from_parts(101_720_000, 6196) + // Minimum execution time: 103_506_000 picoseconds. + Weight::from_parts(106_039_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 659_000 picoseconds. - Weight::from_parts(706_000, 0) + // Minimum execution time: 668_000 picoseconds. + Weight::from_parts(743_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_803_000 picoseconds. + Weight::from_parts(5_983_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 644_000 picoseconds. + Weight::from_parts(684_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +100,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `3568` - // Minimum execution time: 9_665_000 picoseconds. - Weight::from_parts(9_878_000, 3568) + // Minimum execution time: 9_957_000 picoseconds. + Weight::from_parts(10_163_000, 3568) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_959_000 picoseconds. - Weight::from_parts(7_111_000, 0) + // Minimum execution time: 6_663_000 picoseconds. + Weight::from_parts(7_134_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_682_000 picoseconds. - Weight::from_parts(2_799_000, 0) + // Minimum execution time: 3_067_000 picoseconds. + Weight::from_parts(3_175_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 656_000 picoseconds. - Weight::from_parts(683_000, 0) + // Minimum execution time: 650_000 picoseconds. + Weight::from_parts(691_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 687_000 picoseconds. - Weight::from_parts(719_000, 0) + // Minimum execution time: 669_000 picoseconds. + Weight::from_parts(703_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 588_000 picoseconds. - Weight::from_parts(653_000, 0) + // Minimum execution time: 649_000 picoseconds. + Weight::from_parts(691_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` // Minimum execution time: 690_000 picoseconds. - Weight::from_parts(714_000, 0) + Weight::from_parts(735_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 671_000 picoseconds. - Weight::from_parts(710_000, 0) + // Minimum execution time: 681_000 picoseconds. + Weight::from_parts(735_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +173,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 67_374_000 picoseconds. - Weight::from_parts(68_899_000, 6196) + // Minimum execution time: 68_877_000 picoseconds. + Weight::from_parts(69_996_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +184,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `160` // Estimated: `3625` - // Minimum execution time: 12_896_000 picoseconds. - Weight::from_parts(13_191_000, 3625) + // Minimum execution time: 13_276_000 picoseconds. + Weight::from_parts(13_586_000, 3625) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +193,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 634_000 picoseconds. - Weight::from_parts(677_000, 0) + // Minimum execution time: 659_000 picoseconds. + Weight::from_parts(721_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +214,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 28_197_000 picoseconds. - Weight::from_parts(28_752_000, 3610) + // Minimum execution time: 28_656_000 picoseconds. + Weight::from_parts(29_175_000, 3610) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +225,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_678_000 picoseconds. - Weight::from_parts(2_803_000, 0) + // Minimum execution time: 2_608_000 picoseconds. + Weight::from_parts(2_876_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 22_806_000 picoseconds. - Weight::from_parts(23_217_000, 0) + // Minimum execution time: 24_035_000 picoseconds. + Weight::from_parts(24_315_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_221_000 picoseconds. - Weight::from_parts(6_347_000, 0) + // Minimum execution time: 6_558_000 picoseconds. + Weight::from_parts(6_711_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 653_000 picoseconds. - Weight::from_parts(676_000, 0) + // Minimum execution time: 645_000 picoseconds. + Weight::from_parts(700_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 621_000 picoseconds. - Weight::from_parts(678_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(696_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 770_000 picoseconds. - Weight::from_parts(829_000, 0) + // Minimum execution time: 787_000 picoseconds. + Weight::from_parts(866_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +284,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 71_654_000 picoseconds. - Weight::from_parts(73_329_000, 6196) + // Minimum execution time: 75_093_000 picoseconds. + Weight::from_parts(76_165_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +293,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_999_000 picoseconds. - Weight::from_parts(4_179_000, 0) + // Minimum execution time: 4_304_000 picoseconds. + Weight::from_parts(4_577_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +316,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 66_722_000 picoseconds. - Weight::from_parts(68_812_000, 6196) + // Minimum execution time: 68_809_000 picoseconds. + Weight::from_parts(70_037_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +325,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 718_000 picoseconds. - Weight::from_parts(745_000, 0) + // Minimum execution time: 715_000 picoseconds. + Weight::from_parts(766_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 623_000 picoseconds. - Weight::from_parts(682_000, 0) + // Minimum execution time: 639_000 picoseconds. + Weight::from_parts(688_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 664_000 picoseconds. - Weight::from_parts(696_000, 0) + // Minimum execution time: 638_000 picoseconds. + Weight::from_parts(712_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -334,22 +348,29 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `1489` - // Minimum execution time: 2_495_000 picoseconds. - Weight::from_parts(2_604_000, 1489) + // Minimum execution time: 2_521_000 picoseconds. + Weight::from_parts(2_715_000, 1489) .saturating_add(T::DbWeight::get().reads(1)) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 645_000 picoseconds. - Weight::from_parts(673_000, 0) + // Minimum execution time: 619_000 picoseconds. + Weight::from_parts(692_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 643_000 picoseconds. - Weight::from_parts(701_000, 0) + // Minimum execution time: 665_000 picoseconds. + Weight::from_parts(716_000, 0) + } + pub fn alias_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 668_000 picoseconds. + Weight::from_parts(726_000, 0) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 56310959aa80..66743fa3a07e 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -28,7 +28,7 @@ use frame_support::{ parameter_types, traits::{ tokens::imbalance::{ResolveAssetTo, ResolveTo}, - ConstU32, Contains, Equals, Everything, Nothing, PalletInfoAccess, + ConstU32, Contains, Equals, Everything, PalletInfoAccess, }, }; use frame_system::EnsureRoot; @@ -47,26 +47,27 @@ use sp_runtime::traits::{AccountIdConversion, ConvertInto, TryConvertInto}; use testnet_parachains_constants::rococo::snowbridge::{ EthereumNetwork, INBOUND_QUEUE_PALLET_INDEX, }; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, - GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, - MatchedConvertedConcreteId, NetworkExportTableItem, NoChecking, NonFungiblesAdapter, - ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SingleAssetExchangeAdapter, SovereignPaidRemoteExporter, - SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, - WithLatestLocationConverter, WithUniqueTopic, XcmFeeManagerFromComponents, + AccountId32Aliases, AliasChildLocation, AllowExplicitUnpaidExecutionFrom, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, + FungibleAdapter, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, + IsConcrete, LocalMint, MatchedConvertedConcreteId, NetworkExportTableItem, NoChecking, + NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SingleAssetExchangeAdapter, + SovereignPaidRemoteExporter, SovereignSignedViaLocation, StartsWith, + StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithLatestLocationConverter, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; parameter_types! { pub const TokenLocation: Location = Location::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Rococo; + pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); @@ -175,7 +176,7 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte StartsWithExplicitGlobalConsensus, ), Balance, - xcm::v4::Location, + xcm::v5::Location, >; /// Means for transacting foreign assets from different global consensus. @@ -335,14 +336,14 @@ pub type PoolAssetsExchanger = SingleAssetExchangeAdapter< crate::AssetConversion, crate::NativeAndAssets, ( - TrustBackedAssetsAsLocation, + TrustBackedAssetsAsLocation, ForeignAssetsConvertedConcreteId, // `ForeignAssetsConvertedConcreteId` excludes the relay token, so we add it back here. MatchedConvertedConcreteId< - xcm::v4::Location, + xcm::v5::Location, Balance, Equals, - WithLatestLocationConverter, + WithLatestLocationConverter, TryConvertInto, >, ), @@ -389,7 +390,7 @@ impl xcm_executor::Config for XcmConfig { TrustBackedAssetsAsLocation< TrustBackedAssetsPalletLocation, Balance, - xcm::v4::Location, + xcm::v5::Location, >, ForeignAssetsConvertedConcreteId, ), @@ -440,7 +441,8 @@ impl xcm_executor::Config for XcmConfig { (bridging::to_westend::UniversalAliases, bridging::to_ethereum::UniversalAliases); type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Nothing; + // We allow any origin to alias into a child sub-location (equivalent to DescendOrigin). + type Aliasers = AliasChildLocation; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -515,9 +517,9 @@ impl cumulus_pallet_xcm::Config for Runtime { /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> xcm::v4::Location { - xcm::v4::Location::new(1, [xcm::v4::Junction::Parachain(id)]) +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> xcm::v5::Location { + xcm::v5::Location::new(1, [xcm::v5::Junction::Parachain(id)]) } } @@ -581,7 +583,7 @@ pub mod bridging { ] ); - pub const WestendNetwork: NetworkId = NetworkId::Westend; + pub const WestendNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub const EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 }; pub WestendEcosystem: Location = Location::new(2, [GlobalConsensus(WestendNetwork::get())]); pub EthereumEcosystem: Location = Location::new(2, [GlobalConsensus(EthereumNetwork::get())]); @@ -652,7 +654,7 @@ pub mod bridging { /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: alloc::vec::Vec = alloc::vec![ NetworkExportTableItem::new( - EthereumNetwork::get(), + EthereumNetwork::get().into(), Some(alloc::vec![Junctions::Here]), SiblingBridgeHub::get(), Some(( @@ -665,7 +667,7 @@ pub mod bridging { /// Universal aliases pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( alloc::vec![ - (SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get())), + (SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get().into())), ] ); } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs index 814323135325..5da8b45417a3 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs @@ -1078,6 +1078,7 @@ fn limited_reserve_transfer_assets_for_native_asset_over_bridge_works( mod asset_hub_rococo_tests { use super::*; use asset_hub_rococo_runtime::PolkadotXcm; + use xcm::latest::WESTEND_GENESIS_HASH; use xcm_executor::traits::ConvertLocation; fn bridging_to_asset_hub_westend() -> TestBridgingConfig { @@ -1108,8 +1109,10 @@ mod asset_hub_rococo_tests { let block_author_account = AccountId::from(BLOCK_AUTHOR_ACCOUNT); let staking_pot = StakingPot::get(); - let foreign_asset_id_location = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Westend)]); + let foreign_asset_id_location = Location::new( + 2, + [Junction::GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH))], + ); let foreign_asset_id_minimum_balance = 1_000_000_000; // sovereign account as foreign asset owner (can be whoever for this scenario) let foreign_asset_owner = @@ -1143,7 +1146,7 @@ mod asset_hub_rococo_tests { }, ( [PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)].into(), - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), [Parachain(1000)].into() ), || { @@ -1182,8 +1185,10 @@ mod asset_hub_rococo_tests { let block_author_account = AccountId::from(BLOCK_AUTHOR_ACCOUNT); let staking_pot = StakingPot::get(); - let foreign_asset_id_location = - Location::new(2, [Junction::GlobalConsensus(NetworkId::Westend)]); + let foreign_asset_id_location = Location::new( + 2, + [Junction::GlobalConsensus(NetworkId::ByGenesis(WESTEND_GENESIS_HASH))], + ); let foreign_asset_id_minimum_balance = 1_000_000_000; // sovereign account as foreign asset owner (can be whoever for this scenario) let foreign_asset_owner = @@ -1210,7 +1215,7 @@ mod asset_hub_rococo_tests { bridging_to_asset_hub_westend, ( [PalletInstance(bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX)].into(), - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), [Parachain(1000)].into() ), || { 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 7261680677d4..63175222cc26 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -332,11 +332,11 @@ pub type LocalAndForeignAssets = fungibles::UnionOf< Assets, ForeignAssets, LocalFromLeft< - AssetIdForTrustBackedAssetsConvert, + AssetIdForTrustBackedAssetsConvert, AssetIdForTrustBackedAssets, - xcm::v4::Location, + xcm::v5::Location, >, - xcm::v4::Location, + xcm::v5::Location, AccountId, >; @@ -344,21 +344,21 @@ pub type LocalAndForeignAssets = fungibles::UnionOf< pub type NativeAndAssets = fungible::UnionOf< Balances, LocalAndForeignAssets, - TargetFromLeft, - xcm::v4::Location, + TargetFromLeft, + xcm::v5::Location, AccountId, >; pub type PoolIdToAccountId = pallet_asset_conversion::AccountIdConverter< AssetConversionPalletId, - (xcm::v4::Location, xcm::v4::Location), + (xcm::v5::Location, xcm::v5::Location), >; impl pallet_asset_conversion::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type HigherPrecisionBalance = sp_core::U256; - type AssetKind = xcm::v4::Location; + type AssetKind = xcm::v5::Location; type Assets = NativeAndAssets; type PoolId = (Self::AssetKind, Self::AssetKind); type PoolLocator = pallet_asset_conversion::WithFirstAsset< @@ -383,7 +383,7 @@ impl pallet_asset_conversion::Config for Runtime { WestendLocation, parachain_info::Pallet, xcm_config::TrustBackedAssetsPalletIndex, - xcm::v4::Location, + xcm::v5::Location, >; } @@ -417,18 +417,18 @@ pub type ForeignAssetsInstance = pallet_assets::Instance2; impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; - type AssetId = xcm::v4::Location; - type AssetIdParameter = xcm::v4::Location; + type AssetId = xcm::v5::Location; + type AssetIdParameter = xcm::v5::Location; type Currency = Balances; type CreateOrigin = ForeignCreators< ( - FromSiblingParachain, xcm::v4::Location>, - FromNetwork, + FromSiblingParachain, xcm::v5::Location>, + FromNetwork, xcm_config::bridging::to_rococo::RococoAssetFromAssetHubRococo, ), LocationToAccountId, AccountId, - xcm::v4::Location, + xcm::v5::Location, >; type ForceOrigin = AssetsForceOrigin; type AssetDeposit = ForeignAssetsAssetDeposit; @@ -810,7 +810,7 @@ parameter_types! { impl pallet_asset_conversion_tx_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type AssetId = xcm::v4::Location; + type AssetId = xcm::v5::Location; type OnChargeAssetTransaction = SwapAssetAdapter< WestendLocation, NativeAndAssets, @@ -1485,18 +1485,18 @@ impl_runtime_apis! { impl pallet_asset_conversion::AssetConversionApi< Block, Balance, - xcm::v4::Location, + xcm::v5::Location, > for Runtime { - fn quote_price_exact_tokens_for_tokens(asset1: xcm::v4::Location, asset2: xcm::v4::Location, amount: Balance, include_fee: bool) -> Option { + fn quote_price_exact_tokens_for_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option { AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) } - fn quote_price_tokens_for_exact_tokens(asset1: xcm::v4::Location, asset2: xcm::v4::Location, amount: Balance, include_fee: bool) -> Option { + fn quote_price_tokens_for_exact_tokens(asset1: xcm::v5::Location, asset2: xcm::v5::Location, amount: Balance, include_fee: bool) -> Option { AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) } - fn get_reserves(asset1: xcm::v4::Location, asset2: xcm::v4::Location) -> Option<(Balance, Balance)> { + fn get_reserves(asset1: xcm::v5::Location, asset2: xcm::v5::Location) -> Option<(Balance, Balance)> { AssetConversion::get_reserves(asset1, asset2).ok() } } @@ -1530,7 +1530,7 @@ impl_runtime_apis! { // We also accept all assets in a pool with the native token. let assets_in_pool_with_native = assets_common::get_assets_in_pool_with::< Runtime, - xcm::v4::Location + xcm::v5::Location >(&native_token).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?.into_iter(); acceptable_assets.extend(assets_in_pool_with_native); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -1548,7 +1548,7 @@ impl_runtime_apis! { // We recognize assets in a pool with the native one. let assets_in_pool_with_this_asset: Vec<_> = assets_common::get_assets_in_pool_with::< Runtime, - xcm::v4::Location + xcm::v5::Location >(&asset_id.0).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?; if assets_in_pool_with_this_asset .into_iter() @@ -2000,7 +2000,7 @@ impl_runtime_apis! { fn fee_asset() -> Result { Ok(Asset { id: AssetId(WestendLocation::get()), - fun: Fungible(1_000_000 * UNITS), + fun: Fungible(1_000 * UNITS), }) } @@ -2014,7 +2014,12 @@ impl_runtime_apis! { } fn alias_origin() -> Result<(Location, Location), BenchmarkError> { - Err(BenchmarkError::Skip) + // Any location can alias to an internal location. + // Here parachain 1001 aliases to an internal account. + Ok(( + Location::new(1, [Parachain(1001)]), + Location::new(1, [Parachain(1001), AccountId32 { id: [111u8; 32], network: None }]), + )) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs index d39052c5c03b..928f1910cbd2 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs @@ -21,7 +21,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -80,11 +83,7 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -132,12 +131,35 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -150,6 +172,9 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } @@ -223,8 +248,7 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { XcmGeneric::::clear_topic() } fn alias_origin(_: &Location) -> Weight { - // XCM Executor does not currently support alias origin operations - Weight::MAX + XcmGeneric::::alias_origin() } fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 0aeae3184627..97e59c24dd89 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-25, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wmcgzesc-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 32_651_000 picoseconds. - Weight::from_parts(33_225_000, 3593) + // Minimum execution time: 32_698_000 picoseconds. + Weight::from_parts(33_530_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 41_059_000 picoseconds. - Weight::from_parts(41_730_000, 6196) + // Minimum execution time: 41_485_000 picoseconds. + Weight::from_parts(41_963_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -90,8 +90,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `8799` - // Minimum execution time: 102_780_000 picoseconds. - Weight::from_parts(105_302_000, 8799) + // Minimum execution time: 104_952_000 picoseconds. + Weight::from_parts(108_211_000, 8799) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -99,8 +99,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_124_000 picoseconds. - Weight::from_parts(1_201_000, 0) + // Minimum execution time: 1_154_000 picoseconds. + Weight::from_parts(1_238_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -122,8 +122,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 109_024_000 picoseconds. - Weight::from_parts(111_406_000, 6196) + // Minimum execution time: 111_509_000 picoseconds. + Weight::from_parts(114_476_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -131,8 +131,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_887_000 picoseconds. - Weight::from_parts(3_081_000, 0) + // Minimum execution time: 2_572_000 picoseconds. + Weight::from_parts(2_809_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -140,8 +140,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 25_234_000 picoseconds. - Weight::from_parts(25_561_000, 3593) + // Minimum execution time: 25_570_000 picoseconds. + Weight::from_parts(25_933_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -165,8 +165,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `6196` - // Minimum execution time: 83_416_000 picoseconds. - Weight::from_parts(85_683_000, 6196) + // Minimum execution time: 86_148_000 picoseconds. + Weight::from_parts(88_170_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -190,9 +190,34 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 49_271_000 picoseconds. - Weight::from_parts(51_019_000, 3610) + // Minimum execution time: 55_051_000 picoseconds. + Weight::from_parts(56_324_000, 3610) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + // Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `6196` + // Minimum execution time: 90_155_000 picoseconds. + Weight::from_parts(91_699_000, 6196) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) + } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 98ecd7bd3092..7098f175d421 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-25, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wmcgzesc-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 100_823_000 picoseconds. - Weight::from_parts(103_071_000, 6196) + // Minimum execution time: 103_794_000 picoseconds. + Weight::from_parts(106_697_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 600_000 picoseconds. - Weight::from_parts(686_000, 0) + // Minimum execution time: 621_000 picoseconds. + Weight::from_parts(705_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_580_000 picoseconds. + Weight::from_parts(5_950_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 598_000 picoseconds. + Weight::from_parts(700_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +100,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `3568` - // Minimum execution time: 8_226_000 picoseconds. - Weight::from_parts(8_650_000, 3568) + // Minimum execution time: 8_186_000 picoseconds. + Weight::from_parts(8_753_000, 3568) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_131_000 picoseconds. - Weight::from_parts(7_600_000, 0) + // Minimum execution time: 6_924_000 picoseconds. + Weight::from_parts(7_315_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_589_000 picoseconds. - Weight::from_parts(2_705_000, 0) + // Minimum execution time: 2_731_000 picoseconds. + Weight::from_parts(2_828_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 667_000 picoseconds. - Weight::from_parts(744_000, 0) + // Minimum execution time: 655_000 picoseconds. + Weight::from_parts(723_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 646_000 picoseconds. - Weight::from_parts(720_000, 0) + // Minimum execution time: 648_000 picoseconds. + Weight::from_parts(730_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 633_000 picoseconds. - Weight::from_parts(669_000, 0) + // Minimum execution time: 628_000 picoseconds. + Weight::from_parts(697_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 671_000 picoseconds. - Weight::from_parts(726_000, 0) + // Minimum execution time: 714_000 picoseconds. + Weight::from_parts(775_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 615_000 picoseconds. - Weight::from_parts(675_000, 0) + // Minimum execution time: 666_000 picoseconds. + Weight::from_parts(717_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +173,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 67_236_000 picoseconds. - Weight::from_parts(69_899_000, 6196) + // Minimum execution time: 70_263_000 picoseconds. + Weight::from_parts(71_266_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +184,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `160` // Estimated: `3625` - // Minimum execution time: 12_976_000 picoseconds. - Weight::from_parts(13_357_000, 3625) + // Minimum execution time: 13_079_000 picoseconds. + Weight::from_parts(13_569_000, 3625) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +193,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 633_000 picoseconds. - Weight::from_parts(685_000, 0) + // Minimum execution time: 630_000 picoseconds. + Weight::from_parts(710_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +214,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 28_707_000 picoseconds. - Weight::from_parts(31_790_000, 3610) + // Minimum execution time: 29_042_000 picoseconds. + Weight::from_parts(29_633_000, 3610) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +225,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_670_000 picoseconds. - Weight::from_parts(2_833_000, 0) + // Minimum execution time: 2_601_000 picoseconds. + Weight::from_parts(2_855_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 23_459_000 picoseconds. - Weight::from_parts(23_817_000, 0) + // Minimum execution time: 23_696_000 picoseconds. + Weight::from_parts(24_427_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_197_000 picoseconds. - Weight::from_parts(6_338_000, 0) + // Minimum execution time: 6_687_000 picoseconds. + Weight::from_parts(6_820_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 671_000 picoseconds. - Weight::from_parts(715_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(728_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 655_000 picoseconds. - Weight::from_parts(694_000, 0) + // Minimum execution time: 668_000 picoseconds. + Weight::from_parts(721_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 810_000 picoseconds. - Weight::from_parts(858_000, 0) + // Minimum execution time: 832_000 picoseconds. + Weight::from_parts(900_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +284,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 73_136_000 picoseconds. - Weight::from_parts(75_314_000, 6196) + // Minimum execution time: 75_131_000 picoseconds. + Weight::from_parts(77_142_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +293,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_515_000 picoseconds. - Weight::from_parts(4_768_000, 0) + // Minimum execution time: 4_820_000 picoseconds. + Weight::from_parts(5_089_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +316,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `246` // Estimated: `6196` - // Minimum execution time: 68_072_000 picoseconds. - Weight::from_parts(69_866_000, 6196) + // Minimum execution time: 70_079_000 picoseconds. + Weight::from_parts(71_762_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +325,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 696_000 picoseconds. - Weight::from_parts(736_000, 0) + // Minimum execution time: 722_000 picoseconds. + Weight::from_parts(784_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 618_000 picoseconds. - Weight::from_parts(681_000, 0) + // Minimum execution time: 613_000 picoseconds. + Weight::from_parts(674_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 647_000 picoseconds. - Weight::from_parts(672_000, 0) + // Minimum execution time: 608_000 picoseconds. + Weight::from_parts(683_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -334,22 +348,29 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `1489` - // Minimum execution time: 2_496_000 picoseconds. - Weight::from_parts(2_617_000, 1489) + // Minimum execution time: 2_466_000 picoseconds. + Weight::from_parts(2_705_000, 1489) .saturating_add(T::DbWeight::get().reads(1)) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 637_000 picoseconds. - Weight::from_parts(675_000, 0) + // Minimum execution time: 623_000 picoseconds. + Weight::from_parts(687_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 607_000 picoseconds. - Weight::from_parts(683_000, 0) + // Minimum execution time: 673_000 picoseconds. + Weight::from_parts(752_000, 0) + } + pub fn alias_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 638_000 picoseconds. + Weight::from_parts(708_000, 0) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index f16dbcc02519..88ccd42dff7f 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -28,7 +28,7 @@ use frame_support::{ parameter_types, traits::{ tokens::imbalance::{ResolveAssetTo, ResolveTo}, - ConstU32, Contains, Equals, Everything, Nothing, PalletInfoAccess, + ConstU32, Contains, Equals, Everything, PalletInfoAccess, }, }; use frame_system::EnsureRoot; @@ -44,26 +44,27 @@ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use snowbridge_router_primitives::inbound::EthereumLocationsConverterFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto, TryConvertInto}; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, - AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, - EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, - GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, - MatchedConvertedConcreteId, NetworkExportTableItem, NoChecking, NonFungiblesAdapter, - ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SingleAssetExchangeAdapter, SovereignPaidRemoteExporter, - SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, - WithLatestLocationConverter, WithUniqueTopic, XcmFeeManagerFromComponents, + AccountId32Aliases, AliasChildLocation, AllowExplicitUnpaidExecutionFrom, + AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, + AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, + DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, + FungibleAdapter, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, + IsConcrete, LocalMint, MatchedConvertedConcreteId, NetworkExportTableItem, NoChecking, + NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SingleAssetExchangeAdapter, + SovereignPaidRemoteExporter, SovereignSignedViaLocation, StartsWith, + StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithLatestLocationConverter, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; parameter_types! { pub const WestendLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Westend); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); @@ -171,7 +172,7 @@ pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConverte StartsWithExplicitGlobalConsensus, ), Balance, - xcm::v4::Location, + xcm::v5::Location, >; /// Means for transacting foreign assets from different global consensus. @@ -358,14 +359,14 @@ pub type PoolAssetsExchanger = SingleAssetExchangeAdapter< crate::AssetConversion, crate::NativeAndAssets, ( - TrustBackedAssetsAsLocation, + TrustBackedAssetsAsLocation, ForeignAssetsConvertedConcreteId, // `ForeignAssetsConvertedConcreteId` excludes the relay token, so we add it back here. MatchedConvertedConcreteId< - xcm::v4::Location, + xcm::v5::Location, Balance, Equals, - WithLatestLocationConverter, + WithLatestLocationConverter, TryConvertInto, >, ), @@ -411,7 +412,7 @@ impl xcm_executor::Config for XcmConfig { TrustBackedAssetsAsLocation< TrustBackedAssetsPalletLocation, Balance, - xcm::v4::Location, + xcm::v5::Location, >, ForeignAssetsConvertedConcreteId, ), @@ -462,7 +463,8 @@ impl xcm_executor::Config for XcmConfig { (bridging::to_rococo::UniversalAliases, bridging::to_ethereum::UniversalAliases); type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Nothing; + // We allow any origin to alias into a child sub-location (equivalent to DescendOrigin). + type Aliasers = AliasChildLocation; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); @@ -538,9 +540,9 @@ impl cumulus_pallet_xcm::Config for Runtime { /// Simple conversion of `u32` into an `AssetId` for use in benchmarking. pub struct XcmBenchmarkHelper; #[cfg(feature = "runtime-benchmarks")] -impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { - fn create_asset_id_parameter(id: u32) -> xcm::v4::Location { - xcm::v4::Location::new(1, [xcm::v4::Junction::Parachain(id)]) +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> xcm::v5::Location { + xcm::v5::Location::new(1, [xcm::v5::Junction::Parachain(id)]) } } @@ -596,7 +598,7 @@ pub mod bridging { ] ); - pub const RococoNetwork: NetworkId = NetworkId::Rococo; + pub const RococoNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RococoEcosystem: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get())]); pub RocLocation: Location = Location::new(2, [GlobalConsensus(RococoNetwork::get())]); pub AssetHubRococo: Location = Location::new(2, [ @@ -667,7 +669,7 @@ pub mod bridging { /// `Option` represents static "base fee" which is used for total delivery fee calculation. pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ NetworkExportTableItem::new( - EthereumNetwork::get(), + EthereumNetwork::get().into(), Some(sp_std::vec![Junctions::Here]), SiblingBridgeHub::get(), Some(( @@ -680,7 +682,7 @@ pub mod bridging { /// Universal aliases pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( sp_std::vec![ - (SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get())), + (SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get().into())), ] ); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index 6a48b19ce946..5d0f843554a1 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -52,7 +52,10 @@ use sp_core::crypto::Ss58Codec; use sp_runtime::traits::MaybeEquivalence; use std::{convert::Into, ops::Mul}; use testnet_parachains_constants::westend::{consensus::*, currency::UNITS, fee::WeightToFee}; -use xcm::latest::prelude::{Assets as XcmAssets, *}; +use xcm::latest::{ + prelude::{Assets as XcmAssets, *}, + ROCOCO_GENESIS_HASH, +}; use xcm_builder::WithLatestLocationConverter; use xcm_executor::traits::{ConvertLocation, JustTry, WeightTrader}; use xcm_runtime_apis::conversions::LocationToAccountHelper; @@ -87,7 +90,7 @@ fn slot_durations() -> SlotDurations { fn setup_pool_for_paying_fees_with_foreign_assets( (foreign_asset_owner, foreign_asset_id_location, foreign_asset_id_minimum_balance): ( AccountId, - xcm::v4::Location, + xcm::v5::Location, Balance, ), ) { @@ -95,7 +98,7 @@ fn setup_pool_for_paying_fees_with_foreign_assets( // setup a pool to pay fees with `foreign_asset_id_location` tokens let pool_owner: AccountId = [14u8; 32].into(); - let native_asset = xcm::v4::Location::parent(); + let native_asset = xcm::v5::Location::parent(); let pool_liquidity: Balance = existential_deposit.max(foreign_asset_id_minimum_balance).mul(100_000); @@ -220,10 +223,10 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() { assert_ok!(AssetConversion::create_pool( RuntimeHelper::origin_of(bob.clone()), Box::new( - xcm::v4::Location::try_from(native_location.clone()).expect("conversion works") + xcm::v5::Location::try_from(native_location.clone()).expect("conversion works") ), Box::new( - xcm::v4::Location::try_from(asset_1_location.clone()) + xcm::v5::Location::try_from(asset_1_location.clone()) .expect("conversion works") ) )); @@ -231,10 +234,10 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() { assert_ok!(AssetConversion::add_liquidity( RuntimeHelper::origin_of(bob.clone()), Box::new( - xcm::v4::Location::try_from(native_location.clone()).expect("conversion works") + xcm::v5::Location::try_from(native_location.clone()).expect("conversion works") ), Box::new( - xcm::v4::Location::try_from(asset_1_location.clone()) + xcm::v5::Location::try_from(asset_1_location.clone()) .expect("conversion works") ), pool_liquidity, @@ -272,8 +275,8 @@ fn test_buy_and_refund_weight_with_swap_local_asset_xcm_trader() { let refund_weight = Weight::from_parts(1_000_000_000, 0); let refund = WeightToFee::weight_to_fee(&refund_weight); let (reserve1, reserve2) = AssetConversion::get_reserves( - xcm::v4::Location::try_from(native_location).expect("conversion works"), - xcm::v4::Location::try_from(asset_1_location.clone()).expect("conversion works"), + xcm::v5::Location::try_from(native_location).expect("conversion works"), + xcm::v5::Location::try_from(asset_1_location.clone()).expect("conversion works"), ) .unwrap(); let asset_refund = @@ -311,12 +314,12 @@ fn test_buy_and_refund_weight_with_swap_foreign_asset_xcm_trader() { let bob: AccountId = SOME_ASSET_ADMIN.into(); let staking_pot = CollatorSelection::account_id(); let native_location = - xcm::v4::Location::try_from(WestendLocation::get()).expect("conversion works"); - let foreign_location = xcm::v4::Location { + xcm::v5::Location::try_from(WestendLocation::get()).expect("conversion works"); + let foreign_location = xcm::v5::Location { parents: 1, interior: ( - xcm::v4::Junction::Parachain(1234), - xcm::v4::Junction::GeneralIndex(12345), + xcm::v5::Junction::Parachain(1234), + xcm::v5::Junction::GeneralIndex(12345), ) .into(), }; @@ -498,11 +501,11 @@ fn test_foreign_asset_xcm_take_first_trader() { .execute_with(|| { // We need root origin to create a sufficient asset let minimum_asset_balance = 3333333_u128; - let foreign_location = xcm::v4::Location { + let foreign_location = xcm::v5::Location { parents: 1, interior: ( - xcm::v4::Junction::Parachain(1234), - xcm::v4::Junction::GeneralIndex(12345), + xcm::v5::Junction::Parachain(1234), + xcm::v5::Junction::GeneralIndex(12345), ) .into(), }; @@ -522,7 +525,7 @@ fn test_foreign_asset_xcm_take_first_trader() { minimum_asset_balance )); - let asset_location_v4: Location = foreign_location.clone().try_into().unwrap(); + let asset_location_v5: Location = foreign_location.clone().try_into().unwrap(); // Set Alice as block author, who will receive fees RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); @@ -537,7 +540,7 @@ fn test_foreign_asset_xcm_take_first_trader() { // Lets pay with: asset_amount_needed + asset_amount_extra let asset_amount_extra = 100_u128; let asset: Asset = - (asset_location_v4.clone(), asset_amount_needed + asset_amount_extra).into(); + (asset_location_v5.clone(), asset_amount_needed + asset_amount_extra).into(); let mut trader = ::Trader::new(); let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; @@ -546,7 +549,7 @@ fn test_foreign_asset_xcm_take_first_trader() { let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); // Check whether a correct amount of unused assets is returned assert_ok!( - unused_assets.ensure_contains(&(asset_location_v4, asset_amount_extra).into()) + unused_assets.ensure_contains(&(asset_location_v5, asset_amount_extra).into()) ); // Drop trader @@ -834,11 +837,11 @@ fn test_assets_balances_api_works() { .build() .execute_with(|| { let local_asset_id = 1; - let foreign_asset_id_location = xcm::v4::Location { + let foreign_asset_id_location = xcm::v5::Location { parents: 1, interior: [ - xcm::v4::Junction::Parachain(1234), - xcm::v4::Junction::GeneralIndex(12345), + xcm::v5::Junction::Parachain(1234), + xcm::v5::Junction::GeneralIndex(12345), ] .into(), }; @@ -929,7 +932,7 @@ fn test_assets_balances_api_works() { .into()))); // check foreign asset assert!(result.inner().iter().any(|asset| asset.eq(&( - WithLatestLocationConverter::::convert_back( + WithLatestLocationConverter::::convert_back( &foreign_asset_id_location ) .unwrap(), @@ -1022,13 +1025,13 @@ asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_ Runtime, XcmConfig, ForeignAssetsInstance, - xcm::v4::Location, + xcm::v5::Location, JustTry, collator_session_keys(), ExistentialDeposit::get(), - xcm::v4::Location { + xcm::v5::Location { parents: 1, - interior: [xcm::v4::Junction::Parachain(1313), xcm::v4::Junction::GeneralIndex(12345)] + interior: [xcm::v5::Junction::Parachain(1313), xcm::v5::Junction::GeneralIndex(12345)] .into() }, Box::new(|| { @@ -1045,8 +1048,8 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p WeightToFee, LocationToAccountId, ForeignAssetsInstance, - xcm::v4::Location, - WithLatestLocationConverter, + xcm::v5::Location, + WithLatestLocationConverter, collator_session_keys(), ExistentialDeposit::get(), AssetDeposit::get(), @@ -1123,8 +1126,10 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_fees_paid_by_pool_s let block_author_account = AccountId::from(BLOCK_AUTHOR_ACCOUNT); let staking_pot = StakingPot::get(); - let foreign_asset_id_location = - xcm::v4::Location::new(2, [xcm::v4::Junction::GlobalConsensus(xcm::v4::NetworkId::Rococo)]); + let foreign_asset_id_location = xcm::v5::Location::new( + 2, + [xcm::v5::Junction::GlobalConsensus(xcm::v5::NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))], + ); let foreign_asset_id_minimum_balance = 1_000_000_000; // sovereign account as foreign asset owner (can be whoever for this scenario) let foreign_asset_owner = LocationToAccountId::convert_location(&Location::parent()).unwrap(); @@ -1154,7 +1159,7 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_fees_paid_by_pool_s }, ( [PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)].into(), - GlobalConsensus(Rococo), + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), [Parachain(1000)].into() ), || { @@ -1192,8 +1197,10 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_fees_paid_by_suffic let block_author_account = AccountId::from(BLOCK_AUTHOR_ACCOUNT); let staking_pot = StakingPot::get(); - let foreign_asset_id_location = - xcm::v4::Location::new(2, [xcm::v4::Junction::GlobalConsensus(xcm::v4::NetworkId::Rococo)]); + let foreign_asset_id_location = xcm::v5::Location::new( + 2, + [xcm::v5::Junction::GlobalConsensus(xcm::v5::NetworkId::ByGenesis(ROCOCO_GENESIS_HASH))], + ); let foreign_asset_id_minimum_balance = 1_000_000_000; // sovereign account as foreign asset owner (can be whoever for this scenario) let foreign_asset_owner = LocationToAccountId::convert_location(&Location::parent()).unwrap(); @@ -1216,7 +1223,7 @@ fn receive_reserve_asset_deposited_roc_from_asset_hub_rococo_fees_paid_by_suffic bridging_to_asset_hub_rococo, ( [PalletInstance(bp_bridge_hub_westend::WITH_BRIDGE_WESTEND_TO_ROCOCO_MESSAGES_PALLET_INDEX)].into(), - GlobalConsensus(Rococo), + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), [Parachain(1000)].into() ), || { diff --git a/cumulus/parachains/runtimes/assets/common/src/lib.rs b/cumulus/parachains/runtimes/assets/common/src/lib.rs index 26046e5974b5..1d2d45b42c5d 100644 --- a/cumulus/parachains/runtimes/assets/common/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/common/src/lib.rs @@ -293,15 +293,15 @@ mod tests { pub UniversalLocationNetworkId: NetworkId = NetworkId::ByGenesis([9; 32]); } - // set up a converter which uses `xcm::v3::Location` under the hood + // set up a converter which uses `xcm::v4::Location` under the hood type Convert = ForeignAssetsConvertedConcreteId< ( StartsWith, StartsWithExplicitGlobalConsensus, ), u128, - xcm::v3::Location, - WithLatestLocationConverter, + xcm::v4::Location, + WithLatestLocationConverter, >; let test_data = vec![ @@ -348,18 +348,18 @@ mod tests { // ok ( ma_1000(1, [Parachain(200)].into()), - Ok((xcm::v3::Location::new(1, [xcm::v3::Junction::Parachain(200)]), 1000)), + Ok((xcm::v4::Location::new(1, [xcm::v4::Junction::Parachain(200)]), 1000)), ), ( ma_1000(2, [Parachain(200)].into()), - Ok((xcm::v3::Location::new(2, [xcm::v3::Junction::Parachain(200)]), 1000)), + Ok((xcm::v4::Location::new(2, [xcm::v4::Junction::Parachain(200)]), 1000)), ), ( ma_1000(1, [Parachain(200), GeneralIndex(1234)].into()), Ok(( - xcm::v3::Location::new( + xcm::v4::Location::new( 1, - [xcm::v3::Junction::Parachain(200), xcm::v3::Junction::GeneralIndex(1234)], + [xcm::v4::Junction::Parachain(200), xcm::v4::Junction::GeneralIndex(1234)], ), 1000, )), @@ -367,9 +367,9 @@ mod tests { ( ma_1000(2, [Parachain(200), GeneralIndex(1234)].into()), Ok(( - xcm::v3::Location::new( + xcm::v4::Location::new( 2, - [xcm::v3::Junction::Parachain(200), xcm::v3::Junction::GeneralIndex(1234)], + [xcm::v4::Junction::Parachain(200), xcm::v4::Junction::GeneralIndex(1234)], ), 1000, )), @@ -377,9 +377,9 @@ mod tests { ( ma_1000(2, [GlobalConsensus(NetworkId::ByGenesis([7; 32]))].into()), Ok(( - xcm::v3::Location::new( + xcm::v4::Location::new( 2, - [xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::ByGenesis( + [xcm::v4::Junction::GlobalConsensus(xcm::v4::NetworkId::ByGenesis( [7; 32], ))], ), @@ -397,14 +397,14 @@ mod tests { .into(), ), Ok(( - xcm::v3::Location::new( + xcm::v4::Location::new( 2, [ - xcm::v3::Junction::GlobalConsensus(xcm::v3::NetworkId::ByGenesis( + xcm::v4::Junction::GlobalConsensus(xcm::v4::NetworkId::ByGenesis( [7; 32], )), - xcm::v3::Junction::Parachain(200), - xcm::v3::Junction::GeneralIndex(1234), + xcm::v4::Junction::Parachain(200), + xcm::v4::Junction::GeneralIndex(1234), ], ), 1000, @@ -414,7 +414,7 @@ mod tests { for (asset, expected_result) in test_data { assert_eq!( - >::matches_fungibles( + >::matches_fungibles( &asset.clone().try_into().unwrap() ), expected_result, diff --git a/cumulus/parachains/runtimes/assets/common/src/matching.rs b/cumulus/parachains/runtimes/assets/common/src/matching.rs index 5a452f6eed1b..aa9d7929cb93 100644 --- a/cumulus/parachains/runtimes/assets/common/src/matching.rs +++ b/cumulus/parachains/runtimes/assets/common/src/matching.rs @@ -146,10 +146,11 @@ impl, OriginLocation: Get> mod tests { use super::*; use frame_support::parameter_types; + use xcm::latest::{ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}; parameter_types! { - pub UniversalLocation: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into(); - pub ExpectedNetworkId: NetworkId = Westend; + pub UniversalLocation: InteriorLocation = [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(1000)].into(); + pub ExpectedNetworkId: NetworkId = ByGenesis(WESTEND_GENESIS_HASH); } #[test] @@ -158,26 +159,30 @@ mod tests { let asset: Location = ( Parent, Parent, - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1000), PalletInstance(1), GeneralIndex(1), ) .into(); - let origin: Location = (Parent, Parent, GlobalConsensus(Westend), Parachain(1000)).into(); + let origin: Location = + (Parent, Parent, GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1000)) + .into(); assert!(FromNetwork::::contains(&asset, &origin)); // asset and origin from local consensus fails let asset: Location = ( Parent, Parent, - GlobalConsensus(Rococo), + GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(1000), PalletInstance(1), GeneralIndex(1), ) .into(); - let origin: Location = (Parent, Parent, GlobalConsensus(Rococo), Parachain(1000)).into(); + let origin: Location = + (Parent, Parent, GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(1000)) + .into(); assert!(!FromNetwork::::contains(&asset, &origin)); // asset and origin from here fails @@ -195,14 +200,16 @@ mod tests { GeneralIndex(1), ) .into(); - let origin: Location = (Parent, Parent, GlobalConsensus(Westend), Parachain(1000)).into(); + let origin: Location = + (Parent, Parent, GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1000)) + .into(); assert!(!FromNetwork::::contains(&asset, &origin)); // origin from different consensus fails let asset: Location = ( Parent, Parent, - GlobalConsensus(Westend), + GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(1000), PalletInstance(1), GeneralIndex(1), diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs index c80222142304..8dc720e27753 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs @@ -367,9 +367,9 @@ pub fn teleports_for_foreign_assets_works< ::Balance: From + Into, SovereignAccountOf: ConvertLocation>, >::AssetId: - From + Into, + From + Into, >::AssetIdParameter: - From + Into, + From + Into, >::Balance: From + Into, ::AccountId: @@ -381,11 +381,11 @@ pub fn teleports_for_foreign_assets_works< { // foreign parachain with the same consensus currency as asset let foreign_para_id = 2222; - let foreign_asset_id_location = xcm::v4::Location { + let foreign_asset_id_location = xcm::v5::Location { parents: 1, interior: [ - xcm::v4::Junction::Parachain(foreign_para_id), - xcm::v4::Junction::GeneralIndex(1234567), + xcm::v5::Junction::Parachain(foreign_para_id), + xcm::v5::Junction::GeneralIndex(1234567), ] .into(), }; @@ -1202,19 +1202,13 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor let xcm = Xcm(vec![ WithdrawAsset(buy_execution_fee.clone().into()), BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, - Transact { - origin_kind: OriginKind::Xcm, - require_weight_at_most: Weight::from_parts(40_000_000_000, 8000), - call: foreign_asset_create.into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: foreign_asset_create.into() }, Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(20_000_000_000, 8000), call: foreign_asset_set_metadata.into(), }, Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(20_000_000_000, 8000), call: foreign_asset_set_team.into(), }, ExpectTransactStatus(MaybeErrorCode::Success), @@ -1321,11 +1315,7 @@ pub fn create_and_manage_foreign_assets_for_local_consensus_parachain_assets_wor let xcm = Xcm(vec![ WithdrawAsset(buy_execution_fee.clone().into()), BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, - Transact { - origin_kind: OriginKind::Xcm, - require_weight_at_most: Weight::from_parts(20_000_000_000, 8000), - call: foreign_asset_create.into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: foreign_asset_create.into() }, ExpectTransactStatus(MaybeErrorCode::from(DispatchError::BadOrigin.encode())), ]); diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs index d86761174740..4f144e24aa30 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases_over_bridge.rs @@ -331,7 +331,7 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< block_author_account: AccountIdOf, (foreign_asset_owner, foreign_asset_id_location, foreign_asset_id_minimum_balance): ( AccountIdOf, - xcm::v4::Location, + xcm::v5::Location, u128, ), foreign_asset_id_amount_to_transfer: u128, @@ -357,9 +357,9 @@ pub fn receive_reserve_asset_deposited_from_different_consensus_works< BalanceOf: From + Into, XcmConfig: xcm_executor::Config, >::AssetId: - From + Into, + From + Into, >::AssetIdParameter: - From + Into, + From + Into, >::Balance: From + Into + From, ::AccountId: Into<<::RuntimeOrigin as OriginTrait>::AccountId> diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs index c226ed9c4fa0..7e0385692375 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs @@ -246,12 +246,13 @@ where { use pallet_xcm_bridge_hub::{Bridge, BridgeId, BridgeState}; use sp_runtime::traits::Zero; - use xcm::VersionedInteriorLocation; + use xcm::{latest::ROCOCO_GENESIS_HASH, VersionedInteriorLocation}; // insert bridge metadata let lane_id = with; let sibling_parachain = Location::new(1, [Parachain(sibling_para_id)]); - let universal_source = [GlobalConsensus(Rococo), Parachain(sibling_para_id)].into(); + let universal_source = + [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(sibling_para_id)].into(); let universal_destination = [GlobalConsensus(RococoBulletinGlobalConsensusNetwork::get()), Parachain(2075)].into(); let bridge_id = BridgeId::new(&universal_source, &universal_destination); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs index 29ea4e05f29e..0eab3c74a7e2 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs @@ -43,14 +43,14 @@ use parachains_common::xcm_config::{AllSiblingSystemParachains, RelayOrOtherSyst use polkadot_parachain_primitives::primitives::Sibling; use testnet_parachains_constants::rococo::currency::UNITS as ROC; use xcm::{ - latest::prelude::*, + latest::{prelude::*, WESTEND_GENESIS_HASH}, prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, ParentIsPreset, SiblingParachainConvertsVia}; parameter_types! { pub BridgeRococoToWestendMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); - pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::Westend; + pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub WestendGlobalConsensusNetworkLocation: Location = Location::new( 2, [GlobalConsensus(WestendGlobalConsensusNetwork::get())] @@ -175,13 +175,15 @@ where { use pallet_xcm_bridge_hub::{Bridge, BridgeId, BridgeState}; use sp_runtime::traits::Zero; - use xcm::VersionedInteriorLocation; + use xcm::{latest::ROCOCO_GENESIS_HASH, VersionedInteriorLocation}; // insert bridge metadata let lane_id = with; let sibling_parachain = Location::new(1, [Parachain(sibling_para_id)]); - let universal_source = [GlobalConsensus(Rococo), Parachain(sibling_para_id)].into(); - let universal_destination = [GlobalConsensus(Westend), Parachain(2075)].into(); + let universal_source = + [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(sibling_para_id)].into(); + let universal_destination = + [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(2075)].into(); let bridge_id = BridgeId::new(&universal_source, &universal_destination); // insert only bridge metadata, because the benchmarks create lanes diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs index 8b749ae301b5..20ca88bbc542 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs @@ -22,6 +22,7 @@ use parachains_common::{AccountId, AuraId}; use sp_genesis_builder::PresetId; use sp_keyring::Sr25519Keyring; use testnet_parachains_constants::rococo::xcm_version::SAFE_XCM_VERSION; +use xcm::latest::WESTEND_GENESIS_HASH; const BRIDGE_HUB_ROCOCO_ED: Balance = ExistentialDeposit::get(); @@ -102,7 +103,7 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option Weight; @@ -81,11 +84,7 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -133,12 +132,35 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -231,4 +253,7 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index f2cee0e3e807..4a5623fc8b93 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 30_988_000 picoseconds. - Weight::from_parts(31_496_000, 3593) + // Minimum execution time: 32_488_000 picoseconds. + Weight::from_parts(33_257_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `153` // Estimated: `6196` - // Minimum execution time: 42_805_000 picoseconds. - Weight::from_parts(44_207_000, 6196) + // Minimum execution time: 46_250_000 picoseconds. + Weight::from_parts(46_856_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -90,8 +90,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `223` // Estimated: `8799` - // Minimum execution time: 103_376_000 picoseconds. - Weight::from_parts(104_770_000, 8799) + // Minimum execution time: 106_863_000 picoseconds. + Weight::from_parts(109_554_000, 8799) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -124,8 +124,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 71_234_000 picoseconds. - Weight::from_parts(72_990_000, 6196) + // Minimum execution time: 74_835_000 picoseconds. + Weight::from_parts(75_993_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -133,8 +133,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_636_000 picoseconds. - Weight::from_parts(2_777_000, 0) + // Minimum execution time: 2_709_000 picoseconds. + Weight::from_parts(2_901_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -142,8 +142,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `52` // Estimated: `3593` - // Minimum execution time: 23_839_000 picoseconds. - Weight::from_parts(24_568_000, 3593) + // Minimum execution time: 25_194_000 picoseconds. + Weight::from_parts(25_805_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -167,8 +167,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `122` // Estimated: `6196` - // Minimum execution time: 78_345_000 picoseconds. - Weight::from_parts(80_558_000, 6196) + // Minimum execution time: 82_570_000 picoseconds. + Weight::from_parts(84_060_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -192,9 +192,34 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3593` - // Minimum execution time: 46_614_000 picoseconds. - Weight::from_parts(47_354_000, 3593) + // Minimum execution time: 51_959_000 picoseconds. + Weight::from_parts(53_434_000, 3593) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + // Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `122` + // Estimated: `6196` + // Minimum execution time: 86_918_000 picoseconds. + Weight::from_parts(89_460_000, 6196) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 9a9137c18093..b8bd4c4e2d44 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 70_133_000 picoseconds. - Weight::from_parts(71_765_000, 6196) + // Minimum execution time: 69_010_000 picoseconds. + Weight::from_parts(70_067_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 959_000 picoseconds. - Weight::from_parts(996_000, 0) + // Minimum execution time: 1_069_000 picoseconds. + Weight::from_parts(1_116_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_011_000 picoseconds. + Weight::from_parts(2_095_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +93,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_537_000 picoseconds. - Weight::from_parts(7_876_000, 3497) + // Minimum execution time: 7_630_000 picoseconds. + Weight::from_parts(7_992_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_774_000 picoseconds. - Weight::from_parts(7_895_000, 0) + // Minimum execution time: 7_909_000 picoseconds. + Weight::from_parts(8_100_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_577_000 picoseconds. - Weight::from_parts(1_622_000, 0) + // Minimum execution time: 1_749_000 picoseconds. + Weight::from_parts(1_841_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 973_000 picoseconds. - Weight::from_parts(1_008_000, 0) + // Minimum execution time: 1_109_000 picoseconds. + Weight::from_parts(1_156_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_027_000 picoseconds. - Weight::from_parts(1_052_000, 0) + // Minimum execution time: 1_073_000 picoseconds. + Weight::from_parts(1_143_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 953_000 picoseconds. - Weight::from_parts(992_000, 0) + // Minimum execution time: 1_050_000 picoseconds. + Weight::from_parts(1_084_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 949_000 picoseconds. - Weight::from_parts(1_020_000, 0) + // Minimum execution time: 1_060_000 picoseconds. + Weight::from_parts(1_114_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 979_000 picoseconds. - Weight::from_parts(1_032_000, 0) + // Minimum execution time: 1_065_000 picoseconds. + Weight::from_parts(1_112_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +166,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 66_663_000 picoseconds. - Weight::from_parts(67_728_000, 6196) + // Minimum execution time: 65_538_000 picoseconds. + Weight::from_parts(66_943_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +177,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 11_074_000 picoseconds. - Weight::from_parts(11_439_000, 3555) + // Minimum execution time: 10_898_000 picoseconds. + Weight::from_parts(11_262_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +186,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 943_000 picoseconds. - Weight::from_parts(1_021_000, 0) + // Minimum execution time: 1_026_000 picoseconds. + Weight::from_parts(1_104_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +207,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 25_123_000 picoseconds. - Weight::from_parts(25_687_000, 3503) + // Minimum execution time: 25_133_000 picoseconds. + Weight::from_parts(25_526_000, 3503) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +218,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_868_000 picoseconds. - Weight::from_parts(3_124_000, 0) + // Minimum execution time: 2_946_000 picoseconds. + Weight::from_parts(3_074_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_378_000 picoseconds. - Weight::from_parts(1_458_000, 0) + // Minimum execution time: 1_428_000 picoseconds. + Weight::from_parts(1_490_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_036_000 picoseconds. - Weight::from_parts(1_105_000, 0) + // Minimum execution time: 1_158_000 picoseconds. + Weight::from_parts(1_222_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 945_000 picoseconds. - Weight::from_parts(1_021_000, 0) + // Minimum execution time: 1_056_000 picoseconds. + Weight::from_parts(1_117_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 931_000 picoseconds. - Weight::from_parts(1_006_000, 0) + // Minimum execution time: 1_045_000 picoseconds. + Weight::from_parts(1_084_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_139_000 picoseconds. - Weight::from_parts(1_206_000, 0) + // Minimum execution time: 1_224_000 picoseconds. + Weight::from_parts(1_268_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +277,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 72_884_000 picoseconds. - Weight::from_parts(74_331_000, 6196) + // Minimum execution time: 70_789_000 picoseconds. + Weight::from_parts(72_321_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +286,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_432_000 picoseconds. - Weight::from_parts(4_542_000, 0) + // Minimum execution time: 4_521_000 picoseconds. + Weight::from_parts(4_649_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +309,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 67_102_000 picoseconds. - Weight::from_parts(68_630_000, 6196) + // Minimum execution time: 66_129_000 picoseconds. + Weight::from_parts(68_089_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +318,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 995_000 picoseconds. - Weight::from_parts(1_057_000, 0) + // Minimum execution time: 1_094_000 picoseconds. + Weight::from_parts(1_157_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 956_000 picoseconds. - Weight::from_parts(1_021_000, 0) + // Minimum execution time: 1_059_000 picoseconds. + Weight::from_parts(1_109_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 944_000 picoseconds. - Weight::from_parts(986_000, 0) + // Minimum execution time: 1_053_000 picoseconds. + Weight::from_parts(1_080_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -343,12 +350,12 @@ impl WeightInfo { /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `589` - // Estimated: `6529` - // Minimum execution time: 58_111_000 picoseconds. - Weight::from_parts(59_123_071, 6529) - // Standard Error: 167 - .saturating_add(Weight::from_parts(43_658, 0).saturating_mul(x.into())) + // Measured: `190` + // Estimated: `6130` + // Minimum execution time: 42_081_000 picoseconds. + Weight::from_parts(42_977_658, 6130) + // Standard Error: 77 + .saturating_add(Weight::from_parts(44_912, 0).saturating_mul(x.into())) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -356,14 +363,21 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 950_000 picoseconds. - Weight::from_parts(1_002_000, 0) + // Minimum execution time: 1_041_000 picoseconds. + Weight::from_parts(1_084_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 963_000 picoseconds. - Weight::from_parts(1_012_000, 0) + // Minimum execution time: 1_085_000 picoseconds. + Weight::from_parts(1_161_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index 2fb186703a88..d36075444f7b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -40,7 +40,7 @@ use polkadot_runtime_common::xcm_sender::ExponentialPrice; use snowbridge_runtime_common::XcmExportFeeToSibling; use sp_runtime::traits::AccountIdConversion; use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -59,7 +59,7 @@ use xcm_executor::{ parameter_types! { pub const TokenLocation: Location = Location::parent(); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); - pub RelayNetwork: NetworkId = NetworkId::Rococo; + pub RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const MaxInstructions: u32 = 100; @@ -296,7 +296,7 @@ impl, FeeHandler: HandleFee> FeeManager fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool { let Some(loc) = origin else { return false }; if let Export { network, destination: Here } = fee_reason { - if network == EthereumNetwork::get() { + if network == EthereumNetwork::get().into() { return false } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index 01674287fde1..2e7dd98e9dce 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -37,7 +37,7 @@ use sp_runtime::{ AccountId32, Perbill, }; use testnet_parachains_constants::rococo::{consensus::*, fee::WeightToFee}; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_runtime_apis::conversions::LocationToAccountHelper; parameter_types! { @@ -377,7 +377,7 @@ mod bridge_hub_westend_tests { bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, SIBLING_PARACHAIN_ID, - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), || { // we need to create lane between sibling parachain and remote destination bridge_hub_test_utils::ensure_opened_bridge::< @@ -411,7 +411,7 @@ mod bridge_hub_westend_tests { bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, SIBLING_PARACHAIN_ID, - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), || { // we need to create lane between sibling parachain and remote destination bridge_hub_test_utils::ensure_opened_bridge::< @@ -643,7 +643,7 @@ mod bridge_hub_bulletin_tests { slot_durations(), bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, SIBLING_PEOPLE_PARACHAIN_ID, - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), || { // we need to create lane between RococoPeople and RococoBulletin bridge_hub_test_utils::ensure_opened_bridge::< @@ -676,7 +676,7 @@ mod bridge_hub_bulletin_tests { slot_durations(), bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, SIBLING_PEOPLE_PARACHAIN_ID, - Rococo, + ByGenesis(ROCOCO_GENESIS_HASH), || { // we need to create lane between RococoPeople and RococoBulletin bridge_hub_test_utils::ensure_opened_bridge::< diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_ethereum_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_ethereum_config.rs index dbca4166a135..94921fd8af9a 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_ethereum_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_ethereum_config.rs @@ -229,3 +229,48 @@ pub mod benchmark_helpers { } } } + +pub(crate) mod migrations { + use alloc::vec::Vec; + use frame_support::pallet_prelude::*; + use snowbridge_core::TokenId; + + #[frame_support::storage_alias] + pub type OldNativeToForeignId = StorageMap< + snowbridge_pallet_system::Pallet, + Blake2_128Concat, + xcm::v4::Location, + TokenId, + OptionQuery, + >; + + /// One shot migration for NetworkId::Westend to NetworkId::ByGenesis(WESTEND_GENESIS_HASH) + pub struct MigrationForXcmV5(core::marker::PhantomData); + impl frame_support::traits::OnRuntimeUpgrade + for MigrationForXcmV5 + { + fn on_runtime_upgrade() -> Weight { + let mut weight = T::DbWeight::get().reads(1); + + let translate_westend = |pre: xcm::v4::Location| -> Option { + weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); + Some(xcm::v5::Location::try_from(pre).expect("valid location")) + }; + snowbridge_pallet_system::ForeignToNativeId::::translate_values(translate_westend); + + let old_keys = OldNativeToForeignId::::iter_keys().collect::>(); + for old_key in old_keys { + if let Some(old_val) = OldNativeToForeignId::::get(&old_key) { + snowbridge_pallet_system::NativeToForeignId::::insert( + &xcm::v5::Location::try_from(old_key.clone()).expect("valid location"), + old_val, + ); + } + OldNativeToForeignId::::remove(old_key); + weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2)); + } + + weight + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs index aca51b320e9b..62c93da7c831 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs @@ -44,7 +44,7 @@ use parachains_common::xcm_config::{AllSiblingSystemParachains, RelayOrOtherSyst use polkadot_parachain_primitives::primitives::Sibling; use testnet_parachains_constants::westend::currency::UNITS as WND; use xcm::{ - latest::prelude::*, + latest::{prelude::*, ROCOCO_GENESIS_HASH}, prelude::{InteriorLocation, NetworkId}, }; use xcm_builder::{BridgeBlobDispatcher, ParentIsPreset, SiblingParachainConvertsVia}; @@ -57,7 +57,7 @@ parameter_types! { pub const MaxRococoParaHeadDataSize: u32 = bp_rococo::MAX_NESTED_PARACHAIN_HEAD_DATA_SIZE; pub BridgeWestendToRococoMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); - pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo; + pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RococoGlobalConsensusNetworkLocation: Location = Location::new( 2, [GlobalConsensus(RococoGlobalConsensusNetwork::get())] @@ -204,13 +204,15 @@ where { use pallet_xcm_bridge_hub::{Bridge, BridgeId, BridgeState}; use sp_runtime::traits::Zero; - use xcm::VersionedInteriorLocation; + use xcm::{latest::WESTEND_GENESIS_HASH, VersionedInteriorLocation}; // insert bridge metadata let lane_id = with; let sibling_parachain = Location::new(1, [Parachain(sibling_para_id)]); - let universal_source = [GlobalConsensus(Westend), Parachain(sibling_para_id)].into(); - let universal_destination = [GlobalConsensus(Rococo), Parachain(2075)].into(); + let universal_source = + [GlobalConsensus(ByGenesis(WESTEND_GENESIS_HASH)), Parachain(sibling_para_id)].into(); + let universal_destination = + [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(2075)].into(); let bridge_id = BridgeId::new(&universal_source, &universal_destination); // insert only bridge metadata, because the benchmarks create lanes @@ -332,7 +334,6 @@ mod tests { pub mod migration { use super::*; use bp_messages::LegacyLaneId; - use frame_support::traits::ConstBool; parameter_types! { pub AssetHubWestendToAssetHubRococoMessagesLane: LegacyLaneId = LegacyLaneId([0, 0, 0, 2]); @@ -340,18 +341,6 @@ pub mod migration { pub AssetHubRococoUniversalLocation: InteriorLocation = [GlobalConsensus(RococoGlobalConsensusNetwork::get()), Parachain(bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID)].into(); } - /// Ensure that the existing lanes for the AHW<>AHR bridge are correctly configured. - pub type StaticToDynamicLanes = pallet_xcm_bridge_hub::migration::OpenBridgeForLane< - Runtime, - XcmOverBridgeHubRococoInstance, - AssetHubWestendToAssetHubRococoMessagesLane, - // the lanes are already created for AHR<>AHW, but we need to link them to the bridge - // structs - ConstBool, - AssetHubWestendLocation, - AssetHubRococoUniversalLocation, - >; - mod v1_wrong { use bp_messages::{LaneState, MessageNonce, UnrewardedRelayer}; use bp_runtime::AccountIdOf; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs index e639b899149a..421c36246774 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs @@ -22,6 +22,7 @@ use parachains_common::{AccountId, AuraId}; use sp_genesis_builder::PresetId; use sp_keyring::Sr25519Keyring; use testnet_parachains_constants::westend::xcm_version::SAFE_XCM_VERSION; +use xcm::latest::ROCOCO_GENESIS_HASH; const BRIDGE_HUB_WESTEND_ED: Balance = ExistentialDeposit::get(); @@ -102,7 +103,10 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option, - bridge_to_rococo_config::migration::StaticToDynamicLanes, frame_support::migrations::RemoveStorage< BridgeRococoMessagesPalletName, OutboundLanesCongestedSignalsKey, RocksDbWeight, >, pallet_bridge_relayers::migration::v1::MigrationToV1, - // permanent - pallet_xcm::migration::MigrateToLatestXcmVersion, snowbridge_pallet_system::migration::v0::InitializeOnUpgrade< Runtime, ConstU32, ConstU32, >, + bridge_to_ethereum_config::migrations::MigrationForXcmV5, + // permanent + pallet_xcm::migration::MigrateToLatestXcmVersion, ); parameter_types! { @@ -1155,7 +1158,7 @@ impl_runtime_apis! { ); // open bridge - let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(NetworkId::Rococo), Parachain(8765)].into(); + let bridge_destination_universal_location: InteriorLocation = [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH)), Parachain(8765)].into(); let locations = XcmOverBridgeHubRococo::bridge_locations( sibling_parachain_location.clone(), bridge_destination_universal_location.clone(), @@ -1177,7 +1180,7 @@ impl_runtime_apis! { Ok( ( sibling_parachain_location, - NetworkId::Rococo, + NetworkId::ByGenesis(ROCOCO_GENESIS_HASH), [Parachain(8765)].into() ) ) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs index 3961cc6d5cdd..473807ea5eb1 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs @@ -23,7 +23,10 @@ use codec::Encode; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -82,11 +85,7 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -134,12 +133,35 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -152,6 +174,9 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 5bd1d1680aa1..555303d30b61 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 30_218_000 picoseconds. - Weight::from_parts(30_783_000, 3593) + // Minimum execution time: 31_340_000 picoseconds. + Weight::from_parts(32_044_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `153` // Estimated: `6196` - // Minimum execution time: 42_631_000 picoseconds. - Weight::from_parts(43_127_000, 6196) + // Minimum execution time: 44_483_000 picoseconds. + Weight::from_parts(45_215_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -90,8 +90,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `260` // Estimated: `8799` - // Minimum execution time: 100_978_000 picoseconds. - Weight::from_parts(102_819_000, 8799) + // Minimum execution time: 106_531_000 picoseconds. + Weight::from_parts(109_012_000, 8799) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -124,8 +124,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 71_533_000 picoseconds. - Weight::from_parts(72_922_000, 6196) + // Minimum execution time: 75_043_000 picoseconds. + Weight::from_parts(77_425_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -133,8 +133,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_863_000 picoseconds. - Weight::from_parts(2_997_000, 0) + // Minimum execution time: 2_739_000 picoseconds. + Weight::from_parts(2_855_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -142,8 +142,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `52` // Estimated: `3593` - // Minimum execution time: 23_763_000 picoseconds. - Weight::from_parts(24_438_000, 3593) + // Minimum execution time: 25_043_000 picoseconds. + Weight::from_parts(25_297_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -167,8 +167,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `159` // Estimated: `6196` - // Minimum execution time: 78_182_000 picoseconds. - Weight::from_parts(79_575_000, 6196) + // Minimum execution time: 82_421_000 picoseconds. + Weight::from_parts(84_128_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -192,9 +192,34 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `107` // Estimated: `3593` - // Minimum execution time: 46_767_000 picoseconds. - Weight::from_parts(47_823_000, 3593) + // Minimum execution time: 52_465_000 picoseconds. + Weight::from_parts(53_568_000, 3593) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + // Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `159` + // Estimated: `6196` + // Minimum execution time: 87_253_000 picoseconds. + Weight::from_parts(88_932_000, 6196) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(4)) + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 16c483a21817..849456af9255 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 70_715_000 picoseconds. - Weight::from_parts(72_211_000, 6196) + // Minimum execution time: 70_353_000 picoseconds. + Weight::from_parts(72_257_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 968_000 picoseconds. - Weight::from_parts(1_022_000, 0) + // Minimum execution time: 996_000 picoseconds. + Weight::from_parts(1_027_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_926_000 picoseconds. + Weight::from_parts(2_033_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +93,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_718_000 picoseconds. - Weight::from_parts(7_894_000, 3497) + // Minimum execution time: 7_961_000 picoseconds. + Weight::from_parts(8_256_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_662_000 picoseconds. - Weight::from_parts(7_937_000, 0) + // Minimum execution time: 7_589_000 picoseconds. + Weight::from_parts(7_867_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_699_000 picoseconds. - Weight::from_parts(1_783_000, 0) + // Minimum execution time: 1_602_000 picoseconds. + Weight::from_parts(1_660_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 977_000 picoseconds. - Weight::from_parts(1_045_000, 0) + // Minimum execution time: 1_056_000 picoseconds. + Weight::from_parts(1_096_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 971_000 picoseconds. - Weight::from_parts(1_030_000, 0) + // Minimum execution time: 1_014_000 picoseconds. + Weight::from_parts(1_075_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 958_000 picoseconds. - Weight::from_parts(996_000, 0) + // Minimum execution time: 986_000 picoseconds. + Weight::from_parts(1_031_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 992_000 picoseconds. - Weight::from_parts(1_056_000, 0) + // Minimum execution time: 1_015_000 picoseconds. + Weight::from_parts(1_069_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 975_000 picoseconds. - Weight::from_parts(1_026_000, 0) + // Minimum execution time: 993_000 picoseconds. + Weight::from_parts(1_063_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +166,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 67_236_000 picoseconds. - Weight::from_parts(68_712_000, 6196) + // Minimum execution time: 66_350_000 picoseconds. + Weight::from_parts(68_248_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +177,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_890_000 picoseconds. - Weight::from_parts(11_223_000, 3555) + // Minimum execution time: 11_247_000 picoseconds. + Weight::from_parts(11_468_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +186,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 959_000 picoseconds. - Weight::from_parts(1_018_000, 0) + // Minimum execution time: 1_060_000 picoseconds. + Weight::from_parts(1_103_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +207,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 25_162_000 picoseconds. - Weight::from_parts(25_621_000, 3503) + // Minimum execution time: 25_599_000 picoseconds. + Weight::from_parts(26_336_000, 3503) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +218,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_949_000 picoseconds. - Weight::from_parts(3_119_000, 0) + // Minimum execution time: 2_863_000 picoseconds. + Weight::from_parts(3_090_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_329_000 picoseconds. - Weight::from_parts(1_410_000, 0) + // Minimum execution time: 1_385_000 picoseconds. + Weight::from_parts(1_468_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_063_000 picoseconds. - Weight::from_parts(1_101_000, 0) + // Minimum execution time: 1_087_000 picoseconds. + Weight::from_parts(1_164_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 991_000 picoseconds. - Weight::from_parts(1_041_000, 0) + // Minimum execution time: 1_022_000 picoseconds. + Weight::from_parts(1_066_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 944_000 picoseconds. - Weight::from_parts(998_000, 0) + // Minimum execution time: 1_015_000 picoseconds. + Weight::from_parts(1_070_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_100_000 picoseconds. - Weight::from_parts(1_180_000, 0) + // Minimum execution time: 1_203_000 picoseconds. + Weight::from_parts(1_241_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +277,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 71_203_000 picoseconds. - Weight::from_parts(73_644_000, 6196) + // Minimum execution time: 70_773_000 picoseconds. + Weight::from_parts(72_730_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +286,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_018_000 picoseconds. - Weight::from_parts(4_267_000, 0) + // Minimum execution time: 4_173_000 picoseconds. + Weight::from_parts(4_445_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +309,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 67_893_000 picoseconds. - Weight::from_parts(69_220_000, 6196) + // Minimum execution time: 66_471_000 picoseconds. + Weight::from_parts(68_362_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +318,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 980_000 picoseconds. - Weight::from_parts(1_043_000, 0) + // Minimum execution time: 1_067_000 picoseconds. + Weight::from_parts(1_108_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 944_000 picoseconds. - Weight::from_parts(981_000, 0) + // Minimum execution time: 997_000 picoseconds. + Weight::from_parts(1_043_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 930_000 picoseconds. - Weight::from_parts(962_000, 0) + // Minimum execution time: 1_000_000 picoseconds. + Weight::from_parts(1_056_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -343,12 +350,12 @@ impl WeightInfo { /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `552` - // Estimated: `6492` - // Minimum execution time: 56_762_000 picoseconds. - Weight::from_parts(58_320_046, 6492) - // Standard Error: 162 - .saturating_add(Weight::from_parts(51_730, 0).saturating_mul(x.into())) + // Measured: `225` + // Estimated: `6165` + // Minimum execution time: 43_316_000 picoseconds. + Weight::from_parts(45_220_843, 6165) + // Standard Error: 169 + .saturating_add(Weight::from_parts(44_459, 0).saturating_mul(x.into())) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -356,14 +363,21 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 971_000 picoseconds. - Weight::from_parts(1_018_000, 0) + // Minimum execution time: 998_000 picoseconds. + Weight::from_parts(1_054_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 979_000 picoseconds. - Weight::from_parts(1_026_000, 0) + // Minimum execution time: 995_000 picoseconds. + Weight::from_parts(1_060_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index ae31ca4cedf2..e692568932fe 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -39,7 +39,7 @@ use snowbridge_runtime_common::XcmExportFeeToSibling; use sp_runtime::traits::AccountIdConversion; use sp_std::marker::PhantomData; use testnet_parachains_constants::westend::snowbridge::EthereumNetwork; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -57,7 +57,7 @@ use xcm_executor::{ parameter_types! { pub const WestendLocation: Location = Location::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Westend; + pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); @@ -290,7 +290,7 @@ impl, FeeHandler: HandleFee> FeeManager fn is_waived(origin: Option<&Location>, fee_reason: FeeReason) -> bool { let Some(loc) = origin else { return false }; if let Export { network, destination: Here } = fee_reason { - if network == EthereumNetwork::get() { + if network == EthereumNetwork::get().into() { return false } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index e5b67353c0f3..69301b34fe6b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -46,7 +46,7 @@ use sp_runtime::{ AccountId32, Perbill, }; use testnet_parachains_constants::westend::{consensus::*, fee::WeightToFee}; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_runtime_apis::conversions::LocationToAccountHelper; // Random para id of sibling chain used in tests. @@ -296,7 +296,7 @@ fn relayed_incoming_message_works() { bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, SIBLING_PARACHAIN_ID, - Westend, + ByGenesis(WESTEND_GENESIS_HASH), || { // we need to create lane between sibling parachain and remote destination bridge_hub_test_utils::ensure_opened_bridge::< @@ -330,7 +330,7 @@ fn free_relay_extrinsic_works() { bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, SIBLING_PARACHAIN_ID, - Westend, + ByGenesis(WESTEND_GENESIS_HASH), || { // we need to create lane between sibling parachain and remote destination bridge_hub_test_utils::ensure_opened_bridge::< diff --git a/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs index 5f91897262f4..2f5aa76fbdd7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs @@ -23,7 +23,7 @@ use frame_support::{ use pallet_message_queue::OnQueueChanged; use scale_info::TypeInfo; use snowbridge_core::ChannelId; -use xcm::v4::{Junction, Location}; +use xcm::latest::prelude::{Junction, Location}; /// The aggregate origin of an inbound message. /// This is specialized for BridgeHub, as the snowbridge-outbound-queue-pallet is also using @@ -53,7 +53,7 @@ impl From for Location { Here => Location::here(), Parent => Location::parent(), Sibling(id) => Location::new(1, Junction::Parachain(id.into())), - // NOTE: We don't need this conversion for Snowbridge. However we have to + // NOTE: We don't need this conversion for Snowbridge. However, we have to // implement it anyway as xcm_builder::ProcessXcmMessage requires it. Snowbridge(_) => Location::default(), } diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs index 24372f57ae7d..ad6db0b83e80 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs @@ -129,11 +129,8 @@ pub fn initialize_bridge_by_governance_works( }); // execute XCM with Transacts to `initialize bridge` as governance does - assert_ok!(RuntimeHelper::::execute_as_governance( - initialize_call.encode(), - initialize_call.get_dispatch_info().call_weight, - ) - .ensure_complete()); + assert_ok!(RuntimeHelper::::execute_as_governance(initialize_call.encode(),) + .ensure_complete()); // check mode after assert_eq!( @@ -172,7 +169,6 @@ pub fn change_bridge_grandpa_pallet_mode_by_governance_works::execute_as_governance( set_operating_mode_call.encode(), - set_operating_mode_call.get_dispatch_info().call_weight, ) .ensure_complete()); @@ -225,7 +221,6 @@ pub fn change_bridge_parachains_pallet_mode_by_governance_works::execute_as_governance( set_operating_mode_call.encode(), - set_operating_mode_call.get_dispatch_info().call_weight, ) .ensure_complete()); @@ -278,7 +273,6 @@ pub fn change_bridge_messages_pallet_mode_by_governance_works::execute_as_governance( set_operating_mode_call.encode(), - set_operating_mode_call.get_dispatch_info().call_weight, ) .ensure_complete()); diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs index f8e03303c32e..56ef2e8ba02f 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs @@ -33,7 +33,7 @@ use parachains_common::xcm_config::{ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use westend_runtime_constants::xcm as xcm_constants; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -50,7 +50,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const RootLocation: Location = Location::here(); pub const WndLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Westend); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index 39fdd30a0498..0151837aa351 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -36,7 +36,7 @@ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::AccountIdConversion; use testnet_parachains_constants::rococo::currency::CENTS; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -52,7 +52,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const RelayLocation: Location = Location::parent(); - pub const RelayNetwork: NetworkId = NetworkId::Rococo; + pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub const ExecutiveBody: BodyId = BodyId::Executive; diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/coretime.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/coretime.rs index 3910a747e9bb..d76ac443a147 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/coretime.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/coretime.rs @@ -134,7 +134,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1000000000, 200000), call: request_core_count_call.encode().into(), }, ]); @@ -164,7 +163,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1000000000, 200000), call: request_revenue_info_at_call.encode().into(), }, ]); @@ -193,7 +191,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1000000000, 200000), call: credit_account_call.encode().into(), }, ]); @@ -258,7 +255,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1_000_000_000, 200000), call: assign_core_call.encode().into(), }, ]); diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs index b8db473f1066..48f1366e2c5f 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs @@ -22,7 +22,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -81,11 +84,7 @@ impl XcmWeightInfo for CoretimeRococoXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -132,12 +131,35 @@ impl XcmWeightInfo for CoretimeRococoXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -229,4 +251,7 @@ impl XcmWeightInfo for CoretimeRococoXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index c8dbdadf7b15..0a2d74de0cb8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("coretime-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 29_812_000 picoseconds. - Weight::from_parts(30_526_000, 3593) + // Minimum execution time: 31_260_000 picoseconds. + Weight::from_parts(31_771_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 39_430_000 picoseconds. - Weight::from_parts(39_968_000, 6196) + // Minimum execution time: 42_231_000 picoseconds. + Weight::from_parts(42_718_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -88,8 +88,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `207` // Estimated: `6196` - // Minimum execution time: 65_555_000 picoseconds. - Weight::from_parts(67_161_000, 6196) + // Minimum execution time: 68_764_000 picoseconds. + Weight::from_parts(70_505_000, 6196) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -118,8 +118,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 30_491_000 picoseconds. - Weight::from_parts(31_991_000, 3571) + // Minimum execution time: 31_390_000 picoseconds. + Weight::from_parts(32_057_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -127,8 +127,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_568_000 picoseconds. - Weight::from_parts(2_703_000, 0) + // Minimum execution time: 2_288_000 picoseconds. + Weight::from_parts(2_477_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -136,8 +136,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 22_159_000 picoseconds. - Weight::from_parts(22_517_000, 3593) + // Minimum execution time: 22_946_000 picoseconds. + Weight::from_parts(23_462_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3593` - // Minimum execution time: 57_126_000 picoseconds. - Weight::from_parts(58_830_000, 3593) + // Minimum execution time: 59_017_000 picoseconds. + Weight::from_parts(60_338_000, 3593) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -180,9 +180,32 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 26_589_000 picoseconds. - Weight::from_parts(27_285_000, 3571) + // Minimum execution time: 29_953_000 picoseconds. + Weight::from_parts(30_704_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `3593` + // Minimum execution time: 65_118_000 picoseconds. + Weight::from_parts(66_096_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 676048f92ad9..229dafb7c5ed 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-05-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-unxyhko3-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("coretime-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -64,8 +64,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 23_760_000 picoseconds. - Weight::from_parts(24_411_000, 3571) + // Minimum execution time: 29_263_000 picoseconds. + Weight::from_parts(30_387_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -73,8 +73,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 522_000 picoseconds. - Weight::from_parts(546_000, 0) + // Minimum execution time: 603_000 picoseconds. + Weight::from_parts(664_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_530_000 picoseconds. + Weight::from_parts(1_662_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -82,58 +89,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 5_830_000 picoseconds. - Weight::from_parts(6_069_000, 3497) + // Minimum execution time: 7_290_000 picoseconds. + Weight::from_parts(7_493_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_508_000 picoseconds. - Weight::from_parts(5_801_000, 0) + // Minimum execution time: 6_785_000 picoseconds. + Weight::from_parts(7_012_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_130_000 picoseconds. - Weight::from_parts(1_239_000, 0) + // Minimum execution time: 1_299_000 picoseconds. + Weight::from_parts(1_380_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 541_000 picoseconds. - Weight::from_parts(567_000, 0) + // Minimum execution time: 655_000 picoseconds. + Weight::from_parts(681_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 560_000 picoseconds. - Weight::from_parts(591_000, 0) + // Minimum execution time: 625_000 picoseconds. + Weight::from_parts(669_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 505_000 picoseconds. - Weight::from_parts(547_000, 0) + // Minimum execution time: 607_000 picoseconds. + Weight::from_parts(650_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 538_000 picoseconds. - Weight::from_parts(565_000, 0) + // Minimum execution time: 655_000 picoseconds. + Weight::from_parts(688_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 514_000 picoseconds. - Weight::from_parts(541_000, 0) + // Minimum execution time: 602_000 picoseconds. + Weight::from_parts(650_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -151,8 +158,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 20_920_000 picoseconds. - Weight::from_parts(21_437_000, 3571) + // Minimum execution time: 26_176_000 picoseconds. + Weight::from_parts(26_870_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -162,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 8_549_000 picoseconds. - Weight::from_parts(8_821_000, 3555) + // Minimum execution time: 10_674_000 picoseconds. + Weight::from_parts(10_918_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -171,8 +178,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 525_000 picoseconds. - Weight::from_parts(544_000, 0) + // Minimum execution time: 601_000 picoseconds. + Weight::from_parts(639_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -190,8 +197,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `74` // Estimated: `3539` - // Minimum execution time: 19_645_000 picoseconds. - Weight::from_parts(20_104_000, 3539) + // Minimum execution time: 24_220_000 picoseconds. + Weight::from_parts(24_910_000, 3539) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -201,44 +208,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_232_000 picoseconds. - Weight::from_parts(2_334_000, 0) + // Minimum execution time: 2_464_000 picoseconds. + Weight::from_parts(2_618_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 883_000 picoseconds. - Weight::from_parts(945_000, 0) + // Minimum execution time: 984_000 picoseconds. + Weight::from_parts(1_041_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 600_000 picoseconds. - Weight::from_parts(645_000, 0) + // Minimum execution time: 730_000 picoseconds. + Weight::from_parts(769_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 527_000 picoseconds. - Weight::from_parts(552_000, 0) + // Minimum execution time: 615_000 picoseconds. + Weight::from_parts(658_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 527_000 picoseconds. - Weight::from_parts(550_000, 0) + // Minimum execution time: 607_000 picoseconds. + Weight::from_parts(637_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 657_000 picoseconds. - Weight::from_parts(703_000, 0) + // Minimum execution time: 791_000 picoseconds. + Weight::from_parts(838_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -256,8 +263,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 24_999_000 picoseconds. - Weight::from_parts(25_671_000, 3571) + // Minimum execution time: 30_210_000 picoseconds. + Weight::from_parts(30_973_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -265,8 +272,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_159_000 picoseconds. - Weight::from_parts(3_296_000, 0) + // Minimum execution time: 3_097_000 picoseconds. + Weight::from_parts(3_277_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -284,8 +291,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 21_052_000 picoseconds. - Weight::from_parts(22_153_000, 3571) + // Minimum execution time: 26_487_000 picoseconds. + Weight::from_parts(27_445_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -293,35 +300,42 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 547_000 picoseconds. - Weight::from_parts(584_000, 0) + // Minimum execution time: 655_000 picoseconds. + Weight::from_parts(689_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 506_000 picoseconds. - Weight::from_parts(551_000, 0) + // Minimum execution time: 627_000 picoseconds. + Weight::from_parts(659_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 508_000 picoseconds. - Weight::from_parts(527_000, 0) + // Minimum execution time: 603_000 picoseconds. + Weight::from_parts(650_000, 0) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 527_000 picoseconds. - Weight::from_parts(558_000, 0) + // Minimum execution time: 594_000 picoseconds. + Weight::from_parts(645_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 514_000 picoseconds. - Weight::from_parts(553_000, 0) + // Minimum execution time: 650_000 picoseconds. + Weight::from_parts(673_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs index 2eae13de2fd4..37bf1e681447 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs @@ -37,7 +37,7 @@ use parachains_common::{ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::AccountIdConversion; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -53,7 +53,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const RocRelayLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Rococo); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/coretime.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/coretime.rs index 86769cb2da11..f0c03849750a 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/coretime.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/coretime.rs @@ -127,12 +127,6 @@ impl CoretimeInterface for CoretimeAllocator { use crate::coretime::CoretimeProviderCalls::RequestCoreCount; let request_core_count_call = RelayRuntimePallets::Coretime(RequestCoreCount(count)); - // Weight for `request_core_count` from westend benchmarks: - // `ref_time` = 7889000 + (3 * 25000000) + (1 * 100000000) = 182889000 - // `proof_size` = 1636 - // Add 5% to each component and round to 2 significant figures. - let call_weight = Weight::from_parts(190_000_000, 1700); - let message = Xcm(vec![ Instruction::UnpaidExecution { weight_limit: WeightLimit::Unlimited, @@ -140,7 +134,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: call_weight, call: request_core_count_call.encode().into(), }, ]); @@ -170,7 +163,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1000000000, 200000), call: request_revenue_info_at_call.encode().into(), }, ]); @@ -199,7 +191,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(1000000000, 200000), call: credit_account_call.encode().into(), }, ]); @@ -225,12 +216,6 @@ impl CoretimeInterface for CoretimeAllocator { ) { use crate::coretime::CoretimeProviderCalls::AssignCore; - // Weight for `assign_core` from westend benchmarks: - // `ref_time` = 10177115 + (1 * 25000000) + (2 * 100000000) + (57600 * 13932) = 937660315 - // `proof_size` = 3612 - // Add 5% to each component and round to 2 significant figures. - let call_weight = Weight::from_parts(980_000_000, 3800); - // The relay chain currently only allows `assign_core` to be called with a complete mask // and only ever with increasing `begin`. The assignments must be truncated to avoid // dropping that core's assignment completely. @@ -270,7 +255,6 @@ impl CoretimeInterface for CoretimeAllocator { }, Instruction::Transact { origin_kind: OriginKind::Native, - require_weight_at_most: call_weight, call: assign_core_call.encode().into(), }, ]); diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs index f35f7bfc188d..1f4b4aa5c5a8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs @@ -21,7 +21,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -80,11 +83,7 @@ impl XcmWeightInfo for CoretimeWestendXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -132,12 +131,35 @@ impl XcmWeightInfo for CoretimeWestendXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -150,6 +172,9 @@ impl XcmWeightInfo for CoretimeWestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 935636651eb9..227f3617da00 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("coretime-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 29_866_000 picoseconds. - Weight::from_parts(30_363_000, 3593) + // Minimum execution time: 30_623_000 picoseconds. + Weight::from_parts(31_009_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 39_434_000 picoseconds. - Weight::from_parts(40_274_000, 6196) + // Minimum execution time: 40_553_000 picoseconds. + Weight::from_parts(41_309_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -88,8 +88,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `207` // Estimated: `6196` - // Minimum execution time: 66_303_000 picoseconds. - Weight::from_parts(68_294_000, 6196) + // Minimum execution time: 66_837_000 picoseconds. + Weight::from_parts(68_463_000, 6196) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -118,8 +118,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 30_523_000 picoseconds. - Weight::from_parts(31_289_000, 3571) + // Minimum execution time: 30_020_000 picoseconds. + Weight::from_parts(31_409_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -127,8 +127,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_517_000 picoseconds. - Weight::from_parts(2_634_000, 0) + // Minimum execution time: 2_355_000 picoseconds. + Weight::from_parts(2_464_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -136,8 +136,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 22_151_000 picoseconds. - Weight::from_parts(22_907_000, 3593) + // Minimum execution time: 22_702_000 picoseconds. + Weight::from_parts(23_422_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3593` - // Minimum execution time: 57_763_000 picoseconds. - Weight::from_parts(58_941_000, 3593) + // Minimum execution time: 58_610_000 picoseconds. + Weight::from_parts(59_659_000, 3593) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -180,9 +180,32 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 26_322_000 picoseconds. - Weight::from_parts(27_197_000, 3571) + // Minimum execution time: 29_178_000 picoseconds. + Weight::from_parts(29_860_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `3593` + // Minimum execution time: 63_658_000 picoseconds. + Weight::from_parts(64_869_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 7390f35e3974..bd70bc4f4bd9 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-05-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-unxyhko3-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("coretime-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -64,8 +64,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 23_688_000 picoseconds. - Weight::from_parts(24_845_000, 3571) + // Minimum execution time: 29_463_000 picoseconds. + Weight::from_parts(30_178_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -73,8 +73,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 569_000 picoseconds. - Weight::from_parts(619_000, 0) + // Minimum execution time: 568_000 picoseconds. + Weight::from_parts(608_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_530_000 picoseconds. + Weight::from_parts(1_585_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -82,58 +89,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 5_851_000 picoseconds. - Weight::from_parts(6_061_000, 3497) + // Minimum execution time: 7_400_000 picoseconds. + Weight::from_parts(7_572_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_770_000 picoseconds. - Weight::from_parts(5_916_000, 0) + // Minimum execution time: 6_951_000 picoseconds. + Weight::from_parts(7_173_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_155_000 picoseconds. - Weight::from_parts(1_270_000, 0) + // Minimum execution time: 1_245_000 picoseconds. + Weight::from_parts(1_342_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 558_000 picoseconds. - Weight::from_parts(628_000, 0) + // Minimum execution time: 613_000 picoseconds. + Weight::from_parts(657_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 603_000 picoseconds. - Weight::from_parts(630_000, 0) + // Minimum execution time: 613_000 picoseconds. + Weight::from_parts(656_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 533_000 picoseconds. - Weight::from_parts(563_000, 0) + // Minimum execution time: 570_000 picoseconds. + Weight::from_parts(608_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 597_000 picoseconds. - Weight::from_parts(644_000, 0) + // Minimum execution time: 557_000 picoseconds. + Weight::from_parts(607_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 536_000 picoseconds. - Weight::from_parts(588_000, 0) + // Minimum execution time: 557_000 picoseconds. + Weight::from_parts(578_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -151,8 +158,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 21_146_000 picoseconds. - Weight::from_parts(21_771_000, 3571) + // Minimum execution time: 26_179_000 picoseconds. + Weight::from_parts(27_089_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -162,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 8_446_000 picoseconds. - Weight::from_parts(8_660_000, 3555) + // Minimum execution time: 10_724_000 picoseconds. + Weight::from_parts(10_896_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -171,8 +178,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 561_000 picoseconds. - Weight::from_parts(594_000, 0) + // Minimum execution time: 567_000 picoseconds. + Weight::from_parts(623_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -190,8 +197,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `74` // Estimated: `3539` - // Minimum execution time: 19_953_000 picoseconds. - Weight::from_parts(20_608_000, 3539) + // Minimum execution time: 24_367_000 picoseconds. + Weight::from_parts(25_072_000, 3539) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -201,44 +208,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_290_000 picoseconds. - Weight::from_parts(2_370_000, 0) + // Minimum execution time: 2_554_000 picoseconds. + Weight::from_parts(2_757_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 943_000 picoseconds. - Weight::from_parts(987_000, 0) + // Minimum execution time: 922_000 picoseconds. + Weight::from_parts(992_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 635_000 picoseconds. - Weight::from_parts(699_000, 0) + // Minimum execution time: 688_000 picoseconds. + Weight::from_parts(723_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 553_000 picoseconds. - Weight::from_parts(609_000, 0) + // Minimum execution time: 607_000 picoseconds. + Weight::from_parts(647_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 547_000 picoseconds. - Weight::from_parts(581_000, 0) + // Minimum execution time: 591_000 picoseconds. + Weight::from_parts(620_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 700_000 picoseconds. - Weight::from_parts(757_000, 0) + // Minimum execution time: 735_000 picoseconds. + Weight::from_parts(802_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -256,8 +263,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 24_953_000 picoseconds. - Weight::from_parts(25_516_000, 3571) + // Minimum execution time: 29_923_000 picoseconds. + Weight::from_parts(30_770_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -265,8 +272,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_746_000 picoseconds. - Weight::from_parts(2_944_000, 0) + // Minimum execution time: 2_884_000 picoseconds. + Weight::from_parts(3_088_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -284,8 +291,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3571` - // Minimum execution time: 21_325_000 picoseconds. - Weight::from_parts(21_942_000, 3571) + // Minimum execution time: 26_632_000 picoseconds. + Weight::from_parts(27_228_000, 3571) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -293,35 +300,42 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 600_000 picoseconds. - Weight::from_parts(631_000, 0) + // Minimum execution time: 599_000 picoseconds. + Weight::from_parts(655_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 534_000 picoseconds. - Weight::from_parts(566_000, 0) + // Minimum execution time: 587_000 picoseconds. + Weight::from_parts(628_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 540_000 picoseconds. - Weight::from_parts(565_000, 0) + // Minimum execution time: 572_000 picoseconds. + Weight::from_parts(631_000, 0) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 542_000 picoseconds. - Weight::from_parts(581_000, 0) + // Minimum execution time: 570_000 picoseconds. + Weight::from_parts(615_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 568_000 picoseconds. - Weight::from_parts(597_000, 0) + // Minimum execution time: 624_000 picoseconds. + Weight::from_parts(659_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs index 1205be95c932..5616c585a13c 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs @@ -37,7 +37,7 @@ use parachains_common::{ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::AccountIdConversion; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -53,7 +53,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const TokenRelayLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Westend); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/glutton/glutton-westend/src/xcm_config.rs index d1fb50c1ab09..b67c32495d67 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/src/xcm_config.rs @@ -22,7 +22,7 @@ use frame_support::{ traits::{Contains, Everything, Nothing}, weights::Weight, }; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AllowExplicitUnpaidExecutionFrom, FixedWeightBounds, FrameTransactionalProcessor, ParentAsSuperuser, ParentIsPreset, SovereignSignedViaLocation, @@ -30,7 +30,7 @@ use xcm_builder::{ parameter_types! { pub const WestendLocation: Location = Location::parent(); - pub const WestendNetwork: NetworkId = NetworkId::Westend; + pub const WestendNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub UniversalLocation: InteriorLocation = [GlobalConsensus(WestendNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs index 58007173ae1d..b82872a1cbf2 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs @@ -21,7 +21,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -80,11 +83,7 @@ impl XcmWeightInfo for PeopleRococoXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -131,12 +130,35 @@ impl XcmWeightInfo for PeopleRococoXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -228,4 +250,7 @@ impl XcmWeightInfo for PeopleRococoXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 4dd44e66dd5e..f594c45e1cf6 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("people-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 30_428_000 picoseconds. - Weight::from_parts(31_184_000, 3593) + // Minimum execution time: 30_760_000 picoseconds. + Weight::from_parts(31_209_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `153` // Estimated: `6196` - // Minimum execution time: 41_912_000 picoseconds. - Weight::from_parts(43_346_000, 6196) + // Minimum execution time: 43_379_000 picoseconds. + Weight::from_parts(44_202_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -88,8 +88,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `223` // Estimated: `6196` - // Minimum execution time: 67_706_000 picoseconds. - Weight::from_parts(69_671_000, 6196) + // Minimum execution time: 67_467_000 picoseconds. + Weight::from_parts(69_235_000, 6196) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -118,8 +118,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 29_790_000 picoseconds. - Weight::from_parts(30_655_000, 3535) + // Minimum execution time: 29_243_000 picoseconds. + Weight::from_parts(30_176_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -127,8 +127,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_438_000 picoseconds. - Weight::from_parts(2_597_000, 0) + // Minimum execution time: 2_294_000 picoseconds. + Weight::from_parts(2_424_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -136,8 +136,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `52` // Estimated: `3593` - // Minimum execution time: 24_040_000 picoseconds. - Weight::from_parts(24_538_000, 3593) + // Minimum execution time: 24_058_000 picoseconds. + Weight::from_parts(24_588_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `122` // Estimated: `3593` - // Minimum execution time: 58_275_000 picoseconds. - Weight::from_parts(59_899_000, 3593) + // Minimum execution time: 59_164_000 picoseconds. + Weight::from_parts(60_431_000, 3593) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -180,9 +180,32 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 25_638_000 picoseconds. - Weight::from_parts(26_514_000, 3535) + // Minimum execution time: 28_379_000 picoseconds. + Weight::from_parts(29_153_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `122` + // Estimated: `3593` + // Minimum execution time: 64_505_000 picoseconds. + Weight::from_parts(66_587_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 729a32117041..30e28fac7e57 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("people-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -64,8 +64,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 29_430_000 picoseconds. - Weight::from_parts(30_111_000, 3535) + // Minimum execution time: 28_898_000 picoseconds. + Weight::from_parts(29_717_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -73,8 +73,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 607_000 picoseconds. - Weight::from_parts(672_000, 0) + // Minimum execution time: 690_000 picoseconds. + Weight::from_parts(759_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_695_000 picoseconds. + Weight::from_parts(1_799_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -82,58 +89,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_445_000 picoseconds. - Weight::from_parts(7_623_000, 3497) + // Minimum execution time: 7_441_000 picoseconds. + Weight::from_parts(7_746_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_749_000 picoseconds. - Weight::from_parts(7_073_000, 0) + // Minimum execution time: 6_881_000 picoseconds. + Weight::from_parts(7_219_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_275_000 picoseconds. - Weight::from_parts(1_409_000, 0) + // Minimum execution time: 1_390_000 picoseconds. + Weight::from_parts(1_471_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 670_000 picoseconds. - Weight::from_parts(709_000, 0) + // Minimum execution time: 698_000 picoseconds. + Weight::from_parts(743_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 635_000 picoseconds. - Weight::from_parts(723_000, 0) + // Minimum execution time: 695_000 picoseconds. + Weight::from_parts(746_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 650_000 picoseconds. + // Minimum execution time: 664_000 picoseconds. Weight::from_parts(699_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 678_000 picoseconds. - Weight::from_parts(728_000, 0) + // Minimum execution time: 698_000 picoseconds. + Weight::from_parts(748_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 657_000 picoseconds. - Weight::from_parts(703_000, 0) + // Minimum execution time: 669_000 picoseconds. + Weight::from_parts(726_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -151,8 +158,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 25_795_000 picoseconds. - Weight::from_parts(26_415_000, 3535) + // Minimum execution time: 25_991_000 picoseconds. + Weight::from_parts(26_602_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -162,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_792_000 picoseconds. - Weight::from_parts(11_061_000, 3555) + // Minimum execution time: 10_561_000 picoseconds. + Weight::from_parts(10_913_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -171,8 +178,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 624_000 picoseconds. - Weight::from_parts(682_000, 0) + // Minimum execution time: 654_000 picoseconds. + Weight::from_parts(707_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -190,8 +197,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 23_906_000 picoseconds. - Weight::from_parts(24_740_000, 3503) + // Minimum execution time: 23_813_000 picoseconds. + Weight::from_parts(24_352_000, 3503) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -201,44 +208,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_621_000 picoseconds. - Weight::from_parts(2_788_000, 0) + // Minimum execution time: 2_499_000 picoseconds. + Weight::from_parts(2_655_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 954_000 picoseconds. - Weight::from_parts(1_046_000, 0) + // Minimum execution time: 1_065_000 picoseconds. + Weight::from_parts(1_108_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 742_000 picoseconds. - Weight::from_parts(790_000, 0) + // Minimum execution time: 747_000 picoseconds. + Weight::from_parts(807_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 664_000 picoseconds. - Weight::from_parts(722_000, 0) + // Minimum execution time: 685_000 picoseconds. + Weight::from_parts(750_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 619_000 picoseconds. - Weight::from_parts(672_000, 0) + // Minimum execution time: 664_000 picoseconds. + Weight::from_parts(711_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 798_000 picoseconds. - Weight::from_parts(851_000, 0) + // Minimum execution time: 830_000 picoseconds. + Weight::from_parts(880_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -256,8 +263,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 29_580_000 picoseconds. - Weight::from_parts(31_100_000, 3535) + // Minimum execution time: 30_051_000 picoseconds. + Weight::from_parts(30_720_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -265,8 +272,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_150_000 picoseconds. - Weight::from_parts(3_326_000, 0) + // Minimum execution time: 3_136_000 picoseconds. + Weight::from_parts(3_265_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -284,8 +291,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 26_152_000 picoseconds. - Weight::from_parts(26_635_000, 3535) + // Minimum execution time: 25_980_000 picoseconds. + Weight::from_parts(26_868_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -293,35 +300,42 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 693_000 picoseconds. - Weight::from_parts(724_000, 0) + // Minimum execution time: 708_000 picoseconds. + Weight::from_parts(755_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 632_000 picoseconds. - Weight::from_parts(678_000, 0) + // Minimum execution time: 667_000 picoseconds. + Weight::from_parts(702_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 646_000 picoseconds. - Weight::from_parts(694_000, 0) + // Minimum execution time: 660_000 picoseconds. + Weight::from_parts(695_000, 0) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 622_000 picoseconds. - Weight::from_parts(656_000, 0) + // Minimum execution time: 669_000 picoseconds. + Weight::from_parts(707_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 639_000 picoseconds. - Weight::from_parts(679_000, 0) + // Minimum execution time: 685_000 picoseconds. + Weight::from_parts(757_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs index a2e20e2778b6..724d87587c6c 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs @@ -34,7 +34,7 @@ use parachains_common::{ }; use polkadot_parachain_primitives::primitives::Sibling; use sp_runtime::traits::AccountIdConversion; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -51,7 +51,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const RootLocation: Location = Location::here(); pub const RelayLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Rococo); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs index b44e8d4b61b8..8ca9771dca46 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs @@ -21,7 +21,10 @@ use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use xcm::{latest::prelude::*, DoubleEncoded}; +use xcm::{ + latest::{prelude::*, AssetTransferFilter}, + DoubleEncoded, +}; trait WeighAssets { fn weigh_assets(&self, weight: Weight) -> Weight; @@ -80,11 +83,7 @@ impl XcmWeightInfo for PeopleWestendXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::transfer_reserve_asset()) } - fn transact( - _origin_type: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_type: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -131,12 +130,35 @@ impl XcmWeightInfo for PeopleWestendXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmFungibleWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmFungibleWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmFungibleWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -228,4 +250,7 @@ impl XcmWeightInfo for PeopleWestendXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 8f6bfde986bb..c12da204f35b 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("people-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -54,8 +54,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 30_040_000 picoseconds. - Weight::from_parts(30_758_000, 3593) + // Minimum execution time: 30_401_000 picoseconds. + Weight::from_parts(30_813_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -65,8 +65,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `153` // Estimated: `6196` - // Minimum execution time: 42_135_000 picoseconds. - Weight::from_parts(42_970_000, 6196) + // Minimum execution time: 43_150_000 picoseconds. + Weight::from_parts(43_919_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -88,8 +88,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `223` // Estimated: `6196` - // Minimum execution time: 67_385_000 picoseconds. - Weight::from_parts(69_776_000, 6196) + // Minimum execution time: 67_808_000 picoseconds. + Weight::from_parts(69_114_000, 6196) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -118,8 +118,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 29_804_000 picoseconds. - Weight::from_parts(30_662_000, 3535) + // Minimum execution time: 29_312_000 picoseconds. + Weight::from_parts(30_347_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -127,8 +127,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_358_000 picoseconds. - Weight::from_parts(2_497_000, 0) + // Minimum execution time: 2_283_000 picoseconds. + Weight::from_parts(2_448_000, 0) } // Storage: `System::Account` (r:1 w:1) // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -136,8 +136,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `52` // Estimated: `3593` - // Minimum execution time: 23_732_000 picoseconds. - Weight::from_parts(24_098_000, 3593) + // Minimum execution time: 23_556_000 picoseconds. + Weight::from_parts(24_419_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `122` // Estimated: `3593` - // Minimum execution time: 58_449_000 picoseconds. - Weight::from_parts(60_235_000, 3593) + // Minimum execution time: 58_342_000 picoseconds. + Weight::from_parts(59_598_000, 3593) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -180,9 +180,32 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 25_708_000 picoseconds. - Weight::from_parts(26_495_000, 3535) + // Minimum execution time: 28_285_000 picoseconds. + Weight::from_parts(29_016_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `122` + // Estimated: `3593` + // Minimum execution time: 65_211_000 picoseconds. + Weight::from_parts(67_200_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 1377d31f2db7..3c539902abc8 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("people-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -64,8 +64,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 29_537_000 picoseconds. - Weight::from_parts(30_513_000, 3535) + // Minimum execution time: 29_015_000 picoseconds. + Weight::from_parts(30_359_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -73,8 +73,15 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 683_000 picoseconds. - Weight::from_parts(738_000, 0) + // Minimum execution time: 572_000 picoseconds. + Weight::from_parts(637_000, 0) + } + pub fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_550_000 picoseconds. + Weight::from_parts(1_604_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -82,58 +89,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_498_000 picoseconds. - Weight::from_parts(7_904_000, 3497) + // Minimum execution time: 7_354_000 picoseconds. + Weight::from_parts(7_808_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_029_000 picoseconds. - Weight::from_parts(7_325_000, 0) + // Minimum execution time: 6_716_000 picoseconds. + Weight::from_parts(7_067_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_343_000 picoseconds. - Weight::from_parts(1_410_000, 0) + // Minimum execution time: 1_280_000 picoseconds. + Weight::from_parts(1_355_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 696_000 picoseconds. - Weight::from_parts(734_000, 0) + // Minimum execution time: 587_000 picoseconds. + Weight::from_parts(645_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 690_000 picoseconds. - Weight::from_parts(740_000, 0) + // Minimum execution time: 629_000 picoseconds. + Weight::from_parts(662_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 667_000 picoseconds. - Weight::from_parts(697_000, 0) + // Minimum execution time: 590_000 picoseconds. + Weight::from_parts(639_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 692_000 picoseconds. - Weight::from_parts(743_000, 0) + // Minimum execution time: 651_000 picoseconds. + Weight::from_parts(688_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 670_000 picoseconds. - Weight::from_parts(712_000, 0) + // Minimum execution time: 601_000 picoseconds. + Weight::from_parts(630_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -151,8 +158,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 26_405_000 picoseconds. - Weight::from_parts(26_877_000, 3535) + // Minimum execution time: 25_650_000 picoseconds. + Weight::from_parts(26_440_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -162,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_953_000 picoseconds. - Weight::from_parts(11_345_000, 3555) + // Minimum execution time: 10_492_000 picoseconds. + Weight::from_parts(10_875_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -171,8 +178,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 644_000 picoseconds. - Weight::from_parts(693_000, 0) + // Minimum execution time: 597_000 picoseconds. + Weight::from_parts(647_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -190,8 +197,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 24_157_000 picoseconds. - Weight::from_parts(24_980_000, 3503) + // Minimum execution time: 23_732_000 picoseconds. + Weight::from_parts(24_290_000, 3503) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -201,44 +208,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_767_000 picoseconds. - Weight::from_parts(2_844_000, 0) + // Minimum execution time: 2_446_000 picoseconds. + Weight::from_parts(2_613_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_079_000 picoseconds. - Weight::from_parts(1_141_000, 0) + // Minimum execution time: 960_000 picoseconds. + Weight::from_parts(1_045_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 776_000 picoseconds. - Weight::from_parts(829_000, 0) + // Minimum execution time: 703_000 picoseconds. + Weight::from_parts(739_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 696_000 picoseconds. - Weight::from_parts(740_000, 0) + // Minimum execution time: 616_000 picoseconds. + Weight::from_parts(651_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 655_000 picoseconds. - Weight::from_parts(684_000, 0) + // Minimum execution time: 621_000 picoseconds. + Weight::from_parts(660_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 825_000 picoseconds. - Weight::from_parts(853_000, 0) + // Minimum execution time: 794_000 picoseconds. + Weight::from_parts(831_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -256,8 +263,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 30_222_000 picoseconds. - Weight::from_parts(31_110_000, 3535) + // Minimum execution time: 29_527_000 picoseconds. + Weight::from_parts(30_614_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -265,8 +272,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_108_000 picoseconds. - Weight::from_parts(3_325_000, 0) + // Minimum execution time: 3_189_000 picoseconds. + Weight::from_parts(3_296_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -284,8 +291,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `70` // Estimated: `3535` - // Minimum execution time: 26_548_000 picoseconds. - Weight::from_parts(26_911_000, 3535) + // Minimum execution time: 25_965_000 picoseconds. + Weight::from_parts(26_468_000, 3535) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -293,35 +300,42 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 684_000 picoseconds. - Weight::from_parts(726_000, 0) + // Minimum execution time: 618_000 picoseconds. + Weight::from_parts(659_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 649_000 picoseconds. - Weight::from_parts(700_000, 0) + // Minimum execution time: 593_000 picoseconds. + Weight::from_parts(618_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 650_000 picoseconds. - Weight::from_parts(686_000, 0) + // Minimum execution time: 603_000 picoseconds. + Weight::from_parts(634_000, 0) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 652_000 picoseconds. - Weight::from_parts(703_000, 0) + // Minimum execution time: 568_000 picoseconds. + Weight::from_parts(629_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 673_000 picoseconds. - Weight::from_parts(742_000, 0) + // Minimum execution time: 598_000 picoseconds. + Weight::from_parts(655_000, 0) + } + pub fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs index bec5b923d8ad..25256495ef91 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs @@ -34,7 +34,7 @@ use parachains_common::{ }; use polkadot_parachain_primitives::primitives::Sibling; use sp_runtime::traits::AccountIdConversion; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, @@ -51,7 +51,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const RootLocation: Location = Location::here(); pub const RelayLocation: Location = Location::parent(); - pub const RelayNetwork: Option = Some(NetworkId::Westend); + pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into(); diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index 36cf2bf4f83b..05ecf6ca8e81 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -441,15 +441,11 @@ impl< AllPalletsWithoutSystem, > RuntimeHelper { - pub fn execute_as_governance(call: Vec, require_weight_at_most: Weight) -> Outcome { + pub fn execute_as_governance(call: Vec) -> Outcome { // prepare xcm as governance will do let xcm = Xcm(vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, - Transact { - origin_kind: OriginKind::Superuser, - require_weight_at_most, - call: call.into(), - }, + Transact { origin_kind: OriginKind::Superuser, call: call.into() }, ExpectTransactStatus(MaybeErrorCode::Success), ]); @@ -473,11 +469,7 @@ impl< let xcm = Xcm(vec![ WithdrawAsset(buy_execution_fee.clone().into()), BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, - Transact { - origin_kind: OriginKind::Xcm, - require_weight_at_most: call.get_dispatch_info().call_weight, - call: call.encode().into(), - }, + Transact { origin_kind: OriginKind::Xcm, call: call.encode().into() }, ExpectTransactStatus(MaybeErrorCode::Success), ]); diff --git a/cumulus/parachains/runtimes/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/test-utils/src/test_cases.rs index 1c58df189b67..a66163154cf6 100644 --- a/cumulus/parachains/runtimes/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/test-utils/src/test_cases.rs @@ -72,17 +72,9 @@ pub fn change_storage_constant_by_governance_works::SystemWeightInfo::set_storage(1); - // execute XCM with Transact to `set_storage` as governance does - assert_ok!(RuntimeHelper::::execute_as_governance( - set_storage_call, - require_weight_at_most - ) - .ensure_complete()); + assert_ok!(RuntimeHelper::::execute_as_governance(set_storage_call,) + .ensure_complete()); // check delivery reward constant after (stored) assert_eq!(StorageConstant::get(), new_storage_constant_value); @@ -127,19 +119,10 @@ pub fn set_storage_keys_by_governance_works( items: storage_items.clone(), }); - // estimate - storing just 1 value - use frame_system::WeightInfo; - let require_weight_at_most = - ::SystemWeightInfo::set_storage( - storage_items.len().try_into().unwrap(), - ); - // execute XCM with Transact to `set_storage` as governance does - assert_ok!(RuntimeHelper::::execute_as_governance( - kill_storage_call, - require_weight_at_most - ) - .ensure_complete()); + assert_ok!( + RuntimeHelper::::execute_as_governance(kill_storage_call,).ensure_complete() + ); }); runtime.execute_with(|| { assert_storage(); diff --git a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml index 14c4fe520384..3a6b9d42f211 100644 --- a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml @@ -79,6 +79,7 @@ pallet-collator-selection = { workspace = true } parachain-info = { workspace = true } parachains-common = { workspace = true } assets-common = { workspace = true } +snowbridge-router-primitives = { workspace = true } primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "num-traits", "scale-info"] } @@ -123,6 +124,7 @@ std = [ "polkadot-runtime-common/std", "primitive-types/std", "scale-info/std", + "snowbridge-router-primitives/std", "sp-api/std", "sp-block-builder/std", "sp-consensus-aura/std", @@ -168,6 +170,7 @@ runtime-benchmarks = [ "polkadot-parachain-primitives/runtime-benchmarks", "polkadot-primitives/runtime-benchmarks", "polkadot-runtime-common/runtime-benchmarks", + "snowbridge-router-primitives/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index 6c9e3f7f23a5..b51670c792d6 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -36,6 +36,7 @@ extern crate alloc; use alloc::{vec, vec::Vec}; use assets_common::{ + foreign_creators::ForeignCreators, local_and_foreign_assets::{LocalFromLeft, TargetFromLeft}, AssetIdForTrustBackedAssetsConvert, }; @@ -82,7 +83,7 @@ pub use sp_runtime::{traits::ConvertInto, MultiAddress, Perbill, Permill}; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use xcm_config::{ForeignAssetsAssetId, XcmOriginToTransactDispatchOrigin}; +use xcm_config::{ForeignAssetsAssetId, LocationToAccountId, XcmOriginToTransactDispatchOrigin}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; @@ -494,7 +495,10 @@ impl pallet_assets::Config for Runtime { type AssetId = ForeignAssetsAssetId; type AssetIdParameter = ForeignAssetsAssetId; type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; + // This is to allow any other remote location to create foreign assets. Used in tests, not + // recommended on real chains. + type CreateOrigin = + ForeignCreators; type ForceOrigin = EnsureRoot; type AssetDeposit = ForeignAssetsAssetDeposit; type MetadataDepositBase = ForeignAssetsMetadataDepositBase; diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index b72d6d232a1d..375c3d509f48 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -44,13 +44,15 @@ use pallet_xcm::XcmPassthrough; use parachains_common::{xcm_config::AssetFeeAsExistentialDepositMultiplier, TREASURY_PALLET_ID}; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::{impls::ToAuthor, xcm_sender::ExponentialPrice}; +use snowbridge_router_primitives::inbound::EthereumLocationsConverterFor; use sp_runtime::traits::{AccountIdConversion, ConvertInto, Identity, TryConvertInto}; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ - AccountId32Aliases, AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, - ConvertedConcreteId, DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FixedWeightBounds, - FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, HashedDescription, IsConcrete, + AccountId32Aliases, AliasOriginRootUsingFilter, AllowHrmpNotificationsFromRelayChain, + AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, + AsPrefixedGeneralIndex, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily, + EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, + FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, NativeAsset, NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SingleAssetExchangeAdapter, @@ -65,8 +67,8 @@ parameter_types! { pub const PenpalNativeCurrency: Location = Location::here(); // The Penpal runtime is utilized for testing with various environment setups. // This storage item allows us to customize the `NetworkId` where Penpal is deployed. - // By default, it is set to `NetworkId::Rococo` and can be changed using `System::set_storage`. - pub storage RelayNetworkId: NetworkId = NetworkId::Westend; + // By default, it is set to `Westend Network` and can be changed using `System::set_storage`. + pub storage RelayNetworkId: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub RelayNetwork: Option = Some(RelayNetworkId::get()); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [ @@ -92,6 +94,12 @@ pub type LocationToAccountId = ( AccountId32Aliases, // Foreign locations alias into accounts according to a hash of their standard description. HashedDescription>, + // Different global consensus parachain sovereign account. + // (Used for over-bridge transfers and reserve processing) + GlobalConsensusParachainConvertsFor, + // Ethereum contract sovereign account. + // (Used to get convert ethereum contract locations to sovereign account) + EthereumLocationsConverterFor, ); /// Means for transacting assets on this chain. @@ -398,7 +406,8 @@ impl xcm_executor::Config for XcmConfig { type UniversalAliases = Nothing; type CallDispatcher = RuntimeCall; type SafeCallFilter = Everything; - type Aliasers = Nothing; + // We allow trusted Asset Hub root to alias other locations. + type Aliasers = AliasOriginRootUsingFilter; type TransactionalProcessor = FrameTransactionalProcessor; type HrmpNewChannelOpenRequestHandler = (); type HrmpChannelAcceptedHandler = (); diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 095f571974f0..42556e0b493c 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -85,7 +85,7 @@ use xcm_executor::traits::JustTry; // XCM imports use pallet_xcm::{EnsureXcm, IsMajorityOfBody, XcmPassthrough}; use polkadot_parachain_primitives::primitives::Sibling; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, FungibleAdapter, IsConcrete, NativeAsset, @@ -332,7 +332,7 @@ impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { pub const RocLocation: Location = Location::parent(); - pub const RococoNetwork: NetworkId = NetworkId::Rococo; + pub const RococoNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub UniversalLocation: InteriorLocation = [GlobalConsensus(RococoNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); diff --git a/cumulus/xcm/xcm-emulator/src/lib.rs b/cumulus/xcm/xcm-emulator/src/lib.rs index b91246a7bda2..ff14b747973c 100644 --- a/cumulus/xcm/xcm-emulator/src/lib.rs +++ b/cumulus/xcm/xcm-emulator/src/lib.rs @@ -36,7 +36,10 @@ pub use core::{cell::RefCell, fmt::Debug}; pub use cumulus_primitives_core::AggregateMessageOrigin as CumulusAggregateMessageOrigin; pub use frame_support::{ assert_ok, - sp_runtime::{traits::Header as HeaderT, DispatchResult}, + sp_runtime::{ + traits::{Dispatchable, Header as HeaderT}, + DispatchResult, + }, traits::{ EnqueueMessage, ExecuteOverweightError, Get, Hooks, OnInitialize, OriginTrait, ProcessMessage, ProcessMessageError, ServiceQueues, @@ -221,7 +224,7 @@ pub trait Network { pub trait Chain: TestExt { type Network: Network; type Runtime: SystemConfig; - type RuntimeCall; + type RuntimeCall: Clone + Dispatchable; type RuntimeOrigin; type RuntimeEvent; type System; @@ -1221,7 +1224,7 @@ macro_rules! __impl_check_assertion { Args: Clone, { fn check_assertion(test: $crate::Test) { - use $crate::TestExt; + use $crate::{Dispatchable, TestExt}; let chain_name = std::any::type_name::<$chain<$network>>(); @@ -1229,6 +1232,15 @@ macro_rules! __impl_check_assertion { if let Some(dispatchable) = test.hops_dispatchable.get(chain_name) { $crate::assert_ok!(dispatchable(test.clone())); } + if let Some(call) = test.hops_calls.get(chain_name) { + $crate::assert_ok!( + match call.clone().dispatch(test.signed_origin.clone()) { + // We get rid of `post_info`. + Ok(_) => Ok(()), + Err(error_with_post_info) => Err(error_with_post_info.error), + } + ); + } if let Some(assertion) = test.hops_assertion.get(chain_name) { assertion(test); } @@ -1530,11 +1542,12 @@ where pub root_origin: Origin::RuntimeOrigin, pub hops_assertion: HashMap, pub hops_dispatchable: HashMap DispatchResult>, + pub hops_calls: HashMap, pub args: Args, _marker: PhantomData<(Destination, Hops)>, } -/// `Test` implementation +/// `Test` implementation. impl Test where Args: Clone, @@ -1544,7 +1557,7 @@ where Destination::RuntimeOrigin: OriginTrait> + Clone, Hops: Clone + CheckAssertion, { - /// Creates a new `Test` instance + /// Creates a new `Test` instance. pub fn new(test_args: TestContext) -> Self { Test { sender: TestAccount { @@ -1559,6 +1572,7 @@ where root_origin: ::RuntimeOrigin::root(), hops_assertion: Default::default(), hops_dispatchable: Default::default(), + hops_calls: Default::default(), args: test_args.args, _marker: Default::default(), } @@ -1573,6 +1587,11 @@ where let chain_name = std::any::type_name::(); self.hops_dispatchable.insert(chain_name.to_string(), dispatchable); } + /// Stores a call in a particular Chain, this will later be dispatched. + pub fn set_call(&mut self, call: Origin::RuntimeCall) { + let chain_name = std::any::type_name::(); + self.hops_calls.insert(chain_name.to_string(), call); + } /// Executes all dispatchables and assertions in order from `Origin` to `Destination` pub fn assert(&mut self) { Origin::check_assertion(self.clone()); diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index 2f79d223d3c0..9a290f08609a 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -138,6 +138,15 @@ pub enum VersionedLocatableAsset { V3 { location: xcm::v3::Location, asset_id: xcm::v3::AssetId }, #[codec(index = 4)] V4 { location: xcm::v4::Location, asset_id: xcm::v4::AssetId }, + #[codec(index = 5)] + V5 { location: xcm::v5::Location, asset_id: xcm::v5::AssetId }, +} + +/// A conversion from latest xcm to `VersionedLocatableAsset`. +impl From<(xcm::latest::Location, xcm::latest::AssetId)> for VersionedLocatableAsset { + fn from(value: (xcm::latest::Location, xcm::latest::AssetId)) -> Self { + VersionedLocatableAsset::V5 { location: value.0, asset_id: value.1 } + } } /// Converts the [`VersionedLocatableAsset`] to the [`xcm_builder::LocatableAssetId`]. @@ -149,12 +158,22 @@ impl TryConvert asset: VersionedLocatableAsset, ) -> Result { match asset { - VersionedLocatableAsset::V3 { location, asset_id } => + VersionedLocatableAsset::V3 { location, asset_id } => { + let v4_location: xcm::v4::Location = + location.try_into().map_err(|_| asset.clone())?; + let v4_asset_id: xcm::v4::AssetId = + asset_id.try_into().map_err(|_| asset.clone())?; + Ok(xcm_builder::LocatableAssetId { + location: v4_location.try_into().map_err(|_| asset.clone())?, + asset_id: v4_asset_id.try_into().map_err(|_| asset.clone())?, + }) + }, + VersionedLocatableAsset::V4 { ref location, ref asset_id } => Ok(xcm_builder::LocatableAssetId { - location: location.try_into().map_err(|_| asset.clone())?, - asset_id: asset_id.try_into().map_err(|_| asset.clone())?, + location: location.clone().try_into().map_err(|_| asset.clone())?, + asset_id: asset_id.clone().try_into().map_err(|_| asset.clone())?, }), - VersionedLocatableAsset::V4 { location, asset_id } => + VersionedLocatableAsset::V5 { location, asset_id } => Ok(xcm_builder::LocatableAssetId { location, asset_id }), } } @@ -167,12 +186,12 @@ impl TryConvert<&VersionedLocation, xcm::latest::Location> for VersionedLocation location: &VersionedLocation, ) -> Result { let latest = match location.clone() { - VersionedLocation::V2(l) => { - let v3: xcm::v3::Location = l.try_into().map_err(|_| location)?; - v3.try_into().map_err(|_| location)? + VersionedLocation::V3(l) => { + let v4_location: xcm::v4::Location = l.try_into().map_err(|_| location)?; + v4_location.try_into().map_err(|_| location)? }, - VersionedLocation::V3(l) => l.try_into().map_err(|_| location)?, - VersionedLocation::V4(l) => l, + VersionedLocation::V4(l) => l.try_into().map_err(|_| location)?, + VersionedLocation::V5(l) => l, }; Ok(latest) } @@ -188,11 +207,25 @@ where fn contains(asset: &VersionedLocatableAsset) -> bool { use VersionedLocatableAsset::*; let (location, asset_id) = match asset.clone() { - V3 { location, asset_id } => match (location.try_into(), asset_id.try_into()) { + V3 { location, asset_id } => { + let v4_location: xcm::v4::Location = match location.try_into() { + Ok(l) => l, + Err(_) => return false, + }; + let v4_asset_id: xcm::v4::AssetId = match asset_id.try_into() { + Ok(a) => a, + Err(_) => return false, + }; + match (v4_location.try_into(), v4_asset_id.try_into()) { + (Ok(l), Ok(a)) => (l, a), + _ => return false, + } + }, + V4 { location, asset_id } => match (location.try_into(), asset_id.try_into()) { (Ok(l), Ok(a)) => (l, a), _ => return false, }, - V4 { location, asset_id } => (location, asset_id), + V5 { location, asset_id } => (location, asset_id), }; C::contains(&location, &asset_id.0) } @@ -213,17 +246,14 @@ pub mod benchmarks { pub struct AssetRateArguments; impl AssetKindFactory for AssetRateArguments { fn create_asset_kind(seed: u32) -> VersionedLocatableAsset { - VersionedLocatableAsset::V4 { - location: xcm::v4::Location::new(0, [xcm::v4::Junction::Parachain(seed)]), - asset_id: xcm::v4::Location::new( + ( + Location::new(0, [Parachain(seed)]), + AssetId(Location::new( 0, - [ - xcm::v4::Junction::PalletInstance(seed.try_into().unwrap()), - xcm::v4::Junction::GeneralIndex(seed.into()), - ], - ) - .into(), - } + [PalletInstance(seed.try_into().unwrap()), GeneralIndex(seed.into())], + )), + ) + .into() } } @@ -238,26 +268,17 @@ pub mod benchmarks { for TreasuryArguments { fn create_asset_kind(seed: u32) -> VersionedLocatableAsset { - VersionedLocatableAsset::V3 { - location: xcm::v3::Location::new( - Parents::get(), - [xcm::v3::Junction::Parachain(ParaId::get())], - ), - asset_id: xcm::v3::Location::new( + ( + Location::new(Parents::get(), [Junction::Parachain(ParaId::get())]), + AssetId(Location::new( 0, - [ - xcm::v3::Junction::PalletInstance(seed.try_into().unwrap()), - xcm::v3::Junction::GeneralIndex(seed.into()), - ], - ) - .into(), - } + [PalletInstance(seed.try_into().unwrap()), GeneralIndex(seed.into())], + )), + ) + .into() } fn create_beneficiary(seed: [u8; 32]) -> VersionedLocation { - VersionedLocation::V4(xcm::v4::Location::new( - 0, - [xcm::v4::Junction::AccountId32 { network: None, id: seed }], - )) + VersionedLocation::from(Location::new(0, [AccountId32 { network: None, id: seed }])) } } } diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 37fe7f0b59e9..7ff7f69faf14 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -157,7 +157,7 @@ impl InspectMessageQueues for ChildParachainRouter { @@ -62,10 +64,10 @@ mod v_coretime { impl< T: Config, - SendXcm: xcm::v4::SendXcm, + XcmSender: SendXcm, LegacyLease: GetLegacyLease>, const TIMESLICE_PERIOD: u32, - > MigrateToCoretime + > MigrateToCoretime { fn already_migrated() -> bool { // We are using the assigner coretime because the coretime pallet doesn't has any @@ -95,10 +97,10 @@ mod v_coretime { impl< T: Config + crate::dmp::Config, - SendXcm: xcm::v4::SendXcm, + XcmSender: SendXcm, LegacyLease: GetLegacyLease>, const TIMESLICE_PERIOD: u32, - > OnRuntimeUpgrade for MigrateToCoretime + > OnRuntimeUpgrade for MigrateToCoretime { fn on_runtime_upgrade() -> Weight { if Self::already_migrated() { @@ -106,7 +108,7 @@ mod v_coretime { } log::info!("Migrating existing parachains to coretime."); - migrate_to_coretime::() + migrate_to_coretime::() } #[cfg(feature = "try-runtime")] @@ -157,7 +159,7 @@ mod v_coretime { // NOTE: Also migrates `num_cores` config value in configuration::ActiveConfig. fn migrate_to_coretime< T: Config, - SendXcm: xcm::v4::SendXcm, + XcmSender: SendXcm, LegacyLease: GetLegacyLease>, const TIMESLICE_PERIOD: u32, >() -> Weight { @@ -198,9 +200,12 @@ mod v_coretime { c.scheduler_params.num_cores = total_cores; }); - if let Err(err) = - migrate_send_assignments_to_coretime_chain::( - ) { + if let Err(err) = migrate_send_assignments_to_coretime_chain::< + T, + XcmSender, + LegacyLease, + TIMESLICE_PERIOD, + >() { log::error!("Sending legacy chain data to coretime chain failed: {:?}", err); } @@ -215,7 +220,7 @@ mod v_coretime { fn migrate_send_assignments_to_coretime_chain< T: Config, - SendXcm: xcm::v4::SendXcm, + XcmSender: SendXcm, LegacyLease: GetLegacyLease>, const TIMESLICE_PERIOD: u32, >() -> result::Result<(), SendError> { @@ -300,7 +305,7 @@ mod v_coretime { }; for message in messages { - send_xcm::( + send_xcm::( Location::new(0, Junction::Parachain(T::BrokerId::get())), message, )?; diff --git a/polkadot/runtime/parachains/src/coretime/mod.rs b/polkadot/runtime/parachains/src/coretime/mod.rs index 9b9bdb86878f..966b7997a277 100644 --- a/polkadot/runtime/parachains/src/coretime/mod.rs +++ b/polkadot/runtime/parachains/src/coretime/mod.rs @@ -30,20 +30,7 @@ use pallet_broker::{CoreAssignment, CoreIndex as BrokerCoreIndex}; use polkadot_primitives::{Balance, BlockNumber, CoreIndex, Id as ParaId}; use sp_arithmetic::traits::SaturatedConversion; use sp_runtime::traits::TryConvert; -use xcm::{ - prelude::{send_xcm, Instruction, Junction, Location, OriginKind, SendXcm, WeightLimit, Xcm}, - v4::{ - Asset, - AssetFilter::Wild, - AssetId, Assets, Error as XcmError, - Fungibility::Fungible, - Instruction::{DepositAsset, ReceiveTeleportedAsset}, - Junctions::Here, - Reanchorable, - WildAsset::AllCounted, - XcmContext, - }, -}; +use xcm::prelude::*; use xcm_executor::traits::TransactAsset; use crate::{ @@ -119,7 +106,7 @@ pub mod pallet { use crate::configuration; use sp_runtime::traits::TryConvert; - use xcm::v4::InteriorLocation; + use xcm::latest::InteriorLocation; use xcm_executor::traits::TransactAsset; use super::*; @@ -149,11 +136,6 @@ pub mod pallet { type AssetTransactor: TransactAsset; /// AccountId to Location converter type AccountToLocation: for<'a> TryConvert<&'a Self::AccountId, Location>; - - /// Maximum weight for any XCM transact call that should be executed on the coretime chain. - /// - /// Basically should be `max_weight(set_leases, reserve, notify_core_count)`. - type MaxXcmTransactWeight: Get; } #[pallet::event] @@ -351,7 +333,6 @@ impl OnNewSession> for Pallet { fn mk_coretime_call(call: crate::coretime::CoretimeCalls) -> Instruction<()> { Instruction::Transact { origin_kind: OriginKind::Superuser, - require_weight_at_most: T::MaxXcmTransactWeight::get(), call: BrokerRuntimePallets::Broker(call).encode().into(), } } @@ -362,7 +343,7 @@ fn do_notify_revenue(when: BlockNumber, raw_revenue: Balance) -> Resu weight_limit: WeightLimit::Unlimited, check_origin: None, }]; - let asset = Asset { id: AssetId(Location::here()), fun: Fungible(raw_revenue) }; + let asset = Asset { id: Location::here().into(), fun: Fungible(raw_revenue) }; let dummy_xcm_context = XcmContext { origin: None, message_id: [0; 32], topic: None }; if raw_revenue > 0 { diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 9ef3922f0f8c..d701e1f9bd80 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -30,7 +30,9 @@ use polkadot_primitives::CoreIndex; use codec::Decode; use frame_support::{ - assert_ok, derive_impl, parameter_types, + assert_ok, derive_impl, + dispatch::GetDispatchInfo, + parameter_types, traits::{ Currency, ProcessMessage, ProcessMessageError, ValidatorSet, ValidatorSetWithIdentification, }, @@ -56,7 +58,7 @@ use std::{ }; use xcm::{ prelude::XcmVersion, - v4::{Assets, InteriorLocation, Location, SendError, SendResult, SendXcm, Xcm, XcmHash}, + v5::{Assets, InteriorLocation, Location, SendError, SendResult, SendXcm, Xcm, XcmHash}, IntoVersion, VersionedXcm, WrapVersion, }; @@ -260,7 +262,7 @@ thread_local! { /// versions in the `VERSION_WRAPPER`. pub struct TestUsesOnlyStoredVersionWrapper; impl WrapVersion for TestUsesOnlyStoredVersionWrapper { - fn wrap_version( + fn wrap_version( dest: &Location, xcm: impl Into>, ) -> Result, ()> { @@ -419,7 +421,6 @@ impl assigner_coretime::Config for Test {} parameter_types! { pub const BrokerId: u32 = 10u32; - pub MaxXcmTransactWeight: Weight = Weight::from_parts(10_000_000, 10_000); } pub struct BrokerPot; @@ -436,7 +437,6 @@ impl coretime::Config for Test { type BrokerId = BrokerId; type WeightInfo = crate::coretime::TestWeightInfo; type SendXcm = DummyXcmSender; - type MaxXcmTransactWeight = MaxXcmTransactWeight; type BrokerPotLocation = BrokerPot; type AssetTransactor = (); type AccountToLocation = (); diff --git a/polkadot/runtime/rococo/src/impls.rs b/polkadot/runtime/rococo/src/impls.rs index f01440ea02bc..ab796edc54b1 100644 --- a/polkadot/runtime/rococo/src/impls.rs +++ b/polkadot/runtime/rococo/src/impls.rs @@ -21,7 +21,7 @@ use core::marker::PhantomData; use frame_support::pallet_prelude::DispatchResult; use frame_system::RawOrigin; use polkadot_primitives::Balance; -use polkadot_runtime_common::identity_migrator::{OnReapIdentity, WeightInfo}; +use polkadot_runtime_common::identity_migrator::OnReapIdentity; use rococo_runtime_constants::currency::*; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm}; use xcm_executor::traits::TransactAsset; @@ -88,10 +88,7 @@ where AccountId: Into<[u8; 32]> + Clone + Encode, { fn on_reap_identity(who: &AccountId, fields: u32, subs: u32) -> DispatchResult { - use crate::{ - impls::IdentityMigratorCalls::PokeDeposit, - weights::polkadot_runtime_common_identity_migrator::WeightInfo as MigratorWeights, - }; + use crate::impls::IdentityMigratorCalls::PokeDeposit; let total_to_send = Self::calculate_remote_deposit(fields, subs); @@ -144,7 +141,6 @@ where .into(); let poke = PeopleRuntimePallets::::IdentityMigrator(PokeDeposit(who.clone())); - let remote_weight_limit = MigratorWeights::::poke_deposit().saturating_mul(2); // Actual program to execute on People Chain. let program: Xcm<()> = Xcm(vec![ @@ -161,18 +157,14 @@ where .into(), }, // Poke the deposit to reserve the appropriate amount on the parachain. - Transact { - origin_kind: OriginKind::Superuser, - require_weight_at_most: remote_weight_limit, - call: poke.encode().into(), - }, + Transact { origin_kind: OriginKind::Superuser, call: poke.encode().into() }, ]); // send let _ = >::send( RawOrigin::Root.into(), - Box::new(VersionedLocation::V4(destination)), - Box::new(VersionedXcm::V4(program)), + Box::new(VersionedLocation::from(destination)), + Box::new(VersionedXcm::from(program)), )?; Ok(()) } diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index f8f8573bc900..96a97faa4750 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -1098,7 +1098,6 @@ impl parachains_scheduler::Config for Runtime { parameter_types! { pub const BrokerId: u32 = BROKER_ID; pub const BrokerPalletId: PalletId = PalletId(*b"py/broke"); - pub MaxXcmTransactWeight: Weight = Weight::from_parts(200_000_000, 20_000); } pub struct BrokerPot; @@ -1122,7 +1121,6 @@ impl coretime::Config for Runtime { xcm_config::ThisNetwork, ::AccountId, >; - type MaxXcmTransactWeight = MaxXcmTransactWeight; } parameter_types! { diff --git a/polkadot/runtime/rococo/src/weights/xcm/mod.rs b/polkadot/runtime/rococo/src/weights/xcm/mod.rs index bd2b0fbb8c06..007002bf27bb 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/mod.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/mod.rs @@ -24,6 +24,7 @@ use xcm::{latest::prelude::*, DoubleEncoded}; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmBalancesWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use xcm::latest::AssetTransferFilter; /// Types of asset supported by the Rococo runtime. pub enum AssetTypes { @@ -110,11 +111,7 @@ impl XcmWeightInfo for RococoXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmBalancesWeight::::transfer_reserve_asset()) } - fn transact( - _origin_kind: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_kind: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -163,12 +160,35 @@ impl XcmWeightInfo for RococoXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmBalancesWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmBalancesWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmBalancesWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -266,6 +286,9 @@ impl XcmWeightInfo for RococoXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } } #[test] diff --git a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 7d743b209124..c1d5c3fc89d9 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -55,8 +55,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 30_672_000 picoseconds. - Weight::from_parts(31_677_000, 3593) + // Minimum execution time: 32_017_000 picoseconds. + Weight::from_parts(32_841_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -66,8 +66,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 41_132_000 picoseconds. - Weight::from_parts(41_654_000, 6196) + // Minimum execution time: 42_570_000 picoseconds. + Weight::from_parts(43_526_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -85,8 +85,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `6196` - // Minimum execution time: 97_174_000 picoseconds. - Weight::from_parts(99_537_000, 6196) + // Minimum execution time: 103_020_000 picoseconds. + Weight::from_parts(104_906_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -113,8 +113,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `3746` - // Minimum execution time: 67_105_000 picoseconds. - Weight::from_parts(68_659_000, 3746) + // Minimum execution time: 70_944_000 picoseconds. + Weight::from_parts(73_630_000, 3746) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -124,8 +124,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `3593` - // Minimum execution time: 30_780_000 picoseconds. - Weight::from_parts(31_496_000, 3593) + // Minimum execution time: 31_979_000 picoseconds. + Weight::from_parts(32_649_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -135,8 +135,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 23_411_000 picoseconds. - Weight::from_parts(23_891_000, 3593) + // Minimum execution time: 24_462_000 picoseconds. + Weight::from_parts(25_052_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -154,8 +154,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `180` // Estimated: `3645` - // Minimum execution time: 61_541_000 picoseconds. - Weight::from_parts(63_677_000, 3645) + // Minimum execution time: 65_047_000 picoseconds. + Weight::from_parts(67_225_000, 3645) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -173,8 +173,27 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `180` // Estimated: `3645` - // Minimum execution time: 48_574_000 picoseconds. - Weight::from_parts(49_469_000, 3645) + // Minimum execution time: 53_401_000 picoseconds. + Weight::from_parts(55_155_000, 3645) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub(crate) fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `180` + // Estimated: `3645` + // Minimum execution time: 82_584_000 picoseconds. + Weight::from_parts(84_614_000, 3645) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } diff --git a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index df2f9b2d0e8d..677640b45331 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -16,28 +16,27 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-06-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bm3`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("rococo-dev"), DB CACHE: 1024 +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("rococo-dev"), DB CACHE: 1024 // Executed Command: -// ./target/production/polkadot +// target/production/polkadot // benchmark // pallet // --steps=50 // --repeat=20 // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/var/lib/gitlab-runner/builds/zyw4fam_/0/parity/mirrors/polkadot/.git/.artifacts/bench.json +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_xcm_benchmarks::generic // --chain=rococo-dev -// --header=./file_header.txt -// --template=./xcm/pallet-xcm-benchmarks/template.hbs -// --output=./runtime/rococo/src/weights/xcm/ +// --header=./polkadot/file_header.txt +// --template=./polkadot/xcm/pallet-xcm-benchmarks/template.hbs +// --output=./polkadot/runtime/rococo/src/weights/xcm/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -50,130 +49,125 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); impl WeightInfo { - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_holding() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 36_305_000 picoseconds. - Weight::from_parts(37_096_000, 4030) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `281` + // Estimated: `3746` + // Minimum execution time: 64_284_000 picoseconds. + Weight::from_parts(65_590_000, 3746) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } pub(crate) fn buy_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_831_000 picoseconds. - Weight::from_parts(2_904_000, 0) + // Minimum execution time: 777_000 picoseconds. + Weight::from_parts(825_000, 0) } - /// Storage: XcmPallet Queries (r:1 w:0) - /// Proof Skipped: XcmPallet Queries (max_values: None, max_size: None, mode: Measured) + pub(crate) fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_543_000 picoseconds. + Weight::from_parts(1_627_000, 0) + } + /// Storage: `XcmPallet::Queries` (r:1 w:0) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn query_response() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 11_769_000 picoseconds. - Weight::from_parts(12_122_000, 3634) + // Measured: `0` + // Estimated: `3465` + // Minimum execution time: 5_995_000 picoseconds. + Weight::from_parts(6_151_000, 3465) .saturating_add(T::DbWeight::get().reads(1)) } pub(crate) fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_293_000 picoseconds. - Weight::from_parts(12_522_000, 0) + // Minimum execution time: 7_567_000 picoseconds. + Weight::from_parts(7_779_000, 0) } pub(crate) fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_858_000 picoseconds. - Weight::from_parts(2_965_000, 0) + // Minimum execution time: 1_226_000 picoseconds. + Weight::from_parts(1_322_000, 0) } pub(crate) fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_623_000 picoseconds. - Weight::from_parts(2_774_000, 0) + // Minimum execution time: 768_000 picoseconds. + Weight::from_parts(828_000, 0) } pub(crate) fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_664_000 picoseconds. - Weight::from_parts(2_752_000, 0) + // Minimum execution time: 765_000 picoseconds. + Weight::from_parts(814_000, 0) } pub(crate) fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_646_000 picoseconds. - Weight::from_parts(2_709_000, 0) + // Minimum execution time: 739_000 picoseconds. + Weight::from_parts(820_000, 0) } pub(crate) fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_602_000 picoseconds. - Weight::from_parts(3_669_000, 0) + // Minimum execution time: 806_000 picoseconds. + Weight::from_parts(849_000, 0) } pub(crate) fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_609_000 picoseconds. - Weight::from_parts(2_721_000, 0) + // Minimum execution time: 782_000 picoseconds. + Weight::from_parts(820_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_error() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 31_776_000 picoseconds. - Weight::from_parts(32_354_000, 4030) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `281` + // Estimated: `3746` + // Minimum execution time: 61_410_000 picoseconds. + Weight::from_parts(62_813_000, 3746) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: XcmPallet AssetTraps (r:1 w:1) - /// Proof Skipped: XcmPallet AssetTraps (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::AssetTraps` (r:1 w:1) + /// Proof: `XcmPallet::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn claim_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `226` - // Estimated: `3691` - // Minimum execution time: 15_912_000 picoseconds. - Weight::from_parts(16_219_000, 3691) + // Measured: `23` + // Estimated: `3488` + // Minimum execution time: 9_315_000 picoseconds. + Weight::from_parts(9_575_000, 3488) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -181,171 +175,158 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_704_000 picoseconds. - Weight::from_parts(2_777_000, 0) + // Minimum execution time: 733_000 picoseconds. + Weight::from_parts(813_000, 0) } - /// Storage: XcmPallet VersionNotifyTargets (r:1 w:1) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:1 w:1) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn subscribe_version() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 38_690_000 picoseconds. - Weight::from_parts(39_157_000, 4030) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(5)) + // Measured: `180` + // Estimated: `3645` + // Minimum execution time: 30_641_000 picoseconds. + Weight::from_parts(31_822_000, 3645) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: XcmPallet VersionNotifyTargets (r:0 w:1) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:0 w:1) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn unsubscribe_version() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_943_000 picoseconds. - Weight::from_parts(5_128_000, 0) + // Minimum execution time: 2_978_000 picoseconds. + Weight::from_parts(3_260_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub(crate) fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_438_000 picoseconds. - Weight::from_parts(6_500_000, 0) + // Minimum execution time: 1_139_000 picoseconds. + Weight::from_parts(1_272_000, 0) } pub(crate) fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_773_000 picoseconds. - Weight::from_parts(4_840_000, 0) + // Minimum execution time: 850_000 picoseconds. + Weight::from_parts(879_000, 0) } pub(crate) fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_818_000 picoseconds. - Weight::from_parts(2_893_000, 0) + // Minimum execution time: 770_000 picoseconds. + Weight::from_parts(834_000, 0) } pub(crate) fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_611_000 picoseconds. - Weight::from_parts(2_708_000, 0) + // Minimum execution time: 756_000 picoseconds. + Weight::from_parts(797_000, 0) } pub(crate) fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_870_000 picoseconds. - Weight::from_parts(2_958_000, 0) + // Minimum execution time: 888_000 picoseconds. + Weight::from_parts(1_000_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn query_pallet() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 40_735_000 picoseconds. - Weight::from_parts(66_023_000, 4030) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `281` + // Estimated: `3746` + // Minimum execution time: 72_138_000 picoseconds. + Weight::from_parts(73_728_000, 3746) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } pub(crate) fn expect_pallet() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_293_000 picoseconds. - Weight::from_parts(18_088_000, 0) + // Minimum execution time: 8_482_000 picoseconds. + Weight::from_parts(8_667_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Configuration ActiveConfig (r:1 w:0) - /// Proof Skipped: Configuration ActiveConfig (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_transact_status() -> Weight { // Proof Size summary in bytes: - // Measured: `565` - // Estimated: `4030` - // Minimum execution time: 31_438_000 picoseconds. - Weight::from_parts(32_086_000, 4030) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(4)) + // Measured: `281` + // Estimated: `3746` + // Minimum execution time: 61_580_000 picoseconds. + Weight::from_parts(62_928_000, 3746) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } pub(crate) fn clear_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_676_000 picoseconds. - Weight::from_parts(2_746_000, 0) + // Minimum execution time: 807_000 picoseconds. + Weight::from_parts(844_000, 0) } pub(crate) fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_629_000 picoseconds. - Weight::from_parts(2_724_000, 0) + // Minimum execution time: 757_000 picoseconds. + Weight::from_parts(808_000, 0) } pub(crate) fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_602_000 picoseconds. - Weight::from_parts(2_671_000, 0) + // Minimum execution time: 740_000 picoseconds. + Weight::from_parts(810_000, 0) } pub(crate) fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_681_000 picoseconds. - Weight::from_parts(2_768_000, 0) + // Minimum execution time: 752_000 picoseconds. + Weight::from_parts(786_000, 0) } pub(crate) fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_764_000 picoseconds. - Weight::from_parts(2_865_000, 0) + // Minimum execution time: 798_000 picoseconds. + Weight::from_parts(845_000, 0) + } + pub(crate) fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) } } diff --git a/polkadot/runtime/rococo/src/xcm_config.rs b/polkadot/runtime/rococo/src/xcm_config.rs index 05e0ee64820a..82a3136cc0d9 100644 --- a/polkadot/runtime/rococo/src/xcm_config.rs +++ b/polkadot/runtime/rococo/src/xcm_config.rs @@ -35,7 +35,7 @@ use polkadot_runtime_common::{ }; use rococo_runtime_constants::{currency::CENTS, system_parachain::*}; use sp_core::ConstU32; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, @@ -51,7 +51,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub TokenLocation: Location = Here.into_location(); pub RootLocation: Location = Location::here(); - pub const ThisNetwork: NetworkId = NetworkId::Rococo; + pub const ThisNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub UniversalLocation: InteriorLocation = ThisNetwork::get().into(); pub CheckAccount: AccountId = XcmPallet::check_account(); pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local); diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index bb46b19956e8..d2ed5abb6ed1 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -93,7 +93,7 @@ use sp_staking::SessionIndex; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use xcm::v4::{Assets, InteriorLocation, Location, SendError, SendResult, SendXcm, XcmHash}; +use xcm::latest::{Assets, InteriorLocation, Location, SendError, SendResult, SendXcm, XcmHash}; pub use pallet_balances::Call as BalancesCall; #[cfg(feature = "std")] @@ -584,7 +584,6 @@ impl parachains_paras::Config for Runtime { parameter_types! { pub const BrokerId: u32 = 10u32; - pub MaxXcmTransactWeight: Weight = Weight::from_parts(10_000_000, 10_000); } pub struct BrokerPot; @@ -640,7 +639,7 @@ impl SendXcm for DummyXcmSender { type Ticket = (); fn validate( _: &mut Option, - _: &mut Option>, + _: &mut Option>, ) -> SendResult { Ok(((), Assets::new())) } @@ -658,7 +657,6 @@ impl coretime::Config for Runtime { type BrokerId = BrokerId; type WeightInfo = crate::coretime::TestWeightInfo; type SendXcm = DummyXcmSender; - type MaxXcmTransactWeight = MaxXcmTransactWeight; type BrokerPotLocation = BrokerPot; type AssetTransactor = (); type AccountToLocation = (); diff --git a/polkadot/runtime/westend/src/impls.rs b/polkadot/runtime/westend/src/impls.rs index ac3f9e679f8d..d7281dad56d4 100644 --- a/polkadot/runtime/westend/src/impls.rs +++ b/polkadot/runtime/westend/src/impls.rs @@ -21,7 +21,7 @@ use core::marker::PhantomData; use frame_support::pallet_prelude::DispatchResult; use frame_system::RawOrigin; use polkadot_primitives::Balance; -use polkadot_runtime_common::identity_migrator::{OnReapIdentity, WeightInfo}; +use polkadot_runtime_common::identity_migrator::OnReapIdentity; use westend_runtime_constants::currency::*; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm}; use xcm_executor::traits::TransactAsset; @@ -88,10 +88,7 @@ where AccountId: Into<[u8; 32]> + Clone + Encode, { fn on_reap_identity(who: &AccountId, fields: u32, subs: u32) -> DispatchResult { - use crate::{ - impls::IdentityMigratorCalls::PokeDeposit, - weights::polkadot_runtime_common_identity_migrator::WeightInfo as MigratorWeights, - }; + use crate::impls::IdentityMigratorCalls::PokeDeposit; let total_to_send = Self::calculate_remote_deposit(fields, subs); @@ -144,7 +141,6 @@ where .into(); let poke = PeopleRuntimePallets::::IdentityMigrator(PokeDeposit(who.clone())); - let remote_weight_limit = MigratorWeights::::poke_deposit().saturating_mul(2); // Actual program to execute on People Chain. let program: Xcm<()> = Xcm(vec![ @@ -161,18 +157,14 @@ where .into(), }, // Poke the deposit to reserve the appropriate amount on the parachain. - Transact { - origin_kind: OriginKind::Superuser, - require_weight_at_most: remote_weight_limit, - call: poke.encode().into(), - }, + Transact { origin_kind: OriginKind::Superuser, call: poke.encode().into() }, ]); // send let _ = >::send( RawOrigin::Root.into(), - Box::new(VersionedLocation::V4(destination)), - Box::new(VersionedXcm::V4(program)), + Box::new(VersionedLocation::from(destination)), + Box::new(VersionedXcm::from(program)), )?; Ok(()) } diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 21790e259f07..a9a76dbced10 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -1323,7 +1323,6 @@ impl parachains_scheduler::Config for Runtime { parameter_types! { pub const BrokerId: u32 = BROKER_ID; pub const BrokerPalletId: PalletId = PalletId(*b"py/broke"); - pub MaxXcmTransactWeight: Weight = Weight::from_parts(200_000_000, 20_000); } pub struct BrokerPot; @@ -1347,7 +1346,6 @@ impl coretime::Config for Runtime { xcm_config::ThisNetwork, ::AccountId, >; - type MaxXcmTransactWeight = MaxXcmTransactWeight; } parameter_types! { diff --git a/polkadot/runtime/westend/src/weights/xcm/mod.rs b/polkadot/runtime/westend/src/weights/xcm/mod.rs index cb5894ea51e3..e5f4a0d7ca8e 100644 --- a/polkadot/runtime/westend/src/weights/xcm/mod.rs +++ b/polkadot/runtime/westend/src/weights/xcm/mod.rs @@ -27,6 +27,7 @@ use xcm::{ use pallet_xcm_benchmarks_fungible::WeightInfo as XcmBalancesWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use xcm::latest::AssetTransferFilter; /// Types of asset supported by the westend runtime. pub enum AssetTypes { @@ -113,11 +114,7 @@ impl XcmWeightInfo for WestendXcmWeight { fn transfer_reserve_asset(assets: &Assets, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmBalancesWeight::::transfer_reserve_asset()) } - fn transact( - _origin_kind: &OriginKind, - _require_weight_at_most: &Weight, - _call: &DoubleEncoded, - ) -> Weight { + fn transact(_origin_kind: &OriginKind, _call: &DoubleEncoded) -> Weight { XcmGeneric::::transact() } fn hrmp_new_channel_open_request( @@ -166,12 +163,35 @@ impl XcmWeightInfo for WestendXcmWeight { fn initiate_teleport(assets: &AssetFilter, _dest: &Location, _xcm: &Xcm<()>) -> Weight { assets.weigh_assets(XcmBalancesWeight::::initiate_teleport()) } + fn initiate_transfer( + _dest: &Location, + remote_fees: &Option, + _preserve_origin: &bool, + assets: &Vec, + _xcm: &Xcm<()>, + ) -> Weight { + let mut weight = if let Some(remote_fees) = remote_fees { + let fees = remote_fees.inner(); + fees.weigh_assets(XcmBalancesWeight::::initiate_transfer()) + } else { + Weight::zero() + }; + for asset_filter in assets { + let assets = asset_filter.inner(); + let extra = assets.weigh_assets(XcmBalancesWeight::::initiate_transfer()); + weight = weight.saturating_add(extra); + } + weight + } fn report_holding(_response_info: &QueryResponseInfo, _assets: &AssetFilter) -> Weight { XcmGeneric::::report_holding() } fn buy_execution(_fees: &Asset, _weight_limit: &WeightLimit) -> Weight { XcmGeneric::::buy_execution() } + fn pay_fees(_asset: &Asset) -> Weight { + XcmGeneric::::pay_fees() + } fn refund_surplus() -> Weight { XcmGeneric::::refund_surplus() } @@ -184,6 +204,11 @@ impl XcmWeightInfo for WestendXcmWeight { fn clear_error() -> Weight { XcmGeneric::::clear_error() } + + fn set_asset_claimer(_location: &Location) -> Weight { + XcmGeneric::::set_asset_claimer() + } + fn claim_asset(_assets: &Assets, _ticket: &Location) -> Weight { XcmGeneric::::claim_asset() } diff --git a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index e0c61c8e2bf2..f1ce760d48cf 100644 --- a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-10-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 // Executed Command: @@ -55,8 +55,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 31_780_000 picoseconds. - Weight::from_parts(32_602_000, 3593) + // Minimum execution time: 31_578_000 picoseconds. + Weight::from_parts(32_243_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -66,8 +66,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 41_818_000 picoseconds. - Weight::from_parts(42_902_000, 6196) + // Minimum execution time: 42_320_000 picoseconds. + Weight::from_parts(43_036_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -85,8 +85,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `8799` - // Minimum execution time: 101_949_000 picoseconds. - Weight::from_parts(104_190_000, 8799) + // Minimum execution time: 101_972_000 picoseconds. + Weight::from_parts(104_288_000, 8799) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -113,8 +113,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `6196` - // Minimum execution time: 70_123_000 picoseconds. - Weight::from_parts(72_564_000, 6196) + // Minimum execution time: 71_916_000 picoseconds. + Weight::from_parts(73_610_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -124,8 +124,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `3593` - // Minimum execution time: 31_868_000 picoseconds. - Weight::from_parts(32_388_000, 3593) + // Minimum execution time: 31_683_000 picoseconds. + Weight::from_parts(32_138_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -135,8 +135,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 24_532_000 picoseconds. - Weight::from_parts(25_166_000, 3593) + // Minimum execution time: 23_786_000 picoseconds. + Weight::from_parts(24_188_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -154,8 +154,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `147` // Estimated: `3612` - // Minimum execution time: 63_378_000 picoseconds. - Weight::from_parts(65_002_000, 3612) + // Minimum execution time: 63_986_000 picoseconds. + Weight::from_parts(65_356_000, 3612) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -173,9 +173,28 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `147` // Estimated: `3612` - // Minimum execution time: 49_174_000 picoseconds. - Weight::from_parts(50_356_000, 3612) + // Minimum execution time: 52_672_000 picoseconds. + Weight::from_parts(54_623_000, 3612) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub(crate) fn initiate_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `250` + // Estimated: `6196` + // Minimum execution time: 83_853_000 picoseconds. + Weight::from_parts(85_876_000, 6196) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + } } diff --git a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 49beb85c2784..2ad1cd6359a6 100644 --- a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -16,11 +16,11 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-06-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-09-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `bm3`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz` -//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 +//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 // Executed Command: // target/production/polkadot @@ -29,14 +29,14 @@ // --steps=50 // --repeat=20 // --extrinsic=* -// --execution=wasm // --wasm-execution=compiled // --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_xcm_benchmarks::generic // --chain=westend-dev -// --header=./file_header.txt -// --template=./xcm/pallet-xcm-benchmarks/template.hbs -// --output=./runtime/westend/src/weights/xcm/ +// --header=./polkadot/file_header.txt +// --template=./polkadot/xcm/pallet-xcm-benchmarks/template.hbs +// --output=./polkadot/runtime/westend/src/weights/xcm/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -49,126 +49,132 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); impl WeightInfo { - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_holding() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 30_790_000 picoseconds. - Weight::from_parts(31_265_000, 3634) - .saturating_add(T::DbWeight::get().reads(7)) + // Measured: `351` + // Estimated: `6196` + // Minimum execution time: 67_813_000 picoseconds. + Weight::from_parts(69_357_000, 6196) + .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } pub(crate) fn buy_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_741_000 picoseconds. - Weight::from_parts(2_823_000, 0) + // Minimum execution time: 716_000 picoseconds. + Weight::from_parts(780_000, 0) } - /// Storage: XcmPallet Queries (r:1 w:0) - /// Proof Skipped: XcmPallet Queries (max_values: None, max_size: None, mode: Measured) + pub(crate) fn pay_fees() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_601_000 picoseconds. + Weight::from_parts(1_680_000, 0) + } + pub(crate) fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(749_000, 0) + } + /// Storage: `XcmPallet::Queries` (r:1 w:0) + /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn query_response() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 10_848_000 picoseconds. - Weight::from_parts(11_183_000, 3634) + // Measured: `0` + // Estimated: `3465` + // Minimum execution time: 6_574_000 picoseconds. + Weight::from_parts(6_790_000, 3465) .saturating_add(T::DbWeight::get().reads(1)) } pub(crate) fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_145_000 picoseconds. - Weight::from_parts(12_366_000, 0) + // Minimum execution time: 7_232_000 picoseconds. + Weight::from_parts(7_422_000, 0) } pub(crate) fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_837_000 picoseconds. - Weight::from_parts(2_939_000, 0) + // Minimum execution time: 1_180_000 picoseconds. + Weight::from_parts(1_250_000, 0) } pub(crate) fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_526_000 picoseconds. - Weight::from_parts(2_622_000, 0) + // Minimum execution time: 702_000 picoseconds. + Weight::from_parts(766_000, 0) } pub(crate) fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_603_000 picoseconds. - Weight::from_parts(2_642_000, 0) + // Minimum execution time: 700_000 picoseconds. + Weight::from_parts(757_000, 0) } pub(crate) fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_500_000 picoseconds. - Weight::from_parts(2_573_000, 0) + // Minimum execution time: 686_000 picoseconds. + Weight::from_parts(751_000, 0) } pub(crate) fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_323_000 picoseconds. - Weight::from_parts(3_401_000, 0) + // Minimum execution time: 705_000 picoseconds. + Weight::from_parts(765_000, 0) } pub(crate) fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_557_000 picoseconds. - Weight::from_parts(2_620_000, 0) + // Minimum execution time: 687_000 picoseconds. + Weight::from_parts(741_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_error() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 25_828_000 picoseconds. - Weight::from_parts(26_318_000, 3634) - .saturating_add(T::DbWeight::get().reads(7)) + // Measured: `351` + // Estimated: `6196` + // Minimum execution time: 65_398_000 picoseconds. + Weight::from_parts(67_140_000, 6196) + .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } - /// Storage: XcmPallet AssetTraps (r:1 w:1) - /// Proof Skipped: XcmPallet AssetTraps (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::AssetTraps` (r:1 w:1) + /// Proof: `XcmPallet::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn claim_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `226` - // Estimated: `3691` - // Minimum execution time: 14_794_000 picoseconds. - Weight::from_parts(15_306_000, 3691) + // Measured: `23` + // Estimated: `3488` + // Minimum execution time: 9_653_000 picoseconds. + Weight::from_parts(9_944_000, 3488) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -176,165 +182,151 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_534_000 picoseconds. - Weight::from_parts(2_574_000, 0) + // Minimum execution time: 698_000 picoseconds. + Weight::from_parts(759_000, 0) } - /// Storage: XcmPallet VersionNotifyTargets (r:1 w:1) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:1 w:1) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn subscribe_version() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 32_218_000 picoseconds. - Weight::from_parts(32_945_000, 3634) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(5)) + // Measured: `147` + // Estimated: `3612` + // Minimum execution time: 31_300_000 picoseconds. + Weight::from_parts(31_989_000, 3612) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: XcmPallet VersionNotifyTargets (r:0 w:1) - /// Proof Skipped: XcmPallet VersionNotifyTargets (max_values: None, max_size: None, mode: Measured) + /// Storage: `XcmPallet::VersionNotifyTargets` (r:0 w:1) + /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn unsubscribe_version() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_983_000 picoseconds. - Weight::from_parts(5_132_000, 0) + // Minimum execution time: 2_863_000 picoseconds. + Weight::from_parts(3_027_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub(crate) fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_101_000 picoseconds. - Weight::from_parts(4_228_000, 0) + // Minimum execution time: 1_046_000 picoseconds. + Weight::from_parts(1_125_000, 0) } pub(crate) fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_740_000 picoseconds. - Weight::from_parts(2_814_000, 0) + // Minimum execution time: 811_000 picoseconds. + Weight::from_parts(871_000, 0) } pub(crate) fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_716_000 picoseconds. - Weight::from_parts(2_795_000, 0) + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(741_000, 0) } pub(crate) fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_550_000 picoseconds. - Weight::from_parts(2_601_000, 0) + // Minimum execution time: 687_000 picoseconds. + Weight::from_parts(741_000, 0) } pub(crate) fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_762_000 picoseconds. - Weight::from_parts(2_849_000, 0) + // Minimum execution time: 861_000 picoseconds. + Weight::from_parts(931_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn query_pallet() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 31_709_000 picoseconds. - Weight::from_parts(32_288_000, 3634) - .saturating_add(T::DbWeight::get().reads(7)) + // Measured: `351` + // Estimated: `6196` + // Minimum execution time: 74_622_000 picoseconds. + Weight::from_parts(77_059_000, 6196) + .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } pub(crate) fn expect_pallet() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_209_000 picoseconds. - Weight::from_parts(7_332_000, 0) + // Minimum execution time: 7_603_000 picoseconds. + Weight::from_parts(7_871_000, 0) } - /// Storage: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Proof Skipped: unknown `0x3a696e747261626c6f636b5f656e74726f7079` (r:1 w:1) - /// Storage: Dmp DeliveryFeeFactor (r:1 w:0) - /// Proof Skipped: Dmp DeliveryFeeFactor (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet SupportedVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SupportedVersion (max_values: None, max_size: None, mode: Measured) - /// Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) - /// Proof Skipped: XcmPallet VersionDiscoveryQueue (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: XcmPallet SafeXcmVersion (r:1 w:0) - /// Proof Skipped: XcmPallet SafeXcmVersion (max_values: Some(1), max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueues (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueues (max_values: None, max_size: None, mode: Measured) - /// Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) - /// Proof Skipped: Dmp DownwardMessageQueueHeads (max_values: None, max_size: None, mode: Measured) + /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) + /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) + /// Proof: `XcmPallet::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Dmp::DownwardMessageQueues` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueues` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Dmp::DownwardMessageQueueHeads` (r:1 w:1) + /// Proof: `Dmp::DownwardMessageQueueHeads` (`max_values`: None, `max_size`: None, mode: `Measured`) pub(crate) fn report_transact_status() -> Weight { // Proof Size summary in bytes: - // Measured: `169` - // Estimated: `3634` - // Minimum execution time: 26_161_000 picoseconds. - Weight::from_parts(26_605_000, 3634) - .saturating_add(T::DbWeight::get().reads(7)) + // Measured: `351` + // Estimated: `6196` + // Minimum execution time: 65_617_000 picoseconds. + Weight::from_parts(66_719_000, 6196) + .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } pub(crate) fn clear_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_539_000 picoseconds. - Weight::from_parts(2_647_000, 0) + // Minimum execution time: 738_000 picoseconds. + Weight::from_parts(779_000, 0) } pub(crate) fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_494_000 picoseconds. - Weight::from_parts(2_588_000, 0) + // Minimum execution time: 688_000 picoseconds. + Weight::from_parts(755_000, 0) } pub(crate) fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_510_000 picoseconds. - Weight::from_parts(2_590_000, 0) + // Minimum execution time: 684_000 picoseconds. + Weight::from_parts(722_000, 0) } pub(crate) fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_491_000 picoseconds. - Weight::from_parts(2_546_000, 0) + // Minimum execution time: 694_000 picoseconds. + Weight::from_parts(738_000, 0) } pub(crate) fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_696_000 picoseconds. - Weight::from_parts(2_816_000, 0) + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) } } diff --git a/polkadot/runtime/westend/src/xcm_config.rs b/polkadot/runtime/westend/src/xcm_config.rs index d75083929a04..f8bb2676de3f 100644 --- a/polkadot/runtime/westend/src/xcm_config.rs +++ b/polkadot/runtime/westend/src/xcm_config.rs @@ -36,7 +36,7 @@ use sp_core::ConstU32; use westend_runtime_constants::{ currency::CENTS, system_parachain::*, xcm::body::FELLOWSHIP_ADMIN_INDEX, }; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, WESTEND_GENESIS_HASH}; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, @@ -51,7 +51,7 @@ use xcm_executor::XcmExecutor; parameter_types! { pub const TokenLocation: Location = Here.into_location(); pub const RootLocation: Location = Location::here(); - pub const ThisNetwork: NetworkId = Westend; + pub const ThisNetwork: NetworkId = ByGenesis(WESTEND_GENESIS_HASH); pub UniversalLocation: InteriorLocation = [GlobalConsensus(ThisNetwork::get())].into(); pub CheckAccount: AccountId = XcmPallet::check_account(); pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local); diff --git a/polkadot/xcm/Cargo.toml b/polkadot/xcm/Cargo.toml index 862f5557a012..86c7067ad6fa 100644 --- a/polkadot/xcm/Cargo.toml +++ b/polkadot/xcm/Cargo.toml @@ -23,11 +23,12 @@ serde = { features = ["alloc", "derive", "rc"], workspace = true } schemars = { default-features = true, optional = true, workspace = true } xcm-procedural = { workspace = true, default-features = true } environmental = { workspace = true } +hex-literal = { workspace = true, default-features = true } +frame-support = { workspace = true } [dev-dependencies] sp-io = { workspace = true, default-features = true } hex = { workspace = true, default-features = true } -hex-literal = { workspace = true, default-features = true } [features] default = ["std"] @@ -36,6 +37,7 @@ std = [ "bounded-collections/std", "codec/std", "environmental/std", + "frame-support/std", "log/std", "scale-info/std", "serde/std", diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs index f8a1826b8ab1..0180354458ce 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/xcm_config.rs @@ -21,7 +21,7 @@ use frame::{ runtime::prelude::*, traits::{Everything, Nothing}, }; -use xcm::v4::prelude::*; +use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs index 686f86b37b73..cd8701dbbede 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs @@ -23,7 +23,7 @@ use frame::{ traits::{IdentityLookup, ProcessMessage, ProcessMessageError}, }; use polkadot_runtime_parachains::inclusion::{AggregateMessageOrigin, UmpQueueId}; -use xcm::v4::prelude::*; +use xcm::latest::prelude::*; mod xcm_config; pub use xcm_config::LocationToAccountId; diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs index e7b602df7338..06b00c39e8a0 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/xcm_config.rs @@ -21,7 +21,7 @@ use frame::{ runtime::prelude::*, traits::{Everything, Nothing}, }; -use xcm::v4::prelude::*; +use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/tests.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/tests.rs index 792cf6149e7c..b7fdaa34ec8c 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/tests.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/tests.rs @@ -65,9 +65,9 @@ fn reserve_asset_transfers_work() { let assets: Assets = (Here, 50u128 * CENTS as u128).into(); assert_ok!(relay_chain::XcmPallet::transfer_assets( relay_chain::RuntimeOrigin::signed(ALICE), - Box::new(VersionedLocation::V4(destination.clone())), - Box::new(VersionedLocation::V4(beneficiary)), - Box::new(VersionedAssets::V4(assets)), + Box::new(VersionedLocation::from(destination.clone())), + Box::new(VersionedLocation::from(beneficiary)), + Box::new(VersionedAssets::from(assets)), 0, WeightLimit::Unlimited, )); @@ -101,9 +101,9 @@ fn reserve_asset_transfers_work() { let assets: Assets = (Parent, 25u128 * CENTS as u128).into(); assert_ok!(parachain::XcmPallet::transfer_assets( parachain::RuntimeOrigin::signed(BOB), - Box::new(VersionedLocation::V4(destination)), - Box::new(VersionedLocation::V4(beneficiary)), - Box::new(VersionedAssets::V4(assets)), + Box::new(VersionedLocation::from(destination)), + Box::new(VersionedLocation::from(beneficiary)), + Box::new(VersionedAssets::from(assets)), 0, WeightLimit::Unlimited, )); diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index 6ce49074a6e2..303ff9493f71 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -24,7 +24,7 @@ use frame_support::{ weights::Weight, }; use sp_runtime::traits::{Bounded, Zero}; -use xcm::latest::{prelude::*, MAX_ITEMS_IN_ASSETS}; +use xcm::latest::{prelude::*, AssetTransferFilter, MAX_ITEMS_IN_ASSETS}; use xcm_executor::traits::{ConvertLocation, FeeReason, TransactAsset}; benchmarks_instance_pallet! { @@ -299,6 +299,33 @@ benchmarks_instance_pallet! { } } + initiate_transfer { + let (sender_account, sender_location) = account_and_location::(1); + let asset = T::get_asset(); + let mut holding = T::worst_case_holding(1); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + + // Add our asset to the holding. + holding.push(asset.clone()); + + let mut executor = new_executor::(sender_location); + executor.set_holding(holding.into()); + let instruction = Instruction::>::InitiateTransfer { + destination: T::valid_destination()?, + // ReserveDeposit is the most expensive filter. + remote_fees: Some(AssetTransferFilter::ReserveDeposit(asset.clone().into())), + // It's more expensive if we reanchor the origin. + preserve_origin: true, + assets: vec![AssetTransferFilter::ReserveDeposit(asset.into())], + remote_xcm: Xcm::new(), + }; + let xcm = Xcm(vec![instruction]); + }: { + executor.bench_process(xcm)?; + } verify { + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); + } + impl_benchmark_test_suite!( Pallet, crate::fungible::mock::new_test_ext(), diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index f1ec3f604d7b..0d80ef89a1ce 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -19,7 +19,7 @@ use crate::{account_and_location, new_executor, EnsureDelivery, XcmCallOf}; use alloc::{vec, vec::Vec}; use codec::Encode; use frame_benchmarking::{benchmarks, BenchmarkError}; -use frame_support::{dispatch::GetDispatchInfo, traits::fungible::Inspect}; +use frame_support::traits::fungible::Inspect; use xcm::{ latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight, MAX_ITEMS_IN_ASSETS}, DoubleEncoded, @@ -98,6 +98,36 @@ benchmarks! { } + pay_fees { + let holding = T::worst_case_holding(0).into(); + + let mut executor = new_executor::(Default::default()); + executor.set_holding(holding); + // Set some weight to be paid for. + executor.set_message_weight(Weight::from_parts(100_000_000, 100_000)); + + let fee_asset: Asset = T::fee_asset().unwrap(); + + let instruction = Instruction::>::PayFees { asset: fee_asset }; + + let xcm = Xcm(vec![instruction]); + } : { + executor.bench_process(xcm)?; + } verify {} + + set_asset_claimer { + let mut executor = new_executor::(Default::default()); + let (_, sender_location) = account_and_location::(1); + + let instruction = Instruction::SetAssetClaimer{ location:sender_location.clone() }; + + let xcm = Xcm(vec![instruction]); + }: { + executor.bench_process(xcm)?; + } verify { + assert_eq!(executor.asset_claimer(), Some(sender_location.clone())); + } + query_response { let mut executor = new_executor::(Default::default()); let (query_id, response) = T::worst_case_response(); @@ -121,7 +151,6 @@ benchmarks! { let instruction = Instruction::Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: noop_call.get_dispatch_info().call_weight, call: double_encoded_noop_call, }; let xcm = Xcm(vec![instruction]); diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index 404b9358d4d9..e493d4838f5c 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -382,8 +382,8 @@ benchmarks! { asset.clone().into(), &XcmContext { origin: None, message_id: [0u8; 32], topic: None } ); - let versioned_assets = VersionedAssets::V4(asset.into()); - }: _>(claim_origin.into(), Box::new(versioned_assets), Box::new(VersionedLocation::V4(claim_location))) + let versioned_assets = VersionedAssets::from(Assets::from(asset)); + }: _>(claim_origin.into(), Box::new(versioned_assets), Box::new(VersionedLocation::from(claim_location))) impl_benchmark_test_suite!( Pallet, diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 9b8f735b478f..4a97546b38d1 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -2536,7 +2536,7 @@ impl Pallet { /// /// Returns execution result, events, and any forwarded XCMs to other locations. /// Meant to be used in the `xcm_runtime_apis::dry_run::DryRunApi` runtime API. - pub fn dry_run_xcm( + pub fn dry_run_xcm( origin_location: VersionedLocation, xcm: VersionedXcm, ) -> Result::RuntimeEvent>, XcmDryRunApiError> @@ -3067,7 +3067,7 @@ impl xcm_executor::traits::AssetLock for Pallet { } impl WrapVersion for Pallet { - fn wrap_version( + fn wrap_version( dest: &Location, xcm: impl Into>, ) -> Result, ()> { diff --git a/polkadot/xcm/pallet-xcm/src/tests/mod.rs b/polkadot/xcm/pallet-xcm/src/tests/mod.rs index e98a8f8d2ce7..350530f7711f 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/mod.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/mod.rs @@ -482,14 +482,14 @@ fn claim_assets_works() { // Even though assets are trapped, the extrinsic returns success. assert_ok!(XcmPallet::execute( RuntimeOrigin::signed(ALICE), - Box::new(VersionedXcm::V4(trapping_program)), + Box::new(VersionedXcm::from(trapping_program)), BaseXcmWeight::get() * 2, )); assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE - SEND_AMOUNT); // Expected `AssetsTrapped` event info. let source: Location = Junction::AccountId32 { network: None, id: ALICE.into() }.into(); - let versioned_assets = VersionedAssets::V4(Assets::from((Here, SEND_AMOUNT))); + let versioned_assets = VersionedAssets::from(Assets::from((Here, SEND_AMOUNT))); let hash = BlakeTwo256::hash_of(&(source.clone(), versioned_assets.clone())); // Assets were indeed trapped. @@ -512,10 +512,11 @@ fn claim_assets_works() { // Now claim them with the extrinsic. assert_ok!(XcmPallet::claim_assets( RuntimeOrigin::signed(ALICE), - Box::new(VersionedAssets::V4((Here, SEND_AMOUNT).into())), - Box::new(VersionedLocation::V4( - AccountId32 { network: None, id: ALICE.clone().into() }.into() - )), + Box::new(VersionedAssets::from(Assets::from((Here, SEND_AMOUNT)))), + Box::new(VersionedLocation::from(Location::from(AccountId32 { + network: None, + id: ALICE.clone().into() + }))), )); assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE); assert_eq!(AssetTraps::::iter().collect::>(), vec![]); diff --git a/polkadot/xcm/procedural/src/builder_pattern.rs b/polkadot/xcm/procedural/src/builder_pattern.rs index 09ead1389d19..b65290332af9 100644 --- a/polkadot/xcm/procedural/src/builder_pattern.rs +++ b/polkadot/xcm/procedural/src/builder_pattern.rs @@ -160,13 +160,16 @@ fn generate_builder_impl(name: &Ident, data_enum: &DataEnum) -> Result>>()?; @@ -260,50 +263,75 @@ fn generate_builder_impl(name: &Ident, data_enum: &DataEnum) -> Result, _>>()?; // Then we require fees to be paid - let buy_execution_method = data_enum + let pay_fees_variants = data_enum .variants .iter() - .find(|variant| variant.ident == "BuyExecution") - .map_or( - Err(Error::new_spanned(&data_enum.variants, "No BuyExecution instruction")), - |variant| { - let variant_name = &variant.ident; - let method_name_string = &variant_name.to_string().to_snake_case(); - let method_name = syn::Ident::new(method_name_string, variant_name.span()); - let docs = get_doc_comments(variant); - let fields = match &variant.fields { - Fields::Named(fields) => { - let arg_names: Vec<_> = - fields.named.iter().map(|field| &field.ident).collect(); - let arg_types: Vec<_> = - fields.named.iter().map(|field| &field.ty).collect(); - quote! { - #(#docs)* - pub fn #method_name(self, #(#arg_names: impl Into<#arg_types>),*) -> XcmBuilder { - let mut new_instructions = self.instructions; - #(let #arg_names = #arg_names.into();)* - new_instructions.push(#name::::#variant_name { #(#arg_names),* }); - XcmBuilder { - instructions: new_instructions, - state: core::marker::PhantomData, - } + .map(|variant| { + let maybe_builder_attr = variant.attrs.iter().find(|attr| match attr.meta { + Meta::List(ref list) => list.path.is_ident("builder"), + _ => false, + }); + let builder_attr = match maybe_builder_attr { + Some(builder) => builder.clone(), + None => return Ok(None), /* It's not going to be an instruction that pays fees */ + }; + let Meta::List(ref list) = builder_attr.meta else { unreachable!("We checked before") }; + let inner_ident: Ident = syn::parse2(list.tokens.clone()).map_err(|_| { + Error::new_spanned( + &builder_attr, + "Expected `builder(loads_holding)` or `builder(pays_fees)`", + ) + })?; + let ident_to_match: Ident = syn::parse_quote!(pays_fees); + if inner_ident == ident_to_match { + Ok(Some(variant)) + } else { + Ok(None) // Must have been `loads_holding` instead. + } + }) + .collect::>>()?; + + let pay_fees_methods = pay_fees_variants + .into_iter() + .flatten() + .map(|variant| { + let variant_name = &variant.ident; + let method_name_string = &variant_name.to_string().to_snake_case(); + let method_name = syn::Ident::new(method_name_string, variant_name.span()); + let docs = get_doc_comments(variant); + let fields = match &variant.fields { + Fields::Named(fields) => { + let arg_names: Vec<_> = + fields.named.iter().map(|field| &field.ident).collect(); + let arg_types: Vec<_> = + fields.named.iter().map(|field| &field.ty).collect(); + quote! { + #(#docs)* + pub fn #method_name(self, #(#arg_names: impl Into<#arg_types>),*) -> XcmBuilder { + let mut new_instructions = self.instructions; + #(let #arg_names = #arg_names.into();)* + new_instructions.push(#name::::#variant_name { #(#arg_names),* }); + XcmBuilder { + instructions: new_instructions, + state: core::marker::PhantomData, } } - }, - _ => - return Err(Error::new_spanned( - variant, - "BuyExecution should have named fields", - )), - }; - Ok(fields) - }, - )?; + } + }, + _ => + return Err(Error::new_spanned( + variant, + "Both BuyExecution and PayFees have named fields", + )), + }; + Ok(fields) + }) + .collect::>>()?; let second_impl = quote! { impl XcmBuilder { #(#allowed_after_load_holding_methods)* - #buy_execution_method + #(#pay_fees_methods)* } }; diff --git a/polkadot/xcm/procedural/src/lib.rs b/polkadot/xcm/procedural/src/lib.rs index 4980d84d3282..9971fdceb69a 100644 --- a/polkadot/xcm/procedural/src/lib.rs +++ b/polkadot/xcm/procedural/src/lib.rs @@ -20,25 +20,11 @@ use proc_macro::TokenStream; use syn::{parse_macro_input, DeriveInput}; mod builder_pattern; -mod v2; mod v3; mod v4; +mod v5; mod weight_info; -#[proc_macro] -pub fn impl_conversion_functions_for_multilocation_v2(input: TokenStream) -> TokenStream { - v2::multilocation::generate_conversion_functions(input) - .unwrap_or_else(syn::Error::into_compile_error) - .into() -} - -#[proc_macro] -pub fn impl_conversion_functions_for_junctions_v2(input: TokenStream) -> TokenStream { - v2::junctions::generate_conversion_functions(input) - .unwrap_or_else(syn::Error::into_compile_error) - .into() -} - #[proc_macro_derive(XcmWeightInfoTrait)] pub fn derive_xcm_weight_info(item: TokenStream) -> TokenStream { weight_info::derive(item) @@ -72,6 +58,20 @@ pub fn impl_conversion_functions_for_junctions_v4(input: TokenStream) -> TokenSt .into() } +#[proc_macro] +pub fn impl_conversion_functions_for_junctions_v5(input: TokenStream) -> TokenStream { + v5::junctions::generate_conversion_functions(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + +#[proc_macro] +pub fn impl_conversion_functions_for_location_v5(input: TokenStream) -> TokenStream { + v5::location::generate_conversion_functions(input) + .unwrap_or_else(syn::Error::into_compile_error) + .into() +} + /// This is called on the `Instruction` enum, not on the `Xcm` struct, /// and allows for the following syntax for building XCMs: /// let message = Xcm::builder() diff --git a/polkadot/xcm/procedural/src/v2.rs b/polkadot/xcm/procedural/src/v2.rs deleted file mode 100644 index 6878f7755cc7..000000000000 --- a/polkadot/xcm/procedural/src/v2.rs +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -use proc_macro2::{Span, TokenStream}; -use quote::{format_ident, quote}; -use syn::{Result, Token}; - -pub mod multilocation { - use super::*; - - pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { - if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) - } - - // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. - let from_tuples = generate_conversion_from_tuples(8); - let from_v3 = generate_conversion_from_v3(); - - Ok(quote! { - #from_tuples - #from_v3 - }) - } - - fn generate_conversion_from_tuples(max_parents: u8) -> TokenStream { - let mut from_tuples = (0..8usize) - .map(|num_junctions| { - let junctions = - (0..=num_junctions).map(|_| format_ident!("Junction")).collect::>(); - let idents = - (0..=num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); - let variant = &format_ident!("X{}", num_junctions + 1); - let array_size = num_junctions + 1; - - let mut from_tuple = quote! { - impl From<( #(#junctions,)* )> for MultiLocation { - fn from( ( #(#idents,)* ): ( #(#junctions,)* ) ) -> Self { - MultiLocation { parents: 0, interior: Junctions::#variant( #(#idents),* ) } - } - } - - impl From<(u8, #(#junctions),*)> for MultiLocation { - fn from( ( parents, #(#idents),* ): (u8, #(#junctions),* ) ) -> Self { - MultiLocation { parents, interior: Junctions::#variant( #(#idents),* ) } - } - } - - impl From<(Ancestor, #(#junctions),*)> for MultiLocation { - fn from( ( Ancestor(parents), #(#idents),* ): (Ancestor, #(#junctions),* ) ) -> Self { - MultiLocation { parents, interior: Junctions::#variant( #(#idents),* ) } - } - } - - impl From<[Junction; #array_size]> for MultiLocation { - fn from(j: [Junction; #array_size]) -> Self { - let [#(#idents),*] = j; - MultiLocation { parents: 0, interior: Junctions::#variant( #(#idents),* ) } - } - } - }; - - let from_parent_tuples = (1..=max_parents).map(|cur_parents| { - let parents = - (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); - let underscores = - (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); - - quote! { - impl From<( #(#parents,)* #(#junctions),* )> for MultiLocation { - fn from( (#(#underscores,)* #(#idents),*): ( #(#parents,)* #(#junctions),* ) ) -> Self { - MultiLocation { parents: #cur_parents, interior: Junctions::#variant( #(#idents),* ) } - } - } - } - }); - - from_tuple.extend(from_parent_tuples); - from_tuple - }) - .collect::(); - - let from_parent_junctions_tuples = (1..=max_parents).map(|cur_parents| { - let parents = (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); - let underscores = - (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); - - quote! { - impl From<( #(#parents,)* Junctions )> for MultiLocation { - fn from( (#(#underscores,)* junctions): ( #(#parents,)* Junctions ) ) -> Self { - MultiLocation { parents: #cur_parents, interior: junctions } - } - } - } - }); - from_tuples.extend(from_parent_junctions_tuples); - - quote! { - impl From for MultiLocation { - fn from(junctions: Junctions) -> Self { - MultiLocation { parents: 0, interior: junctions } - } - } - - impl From<(u8, Junctions)> for MultiLocation { - fn from((parents, interior): (u8, Junctions)) -> Self { - MultiLocation { parents, interior } - } - } - - impl From<(Ancestor, Junctions)> for MultiLocation { - fn from((Ancestor(parents), interior): (Ancestor, Junctions)) -> Self { - MultiLocation { parents, interior } - } - } - - impl From<()> for MultiLocation { - fn from(_: ()) -> Self { - MultiLocation { parents: 0, interior: Junctions::Here } - } - } - - impl From<(u8,)> for MultiLocation { - fn from((parents,): (u8,)) -> Self { - MultiLocation { parents, interior: Junctions::Here } - } - } - - impl From for MultiLocation { - fn from(x: Junction) -> Self { - MultiLocation { parents: 0, interior: Junctions::X1(x) } - } - } - - impl From<[Junction; 0]> for MultiLocation { - fn from(_: [Junction; 0]) -> Self { - MultiLocation { parents: 0, interior: Junctions::Here } - } - } - - #from_tuples - } - } - - fn generate_conversion_from_v3() -> TokenStream { - let match_variants = (0..8u8) - .map(|cur_num| { - let num_ancestors = cur_num + 1; - let variant = format_ident!("X{}", num_ancestors); - let idents = (0..=cur_num).map(|i| format_ident!("j{}", i)).collect::>(); - - quote! { - crate::v3::Junctions::#variant( #(#idents),* ) => - #variant( #( core::convert::TryInto::try_into(#idents)? ),* ), - } - }) - .collect::(); - - quote! { - impl core::convert::TryFrom for Junctions { - type Error = (); - fn try_from(mut new: crate::v3::Junctions) -> core::result::Result { - use Junctions::*; - Ok(match new { - crate::v3::Junctions::Here => Here, - #match_variants - }) - } - } - } - } -} - -pub mod junctions { - use super::*; - - pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { - if !input.is_empty() { - return Err(syn::Error::new(Span::call_site(), "No arguments expected")) - } - - let from_slice_syntax = generate_conversion_from_slice_syntax(); - - Ok(quote! { - #from_slice_syntax - }) - } - - fn generate_conversion_from_slice_syntax() -> TokenStream { - quote! { - macro_rules! impl_junction { - ($count:expr, $variant:ident, ($($index:literal),+)) => { - /// Additional helper for building junctions - /// Useful for converting to future XCM versions - impl From<[Junction; $count]> for Junctions { - fn from(junctions: [Junction; $count]) -> Self { - Self::$variant($(junctions[$index].clone()),*) - } - } - }; - } - - impl_junction!(1, X1, (0)); - impl_junction!(2, X2, (0, 1)); - impl_junction!(3, X3, (0, 1, 2)); - impl_junction!(4, X4, (0, 1, 2, 3)); - impl_junction!(5, X5, (0, 1, 2, 3, 4)); - impl_junction!(6, X6, (0, 1, 2, 3, 4, 5)); - impl_junction!(7, X7, (0, 1, 2, 3, 4, 5, 6)); - impl_junction!(8, X8, (0, 1, 2, 3, 4, 5, 6, 7)); - } - } -} diff --git a/polkadot/xcm/procedural/src/v3.rs b/polkadot/xcm/procedural/src/v3.rs index f0556d5a8d44..1292b56277dd 100644 --- a/polkadot/xcm/procedural/src/v3.rs +++ b/polkadot/xcm/procedural/src/v3.rs @@ -127,12 +127,10 @@ pub mod junctions { } // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. - let from_v2 = generate_conversion_from_v2(MAX_JUNCTIONS); let from_v4 = generate_conversion_from_v4(); let from_tuples = generate_conversion_from_tuples(MAX_JUNCTIONS); Ok(quote! { - #from_v2 #from_v4 #from_tuples }) @@ -194,32 +192,4 @@ pub mod junctions { } } } - - fn generate_conversion_from_v2(max_junctions: usize) -> TokenStream { - let match_variants = (0..max_junctions) - .map(|cur_num| { - let num_ancestors = cur_num + 1; - let variant = format_ident!("X{}", num_ancestors); - let idents = (0..=cur_num).map(|i| format_ident!("j{}", i)).collect::>(); - - quote! { - crate::v2::Junctions::#variant( #(#idents),* ) => - #variant( #( core::convert::TryInto::try_into(#idents)? ),* ), - } - }) - .collect::(); - - quote! { - impl core::convert::TryFrom for Junctions { - type Error = (); - fn try_from(mut old: crate::v2::Junctions) -> core::result::Result { - use Junctions::*; - Ok(match old { - crate::v2::Junctions::Here => Here, - #match_variants - }) - } - } - } - } } diff --git a/polkadot/xcm/procedural/src/v4.rs b/polkadot/xcm/procedural/src/v4.rs index 5f5e10d3081b..9bc2f094d021 100644 --- a/polkadot/xcm/procedural/src/v4.rs +++ b/polkadot/xcm/procedural/src/v4.rs @@ -132,10 +132,12 @@ pub mod junctions { // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. let from_v3 = generate_conversion_from_v3(MAX_JUNCTIONS); + let from_v5 = generate_conversion_from_v5(MAX_JUNCTIONS); let from_tuples = generate_conversion_from_tuples(MAX_JUNCTIONS); Ok(quote! { #from_v3 + #from_v5 #from_tuples }) } @@ -193,4 +195,43 @@ pub mod junctions { } } } + + fn generate_conversion_from_v5(max_junctions: usize) -> TokenStream { + let match_variants = (0..max_junctions) + .map(|current_number| { + let number_ancestors = current_number + 1; + let variant = format_ident!("X{}", number_ancestors); + let idents = + (0..=current_number).map(|i| format_ident!("j{}", i)).collect::>(); + let convert = idents + .iter() + .map(|ident| { + quote! { let #ident = core::convert::TryInto::try_into(#ident.clone())?; } + }) + .collect::>(); + + quote! { + crate::v5::Junctions::#variant( junctions ) => { + let [#(#idents),*] = &*junctions; + #(#convert);* + [#(#idents),*].into() + }, + } + }) + .collect::(); + + quote! { + impl core::convert::TryFrom for Junctions { + type Error = (); + + fn try_from(mut new: crate::v5::Junctions) -> core::result::Result { + use Junctions::*; + Ok(match new { + crate::v5::Junctions::Here => Here, + #match_variants + }) + } + } + } + } } diff --git a/polkadot/xcm/procedural/src/v5.rs b/polkadot/xcm/procedural/src/v5.rs new file mode 100644 index 000000000000..895a323c1738 --- /dev/null +++ b/polkadot/xcm/procedural/src/v5.rs @@ -0,0 +1,198 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote}; +use syn::{Result, Token}; + +const MAX_JUNCTIONS: usize = 8; + +pub mod location { + use super::*; + + /// Generates conversion functions from other types to the `Location` type: + /// - [PalletInstance(50), GeneralIndex(1984)].into() + /// - (Parent, Parachain(1000), AccountId32 { .. }).into() + pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + } + + let from_tuples = generate_conversion_from_tuples(8, 8); + + Ok(quote! { + #from_tuples + }) + } + + fn generate_conversion_from_tuples(max_junctions: usize, max_parents: usize) -> TokenStream { + let mut from_tuples = (0..=max_junctions) + .map(|num_junctions| { + let types = (0..num_junctions).map(|i| format_ident!("J{}", i)).collect::>(); + let idents = + (0..num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); + let array_size = num_junctions; + let interior = if num_junctions == 0 { + quote!(Junctions::Here) + } else { + let variant = format_ident!("X{}", num_junctions); + quote! { + Junctions::#variant( alloc::sync::Arc::new( [#(#idents .into()),*] ) ) + } + }; + + let mut from_tuple = quote! { + impl< #(#types : Into,)* > From<( Ancestor, #( #types ),* )> for Location { + fn from( ( Ancestor(parents), #(#idents),* ): ( Ancestor, #( #types ),* ) ) -> Self { + Location { parents, interior: #interior } + } + } + + impl From<[Junction; #array_size]> for Location { + fn from(j: [Junction; #array_size]) -> Self { + let [#(#idents),*] = j; + Location { parents: 0, interior: #interior } + } + } + }; + + let from_parent_tuples = (0..=max_parents).map(|cur_parents| { + let parents = + (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); + let underscores = + (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); + + quote! { + impl< #(#types : Into,)* > From<( #( #parents , )* #( #types , )* )> for Location { + fn from( ( #(#underscores,)* #(#idents,)* ): ( #(#parents,)* #(#types,)* ) ) -> Self { + Self { parents: #cur_parents as u8, interior: #interior } + } + } + } + }); + + from_tuple.extend(from_parent_tuples); + from_tuple + }) + .collect::(); + + let from_parent_junctions_tuples = (0..=max_parents).map(|cur_parents| { + let parents = (0..cur_parents).map(|_| format_ident!("Parent")).collect::>(); + let underscores = + (0..cur_parents).map(|_| Token![_](Span::call_site())).collect::>(); + + quote! { + impl From<( #(#parents,)* Junctions )> for Location { + fn from( (#(#underscores,)* junctions): ( #(#parents,)* Junctions ) ) -> Self { + Location { parents: #cur_parents as u8, interior: junctions } + } + } + } + }); + from_tuples.extend(from_parent_junctions_tuples); + + quote! { + impl From<(Ancestor, Junctions)> for Location { + fn from((Ancestor(parents), interior): (Ancestor, Junctions)) -> Self { + Location { parents, interior } + } + } + + impl From for Location { + fn from(x: Junction) -> Self { + Location { parents: 0, interior: [x].into() } + } + } + + #from_tuples + } + } +} + +pub mod junctions { + use super::*; + + pub fn generate_conversion_functions(input: proc_macro::TokenStream) -> Result { + if !input.is_empty() { + return Err(syn::Error::new(Span::call_site(), "No arguments expected")) + } + + // Support up to 8 Parents in a tuple, assuming that most use cases don't go past 8 parents. + let from_v4 = generate_conversion_from_v4(MAX_JUNCTIONS); + let from_tuples = generate_conversion_from_tuples(MAX_JUNCTIONS); + + Ok(quote! { + #from_v4 + #from_tuples + }) + } + + fn generate_conversion_from_tuples(max_junctions: usize) -> TokenStream { + (1..=max_junctions) + .map(|num_junctions| { + let idents = + (0..num_junctions).map(|i| format_ident!("j{}", i)).collect::>(); + let types = (0..num_junctions).map(|i| format_ident!("J{}", i)).collect::>(); + + quote! { + impl<#(#types : Into,)*> From<( #(#types,)* )> for Junctions { + fn from( ( #(#idents,)* ): ( #(#types,)* ) ) -> Self { + [#(#idents .into()),*].into() + } + } + } + }) + .collect() + } + + fn generate_conversion_from_v4(max_junctions: usize) -> TokenStream { + let match_variants = (0..max_junctions) + .map(|cur_num| { + let num_ancestors = cur_num + 1; + let variant = format_ident!("X{}", num_ancestors); + let idents = (0..=cur_num).map(|i| format_ident!("j{}", i)).collect::>(); + let convert = idents + .iter() + .enumerate() + .map(|(index, ident)| { + quote! { let #ident = core::convert::TryInto::try_into(slice[#index].clone())?; } + }) + .collect::>(); + + quote! { + crate::v4::Junctions::#variant( arc ) => { + let slice = &arc[..]; + #(#convert);*; + let junctions: Junctions = [#(#idents),*].into(); + junctions + }, + } + }) + .collect::(); + + quote! { + impl core::convert::TryFrom for Junctions { + type Error = (); + fn try_from(mut old: crate::v4::Junctions) -> core::result::Result { + Ok(match old { + crate::v4::Junctions::Here => Junctions::Here, + #match_variants + }) + } + } + } + } +} diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/badly_formatted_attribute.stderr b/polkadot/xcm/procedural/tests/ui/builder_pattern/badly_formatted_attribute.stderr index 978faf2e868d..e4038dc25ae6 100644 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/badly_formatted_attribute.stderr +++ b/polkadot/xcm/procedural/tests/ui/builder_pattern/badly_formatted_attribute.stderr @@ -1,4 +1,4 @@ -error: Expected `builder(loads_holding)` +error: Expected `builder(loads_holding)` or `builder(pays_fees)` --> tests/ui/builder_pattern/badly_formatted_attribute.rs:25:5 | 25 | #[builder(funds_holding = 2)] diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.rs b/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.rs deleted file mode 100644 index dc5c679a96e7..000000000000 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Test error when the `BuyExecution` instruction doesn't take named fields. - -use xcm_procedural::Builder; - -struct Xcm(pub Vec>); - -#[derive(Builder)] -enum Instruction { - BuyExecution(u128), - UnpaidExecution { weight_limit: (u32, u32) }, - Transact { call: Call }, -} - -fn main() {} diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.stderr b/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.stderr deleted file mode 100644 index dc8246770ba3..000000000000 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/buy_execution_named_fields.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: BuyExecution should have named fields - --> tests/ui/builder_pattern/buy_execution_named_fields.rs:25:5 - | -25 | BuyExecution(u128), - | ^^^^^^^^^^^^^^^^^^ diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.stderr b/polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.stderr deleted file mode 100644 index d8798c8223f1..000000000000 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.stderr +++ /dev/null @@ -1,6 +0,0 @@ -error: No BuyExecution instruction - --> tests/ui/builder_pattern/no_buy_execution.rs:25:5 - | -25 | / UnpaidExecution { weight_limit: (u32, u32) }, -26 | | Transact { call: Call }, - | |____________________________^ diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.rs b/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.rs deleted file mode 100644 index 5808ec571ce7..000000000000 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.rs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Test error when using wrong attribute. - -use xcm_procedural::Builder; - -struct Xcm(pub Vec>); - -#[derive(Builder)] -enum Instruction { - #[builder(funds_holding)] - WithdrawAsset(u128), - BuyExecution { fees: u128 }, - UnpaidExecution { weight_limit: (u32, u32) }, - Transact { call: Call }, -} - -fn main() {} diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.stderr b/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.stderr deleted file mode 100644 index 1ff9d1851368..000000000000 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/unexpected_attribute.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: Expected `builder(loads_holding)` - --> tests/ui/builder_pattern/unexpected_attribute.rs:25:5 - | -25 | #[builder(funds_holding)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/polkadot/xcm/src/lib.rs b/polkadot/xcm/src/lib.rs index 0b916c87f549..a41a8e797b0f 100644 --- a/polkadot/xcm/src/lib.rs +++ b/polkadot/xcm/src/lib.rs @@ -21,28 +21,24 @@ // // Hence, `no_std` rather than sp-runtime. #![cfg_attr(not(feature = "std"), no_std)] -// Because of XCMv2. -#![allow(deprecated)] extern crate alloc; use codec::{Decode, DecodeLimit, Encode, Error as CodecError, Input, MaxEncodedLen}; use derivative::Derivative; +use frame_support::dispatch::GetDispatchInfo; use scale_info::TypeInfo; -#[deprecated( - note = "XCMv2 will be removed once XCMv5 is released. Please use XCMv3 or XCMv4 instead." -)] -pub mod v2; pub mod v3; pub mod v4; +pub mod v5; pub mod lts { pub use super::v4::*; } pub mod latest { - pub use super::v4::*; + pub use super::v5::*; } mod double_encoded; @@ -81,12 +77,16 @@ pub trait TryAs { fn try_as(&self) -> Result<&T, ()>; } +// Macro that generated versioned wrapper types. +// NOTE: converting a v4 type into a versioned type will make it v5. macro_rules! versioned_type { ($(#[$attr:meta])* pub enum $n:ident { $(#[$index3:meta])+ V3($v3:ty), $(#[$index4:meta])+ V4($v4:ty), + $(#[$index5:meta])+ + V5($v5:ty), }) => { #[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative( @@ -104,6 +104,8 @@ macro_rules! versioned_type { V3($v3), $(#[$index4])* V4($v4), + $(#[$index5])* + V5($v5), } impl $n { pub fn try_as(&self) -> Result<&T, ()> where Self: TryAs { @@ -126,11 +128,20 @@ macro_rules! versioned_type { } } } + impl TryAs<$v5> for $n { + fn try_as(&self) -> Result<&$v5, ()> { + match &self { + Self::V5(ref x) => Ok(x), + _ => Err(()), + } + } + } impl IntoVersion for $n { fn into_version(self, n: Version) -> Result { Ok(match n { 3 => Self::V3(self.try_into()?), 4 => Self::V4(self.try_into()?), + 5 => Self::V5(self.try_into()?), _ => return Err(()), }) } @@ -140,9 +151,9 @@ macro_rules! versioned_type { $n::V3(x.into()) } } - impl From<$v4> for $n { - fn from(x: $v4) -> Self { - $n::V4(x.into()) + impl> From for $n { + fn from(x: T) -> Self { + $n::V5(x.into()) } } impl TryFrom<$n> for $v3 { @@ -151,7 +162,11 @@ macro_rules! versioned_type { use $n::*; match x { V3(x) => Ok(x), - V4(x) => x.try_into(), + V4(x) => x.try_into().map_err(|_| ()), + V5(x) => { + let v4: $v4 = x.try_into().map_err(|_| ())?; + v4.try_into().map_err(|_| ()) + } } } } @@ -162,137 +177,21 @@ macro_rules! versioned_type { match x { V3(x) => x.try_into().map_err(|_| ()), V4(x) => Ok(x), + V5(x) => x.try_into().map_err(|_| ()), } } } - impl MaxEncodedLen for $n { - fn max_encoded_len() -> usize { - <$v3>::max_encoded_len() - } - } - impl IdentifyVersion for $n { - fn identify_version(&self) -> Version { - use $n::*; - match self { - V3(_) => v3::VERSION, - V4(_) => v4::VERSION, - } - } - } - }; - - ($(#[$attr:meta])* pub enum $n:ident { - $(#[$index2:meta])+ - V2($v2:ty), - $(#[$index3:meta])+ - V3($v3:ty), - $(#[$index4:meta])+ - V4($v4:ty), - }) => { - #[derive(Derivative, Encode, Decode, TypeInfo)] - #[derivative( - Clone(bound = ""), - Eq(bound = ""), - PartialEq(bound = ""), - Debug(bound = "") - )] - #[codec(encode_bound())] - #[codec(decode_bound())] - #[scale_info(replace_segment("staging_xcm", "xcm"))] - $(#[$attr])* - pub enum $n { - $(#[$index2])* - V2($v2), - $(#[$index3])* - V3($v3), - $(#[$index4])* - V4($v4), - } - impl $n { - pub fn try_as(&self) -> Result<&T, ()> where Self: TryAs { - >::try_as(&self) - } - } - impl TryAs<$v2> for $n { - fn try_as(&self) -> Result<&$v2, ()> { - match &self { - Self::V2(ref x) => Ok(x), - _ => Err(()), - } - } - } - impl TryAs<$v3> for $n { - fn try_as(&self) -> Result<&$v3, ()> { - match &self { - Self::V3(ref x) => Ok(x), - _ => Err(()), - } - } - } - impl TryAs<$v4> for $n { - fn try_as(&self) -> Result<&$v4, ()> { - match &self { - Self::V4(ref x) => Ok(x), - _ => Err(()), - } - } - } - impl IntoVersion for $n { - fn into_version(self, n: Version) -> Result { - Ok(match n { - 1 | 2 => Self::V2(self.try_into()?), - 3 => Self::V3(self.try_into()?), - 4 => Self::V4(self.try_into()?), - _ => return Err(()), - }) - } - } - impl From<$v2> for $n { - fn from(x: $v2) -> Self { - $n::V2(x) - } - } - impl> From for $n { - fn from(x: T) -> Self { - $n::V4(x.into()) - } - } - impl TryFrom<$n> for $v2 { + impl TryFrom<$n> for $v5 { type Error = (); fn try_from(x: $n) -> Result { use $n::*; match x { - V2(x) => Ok(x), - V3(x) => x.try_into(), - V4(x) => { - let v3: $v3 = x.try_into().map_err(|_| ())?; - v3.try_into() + V3(x) => { + let v4: $v4 = x.try_into().map_err(|_| ())?; + v4.try_into().map_err(|_| ()) }, - } - } - } - impl TryFrom<$n> for $v3 { - type Error = (); - fn try_from(x: $n) -> Result { - use $n::*; - match x { - V2(x) => x.try_into(), - V3(x) => Ok(x), V4(x) => x.try_into().map_err(|_| ()), - } - } - } - impl TryFrom<$n> for $v4 { - type Error = (); - fn try_from(x: $n) -> Result { - use $n::*; - match x { - V2(x) => { - let v3: $v3 = x.try_into().map_err(|_| ())?; - v3.try_into().map_err(|_| ()) - }, - V3(x) => x.try_into().map_err(|_| ()), - V4(x) => Ok(x), + V5(x) => Ok(x), } } } @@ -305,9 +204,9 @@ macro_rules! versioned_type { fn identify_version(&self) -> Version { use $n::*; match self { - V2(_) => v2::VERSION, V3(_) => v3::VERSION, V4(_) => v4::VERSION, + V5(_) => v5::VERSION, } } } @@ -321,42 +220,44 @@ versioned_type! { V3(v3::AssetId), #[codec(index = 4)] V4(v4::AssetId), + #[codec(index = 5)] + V5(v5::AssetId), } } versioned_type! { /// A single version's `Response` value, together with its version code. pub enum VersionedResponse { - #[codec(index = 2)] - V2(v2::Response), #[codec(index = 3)] V3(v3::Response), #[codec(index = 4)] V4(v4::Response), + #[codec(index = 5)] + V5(v5::Response), } } versioned_type! { /// A single `NetworkId` value, together with its version code. pub enum VersionedNetworkId { - #[codec(index = 2)] - V2(v2::NetworkId), #[codec(index = 3)] V3(v3::NetworkId), #[codec(index = 4)] V4(v4::NetworkId), + #[codec(index = 5)] + V5(v5::NetworkId), } } versioned_type! { /// A single `Junction` value, together with its version code. pub enum VersionedJunction { - #[codec(index = 2)] - V2(v2::Junction), #[codec(index = 3)] V3(v3::Junction), #[codec(index = 4)] V4(v4::Junction), + #[codec(index = 5)] + V5(v5::Junction), } } @@ -364,63 +265,51 @@ versioned_type! { /// A single `Location` value, together with its version code. #[derive(Ord, PartialOrd)] pub enum VersionedLocation { - #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index - V2(v2::MultiLocation), #[codec(index = 3)] V3(v3::MultiLocation), #[codec(index = 4)] V4(v4::Location), + #[codec(index = 5)] + V5(v5::Location), } } -#[deprecated(note = "Use `VersionedLocation` instead")] -pub type VersionedMultiLocation = VersionedLocation; - versioned_type! { /// A single `InteriorLocation` value, together with its version code. pub enum VersionedInteriorLocation { - #[codec(index = 2)] // while this is same as v1::Junctions, VersionedInteriorLocation is introduced in v3 - V2(v2::InteriorMultiLocation), #[codec(index = 3)] V3(v3::InteriorMultiLocation), #[codec(index = 4)] V4(v4::InteriorLocation), + #[codec(index = 5)] + V5(v5::InteriorLocation), } } -#[deprecated(note = "Use `VersionedInteriorLocation` instead")] -pub type VersionedInteriorMultiLocation = VersionedInteriorLocation; - versioned_type! { /// A single `Asset` value, together with its version code. pub enum VersionedAsset { - #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index - V2(v2::MultiAsset), #[codec(index = 3)] V3(v3::MultiAsset), #[codec(index = 4)] V4(v4::Asset), + #[codec(index = 5)] + V5(v5::Asset), } } -#[deprecated(note = "Use `VersionedAsset` instead")] -pub type VersionedMultiAsset = VersionedAsset; - versioned_type! { /// A single `MultiAssets` value, together with its version code. pub enum VersionedAssets { - #[codec(index = 1)] // v2 is same as v1 and therefore re-using the v1 index - V2(v2::MultiAssets), #[codec(index = 3)] V3(v3::MultiAssets), #[codec(index = 4)] V4(v4::Assets), + #[codec(index = 5)] + V5(v5::Assets), } } -#[deprecated(note = "Use `VersionedAssets` instead")] -pub type VersionedMultiAssets = VersionedAssets; - /// A single XCM message, together with its version code. #[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] @@ -429,21 +318,20 @@ pub type VersionedMultiAssets = VersionedAssets; #[scale_info(bounds(), skip_type_params(RuntimeCall))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum VersionedXcm { - #[codec(index = 2)] - #[deprecated] - V2(v2::Xcm), #[codec(index = 3)] V3(v3::Xcm), #[codec(index = 4)] V4(v4::Xcm), + #[codec(index = 5)] + V5(v5::Xcm), } -impl IntoVersion for VersionedXcm { +impl IntoVersion for VersionedXcm { fn into_version(self, n: Version) -> Result { Ok(match n { - 2 => Self::V2(self.try_into()?), 3 => Self::V3(self.try_into()?), 4 => Self::V4(self.try_into()?), + 5 => Self::V5(self.try_into()?), _ => return Err(()), }) } @@ -452,9 +340,9 @@ impl IntoVersion for VersionedXcm { impl IdentifyVersion for VersionedXcm { fn identify_version(&self) -> Version { match self { - Self::V2(_) => v2::VERSION, Self::V3(_) => v3::VERSION, Self::V4(_) => v4::VERSION, + Self::V5(_) => v5::VERSION, } } } @@ -476,12 +364,6 @@ impl VersionedXcm { } } -impl From> for VersionedXcm { - fn from(x: v2::Xcm) -> Self { - VersionedXcm::V2(x) - } -} - impl From> for VersionedXcm { fn from(x: v3::Xcm) -> Self { VersionedXcm::V3(x) @@ -494,44 +376,50 @@ impl From> for VersionedXcm { } } -impl TryFrom> for v2::Xcm { +impl From> for VersionedXcm { + fn from(x: v5::Xcm) -> Self { + VersionedXcm::V5(x) + } +} + +impl TryFrom> for v3::Xcm { type Error = (); - fn try_from(x: VersionedXcm) -> Result { + fn try_from(x: VersionedXcm) -> Result { use VersionedXcm::*; match x { - V2(x) => Ok(x), - V3(x) => x.try_into(), - V4(x) => { - let v3: v3::Xcm = x.try_into()?; - v3.try_into() + V3(x) => Ok(x), + V4(x) => x.try_into(), + V5(x) => { + let v4: v4::Xcm = x.try_into()?; + v4.try_into() }, } } } -impl TryFrom> for v3::Xcm { +impl TryFrom> for v4::Xcm { type Error = (); fn try_from(x: VersionedXcm) -> Result { use VersionedXcm::*; match x { - V2(x) => x.try_into(), - V3(x) => Ok(x), - V4(x) => x.try_into(), + V3(x) => x.try_into(), + V4(x) => Ok(x), + V5(x) => x.try_into(), } } } -impl TryFrom> for v4::Xcm { +impl TryFrom> for v5::Xcm { type Error = (); fn try_from(x: VersionedXcm) -> Result { use VersionedXcm::*; match x { - V2(x) => { - let v3: v3::Xcm = x.try_into()?; - v3.try_into() + V3(x) => { + let v4: v4::Xcm = x.try_into()?; + v4.try_into() }, - V3(x) => x.try_into(), - V4(x) => Ok(x), + V4(x) => x.try_into(), + V5(x) => Ok(x), } } } @@ -539,7 +427,7 @@ impl TryFrom> for v4::Xcm { /// Convert an `Xcm` datum into a `VersionedXcm`, based on a destination `Location` which will /// interpret it. pub trait WrapVersion { - fn wrap_version( + fn wrap_version( dest: &latest::Location, xcm: impl Into>, ) -> Result, ()>; @@ -568,28 +456,11 @@ impl WrapVersion for () { } } -/// `WrapVersion` implementation which attempts to always convert the XCM to version 2 before -/// wrapping it. -pub struct AlwaysV2; -impl WrapVersion for AlwaysV2 { - fn wrap_version( - _: &latest::Location, - xcm: impl Into>, - ) -> Result, ()> { - Ok(VersionedXcm::::V2(xcm.into().try_into()?)) - } -} -impl GetVersion for AlwaysV2 { - fn get_version_for(_dest: &latest::Location) -> Option { - Some(v2::VERSION) - } -} - /// `WrapVersion` implementation which attempts to always convert the XCM to version 3 before /// wrapping it. pub struct AlwaysV3; impl WrapVersion for AlwaysV3 { - fn wrap_version( + fn wrap_version( _: &latest::Location, xcm: impl Into>, ) -> Result, ()> { @@ -606,7 +477,7 @@ impl GetVersion for AlwaysV3 { /// wrapping it. pub struct AlwaysV4; impl WrapVersion for AlwaysV4 { - fn wrap_version( + fn wrap_version( _: &latest::Location, xcm: impl Into>, ) -> Result, ()> { @@ -619,9 +490,26 @@ impl GetVersion for AlwaysV4 { } } +/// `WrapVersion` implementation which attempts to always convert the XCM to version 3 before +/// wrapping it. +pub struct AlwaysV5; +impl WrapVersion for AlwaysV5 { + fn wrap_version( + _: &latest::Location, + xcm: impl Into>, + ) -> Result, ()> { + Ok(VersionedXcm::::V5(xcm.into().try_into()?)) + } +} +impl GetVersion for AlwaysV5 { + fn get_version_for(_dest: &latest::Location) -> Option { + Some(v5::VERSION) + } +} + /// `WrapVersion` implementation which attempts to always convert the XCM to the latest version /// before wrapping it. -pub type AlwaysLatest = AlwaysV4; +pub type AlwaysLatest = AlwaysV5; /// `WrapVersion` implementation which attempts to always convert the XCM to the most recent Long- /// Term-Support version before wrapping it. @@ -629,7 +517,7 @@ pub type AlwaysLts = AlwaysV4; pub mod prelude { pub use super::{ - latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV2, AlwaysV3, AlwaysV4, GetVersion, + latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV3, AlwaysV4, AlwaysV5, GetVersion, IdentifyVersion, IntoVersion, Unsupported, Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets, VersionedInteriorLocation, VersionedLocation, VersionedResponse, VersionedXcm, WrapVersion, @@ -637,12 +525,6 @@ pub mod prelude { } pub mod opaque { - pub mod v2 { - // Everything from v2 - pub use crate::v2::*; - // Then override with the opaque types in v2 - pub use crate::v2::opaque::{Instruction, Xcm}; - } pub mod v3 { // Everything from v3 pub use crate::v3::*; @@ -655,9 +537,15 @@ pub mod opaque { // Then override with the opaque types in v4 pub use crate::v4::opaque::{Instruction, Xcm}; } + pub mod v5 { + // Everything from v4 + pub use crate::v5::*; + // Then override with the opaque types in v5 + pub use crate::v5::opaque::{Instruction, Xcm}; + } pub mod latest { - pub use super::v4::*; + pub use super::v5::*; } pub mod lts { @@ -709,7 +597,7 @@ fn size_limits() { } check_sizes! { - (crate::latest::Instruction<()>, 112), + (crate::latest::Instruction<()>, 128), (crate::latest::Asset, 80), (crate::latest::Location, 24), (crate::latest::AssetId, 40), diff --git a/polkadot/xcm/src/tests.rs b/polkadot/xcm/src/tests.rs index 4c666063f3f4..5a267b3a9048 100644 --- a/polkadot/xcm/src/tests.rs +++ b/polkadot/xcm/src/tests.rs @@ -34,43 +34,43 @@ fn encode_decode_versioned_asset_id_v3() { } #[test] -fn encode_decode_versioned_response_v2() { - let response = VersionedResponse::V2(v2::Response::Null); +fn encode_decode_versioned_response_v3() { + let response = VersionedResponse::V3(v3::Response::Null); let encoded = response.encode(); - assert_eq!(encoded, hex_literal::hex!("0200"), "encode format changed"); - assert_eq!(encoded[0], 2, "bad version number"); + assert_eq!(encoded, hex_literal::hex!("0300"), "encode format changed"); + assert_eq!(encoded[0], 3, "bad version number"); let decoded = VersionedResponse::decode(&mut &encoded[..]).unwrap(); assert_eq!(response, decoded); } #[test] -fn encode_decode_versioned_response_v3() { - let response = VersionedResponse::V3(v3::Response::Null); +fn encode_decode_versioned_response_v4() { + let response = VersionedResponse::V4(v4::Response::Null); let encoded = response.encode(); - assert_eq!(encoded, hex_literal::hex!("0300"), "encode format changed"); - assert_eq!(encoded[0], 3, "bad version number"); + assert_eq!(encoded, hex_literal::hex!("0400"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); let decoded = VersionedResponse::decode(&mut &encoded[..]).unwrap(); assert_eq!(response, decoded); } #[test] -fn encode_decode_versioned_multi_location_v2() { - let location = VersionedLocation::V2(v2::MultiLocation::new(0, v2::Junctions::Here)); - let encoded = location.encode(); +fn encode_decode_versioned_response_v5() { + let response = VersionedResponse::V5(v5::Response::Null); + let encoded = response.encode(); - assert_eq!(encoded, hex_literal::hex!("010000"), "encode format changed"); - assert_eq!(encoded[0], 1, "bad version number"); // this is introduced in v1 + assert_eq!(encoded, hex_literal::hex!("0500"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); - let decoded = VersionedLocation::decode(&mut &encoded[..]).unwrap(); - assert_eq!(location, decoded); + let decoded = VersionedResponse::decode(&mut &encoded[..]).unwrap(); + assert_eq!(response, decoded); } #[test] -fn encode_decode_versioned_multi_location_v3() { +fn encode_decode_versioned_location_v3() { let location = VersionedLocation::V3(v3::MultiLocation::new(0, v3::Junctions::Here)); let encoded = location.encode(); @@ -82,19 +82,31 @@ fn encode_decode_versioned_multi_location_v3() { } #[test] -fn encode_decode_versioned_interior_multi_location_v2() { - let location = VersionedInteriorLocation::V2(v2::InteriorMultiLocation::Here); +fn encode_decode_versioned_location_v4() { + let location = VersionedLocation::V4(v4::Location::new(0, v4::Junctions::Here)); let encoded = location.encode(); - assert_eq!(encoded, hex_literal::hex!("0200"), "encode format changed"); - assert_eq!(encoded[0], 2, "bad version number"); + assert_eq!(encoded, hex_literal::hex!("040000"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); - let decoded = VersionedInteriorLocation::decode(&mut &encoded[..]).unwrap(); + let decoded = VersionedLocation::decode(&mut &encoded[..]).unwrap(); assert_eq!(location, decoded); } #[test] -fn encode_decode_versioned_interior_multi_location_v3() { +fn encode_decode_versioned_location_v5() { + let location = VersionedLocation::V5(v5::Location::new(0, v5::Junctions::Here)); + let encoded = location.encode(); + + assert_eq!(encoded, hex_literal::hex!("050000"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); + + let decoded = VersionedLocation::decode(&mut &encoded[..]).unwrap(); + assert_eq!(location, decoded); +} + +#[test] +fn encode_decode_versioned_interior_location_v3() { let location = VersionedInteriorLocation::V3(v3::InteriorMultiLocation::Here); let encoded = location.encode(); @@ -106,19 +118,31 @@ fn encode_decode_versioned_interior_multi_location_v3() { } #[test] -fn encode_decode_versioned_multi_asset_v2() { - let asset = VersionedAsset::V2(v2::MultiAsset::from(((0, v2::Junctions::Here), 1))); - let encoded = asset.encode(); +fn encode_decode_versioned_interior_location_v4() { + let location = VersionedInteriorLocation::V4(v4::InteriorLocation::Here); + let encoded = location.encode(); - assert_eq!(encoded, hex_literal::hex!("010000000004"), "encode format changed"); - assert_eq!(encoded[0], 1, "bad version number"); + assert_eq!(encoded, hex_literal::hex!("0400"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); - let decoded = VersionedAsset::decode(&mut &encoded[..]).unwrap(); - assert_eq!(asset, decoded); + let decoded = VersionedInteriorLocation::decode(&mut &encoded[..]).unwrap(); + assert_eq!(location, decoded); } #[test] -fn encode_decode_versioned_multi_asset_v3() { +fn encode_decode_versioned_interior_location_v5() { + let location = VersionedInteriorLocation::V5(v5::InteriorLocation::Here); + let encoded = location.encode(); + + assert_eq!(encoded, hex_literal::hex!("0500"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); + + let decoded = VersionedInteriorLocation::decode(&mut &encoded[..]).unwrap(); + assert_eq!(location, decoded); +} + +#[test] +fn encode_decode_versioned_asset_v3() { let asset = VersionedAsset::V3(v3::MultiAsset::from((v3::MultiLocation::default(), 1))); let encoded = asset.encode(); @@ -130,22 +154,31 @@ fn encode_decode_versioned_multi_asset_v3() { } #[test] -fn encode_decode_versioned_multi_assets_v2() { - let assets = VersionedAssets::V2(v2::MultiAssets::from(vec![v2::MultiAsset::from(( - (0, v2::Junctions::Here), - 1, - ))])); - let encoded = assets.encode(); +fn encode_decode_versioned_asset_v4() { + let asset = VersionedAsset::V4(v4::Asset::from((v4::Location::default(), 1))); + let encoded = asset.encode(); - assert_eq!(encoded, hex_literal::hex!("01040000000004"), "encode format changed"); - assert_eq!(encoded[0], 1, "bad version number"); + assert_eq!(encoded, hex_literal::hex!("0400000004"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); - let decoded = VersionedAssets::decode(&mut &encoded[..]).unwrap(); - assert_eq!(assets, decoded); + let decoded = VersionedAsset::decode(&mut &encoded[..]).unwrap(); + assert_eq!(asset, decoded); } #[test] -fn encode_decode_versioned_multi_assets_v3() { +fn encode_decode_versioned_asset_v5() { + let asset = VersionedAsset::V5(v5::Asset::from((v5::Location::default(), 1))); + let encoded = asset.encode(); + + assert_eq!(encoded, hex_literal::hex!("0500000004"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); + + let decoded = VersionedAsset::decode(&mut &encoded[..]).unwrap(); + assert_eq!(asset, decoded); +} + +#[test] +fn encode_decode_versioned_assets_v3() { let assets = VersionedAssets::V3(v3::MultiAssets::from(vec![ (v3::MultiAsset::from((v3::MultiLocation::default(), 1))), ])); @@ -158,6 +191,34 @@ fn encode_decode_versioned_multi_assets_v3() { assert_eq!(assets, decoded); } +#[test] +fn encode_decode_versioned_assets_v4() { + let assets = VersionedAssets::V4(v4::Assets::from(vec![ + (v4::Asset::from((v4::Location::default(), 1))), + ])); + let encoded = assets.encode(); + + assert_eq!(encoded, hex_literal::hex!("040400000004"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); + + let decoded = VersionedAssets::decode(&mut &encoded[..]).unwrap(); + assert_eq!(assets, decoded); +} + +#[test] +fn encode_decode_versioned_assets_v5() { + let assets = VersionedAssets::V5(v5::Assets::from(vec![ + (v5::Asset::from((v5::Location::default(), 1))), + ])); + let encoded = assets.encode(); + + assert_eq!(encoded, hex_literal::hex!("050400000004"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); + + let decoded = VersionedAssets::decode(&mut &encoded[..]).unwrap(); + assert_eq!(assets, decoded); +} + #[test] fn encode_decode_versioned_xcm_v3() { let xcm = VersionedXcm::V3(v3::Xcm::<()>::new()); @@ -170,6 +231,30 @@ fn encode_decode_versioned_xcm_v3() { assert_eq!(xcm, decoded); } +#[test] +fn encode_decode_versioned_xcm_v4() { + let xcm = VersionedXcm::V4(v4::Xcm::<()>::new()); + let encoded = xcm.encode(); + + assert_eq!(encoded, hex_literal::hex!("0400"), "encode format changed"); + assert_eq!(encoded[0], 4, "bad version number"); + + let decoded = VersionedXcm::decode(&mut &encoded[..]).unwrap(); + assert_eq!(xcm, decoded); +} + +#[test] +fn encode_decode_versioned_xcm_v5() { + let xcm = VersionedXcm::V5(v5::Xcm::<()>::new()); + let encoded = xcm.encode(); + + assert_eq!(encoded, hex_literal::hex!("0500"), "encode format changed"); + assert_eq!(encoded[0], 5, "bad version number"); + + let decoded = VersionedXcm::decode(&mut &encoded[..]).unwrap(); + assert_eq!(xcm, decoded); +} + // With the renaming of the crate to `staging-xcm` the naming in the metadata changed as well and // this broke downstream users. This test ensures that the name in the metadata isn't changed. #[test] diff --git a/polkadot/xcm/src/v2/junction.rs b/polkadot/xcm/src/v2/junction.rs deleted file mode 100644 index 68a7886f3039..000000000000 --- a/polkadot/xcm/src/v2/junction.rs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Support data structures for `MultiLocation`, primarily the `Junction` datatype. - -use super::{BodyId, BodyPart, Junctions, MultiLocation, NetworkId}; -use crate::v3::Junction as NewJunction; -use bounded_collections::{ConstU32, WeakBoundedVec}; -use codec::{Decode, Encode, MaxEncodedLen}; -use scale_info::TypeInfo; - -/// A single item in a path to describe the relative location of a consensus system. -/// -/// Each item assumes a pre-existing location as its context and is defined in terms of it. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Junction { - /// An indexed parachain belonging to and operated by the context. - /// - /// Generally used when the context is a Polkadot Relay-chain. - Parachain(#[codec(compact)] u32), - /// A 32-byte identifier for an account of a specific network that is respected as a sovereign - /// endpoint within the context. - /// - /// Generally used when the context is a Substrate-based chain. - AccountId32 { network: NetworkId, id: [u8; 32] }, - /// An 8-byte index for an account of a specific network that is respected as a sovereign - /// endpoint within the context. - /// - /// May be used when the context is a Frame-based chain and includes e.g. an indices pallet. - AccountIndex64 { - network: NetworkId, - #[codec(compact)] - index: u64, - }, - /// A 20-byte identifier for an account of a specific network that is respected as a sovereign - /// endpoint within the context. - /// - /// May be used when the context is an Ethereum or Bitcoin chain or smart-contract. - AccountKey20 { network: NetworkId, key: [u8; 20] }, - /// An instanced, indexed pallet that forms a constituent part of the context. - /// - /// Generally used when the context is a Frame-based chain. - PalletInstance(u8), - /// A non-descript index within the context location. - /// - /// Usage will vary widely owing to its generality. - /// - /// NOTE: Try to avoid using this and instead use a more specific item. - GeneralIndex(#[codec(compact)] u128), - /// A nondescript datum acting as a key within the context location. - /// - /// Usage will vary widely owing to its generality. - /// - /// NOTE: Try to avoid using this and instead use a more specific item. - GeneralKey(WeakBoundedVec>), - /// The unambiguous child. - /// - /// Not currently used except as a fallback when deriving ancestry. - OnlyChild, - /// A pluralistic body existing within consensus. - /// - /// Typical to be used to represent a governance origin of a chain, but could in principle be - /// used to represent things such as multisigs also. - Plurality { id: BodyId, part: BodyPart }, -} - -impl TryFrom for Junction { - type Error = (); - - fn try_from(value: NewJunction) -> Result { - use NewJunction::*; - Ok(match value { - Parachain(id) => Self::Parachain(id), - AccountId32 { network, id } => Self::AccountId32 { network: network.try_into()?, id }, - AccountIndex64 { network, index } => - Self::AccountIndex64 { network: network.try_into()?, index }, - AccountKey20 { network, key } => - Self::AccountKey20 { network: network.try_into()?, key }, - PalletInstance(index) => Self::PalletInstance(index), - GeneralIndex(id) => Self::GeneralIndex(id), - GeneralKey { length, data } => Self::GeneralKey( - data[0..data.len().min(length as usize)] - .to_vec() - .try_into() - .expect("key is bounded to 32 and so will never be out of bounds; qed"), - ), - OnlyChild => Self::OnlyChild, - Plurality { id, part } => Self::Plurality { id: id.into(), part: part.into() }, - _ => return Err(()), - }) - } -} - -impl Junction { - /// Convert `self` into a `MultiLocation` containing 0 parents. - /// - /// Similar to `Into::into`, except that this method can be used in a const evaluation context. - pub const fn into(self) -> MultiLocation { - MultiLocation { parents: 0, interior: Junctions::X1(self) } - } - - /// Convert `self` into a `MultiLocation` containing `n` parents. - /// - /// Similar to `Self::into`, with the added ability to specify the number of parent junctions. - pub const fn into_exterior(self, n: u8) -> MultiLocation { - MultiLocation { parents: n, interior: Junctions::X1(self) } - } -} diff --git a/polkadot/xcm/src/v2/mod.rs b/polkadot/xcm/src/v2/mod.rs deleted file mode 100644 index e3358f08d410..000000000000 --- a/polkadot/xcm/src/v2/mod.rs +++ /dev/null @@ -1,1222 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! # XCM Version 2 -//! -//! WARNING: DEPRECATED, please use version 3 or 4. -//! -//! Version 2 of the Cross-Consensus Message format data structures. The comprehensive list of -//! changes can be found in -//! [this PR description](https://github.com/paritytech/polkadot/pull/3629#issue-968428279). -//! -//! ## Changes to be aware of -//! The biggest change here is the restructuring of XCM messages: instead of having `Order` and -//! `Xcm` types, the `Xcm` type now simply wraps a `Vec` containing `Instruction`s. However, most -//! changes should still be automatically convertible via the `try_from` and `from` conversion -//! functions. -//! -//! ### Junction -//! - No special attention necessary -//! -//! ### `MultiLocation` -//! - No special attention necessary -//! -//! ### `MultiAsset` -//! - No special attention necessary -//! -//! ### XCM and Order -//! - `Xcm` and `Order` variants are now combined under a single `Instruction` enum. -//! - `Order` is now obsolete and replaced entirely by `Instruction`. -//! - `Xcm` is now a simple wrapper around a `Vec`. -//! - During conversion from `Order` to `Instruction`, we do not handle `BuyExecution`s that have -//! nested XCMs, i.e. if the `instructions` field in the `BuyExecution` enum struct variant is not -//! empty, then the conversion will fail. To address this, rewrite the XCM using `Instruction`s in -//! chronological order. -//! - During conversion from `Xcm` to `Instruction`, we do not handle `RelayedFrom` messages at all. -//! -//! ### XCM Pallet -//! - The `Weigher` configuration item must have sensible weights defined for `BuyExecution` and -//! `DepositAsset` instructions. Failing that, dispatch calls to `teleport_assets` and -//! `reserve_transfer_assets` will fail with `UnweighableMessage`. - -use super::{ - v3::{ - BodyId as NewBodyId, BodyPart as NewBodyPart, Instruction as NewInstruction, - NetworkId as NewNetworkId, OriginKind as NewOriginKind, Response as NewResponse, - WeightLimit as NewWeightLimit, Xcm as NewXcm, - }, - DoubleEncoded, -}; -use alloc::{vec, vec::Vec}; -use bounded_collections::{ConstU32, WeakBoundedVec}; -use codec::{ - self, decode_vec_with_len, Compact, Decode, Encode, Error as CodecError, Input as CodecInput, - MaxEncodedLen, -}; -use core::{fmt::Debug, result}; -use derivative::Derivative; -use scale_info::TypeInfo; - -mod junction; -mod multiasset; -mod multilocation; -mod traits; - -pub use junction::Junction; -pub use multiasset::{ - AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, - WildFungibility, WildMultiAsset, -}; -pub use multilocation::{ - Ancestor, AncestorThen, InteriorMultiLocation, Junctions, MultiLocation, Parent, ParentThen, -}; -pub use traits::{Error, ExecuteXcm, GetWeight, Outcome, Result, SendError, SendResult, SendXcm}; - -/// Basically just the XCM (more general) version of `ParachainDispatchOrigin`. -#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] -pub enum OriginKind { - /// Origin should just be the native dispatch origin representation for the sender in the - /// local runtime framework. For Cumulus/Frame chains this is the `Parachain` or `Relay` origin - /// if coming from a chain, though there may be others if the `MultiLocation` XCM origin has a - /// primary/native dispatch origin form. - Native, - - /// Origin should just be the standard account-based origin with the sovereign account of - /// the sender. For Cumulus/Frame chains, this is the `Signed` origin. - SovereignAccount, - - /// Origin should be the super-user. For Cumulus/Frame chains, this is the `Root` origin. - /// This will not usually be an available option. - Superuser, - - /// Origin should be interpreted as an XCM native origin and the `MultiLocation` should be - /// encoded directly in the dispatch origin unchanged. For Cumulus/Frame chains, this will be - /// the `pallet_xcm::Origin::Xcm` type. - Xcm, -} - -impl From for OriginKind { - fn from(new: NewOriginKind) -> Self { - use NewOriginKind::*; - match new { - Native => Self::Native, - SovereignAccount => Self::SovereignAccount, - Superuser => Self::Superuser, - Xcm => Self::Xcm, - } - } -} - -/// A global identifier of an account-bearing consensus system. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum NetworkId { - /// Unidentified/any. - Any, - /// Some named network. - Named(WeakBoundedVec>), - /// The Polkadot Relay chain - Polkadot, - /// Kusama. - Kusama, -} - -impl TryFrom> for NetworkId { - type Error = (); - fn try_from(new: Option) -> result::Result { - match new { - None => Ok(NetworkId::Any), - Some(id) => Self::try_from(id), - } - } -} - -impl TryFrom for NetworkId { - type Error = (); - fn try_from(new: NewNetworkId) -> result::Result { - use NewNetworkId::*; - match new { - Polkadot => Ok(NetworkId::Polkadot), - Kusama => Ok(NetworkId::Kusama), - _ => Err(()), - } - } -} - -/// An identifier of a pluralistic body. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum BodyId { - /// The only body in its context. - Unit, - /// A named body. - Named(WeakBoundedVec>), - /// An indexed body. - Index(#[codec(compact)] u32), - /// The unambiguous executive body (for Polkadot, this would be the Polkadot council). - Executive, - /// The unambiguous technical body (for Polkadot, this would be the Technical Committee). - Technical, - /// The unambiguous legislative body (for Polkadot, this could be considered the opinion of a - /// majority of lock-voters). - Legislative, - /// The unambiguous judicial body (this doesn't exist on Polkadot, but if it were to get a - /// "grand oracle", it may be considered as that). - Judicial, - /// The unambiguous defense body (for Polkadot, an opinion on the topic given via a public - /// referendum on the `staking_admin` track). - Defense, - /// The unambiguous administration body (for Polkadot, an opinion on the topic given via a - /// public referendum on the `general_admin` track). - Administration, - /// The unambiguous treasury body (for Polkadot, an opinion on the topic given via a public - /// referendum on the `treasurer` track). - Treasury, -} - -impl From for BodyId { - fn from(n: NewBodyId) -> Self { - use NewBodyId::*; - match n { - Unit => Self::Unit, - Moniker(n) => Self::Named( - n[..] - .to_vec() - .try_into() - .expect("array size is 4 and so will never be out of bounds; qed"), - ), - Index(n) => Self::Index(n), - Executive => Self::Executive, - Technical => Self::Technical, - Legislative => Self::Legislative, - Judicial => Self::Judicial, - Defense => Self::Defense, - Administration => Self::Administration, - Treasury => Self::Treasury, - } - } -} - -/// A part of a pluralistic body. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum BodyPart { - /// The body's declaration, under whatever means it decides. - Voice, - /// A given number of members of the body. - Members { - #[codec(compact)] - count: u32, - }, - /// A given number of members of the body, out of some larger caucus. - Fraction { - #[codec(compact)] - nom: u32, - #[codec(compact)] - denom: u32, - }, - /// No less than the given proportion of members of the body. - AtLeastProportion { - #[codec(compact)] - nom: u32, - #[codec(compact)] - denom: u32, - }, - /// More than the given proportion of members of the body. - MoreThanProportion { - #[codec(compact)] - nom: u32, - #[codec(compact)] - denom: u32, - }, -} - -impl BodyPart { - /// Returns `true` if the part represents a strict majority (> 50%) of the body in question. - pub fn is_majority(&self) -> bool { - match self { - BodyPart::Fraction { nom, denom } if *nom * 2 > *denom => true, - BodyPart::AtLeastProportion { nom, denom } if *nom * 2 > *denom => true, - BodyPart::MoreThanProportion { nom, denom } if *nom * 2 >= *denom => true, - _ => false, - } - } -} - -impl From for BodyPart { - fn from(n: NewBodyPart) -> Self { - use NewBodyPart::*; - match n { - Voice => Self::Voice, - Members { count } => Self::Members { count }, - Fraction { nom, denom } => Self::Fraction { nom, denom }, - AtLeastProportion { nom, denom } => Self::AtLeastProportion { nom, denom }, - MoreThanProportion { nom, denom } => Self::MoreThanProportion { nom, denom }, - } - } -} - -/// This module's XCM version. -pub const VERSION: super::Version = 2; - -/// An identifier for a query. -pub type QueryId = u64; - -/// DEPRECATED. Please use XCMv3 or XCMv4 instead. -#[derive(Derivative, Default, Encode, TypeInfo)] -#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] -#[codec(encode_bound())] -#[codec(decode_bound())] -#[scale_info(bounds(), skip_type_params(RuntimeCall))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub struct Xcm(pub Vec>); - -environmental::environmental!(instructions_count: u8); - -impl Decode for Xcm { - fn decode(input: &mut I) -> core::result::Result { - instructions_count::using_once(&mut 0, || { - let number_of_instructions: u32 = >::decode(input)?.into(); - instructions_count::with(|count| { - *count = count.saturating_add(number_of_instructions as u8); - if *count > MAX_INSTRUCTIONS_TO_DECODE { - return Err(CodecError::from("Max instructions exceeded")) - } - Ok(()) - }) - .unwrap_or(Ok(()))?; - let decoded_instructions = decode_vec_with_len(input, number_of_instructions as usize)?; - Ok(Self(decoded_instructions)) - }) - } -} - -/// The maximal number of instructions in an XCM before decoding fails. -/// -/// This is a deliberate limit - not a technical one. -pub const MAX_INSTRUCTIONS_TO_DECODE: u8 = 100; - -impl Xcm { - /// Create an empty instance. - pub fn new() -> Self { - Self(vec![]) - } - - /// Return `true` if no instructions are held in `self`. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - - /// Return the number of instructions held in `self`. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Consume and either return `self` if it contains some instructions, or if it's empty, then - /// instead return the result of `f`. - pub fn or_else(self, f: impl FnOnce() -> Self) -> Self { - if self.0.is_empty() { - f() - } else { - self - } - } - - /// Return the first instruction, if any. - pub fn first(&self) -> Option<&Instruction> { - self.0.first() - } - - /// Return the last instruction, if any. - pub fn last(&self) -> Option<&Instruction> { - self.0.last() - } - - /// Return the only instruction, contained in `Self`, iff only one exists (`None` otherwise). - pub fn only(&self) -> Option<&Instruction> { - if self.0.len() == 1 { - self.0.first() - } else { - None - } - } - - /// Return the only instruction, contained in `Self`, iff only one exists (returns `self` - /// otherwise). - pub fn into_only(mut self) -> core::result::Result, Self> { - if self.0.len() == 1 { - self.0.pop().ok_or(self) - } else { - Err(self) - } - } -} - -/// A prelude for importing all types typically used when interacting with XCM messages. -pub mod prelude { - mod contents { - pub use super::super::{ - Ancestor, AncestorThen, - AssetId::{self, *}, - AssetInstance::{self, *}, - BodyId, BodyPart, Error as XcmError, ExecuteXcm, - Fungibility::{self, *}, - Instruction::*, - InteriorMultiLocation, - Junction::{self, *}, - Junctions::{self, *}, - MultiAsset, - MultiAssetFilter::{self, *}, - MultiAssets, MultiLocation, - NetworkId::{self, *}, - OriginKind, Outcome, Parent, ParentThen, QueryId, Response, Result as XcmResult, - SendError, SendResult, SendXcm, - WeightLimit::{self, *}, - WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible}, - WildMultiAsset::{self, *}, - XcmWeightInfo, VERSION as XCM_VERSION, - }; - } - pub use super::{Instruction, Xcm}; - pub use contents::*; - pub mod opaque { - pub use super::{ - super::opaque::{Instruction, Xcm}, - contents::*, - }; - } -} - -/// Response data to a query. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Response { - /// No response. Serves as a neutral default. - Null, - /// Some assets. - Assets(MultiAssets), - /// The outcome of an XCM instruction. - ExecutionResult(Option<(u32, Error)>), - /// An XCM version. - Version(super::Version), -} - -impl Default for Response { - fn default() -> Self { - Self::Null - } -} - -/// An optional weight limit. -#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum WeightLimit { - /// No weight limit imposed. - Unlimited, - /// Weight limit imposed of the inner value. - Limited(#[codec(compact)] u64), -} - -impl From> for WeightLimit { - fn from(x: Option) -> Self { - match x { - Some(w) => WeightLimit::Limited(w), - None => WeightLimit::Unlimited, - } - } -} - -impl From for Option { - fn from(x: WeightLimit) -> Self { - match x { - WeightLimit::Limited(w) => Some(w), - WeightLimit::Unlimited => None, - } - } -} - -impl TryFrom for WeightLimit { - type Error = (); - fn try_from(x: NewWeightLimit) -> result::Result { - use NewWeightLimit::*; - match x { - Limited(w) => Ok(Self::Limited(w.ref_time())), - Unlimited => Ok(Self::Unlimited), - } - } -} - -/// Local weight type; execution time in picoseconds. -pub type Weight = u64; - -/// Cross-Consensus Message: A message from one consensus system to another. -/// -/// Consensus systems that may send and receive messages include blockchains and smart contracts. -/// -/// All messages are delivered from a known *origin*, expressed as a `MultiLocation`. -/// -/// This is the inner XCM format and is version-sensitive. Messages are typically passed using the -/// outer XCM format, known as `VersionedXcm`. -#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)] -#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] -#[codec(encode_bound())] -#[codec(decode_bound())] -#[scale_info(bounds(), skip_type_params(RuntimeCall))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Instruction { - /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place them into the Holding - /// Register. - /// - /// - `assets`: The asset(s) to be withdrawn into holding. - /// - /// Kind: *Command*. - /// - /// Errors: - WithdrawAsset(MultiAssets), - - /// Asset(s) (`assets`) have been received into the ownership of this system on the `origin` - /// system and equivalent derivatives should be placed into the Holding Register. - /// - /// - `assets`: The asset(s) that are minted into holding. - /// - /// Safety: `origin` must be trusted to have received and be storing `assets` such that they - /// may later be withdrawn should this system send a corresponding message. - /// - /// Kind: *Trusted Indication*. - /// - /// Errors: - ReserveAssetDeposited(MultiAssets), - - /// Asset(s) (`assets`) have been destroyed on the `origin` system and equivalent assets should - /// be created and placed into the Holding Register. - /// - /// - `assets`: The asset(s) that are minted into the Holding Register. - /// - /// Safety: `origin` must be trusted to have irrevocably destroyed the corresponding `assets` - /// prior as a consequence of sending this message. - /// - /// Kind: *Trusted Indication*. - /// - /// Errors: - ReceiveTeleportedAsset(MultiAssets), - - /// Respond with information that the local system is expecting. - /// - /// - `query_id`: The identifier of the query that resulted in this message being sent. - /// - `response`: The message content. - /// - `max_weight`: The maximum weight that handling this response should take. - /// - /// Safety: No concerns. - /// - /// Kind: *Information*. - /// - /// Errors: - QueryResponse { - #[codec(compact)] - query_id: QueryId, - response: Response, - #[codec(compact)] - max_weight: u64, - }, - - /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets - /// under the ownership of `beneficiary`. - /// - /// - `assets`: The asset(s) to be withdrawn. - /// - `beneficiary`: The new owner for the assets. - /// - /// Safety: No concerns. - /// - /// Kind: *Command*. - /// - /// Errors: - TransferAsset { assets: MultiAssets, beneficiary: MultiLocation }, - - /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets - /// under the ownership of `dest` within this consensus system (i.e. its sovereign account). - /// - /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given - /// `xcm`. - /// - /// - `assets`: The asset(s) to be withdrawn. - /// - `dest`: The location whose sovereign account will own the assets and thus the effective - /// beneficiary for the assets and the notification target for the reserve asset deposit - /// message. - /// - `xcm`: The instructions that should follow the `ReserveAssetDeposited` instruction, which - /// is sent onwards to `dest`. - /// - /// Safety: No concerns. - /// - /// Kind: *Command*. - /// - /// Errors: - TransferReserveAsset { assets: MultiAssets, dest: MultiLocation, xcm: Xcm<()> }, - - /// Apply the encoded transaction `call`, whose dispatch-origin should be `origin` as expressed - /// by the kind of origin `origin_type`. - /// - /// - `origin_type`: The means of expressing the message origin as a dispatch origin. - /// - `max_weight`: The weight of `call`; this should be at least the chain's calculated weight - /// and will be used in the weight determination arithmetic. - /// - `call`: The encoded transaction to be applied. - /// - /// Safety: No concerns. - /// - /// Kind: *Command*. - /// - /// Errors: - Transact { - origin_type: OriginKind, - #[codec(compact)] - require_weight_at_most: u64, - call: DoubleEncoded, - }, - - /// A message to notify about a new incoming HRMP channel. This message is meant to be sent by - /// the relay-chain to a para. - /// - /// - `sender`: The sender in the to-be opened channel. Also, the initiator of the channel - /// opening. - /// - `max_message_size`: The maximum size of a message proposed by the sender. - /// - `max_capacity`: The maximum number of messages that can be queued in the channel. - /// - /// Safety: The message should originate directly from the relay-chain. - /// - /// Kind: *System Notification* - HrmpNewChannelOpenRequest { - #[codec(compact)] - sender: u32, - #[codec(compact)] - max_message_size: u32, - #[codec(compact)] - max_capacity: u32, - }, - - /// A message to notify about that a previously sent open channel request has been accepted by - /// the recipient. That means that the channel will be opened during the next relay-chain - /// session change. This message is meant to be sent by the relay-chain to a para. - /// - /// Safety: The message should originate directly from the relay-chain. - /// - /// Kind: *System Notification* - /// - /// Errors: - HrmpChannelAccepted { - // NOTE: We keep this as a structured item to a) keep it consistent with the other Hrmp - // items; and b) because the field's meaning is not obvious/mentioned from the item name. - #[codec(compact)] - recipient: u32, - }, - - /// A message to notify that the other party in an open channel decided to close it. In - /// particular, `initiator` is going to close the channel opened from `sender` to the - /// `recipient`. The close will be enacted at the next relay-chain session change. This message - /// is meant to be sent by the relay-chain to a para. - /// - /// Safety: The message should originate directly from the relay-chain. - /// - /// Kind: *System Notification* - /// - /// Errors: - HrmpChannelClosing { - #[codec(compact)] - initiator: u32, - #[codec(compact)] - sender: u32, - #[codec(compact)] - recipient: u32, - }, - - /// Clear the origin. - /// - /// This may be used by the XCM author to ensure that later instructions cannot command the - /// authority of the origin (e.g. if they are being relayed from an untrusted source, as often - /// the case with `ReserveAssetDeposited`). - /// - /// Safety: No concerns. - /// - /// Kind: *Command*. - /// - /// Errors: - ClearOrigin, - - /// Mutate the origin to some interior location. - /// - /// Kind: *Command* - /// - /// Errors: - DescendOrigin(InteriorMultiLocation), - - /// Immediately report the contents of the Error Register to the given destination via XCM. - /// - /// A `QueryResponse` message of type `ExecutionOutcome` is sent to `dest` with the given - /// `query_id` and the outcome of the XCM. - /// - /// - `query_id`: An identifier that will be replicated into the returned XCM message. - /// - `dest`: A valid destination for the returned XCM message. - /// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which - /// is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the - /// response may not execute at all. - /// - /// Kind: *Command* - /// - /// Errors: - ReportError { - #[codec(compact)] - query_id: QueryId, - dest: MultiLocation, - #[codec(compact)] - max_response_weight: u64, - }, - - /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under - /// the ownership of `beneficiary` within this consensus system. - /// - /// - `assets`: The asset(s) to remove from holding. - /// - `max_assets`: The maximum number of unique assets/asset instances to remove from holding. - /// Only the first `max_assets` assets/instances of those matched by `assets` will be - /// removed, prioritized under standard asset ordering. Any others will remain in holding. - /// - `beneficiary`: The new owner for the assets. - /// - /// Kind: *Command* - /// - /// Errors: - DepositAsset { - assets: MultiAssetFilter, - #[codec(compact)] - max_assets: u32, - beneficiary: MultiLocation, - }, - - /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under - /// the ownership of `dest` within this consensus system (i.e. deposit them into its sovereign - /// account). - /// - /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given `effects`. - /// - /// - `assets`: The asset(s) to remove from holding. - /// - `max_assets`: The maximum number of unique assets/asset instances to remove from holding. - /// Only the first `max_assets` assets/instances of those matched by `assets` will be - /// removed, prioritized under standard asset ordering. Any others will remain in holding. - /// - `dest`: The location whose sovereign account will own the assets and thus the effective - /// beneficiary for the assets and the notification target for the reserve asset deposit - /// message. - /// - `xcm`: The orders that should follow the `ReserveAssetDeposited` instruction which is - /// sent onwards to `dest`. - /// - /// Kind: *Command* - /// - /// Errors: - DepositReserveAsset { - assets: MultiAssetFilter, - #[codec(compact)] - max_assets: u32, - dest: MultiLocation, - xcm: Xcm<()>, - }, - - /// Remove the asset(s) (`give`) from the Holding Register and replace them with alternative - /// assets. - /// - /// The minimum amount of assets to be received into the Holding Register for the order not to - /// fail may be stated. - /// - /// - `give`: The asset(s) to remove from holding. - /// - `receive`: The minimum amount of assets(s) which `give` should be exchanged for. - /// - /// Kind: *Command* - /// - /// Errors: - ExchangeAsset { give: MultiAssetFilter, receive: MultiAssets }, - - /// Remove the asset(s) (`assets`) from holding and send a `WithdrawAsset` XCM message to a - /// reserve location. - /// - /// - `assets`: The asset(s) to remove from holding. - /// - `reserve`: A valid location that acts as a reserve for all asset(s) in `assets`. The - /// sovereign account of this consensus system *on the reserve location* will have - /// appropriate assets withdrawn and `effects` will be executed on them. There will typically - /// be only one valid location on any given asset/chain combination. - /// - `xcm`: The instructions to execute on the assets once withdrawn *on the reserve - /// location*. - /// - /// Kind: *Command* - /// - /// Errors: - InitiateReserveWithdraw { assets: MultiAssetFilter, reserve: MultiLocation, xcm: Xcm<()> }, - - /// Remove the asset(s) (`assets`) from holding and send a `ReceiveTeleportedAsset` XCM message - /// to a `dest` location. - /// - /// - `assets`: The asset(s) to remove from holding. - /// - `dest`: A valid location that respects teleports coming from this location. - /// - `xcm`: The instructions to execute on the assets once arrived *on the destination - /// location*. - /// - /// NOTE: The `dest` location *MUST* respect this origin as a valid teleportation origin for - /// all `assets`. If it does not, then the assets may be lost. - /// - /// Kind: *Command* - /// - /// Errors: - InitiateTeleport { assets: MultiAssetFilter, dest: MultiLocation, xcm: Xcm<()> }, - - /// Send a `Balances` XCM message with the `assets` value equal to the holding contents, or a - /// portion thereof. - /// - /// - `query_id`: An identifier that will be replicated into the returned XCM message. - /// - `dest`: A valid destination for the returned XCM message. This may be limited to the - /// current origin. - /// - `assets`: A filter for the assets that should be reported back. The assets reported back - /// will be, asset-wise, *the lesser of this value and the holding register*. No wildcards - /// will be used when reporting assets back. - /// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which - /// is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the - /// response may not execute at all. - /// - /// Kind: *Command* - /// - /// Errors: - QueryHolding { - #[codec(compact)] - query_id: QueryId, - dest: MultiLocation, - assets: MultiAssetFilter, - #[codec(compact)] - max_response_weight: u64, - }, - - /// Pay for the execution of some XCM `xcm` and `orders` with up to `weight` - /// picoseconds of execution time, paying for this with up to `fees` from the Holding Register. - /// - /// - `fees`: The asset(s) to remove from the Holding Register to pay for fees. - /// - `weight_limit`: The maximum amount of weight to purchase; this must be at least the - /// expected maximum weight of the total XCM to be executed for the - /// `AllowTopLevelPaidExecutionFrom` barrier to allow the XCM be executed. - /// - /// Kind: *Command* - /// - /// Errors: - BuyExecution { fees: MultiAsset, weight_limit: WeightLimit }, - - /// Refund any surplus weight previously bought with `BuyExecution`. - /// - /// Kind: *Command* - /// - /// Errors: None. - RefundSurplus, - - /// Set the Error Handler Register. This is code that should be called in the case of an error - /// happening. - /// - /// An error occurring within execution of this code will _NOT_ result in the error register - /// being set, nor will an error handler be called due to it. The error handler and appendix - /// may each still be set. - /// - /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing - /// weight however includes only the difference between the previous handler and the new - /// handler, which can reasonably be negative, which would result in a surplus. - /// - /// Kind: *Command* - /// - /// Errors: None. - SetErrorHandler(Xcm), - - /// Set the Appendix Register. This is code that should be called after code execution - /// (including the error handler if any) is finished. This will be called regardless of whether - /// an error occurred. - /// - /// Any error occurring due to execution of this code will result in the error register being - /// set, and the error handler (if set) firing. - /// - /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing - /// weight however includes only the difference between the previous appendix and the new - /// appendix, which can reasonably be negative, which would result in a surplus. - /// - /// Kind: *Command* - /// - /// Errors: None. - SetAppendix(Xcm), - - /// Clear the Error Register. - /// - /// Kind: *Command* - /// - /// Errors: None. - ClearError, - - /// Create some assets which are being held on behalf of the origin. - /// - /// - `assets`: The assets which are to be claimed. This must match exactly with the assets - /// claimable by the origin of the ticket. - /// - `ticket`: The ticket of the asset; this is an abstract identifier to help locate the - /// asset. - /// - /// Kind: *Command* - /// - /// Errors: - ClaimAsset { assets: MultiAssets, ticket: MultiLocation }, - - /// Always throws an error of type `Trap`. - /// - /// Kind: *Command* - /// - /// Errors: - /// - `Trap`: All circumstances, whose inner value is the same as this item's inner value. - Trap(#[codec(compact)] u64), - - /// Ask the destination system to respond with the most recent version of XCM that they - /// support in a `QueryResponse` instruction. Any changes to this should also elicit similar - /// responses when they happen. - /// - /// - `query_id`: An identifier that will be replicated into the returned XCM message. - /// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which - /// is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the - /// response may not execute at all. - /// - /// Kind: *Command* - /// - /// Errors: *Fallible* - SubscribeVersion { - #[codec(compact)] - query_id: QueryId, - #[codec(compact)] - max_response_weight: u64, - }, - - /// Cancel the effect of a previous `SubscribeVersion` instruction. - /// - /// Kind: *Command* - /// - /// Errors: *Fallible* - UnsubscribeVersion, -} - -impl Xcm { - pub fn into(self) -> Xcm { - Xcm::from(self) - } - pub fn from(xcm: Xcm) -> Self { - Self(xcm.0.into_iter().map(Instruction::::from).collect()) - } -} - -impl Instruction { - pub fn into(self) -> Instruction { - Instruction::from(self) - } - pub fn from(xcm: Instruction) -> Self { - use Instruction::*; - match xcm { - WithdrawAsset(assets) => WithdrawAsset(assets), - ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), - ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), - QueryResponse { query_id, response, max_weight } => - QueryResponse { query_id, response, max_weight }, - TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, - TransferReserveAsset { assets, dest, xcm } => - TransferReserveAsset { assets, dest, xcm }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, - HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_type, require_weight_at_most, call } => - Transact { origin_type, require_weight_at_most, call: call.into() }, - ReportError { query_id, dest, max_response_weight } => - ReportError { query_id, dest, max_response_weight }, - DepositAsset { assets, max_assets, beneficiary } => - DepositAsset { assets, max_assets, beneficiary }, - DepositReserveAsset { assets, max_assets, dest, xcm } => - DepositReserveAsset { assets, max_assets, dest, xcm }, - ExchangeAsset { give, receive } => ExchangeAsset { give, receive }, - InitiateReserveWithdraw { assets, reserve, xcm } => - InitiateReserveWithdraw { assets, reserve, xcm }, - InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, - QueryHolding { query_id, dest, assets, max_response_weight } => - QueryHolding { query_id, dest, assets, max_response_weight }, - BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, - ClearOrigin => ClearOrigin, - DescendOrigin(who) => DescendOrigin(who), - RefundSurplus => RefundSurplus, - SetErrorHandler(xcm) => SetErrorHandler(xcm.into()), - SetAppendix(xcm) => SetAppendix(xcm.into()), - ClearError => ClearError, - ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, - Trap(code) => Trap(code), - SubscribeVersion { query_id, max_response_weight } => - SubscribeVersion { query_id, max_response_weight }, - UnsubscribeVersion => UnsubscribeVersion, - } - } -} - -// TODO: Automate Generation -impl> GetWeight for Instruction { - fn weight(&self) -> sp_weights::Weight { - use Instruction::*; - match self { - WithdrawAsset(assets) => sp_weights::Weight::from_parts(W::withdraw_asset(assets), 0), - ReserveAssetDeposited(assets) => - sp_weights::Weight::from_parts(W::reserve_asset_deposited(assets), 0), - ReceiveTeleportedAsset(assets) => - sp_weights::Weight::from_parts(W::receive_teleported_asset(assets), 0), - QueryResponse { query_id, response, max_weight } => - sp_weights::Weight::from_parts(W::query_response(query_id, response, max_weight), 0), - TransferAsset { assets, beneficiary } => - sp_weights::Weight::from_parts(W::transfer_asset(assets, beneficiary), 0), - TransferReserveAsset { assets, dest, xcm } => - sp_weights::Weight::from_parts(W::transfer_reserve_asset(&assets, dest, xcm), 0), - Transact { origin_type, require_weight_at_most, call } => - sp_weights::Weight::from_parts( - W::transact(origin_type, require_weight_at_most, call), - 0, - ), - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - sp_weights::Weight::from_parts( - W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), - 0, - ), - HrmpChannelAccepted { recipient } => - sp_weights::Weight::from_parts(W::hrmp_channel_accepted(recipient), 0), - HrmpChannelClosing { initiator, sender, recipient } => sp_weights::Weight::from_parts( - W::hrmp_channel_closing(initiator, sender, recipient), - 0, - ), - ClearOrigin => sp_weights::Weight::from_parts(W::clear_origin(), 0), - DescendOrigin(who) => sp_weights::Weight::from_parts(W::descend_origin(who), 0), - ReportError { query_id, dest, max_response_weight } => sp_weights::Weight::from_parts( - W::report_error(query_id, dest, max_response_weight), - 0, - ), - DepositAsset { assets, max_assets, beneficiary } => - sp_weights::Weight::from_parts(W::deposit_asset(assets, max_assets, beneficiary), 0), - DepositReserveAsset { assets, max_assets, dest, xcm } => - sp_weights::Weight::from_parts( - W::deposit_reserve_asset(assets, max_assets, dest, xcm), - 0, - ), - ExchangeAsset { give, receive } => - sp_weights::Weight::from_parts(W::exchange_asset(give, receive), 0), - InitiateReserveWithdraw { assets, reserve, xcm } => sp_weights::Weight::from_parts( - W::initiate_reserve_withdraw(assets, reserve, xcm), - 0, - ), - InitiateTeleport { assets, dest, xcm } => - sp_weights::Weight::from_parts(W::initiate_teleport(assets, dest, xcm), 0), - QueryHolding { query_id, dest, assets, max_response_weight } => - sp_weights::Weight::from_parts( - W::query_holding(query_id, dest, assets, max_response_weight), - 0, - ), - BuyExecution { fees, weight_limit } => - sp_weights::Weight::from_parts(W::buy_execution(fees, weight_limit), 0), - RefundSurplus => sp_weights::Weight::from_parts(W::refund_surplus(), 0), - SetErrorHandler(xcm) => sp_weights::Weight::from_parts(W::set_error_handler(xcm), 0), - SetAppendix(xcm) => sp_weights::Weight::from_parts(W::set_appendix(xcm), 0), - ClearError => sp_weights::Weight::from_parts(W::clear_error(), 0), - ClaimAsset { assets, ticket } => - sp_weights::Weight::from_parts(W::claim_asset(assets, ticket), 0), - Trap(code) => sp_weights::Weight::from_parts(W::trap(code), 0), - SubscribeVersion { query_id, max_response_weight } => sp_weights::Weight::from_parts( - W::subscribe_version(query_id, max_response_weight), - 0, - ), - UnsubscribeVersion => sp_weights::Weight::from_parts(W::unsubscribe_version(), 0), - } - } -} - -pub mod opaque { - /// The basic concrete type of `Xcm`, which doesn't make any assumptions about the - /// format of a call other than it is pre-encoded. - pub type Xcm = super::Xcm<()>; - - /// The basic concrete type of `Instruction`, which doesn't make any assumptions about the - /// format of a call other than it is pre-encoded. - pub type Instruction = super::Instruction<()>; -} - -// Convert from a v3 response to a v2 response -impl TryFrom for Response { - type Error = (); - fn try_from(response: NewResponse) -> result::Result { - Ok(match response { - NewResponse::Assets(assets) => Self::Assets(assets.try_into()?), - NewResponse::Version(version) => Self::Version(version), - NewResponse::ExecutionResult(error) => Self::ExecutionResult(match error { - Some((i, e)) => Some((i, e.try_into()?)), - None => None, - }), - NewResponse::Null => Self::Null, - _ => return Err(()), - }) - } -} - -// Convert from a v3 XCM to a v2 XCM. -impl TryFrom> for Xcm { - type Error = (); - fn try_from(new_xcm: NewXcm) -> result::Result { - Ok(Xcm(new_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) - } -} - -// Convert from a v3 instruction to a v2 instruction -impl TryFrom> for Instruction { - type Error = (); - fn try_from(instruction: NewInstruction) -> result::Result { - use NewInstruction::*; - Ok(match instruction { - WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), - ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), - ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight, .. } => Self::QueryResponse { - query_id, - response: response.try_into()?, - max_weight: max_weight.ref_time(), - }, - TransferAsset { assets, beneficiary } => Self::TransferAsset { - assets: assets.try_into()?, - beneficiary: beneficiary.try_into()?, - }, - TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { - assets: assets.try_into()?, - dest: dest.try_into()?, - xcm: xcm.try_into()?, - }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, - HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_kind, require_weight_at_most, call } => Self::Transact { - origin_type: origin_kind.into(), - require_weight_at_most: require_weight_at_most.ref_time(), - call: call.into(), - }, - ReportError(response_info) => Self::ReportError { - query_id: response_info.query_id, - dest: response_info.destination.try_into()?, - max_response_weight: response_info.max_weight.ref_time(), - }, - DepositAsset { assets, beneficiary } => { - let max_assets = assets.count().ok_or(())?; - let beneficiary = beneficiary.try_into()?; - let assets = assets.try_into()?; - Self::DepositAsset { assets, max_assets, beneficiary } - }, - DepositReserveAsset { assets, dest, xcm } => { - let max_assets = assets.count().ok_or(())?; - let dest = dest.try_into()?; - let xcm = xcm.try_into()?; - let assets = assets.try_into()?; - Self::DepositReserveAsset { assets, max_assets, dest, xcm } - }, - ExchangeAsset { give, want, .. } => { - let give = give.try_into()?; - let receive = want.try_into()?; - Self::ExchangeAsset { give, receive } - }, - InitiateReserveWithdraw { assets, reserve, xcm } => { - // No `max_assets` here, so if there's a connt, then we cannot translate. - let assets = assets.try_into()?; - let reserve = reserve.try_into()?; - let xcm = xcm.try_into()?; - Self::InitiateReserveWithdraw { assets, reserve, xcm } - }, - InitiateTeleport { assets, dest, xcm } => { - // No `max_assets` here, so if there's a connt, then we cannot translate. - let assets = assets.try_into()?; - let dest = dest.try_into()?; - let xcm = xcm.try_into()?; - Self::InitiateTeleport { assets, dest, xcm } - }, - ReportHolding { response_info, assets } => Self::QueryHolding { - query_id: response_info.query_id, - dest: response_info.destination.try_into()?, - assets: assets.try_into()?, - max_response_weight: response_info.max_weight.ref_time(), - }, - BuyExecution { fees, weight_limit } => { - let fees = fees.try_into()?; - let weight_limit = weight_limit.try_into()?; - Self::BuyExecution { fees, weight_limit } - }, - ClearOrigin => Self::ClearOrigin, - DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), - RefundSurplus => Self::RefundSurplus, - SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), - SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), - ClearError => Self::ClearError, - ClaimAsset { assets, ticket } => { - let assets = assets.try_into()?; - let ticket = ticket.try_into()?; - Self::ClaimAsset { assets, ticket } - }, - Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => Self::SubscribeVersion { - query_id, - max_response_weight: max_response_weight.ref_time(), - }, - UnsubscribeVersion => Self::UnsubscribeVersion, - i => { - log::debug!(target: "xcm::v3tov2", "`{i:?}` not supported by v2"); - return Err(()); - }, - }) - } -} - -#[cfg(test)] -mod tests { - use super::{prelude::*, *}; - - #[test] - fn decoding_respects_limit() { - let max_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize]); - let encoded = max_xcm.encode(); - assert!(Xcm::<()>::decode(&mut &encoded[..]).is_ok()); - - let big_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize + 1]); - let encoded = big_xcm.encode(); - assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); - - let nested_xcm = Xcm::<()>(vec![ - DepositReserveAsset { - assets: All.into(), - dest: Here.into(), - xcm: max_xcm, - max_assets: 1, - }; - (MAX_INSTRUCTIONS_TO_DECODE / 2) as usize - ]); - let encoded = nested_xcm.encode(); - assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); - - let even_more_nested_xcm = Xcm::<()>(vec![SetAppendix(nested_xcm); 64]); - let encoded = even_more_nested_xcm.encode(); - assert_eq!(encoded.len(), 345730); - // This should not decode since the limit is 100 - assert_eq!(MAX_INSTRUCTIONS_TO_DECODE, 100, "precondition"); - assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); - } -} diff --git a/polkadot/xcm/src/v2/multiasset.rs b/polkadot/xcm/src/v2/multiasset.rs deleted file mode 100644 index 218f21b63b0a..000000000000 --- a/polkadot/xcm/src/v2/multiasset.rs +++ /dev/null @@ -1,626 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Cross-Consensus Message format asset data structures. -//! -//! This encompasses four types for representing assets: -//! - `MultiAsset`: A description of a single asset, either an instance of a non-fungible or some -//! amount of a fungible. -//! - `MultiAssets`: A collection of `MultiAsset`s. These are stored in a `Vec` and sorted with -//! fungibles first. -//! - `Wild`: A single asset wildcard, this can either be "all" assets, or all assets of a specific -//! kind. -//! - `MultiAssetFilter`: A combination of `Wild` and `MultiAssets` designed for efficiently -//! filtering an XCM holding account. - -use super::MultiLocation; -use crate::v3::{ - AssetId as NewAssetId, AssetInstance as NewAssetInstance, Fungibility as NewFungibility, - MultiAsset as NewMultiAsset, MultiAssetFilter as NewMultiAssetFilter, - MultiAssets as NewMultiAssets, WildFungibility as NewWildFungibility, - WildMultiAsset as NewWildMultiAsset, -}; -use alloc::{vec, vec::Vec}; -use codec::{self as codec, Decode, Encode}; -use core::cmp::Ordering; -use scale_info::TypeInfo; - -/// A general identifier for an instance of a non-fungible asset class. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum AssetInstance { - /// Undefined - used if the non-fungible asset class has only one instance. - Undefined, - - /// A compact index. Technically this could be greater than `u128`, but this implementation - /// supports only values up to `2**128 - 1`. - Index(#[codec(compact)] u128), - - /// A 4-byte fixed-length datum. - Array4([u8; 4]), - - /// An 8-byte fixed-length datum. - Array8([u8; 8]), - - /// A 16-byte fixed-length datum. - Array16([u8; 16]), - - /// A 32-byte fixed-length datum. - Array32([u8; 32]), - - /// An arbitrary piece of data. Use only when necessary. - Blob(Vec), -} - -impl From<()> for AssetInstance { - fn from(_: ()) -> Self { - Self::Undefined - } -} - -impl From<[u8; 4]> for AssetInstance { - fn from(x: [u8; 4]) -> Self { - Self::Array4(x) - } -} - -impl From<[u8; 8]> for AssetInstance { - fn from(x: [u8; 8]) -> Self { - Self::Array8(x) - } -} - -impl From<[u8; 16]> for AssetInstance { - fn from(x: [u8; 16]) -> Self { - Self::Array16(x) - } -} - -impl From<[u8; 32]> for AssetInstance { - fn from(x: [u8; 32]) -> Self { - Self::Array32(x) - } -} - -impl From> for AssetInstance { - fn from(x: Vec) -> Self { - Self::Blob(x) - } -} - -impl TryFrom for AssetInstance { - type Error = (); - fn try_from(value: NewAssetInstance) -> Result { - use NewAssetInstance::*; - Ok(match value { - Undefined => Self::Undefined, - Index(n) => Self::Index(n), - Array4(n) => Self::Array4(n), - Array8(n) => Self::Array8(n), - Array16(n) => Self::Array16(n), - Array32(n) => Self::Array32(n), - }) - } -} - -/// Classification of an asset being concrete or abstract. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum AssetId { - Concrete(MultiLocation), - Abstract(Vec), -} - -impl> From for AssetId { - fn from(x: T) -> Self { - Self::Concrete(x.into()) - } -} - -impl From> for AssetId { - fn from(x: Vec) -> Self { - Self::Abstract(x) - } -} - -impl TryFrom for AssetId { - type Error = (); - fn try_from(old: NewAssetId) -> Result { - use NewAssetId::*; - Ok(match old { - Concrete(l) => Self::Concrete(l.try_into()?), - Abstract(v) => { - let zeroes = v.iter().rev().position(|n| *n != 0).unwrap_or(v.len()); - Self::Abstract(v[0..(32 - zeroes)].to_vec()) - }, - }) - } -} - -impl AssetId { - /// Prepend a `MultiLocation` to a concrete asset, giving it a new root location. - pub fn prepend_with(&mut self, prepend: &MultiLocation) -> Result<(), ()> { - if let AssetId::Concrete(ref mut l) = self { - l.prepend_with(prepend.clone()).map_err(|_| ())?; - } - Ok(()) - } - - /// Mutate the asset to represent the same value from the perspective of a new `target` - /// location. The local chain's location is provided in `ancestry`. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - if let AssetId::Concrete(ref mut l) = self { - l.reanchor(target, ancestry)?; - } - Ok(()) - } - - /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding - /// `MultiAsset` value. - pub fn into_multiasset(self, fun: Fungibility) -> MultiAsset { - MultiAsset { fun, id: self } - } - - /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding - /// `WildMultiAsset` wildcard (`AllOf`) value. - pub fn into_wild(self, fun: WildFungibility) -> WildMultiAsset { - WildMultiAsset::AllOf { fun, id: self } - } -} - -/// Classification of whether an asset is fungible or not, along with a mandatory amount or -/// instance. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Fungibility { - Fungible(#[codec(compact)] u128), - NonFungible(AssetInstance), -} - -impl Fungibility { - pub fn is_kind(&self, w: WildFungibility) -> bool { - use Fungibility::*; - use WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible}; - matches!((self, w), (Fungible(_), WildFungible) | (NonFungible(_), WildNonFungible)) - } -} - -impl From for Fungibility { - fn from(amount: u128) -> Fungibility { - debug_assert_ne!(amount, 0); - Fungibility::Fungible(amount) - } -} - -impl> From for Fungibility { - fn from(instance: T) -> Fungibility { - Fungibility::NonFungible(instance.into()) - } -} - -impl TryFrom for Fungibility { - type Error = (); - fn try_from(value: NewFungibility) -> Result { - use NewFungibility::*; - Ok(match value { - Fungible(n) => Self::Fungible(n), - NonFungible(i) => Self::NonFungible(i.try_into()?), - }) - } -} - -#[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub struct MultiAsset { - pub id: AssetId, - pub fun: Fungibility, -} - -impl PartialOrd for MultiAsset { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for MultiAsset { - fn cmp(&self, other: &Self) -> Ordering { - match (&self.fun, &other.fun) { - (Fungibility::Fungible(..), Fungibility::NonFungible(..)) => Ordering::Less, - (Fungibility::NonFungible(..), Fungibility::Fungible(..)) => Ordering::Greater, - _ => (&self.id, &self.fun).cmp(&(&other.id, &other.fun)), - } - } -} - -impl, B: Into> From<(A, B)> for MultiAsset { - fn from((id, fun): (A, B)) -> MultiAsset { - MultiAsset { fun: fun.into(), id: id.into() } - } -} - -impl MultiAsset { - pub fn is_fungible(&self, maybe_id: Option) -> bool { - use Fungibility::*; - matches!(self.fun, Fungible(..)) && maybe_id.map_or(true, |i| i == self.id) - } - - pub fn is_non_fungible(&self, maybe_id: Option) -> bool { - use Fungibility::*; - matches!(self.fun, NonFungible(..)) && maybe_id.map_or(true, |i| i == self.id) - } - - /// Prepend a `MultiLocation` to a concrete asset, giving it a new root location. - pub fn prepend_with(&mut self, prepend: &MultiLocation) -> Result<(), ()> { - self.id.prepend_with(prepend) - } - - /// Mutate the location of the asset identifier if concrete, giving it the same location - /// relative to a `target` context. The local context is provided as `ancestry`. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - self.id.reanchor(target, ancestry) - } - - /// Mutate the location of the asset identifier if concrete, giving it the same location - /// relative to a `target` context. The local context is provided as `ancestry`. - pub fn reanchored( - mut self, - target: &MultiLocation, - ancestry: &MultiLocation, - ) -> Result { - self.id.reanchor(target, ancestry)?; - Ok(self) - } - - /// Returns true if `self` is a super-set of the given `inner`. - pub fn contains(&self, inner: &MultiAsset) -> bool { - use Fungibility::*; - if self.id == inner.id { - match (&self.fun, &inner.fun) { - (Fungible(a), Fungible(i)) if a >= i => return true, - (NonFungible(a), NonFungible(i)) if a == i => return true, - _ => (), - } - } - false - } -} - -impl TryFrom for MultiAsset { - type Error = (); - fn try_from(new: NewMultiAsset) -> Result { - Ok(Self { id: new.id.try_into()?, fun: new.fun.try_into()? }) - } -} - -/// A `Vec` of `MultiAsset`s. There may be no duplicate fungible items in here and when decoding, -/// they must be sorted. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub struct MultiAssets(Vec); - -impl Decode for MultiAssets { - fn decode(input: &mut I) -> Result { - Self::from_sorted_and_deduplicated(Vec::::decode(input)?) - .map_err(|()| "Out of order".into()) - } -} - -impl TryFrom for MultiAssets { - type Error = (); - fn try_from(new: NewMultiAssets) -> Result { - let v = new - .into_inner() - .into_iter() - .map(MultiAsset::try_from) - .collect::, ()>>()?; - Ok(MultiAssets(v)) - } -} - -impl From> for MultiAssets { - fn from(mut assets: Vec) -> Self { - let mut res = Vec::with_capacity(assets.len()); - if !assets.is_empty() { - assets.sort(); - let mut iter = assets.into_iter(); - if let Some(first) = iter.next() { - let last = iter.fold(first, |a, b| -> MultiAsset { - match (a, b) { - ( - MultiAsset { fun: Fungibility::Fungible(a_amount), id: a_id }, - MultiAsset { fun: Fungibility::Fungible(b_amount), id: b_id }, - ) if a_id == b_id => MultiAsset { - id: a_id, - fun: Fungibility::Fungible(a_amount.saturating_add(b_amount)), - }, - ( - MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id }, - MultiAsset { fun: Fungibility::NonFungible(b_instance), id: b_id }, - ) if a_id == b_id && a_instance == b_instance => - MultiAsset { fun: Fungibility::NonFungible(a_instance), id: a_id }, - (to_push, to_remember) => { - res.push(to_push); - to_remember - }, - } - }); - res.push(last); - } - } - Self(res) - } -} - -impl> From for MultiAssets { - fn from(x: T) -> Self { - Self(vec![x.into()]) - } -} - -impl MultiAssets { - /// A new (empty) value. - pub fn new() -> Self { - Self(Vec::new()) - } - - /// Create a new instance of `MultiAssets` from a `Vec` whose contents are sorted - /// and which contain no duplicates. - /// - /// Returns `Ok` if the operation succeeds and `Err` if `r` is out of order or had duplicates. - /// If you can't guarantee that `r` is sorted and deduplicated, then use - /// `From::>::from` which is infallible. - pub fn from_sorted_and_deduplicated(r: Vec) -> Result { - if r.is_empty() { - return Ok(Self(Vec::new())) - } - r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&MultiAsset, ()> { - if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { - Ok(b) - } else { - Err(()) - } - })?; - Ok(Self(r)) - } - - /// Create a new instance of `MultiAssets` from a `Vec` whose contents are sorted - /// and which contain no duplicates. - /// - /// In release mode, this skips any checks to ensure that `r` is correct, making it a - /// negligible-cost operation. Generally though you should avoid using it unless you have a - /// strict proof that `r` is valid. - #[cfg(test)] - pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { - Self::from_sorted_and_deduplicated(r).expect("Invalid input r is not sorted/deduped") - } - /// Create a new instance of `MultiAssets` from a `Vec` whose contents are sorted - /// and which contain no duplicates. - /// - /// In release mode, this skips any checks to ensure that `r` is correct, making it a - /// negligible-cost operation. Generally though you should avoid using it unless you have a - /// strict proof that `r` is valid. - /// - /// In test mode, this checks anyway and panics on fail. - #[cfg(not(test))] - pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { - Self(r) - } - - /// Add some asset onto the list, saturating. This is quite a laborious operation since it - /// maintains the ordering. - pub fn push(&mut self, a: MultiAsset) { - if let Fungibility::Fungible(ref amount) = a.fun { - for asset in self.0.iter_mut().filter(|x| x.id == a.id) { - if let Fungibility::Fungible(ref mut balance) = asset.fun { - *balance = balance.saturating_add(*amount); - return - } - } - } - self.0.push(a); - self.0.sort(); - } - - /// Returns `true` if this definitely represents no asset. - pub fn is_none(&self) -> bool { - self.0.is_empty() - } - - /// Returns true if `self` is a super-set of the given `inner`. - pub fn contains(&self, inner: &MultiAsset) -> bool { - self.0.iter().any(|i| i.contains(inner)) - } - - /// Consume `self` and return the inner vec. - pub fn drain(self) -> Vec { - self.0 - } - - /// Return a reference to the inner vec. - pub fn inner(&self) -> &Vec { - &self.0 - } - - /// Return the number of distinct asset instances contained. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Prepend a `MultiLocation` to any concrete asset items, giving it a new root location. - pub fn prepend_with(&mut self, prefix: &MultiLocation) -> Result<(), ()> { - self.0.iter_mut().try_for_each(|i| i.prepend_with(prefix)) - } - - /// Mutate the location of the asset identifier if concrete, giving it the same location - /// relative to a `target` context. The local context is provided as `ancestry`. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - self.0.iter_mut().try_for_each(|i| i.reanchor(target, ancestry)) - } - - /// Return a reference to an item at a specific index or `None` if it doesn't exist. - pub fn get(&self, index: usize) -> Option<&MultiAsset> { - self.0.get(index) - } -} - -/// Classification of whether an asset is fungible or not. -#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum WildFungibility { - Fungible, - NonFungible, -} - -impl TryFrom for WildFungibility { - type Error = (); - fn try_from(value: NewWildFungibility) -> Result { - use NewWildFungibility::*; - Ok(match value { - Fungible => Self::Fungible, - NonFungible => Self::NonFungible, - }) - } -} - -/// A wildcard representing a set of assets. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum WildMultiAsset { - /// All assets in the holding register, up to `usize` individual assets (different instances of - /// non-fungibles could be separate assets). - All, - /// All assets in the holding register of a given fungibility and ID. If operating on - /// non-fungibles, then a limit is provided for the maximum amount of matching instances. - AllOf { id: AssetId, fun: WildFungibility }, -} - -impl WildMultiAsset { - /// Returns true if `self` is a super-set of the given `inner`. - /// - /// Typically, any wildcard is never contained in anything else, and a wildcard can contain any - /// other non-wildcard. For more details, see the implementation and tests. - pub fn contains(&self, inner: &MultiAsset) -> bool { - use WildMultiAsset::*; - match self { - AllOf { fun, id } => inner.fun.is_kind(*fun) && &inner.id == id, - All => true, - } - } - - /// Mutate the location of the asset identifier if concrete, giving it the same location - /// relative to a `target` context. The local context is provided as `ancestry`. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - use WildMultiAsset::*; - match self { - AllOf { ref mut id, .. } => id.reanchor(target, ancestry).map_err(|_| ()), - All => Ok(()), - } - } -} - -impl, B: Into> From<(A, B)> for WildMultiAsset { - fn from((id, fun): (A, B)) -> WildMultiAsset { - WildMultiAsset::AllOf { fun: fun.into(), id: id.into() } - } -} - -/// `MultiAsset` collection, either `MultiAssets` or a single wildcard. -/// -/// Note: Vectors of wildcards whose encoding is supported in XCM v0 are unsupported -/// in this implementation and will result in a decode error. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum MultiAssetFilter { - Definite(MultiAssets), - Wild(WildMultiAsset), -} - -impl> From for MultiAssetFilter { - fn from(x: T) -> Self { - Self::Wild(x.into()) - } -} - -impl From for MultiAssetFilter { - fn from(x: MultiAsset) -> Self { - Self::Definite(vec![x].into()) - } -} - -impl From> for MultiAssetFilter { - fn from(x: Vec) -> Self { - Self::Definite(x.into()) - } -} - -impl From for MultiAssetFilter { - fn from(x: MultiAssets) -> Self { - Self::Definite(x) - } -} - -impl MultiAssetFilter { - /// Returns true if `self` is a super-set of the given `inner`. - /// - /// Typically, any wildcard is never contained in anything else, and a wildcard can contain any - /// other non-wildcard. For more details, see the implementation and tests. - pub fn contains(&self, inner: &MultiAsset) -> bool { - match self { - MultiAssetFilter::Definite(ref assets) => assets.contains(inner), - MultiAssetFilter::Wild(ref wild) => wild.contains(inner), - } - } - - /// Mutate the location of the asset identifier if concrete, giving it the same location - /// relative to a `target` context. The local context is provided as `ancestry`. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - match self { - MultiAssetFilter::Definite(ref mut assets) => assets.reanchor(target, ancestry), - MultiAssetFilter::Wild(ref mut wild) => wild.reanchor(target, ancestry), - } - } -} - -impl TryFrom for WildMultiAsset { - type Error = (); - fn try_from(new: NewWildMultiAsset) -> Result { - use NewWildMultiAsset::*; - Ok(match new { - AllOf { id, fun } | AllOfCounted { id, fun, .. } => - Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, - All | AllCounted(_) => Self::All, - }) - } -} - -impl TryFrom for MultiAssetFilter { - type Error = (); - fn try_from(old: NewMultiAssetFilter) -> Result { - use NewMultiAssetFilter::*; - Ok(match old { - Definite(x) => Self::Definite(x.try_into()?), - Wild(x) => Self::Wild(x.try_into()?), - }) - } -} diff --git a/polkadot/xcm/src/v2/multilocation.rs b/polkadot/xcm/src/v2/multilocation.rs deleted file mode 100644 index 9399ca6619c0..000000000000 --- a/polkadot/xcm/src/v2/multilocation.rs +++ /dev/null @@ -1,1105 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Cross-Consensus Message format data structures. - -use super::Junction; -use crate::v3::MultiLocation as NewMultiLocation; -use codec::{Decode, Encode, MaxEncodedLen}; -use core::{mem, result}; -use scale_info::TypeInfo; - -/// A relative path between state-bearing consensus systems. -/// -/// A location in a consensus system is defined as an *isolatable state machine* held within global -/// consensus. The location in question need not have a sophisticated consensus algorithm of its -/// own; a single account within Ethereum, for example, could be considered a location. -/// -/// A very-much non-exhaustive list of types of location include: -/// - A (normal, layer-1) block chain, e.g. the Bitcoin mainnet or a parachain. -/// - A layer-0 super-chain, e.g. the Polkadot Relay chain. -/// - A layer-2 smart contract, e.g. an ERC-20 on Ethereum. -/// - A logical functional component of a chain, e.g. a single instance of a pallet on a Frame-based -/// Substrate chain. -/// - An account. -/// -/// A `MultiLocation` is a *relative identifier*, meaning that it can only be used to define the -/// relative path between two locations, and cannot generally be used to refer to a location -/// universally. It is comprised of an integer number of parents specifying the number of times to -/// "escape" upwards into the containing consensus system and then a number of *junctions*, each -/// diving down and specifying some interior portion of state (which may be considered a -/// "sub-consensus" system). -/// -/// This specific `MultiLocation` implementation uses a `Junctions` datatype which is a Rust `enum` -/// in order to make pattern matching easier. There are occasions where it is important to ensure -/// that a value is strictly an interior location, in those cases, `Junctions` may be used. -/// -/// The `MultiLocation` value of `Null` simply refers to the interpreting consensus system. -#[derive(Clone, Decode, Encode, Eq, PartialEq, Ord, PartialOrd, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub struct MultiLocation { - /// The number of parent junctions at the beginning of this `MultiLocation`. - pub parents: u8, - /// The interior (i.e. non-parent) junctions that this `MultiLocation` contains. - pub interior: Junctions, -} - -impl Default for MultiLocation { - fn default() -> Self { - Self { parents: 0, interior: Junctions::Here } - } -} - -/// A relative location which is constrained to be an interior location of the context. -/// -/// See also `MultiLocation`. -pub type InteriorMultiLocation = Junctions; - -impl MultiLocation { - /// Creates a new `MultiLocation` with the given number of parents and interior junctions. - pub fn new(parents: u8, junctions: Junctions) -> MultiLocation { - MultiLocation { parents, interior: junctions } - } - - /// Consume `self` and return the equivalent `VersionedLocation` value. - pub fn versioned(self) -> crate::VersionedLocation { - self.into() - } - - /// Creates a new `MultiLocation` with 0 parents and a `Here` interior. - /// - /// The resulting `MultiLocation` can be interpreted as the "current consensus system". - pub const fn here() -> MultiLocation { - MultiLocation { parents: 0, interior: Junctions::Here } - } - - /// Creates a new `MultiLocation` which evaluates to the parent context. - pub const fn parent() -> MultiLocation { - MultiLocation { parents: 1, interior: Junctions::Here } - } - - /// Creates a new `MultiLocation` which evaluates to the grand parent context. - pub const fn grandparent() -> MultiLocation { - MultiLocation { parents: 2, interior: Junctions::Here } - } - - /// Creates a new `MultiLocation` with `parents` and an empty (`Here`) interior. - pub const fn ancestor(parents: u8) -> MultiLocation { - MultiLocation { parents, interior: Junctions::Here } - } - - /// Whether the `MultiLocation` has no parents and has a `Here` interior. - pub const fn is_here(&self) -> bool { - self.parents == 0 && self.interior.len() == 0 - } - - /// Return a reference to the interior field. - pub fn interior(&self) -> &Junctions { - &self.interior - } - - /// Return a mutable reference to the interior field. - pub fn interior_mut(&mut self) -> &mut Junctions { - &mut self.interior - } - - /// Returns the number of `Parent` junctions at the beginning of `self`. - pub const fn parent_count(&self) -> u8 { - self.parents - } - - /// Returns boolean indicating whether `self` contains only the specified amount of - /// parents and no interior junctions. - pub const fn contains_parents_only(&self, count: u8) -> bool { - matches!(self.interior, Junctions::Here) && self.parents == count - } - - /// Returns the number of parents and junctions in `self`. - pub const fn len(&self) -> usize { - self.parent_count() as usize + self.interior.len() - } - - /// Returns the first interior junction, or `None` if the location is empty or contains only - /// parents. - pub fn first_interior(&self) -> Option<&Junction> { - self.interior.first() - } - - /// Returns last junction, or `None` if the location is empty or contains only parents. - pub fn last(&self) -> Option<&Junction> { - self.interior.last() - } - - /// Splits off the first interior junction, returning the remaining suffix (first item in tuple) - /// and the first element (second item in tuple) or `None` if it was empty. - pub fn split_first_interior(self) -> (MultiLocation, Option) { - let MultiLocation { parents, interior: junctions } = self; - let (suffix, first) = junctions.split_first(); - let multilocation = MultiLocation { parents, interior: suffix }; - (multilocation, first) - } - - /// Splits off the last interior junction, returning the remaining prefix (first item in tuple) - /// and the last element (second item in tuple) or `None` if it was empty or if `self` only - /// contains parents. - pub fn split_last_interior(self) -> (MultiLocation, Option) { - let MultiLocation { parents, interior: junctions } = self; - let (prefix, last) = junctions.split_last(); - let multilocation = MultiLocation { parents, interior: prefix }; - (multilocation, last) - } - - /// Mutates `self`, suffixing its interior junctions with `new`. Returns `Err` with `new` in - /// case of overflow. - pub fn push_interior(&mut self, new: Junction) -> result::Result<(), Junction> { - self.interior.push(new) - } - - /// Mutates `self`, prefixing its interior junctions with `new`. Returns `Err` with `new` in - /// case of overflow. - pub fn push_front_interior(&mut self, new: Junction) -> result::Result<(), Junction> { - self.interior.push_front(new) - } - - /// Consumes `self` and returns a `MultiLocation` suffixed with `new`, or an `Err` with - /// the original value of `self` in case of overflow. - pub fn pushed_with_interior(self, new: Junction) -> result::Result { - match self.interior.pushed_with(new) { - Ok(i) => Ok(MultiLocation { interior: i, parents: self.parents }), - Err((i, j)) => Err((MultiLocation { interior: i, parents: self.parents }, j)), - } - } - - /// Consumes `self` and returns a `MultiLocation` prefixed with `new`, or an `Err` with the - /// original value of `self` in case of overflow. - pub fn pushed_front_with_interior( - self, - new: Junction, - ) -> result::Result { - match self.interior.pushed_front_with(new) { - Ok(i) => Ok(MultiLocation { interior: i, parents: self.parents }), - Err((i, j)) => Err((MultiLocation { interior: i, parents: self.parents }, j)), - } - } - - /// Returns the junction at index `i`, or `None` if the location is a parent or if the location - /// does not contain that many elements. - pub fn at(&self, i: usize) -> Option<&Junction> { - let num_parents = self.parents as usize; - if i < num_parents { - return None - } - self.interior.at(i - num_parents) - } - - /// Returns a mutable reference to the junction at index `i`, or `None` if the location is a - /// parent or if it doesn't contain that many elements. - pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { - let num_parents = self.parents as usize; - if i < num_parents { - return None - } - self.interior.at_mut(i - num_parents) - } - - /// Decrements the parent count by 1. - pub fn dec_parent(&mut self) { - self.parents = self.parents.saturating_sub(1); - } - - /// Removes the first interior junction from `self`, returning it - /// (or `None` if it was empty or if `self` contains only parents). - pub fn take_first_interior(&mut self) -> Option { - self.interior.take_first() - } - - /// Removes the last element from `interior`, returning it (or `None` if it was empty or if - /// `self` only contains parents). - pub fn take_last(&mut self) -> Option { - self.interior.take_last() - } - - /// Ensures that `self` has the same number of parents as `prefix`, its junctions begins with - /// the junctions of `prefix` and that it has a single `Junction` item following. - /// If so, returns a reference to this `Junction` item. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(1, [PalletInstance(3), OnlyChild].into()); - /// assert_eq!( - /// m.match_and_split(&MultiLocation::new(1, [PalletInstance(3)].into())), - /// Some(&OnlyChild), - /// ); - /// assert_eq!(m.match_and_split(&MultiLocation::new(1, Here)), None); - /// ``` - pub fn match_and_split(&self, prefix: &MultiLocation) -> Option<&Junction> { - if self.parents != prefix.parents { - return None - } - self.interior.match_and_split(&prefix.interior) - } - - /// Returns whether `self` has the same number of parents as `prefix` and its junctions begins - /// with the junctions of `prefix`. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let m = MultiLocation::new(1, [PalletInstance(3), OnlyChild, OnlyChild].into()); - /// assert!(m.starts_with(&MultiLocation::new(1, [PalletInstance(3)].into()))); - /// assert!(!m.starts_with(&MultiLocation::new(1, [GeneralIndex(99)].into()))); - /// assert!(!m.starts_with(&MultiLocation::new(0, [PalletInstance(3)].into()))); - /// ``` - pub fn starts_with(&self, prefix: &MultiLocation) -> bool { - if self.parents != prefix.parents { - return false - } - self.interior.starts_with(&prefix.interior) - } - - /// Mutate `self` so that it is suffixed with `suffix`. - /// - /// Does not modify `self` and returns `Err` with `suffix` in case of overflow. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(1, [Parachain(21)].into()); - /// assert_eq!(m.append_with([PalletInstance(3)].into()), Ok(())); - /// assert_eq!(m, MultiLocation::new(1, [Parachain(21), PalletInstance(3)].into())); - /// ``` - pub fn append_with(&mut self, suffix: Junctions) -> Result<(), Junctions> { - if self.interior.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { - return Err(suffix) - } - for j in suffix.into_iter() { - self.interior.push(j).expect("Already checked the sum of the len()s; qed") - } - Ok(()) - } - - /// Mutate `self` so that it is prefixed with `prefix`. - /// - /// Does not modify `self` and returns `Err` with `prefix` in case of overflow. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*, MultiLocation}; - /// let mut m = MultiLocation::new(2, [PalletInstance(3)].into()); - /// assert_eq!(m.prepend_with(MultiLocation::new(1, [Parachain(21), OnlyChild].into())), Ok(())); - /// assert_eq!(m, MultiLocation::new(1, [PalletInstance(3)].into())); - /// ``` - pub fn prepend_with(&mut self, mut prefix: MultiLocation) -> Result<(), MultiLocation> { - // prefix self (suffix) - // P .. P I .. I p .. p i .. i - let prepend_interior = prefix.interior.len().saturating_sub(self.parents as usize); - let final_interior = self.interior.len().saturating_add(prepend_interior); - if final_interior > MAX_JUNCTIONS { - return Err(prefix) - } - let suffix_parents = (self.parents as usize).saturating_sub(prefix.interior.len()); - let final_parents = (prefix.parents as usize).saturating_add(suffix_parents); - if final_parents > 255 { - return Err(prefix) - } - - // cancel out the final item on the prefix interior for one of the suffix's parents. - while self.parents > 0 && prefix.take_last().is_some() { - self.dec_parent(); - } - - // now we have either removed all suffix's parents or prefix interior. - // this means we can combine the prefix's and suffix's remaining parents/interior since - // we know that with at least one empty, the overall order will be respected: - // prefix self (suffix) - // P .. P (I) p .. p i .. i => P + p .. (no I) i - // -- or -- - // P .. P I .. I (p) i .. i => P (no p) .. I + i - - self.parents = self.parents.saturating_add(prefix.parents); - for j in prefix.interior.into_iter().rev() { - self.push_front_interior(j) - .expect("final_interior no greater than MAX_JUNCTIONS; qed"); - } - Ok(()) - } - - /// Consume `self` and return the value representing the same location from the point of view - /// of `target`. The context of `self` is provided as `ancestry`. - /// - /// Returns an `Err` with the unmodified `self` in the case of error. - pub fn reanchored( - mut self, - target: &MultiLocation, - ancestry: &MultiLocation, - ) -> Result { - match self.reanchor(target, ancestry) { - Ok(()) => Ok(self), - Err(()) => Err(self), - } - } - - /// Mutate `self` so that it represents the same location from the point of view of `target`. - /// The context of `self` is provided as `ancestry`. - /// - /// Does not modify `self` in case of overflow. - pub fn reanchor(&mut self, target: &MultiLocation, ancestry: &MultiLocation) -> Result<(), ()> { - // TODO: https://github.com/paritytech/polkadot/issues/4489 Optimize this. - - // 1. Use our `ancestry` to figure out how the `target` would address us. - let inverted_target = ancestry.inverted(target)?; - - // 2. Prepend `inverted_target` to `self` to get self's location from the perspective of - // `target`. - self.prepend_with(inverted_target).map_err(|_| ())?; - - // 3. Given that we know some of `target` ancestry, ensure that any parents in `self` are - // strictly needed. - self.simplify(target.interior()); - - Ok(()) - } - - /// Treating `self` as a context, determine how it would be referenced by a `target` location. - pub fn inverted(&self, target: &MultiLocation) -> Result { - use Junction::OnlyChild; - let mut ancestry = self.clone(); - let mut junctions = Junctions::Here; - for _ in 0..target.parent_count() { - junctions = junctions - .pushed_front_with(ancestry.interior.take_last().unwrap_or(OnlyChild)) - .map_err(|_| ())?; - } - let parents = target.interior().len() as u8; - Ok(MultiLocation::new(parents, junctions)) - } - - /// Remove any unneeded parents/junctions in `self` based on the given context it will be - /// interpreted in. - pub fn simplify(&mut self, context: &Junctions) { - if context.len() < self.parents as usize { - // Not enough context - return - } - while self.parents > 0 { - let maybe = context.at(context.len() - (self.parents as usize)); - match (self.interior.first(), maybe) { - (Some(i), Some(j)) if i == j => { - self.interior.take_first(); - self.parents -= 1; - }, - _ => break, - } - } - } -} - -impl TryFrom for MultiLocation { - type Error = (); - fn try_from(x: NewMultiLocation) -> result::Result { - Ok(MultiLocation { parents: x.parents, interior: x.interior.try_into()? }) - } -} - -/// A unit struct which can be converted into a `MultiLocation` of `parents` value 1. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct Parent; -impl From for MultiLocation { - fn from(_: Parent) -> Self { - MultiLocation { parents: 1, interior: Junctions::Here } - } -} - -/// A tuple struct which can be converted into a `MultiLocation` of `parents` value 1 with the inner -/// interior. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct ParentThen(pub Junctions); -impl From for MultiLocation { - fn from(ParentThen(interior): ParentThen) -> Self { - MultiLocation { parents: 1, interior } - } -} - -/// A unit struct which can be converted into a `MultiLocation` of the inner `parents` value. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct Ancestor(pub u8); -impl From for MultiLocation { - fn from(Ancestor(parents): Ancestor) -> Self { - MultiLocation { parents, interior: Junctions::Here } - } -} - -/// A unit struct which can be converted into a `MultiLocation` of the inner `parents` value and the -/// inner interior. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] -pub struct AncestorThen(pub u8, pub Interior); -impl> From> for MultiLocation { - fn from(AncestorThen(parents, interior): AncestorThen) -> Self { - MultiLocation { parents, interior: interior.into() } - } -} - -xcm_procedural::impl_conversion_functions_for_multilocation_v2!(); -xcm_procedural::impl_conversion_functions_for_junctions_v2!(); - -/// Maximum number of `Junction`s that a `Junctions` can contain. -const MAX_JUNCTIONS: usize = 8; - -/// Non-parent junctions that can be constructed, up to the length of 8. This specific `Junctions` -/// implementation uses a Rust `enum` in order to make pattern matching easier. -/// -/// Parent junctions cannot be constructed with this type. Refer to `MultiLocation` for -/// instructions on constructing parent junctions. -#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] -#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Junctions { - /// The interpreting consensus system. - Here, - /// A relative path comprising 1 junction. - X1(Junction), - /// A relative path comprising 2 junctions. - X2(Junction, Junction), - /// A relative path comprising 3 junctions. - X3(Junction, Junction, Junction), - /// A relative path comprising 4 junctions. - X4(Junction, Junction, Junction, Junction), - /// A relative path comprising 5 junctions. - X5(Junction, Junction, Junction, Junction, Junction), - /// A relative path comprising 6 junctions. - X6(Junction, Junction, Junction, Junction, Junction, Junction), - /// A relative path comprising 7 junctions. - X7(Junction, Junction, Junction, Junction, Junction, Junction, Junction), - /// A relative path comprising 8 junctions. - X8(Junction, Junction, Junction, Junction, Junction, Junction, Junction, Junction), -} - -pub struct JunctionsIterator(Junctions); -impl Iterator for JunctionsIterator { - type Item = Junction; - fn next(&mut self) -> Option { - self.0.take_first() - } -} - -impl DoubleEndedIterator for JunctionsIterator { - fn next_back(&mut self) -> Option { - self.0.take_last() - } -} - -pub struct JunctionsRefIterator<'a> { - junctions: &'a Junctions, - next: usize, - back: usize, -} - -impl<'a> Iterator for JunctionsRefIterator<'a> { - type Item = &'a Junction; - fn next(&mut self) -> Option<&'a Junction> { - if self.next.saturating_add(self.back) >= self.junctions.len() { - return None - } - - let result = self.junctions.at(self.next); - self.next += 1; - result - } -} - -impl<'a> DoubleEndedIterator for JunctionsRefIterator<'a> { - fn next_back(&mut self) -> Option<&'a Junction> { - let next_back = self.back.saturating_add(1); - // checked_sub here, because if the result is less than 0, we end iteration - let index = self.junctions.len().checked_sub(next_back)?; - if self.next > index { - return None - } - self.back = next_back; - - self.junctions.at(index) - } -} - -impl<'a> IntoIterator for &'a Junctions { - type Item = &'a Junction; - type IntoIter = JunctionsRefIterator<'a>; - fn into_iter(self) -> Self::IntoIter { - JunctionsRefIterator { junctions: self, next: 0, back: 0 } - } -} - -impl IntoIterator for Junctions { - type Item = Junction; - type IntoIter = JunctionsIterator; - fn into_iter(self) -> Self::IntoIter { - JunctionsIterator(self) - } -} - -impl Junctions { - /// Convert `self` into a `MultiLocation` containing 0 parents. - /// - /// Similar to `Into::into`, except that this method can be used in a const evaluation context. - pub const fn into(self) -> MultiLocation { - MultiLocation { parents: 0, interior: self } - } - - /// Convert `self` into a `MultiLocation` containing `n` parents. - /// - /// Similar to `Self::into`, with the added ability to specify the number of parent junctions. - pub const fn into_exterior(self, n: u8) -> MultiLocation { - MultiLocation { parents: n, interior: self } - } - - /// Returns first junction, or `None` if the location is empty. - pub fn first(&self) -> Option<&Junction> { - match &self { - Junctions::Here => None, - Junctions::X1(ref a) => Some(a), - Junctions::X2(ref a, ..) => Some(a), - Junctions::X3(ref a, ..) => Some(a), - Junctions::X4(ref a, ..) => Some(a), - Junctions::X5(ref a, ..) => Some(a), - Junctions::X6(ref a, ..) => Some(a), - Junctions::X7(ref a, ..) => Some(a), - Junctions::X8(ref a, ..) => Some(a), - } - } - - /// Returns last junction, or `None` if the location is empty. - pub fn last(&self) -> Option<&Junction> { - match &self { - Junctions::Here => None, - Junctions::X1(ref a) => Some(a), - Junctions::X2(.., ref a) => Some(a), - Junctions::X3(.., ref a) => Some(a), - Junctions::X4(.., ref a) => Some(a), - Junctions::X5(.., ref a) => Some(a), - Junctions::X6(.., ref a) => Some(a), - Junctions::X7(.., ref a) => Some(a), - Junctions::X8(.., ref a) => Some(a), - } - } - - /// Splits off the first junction, returning the remaining suffix (first item in tuple) and the - /// first element (second item in tuple) or `None` if it was empty. - pub fn split_first(self) -> (Junctions, Option) { - match self { - Junctions::Here => (Junctions::Here, None), - Junctions::X1(a) => (Junctions::Here, Some(a)), - Junctions::X2(a, b) => (Junctions::X1(b), Some(a)), - Junctions::X3(a, b, c) => (Junctions::X2(b, c), Some(a)), - Junctions::X4(a, b, c, d) => (Junctions::X3(b, c, d), Some(a)), - Junctions::X5(a, b, c, d, e) => (Junctions::X4(b, c, d, e), Some(a)), - Junctions::X6(a, b, c, d, e, f) => (Junctions::X5(b, c, d, e, f), Some(a)), - Junctions::X7(a, b, c, d, e, f, g) => (Junctions::X6(b, c, d, e, f, g), Some(a)), - Junctions::X8(a, b, c, d, e, f, g, h) => (Junctions::X7(b, c, d, e, f, g, h), Some(a)), - } - } - - /// Splits off the last junction, returning the remaining prefix (first item in tuple) and the - /// last element (second item in tuple) or `None` if it was empty. - pub fn split_last(self) -> (Junctions, Option) { - match self { - Junctions::Here => (Junctions::Here, None), - Junctions::X1(a) => (Junctions::Here, Some(a)), - Junctions::X2(a, b) => (Junctions::X1(a), Some(b)), - Junctions::X3(a, b, c) => (Junctions::X2(a, b), Some(c)), - Junctions::X4(a, b, c, d) => (Junctions::X3(a, b, c), Some(d)), - Junctions::X5(a, b, c, d, e) => (Junctions::X4(a, b, c, d), Some(e)), - Junctions::X6(a, b, c, d, e, f) => (Junctions::X5(a, b, c, d, e), Some(f)), - Junctions::X7(a, b, c, d, e, f, g) => (Junctions::X6(a, b, c, d, e, f), Some(g)), - Junctions::X8(a, b, c, d, e, f, g, h) => (Junctions::X7(a, b, c, d, e, f, g), Some(h)), - } - } - - /// Removes the first element from `self`, returning it (or `None` if it was empty). - pub fn take_first(&mut self) -> Option { - let mut d = Junctions::Here; - mem::swap(&mut *self, &mut d); - let (tail, head) = d.split_first(); - *self = tail; - head - } - - /// Removes the last element from `self`, returning it (or `None` if it was empty). - pub fn take_last(&mut self) -> Option { - let mut d = Junctions::Here; - mem::swap(&mut *self, &mut d); - let (head, tail) = d.split_last(); - *self = head; - tail - } - - /// Mutates `self` to be appended with `new` or returns an `Err` with `new` if would overflow. - pub fn push(&mut self, new: Junction) -> result::Result<(), Junction> { - let mut dummy = Junctions::Here; - mem::swap(self, &mut dummy); - match dummy.pushed_with(new) { - Ok(s) => { - *self = s; - Ok(()) - }, - Err((s, j)) => { - *self = s; - Err(j) - }, - } - } - - /// Mutates `self` to be prepended with `new` or returns an `Err` with `new` if would overflow. - pub fn push_front(&mut self, new: Junction) -> result::Result<(), Junction> { - let mut dummy = Junctions::Here; - mem::swap(self, &mut dummy); - match dummy.pushed_front_with(new) { - Ok(s) => { - *self = s; - Ok(()) - }, - Err((s, j)) => { - *self = s; - Err(j) - }, - } - } - - /// Consumes `self` and returns a `Junctions` suffixed with `new`, or an `Err` with the - /// original value of `self` and `new` in case of overflow. - pub fn pushed_with(self, new: Junction) -> result::Result { - Ok(match self { - Junctions::Here => Junctions::X1(new), - Junctions::X1(a) => Junctions::X2(a, new), - Junctions::X2(a, b) => Junctions::X3(a, b, new), - Junctions::X3(a, b, c) => Junctions::X4(a, b, c, new), - Junctions::X4(a, b, c, d) => Junctions::X5(a, b, c, d, new), - Junctions::X5(a, b, c, d, e) => Junctions::X6(a, b, c, d, e, new), - Junctions::X6(a, b, c, d, e, f) => Junctions::X7(a, b, c, d, e, f, new), - Junctions::X7(a, b, c, d, e, f, g) => Junctions::X8(a, b, c, d, e, f, g, new), - s => Err((s, new))?, - }) - } - - /// Consumes `self` and returns a `Junctions` prefixed with `new`, or an `Err` with the - /// original value of `self` and `new` in case of overflow. - pub fn pushed_front_with(self, new: Junction) -> result::Result { - Ok(match self { - Junctions::Here => Junctions::X1(new), - Junctions::X1(a) => Junctions::X2(new, a), - Junctions::X2(a, b) => Junctions::X3(new, a, b), - Junctions::X3(a, b, c) => Junctions::X4(new, a, b, c), - Junctions::X4(a, b, c, d) => Junctions::X5(new, a, b, c, d), - Junctions::X5(a, b, c, d, e) => Junctions::X6(new, a, b, c, d, e), - Junctions::X6(a, b, c, d, e, f) => Junctions::X7(new, a, b, c, d, e, f), - Junctions::X7(a, b, c, d, e, f, g) => Junctions::X8(new, a, b, c, d, e, f, g), - s => Err((s, new))?, - }) - } - - /// Returns the number of junctions in `self`. - pub const fn len(&self) -> usize { - match &self { - Junctions::Here => 0, - Junctions::X1(..) => 1, - Junctions::X2(..) => 2, - Junctions::X3(..) => 3, - Junctions::X4(..) => 4, - Junctions::X5(..) => 5, - Junctions::X6(..) => 6, - Junctions::X7(..) => 7, - Junctions::X8(..) => 8, - } - } - - /// Returns the junction at index `i`, or `None` if the location doesn't contain that many - /// elements. - pub fn at(&self, i: usize) -> Option<&Junction> { - Some(match (i, self) { - (0, Junctions::X1(ref a)) => a, - (0, Junctions::X2(ref a, ..)) => a, - (0, Junctions::X3(ref a, ..)) => a, - (0, Junctions::X4(ref a, ..)) => a, - (0, Junctions::X5(ref a, ..)) => a, - (0, Junctions::X6(ref a, ..)) => a, - (0, Junctions::X7(ref a, ..)) => a, - (0, Junctions::X8(ref a, ..)) => a, - (1, Junctions::X2(_, ref a)) => a, - (1, Junctions::X3(_, ref a, ..)) => a, - (1, Junctions::X4(_, ref a, ..)) => a, - (1, Junctions::X5(_, ref a, ..)) => a, - (1, Junctions::X6(_, ref a, ..)) => a, - (1, Junctions::X7(_, ref a, ..)) => a, - (1, Junctions::X8(_, ref a, ..)) => a, - (2, Junctions::X3(_, _, ref a)) => a, - (2, Junctions::X4(_, _, ref a, ..)) => a, - (2, Junctions::X5(_, _, ref a, ..)) => a, - (2, Junctions::X6(_, _, ref a, ..)) => a, - (2, Junctions::X7(_, _, ref a, ..)) => a, - (2, Junctions::X8(_, _, ref a, ..)) => a, - (3, Junctions::X4(_, _, _, ref a)) => a, - (3, Junctions::X5(_, _, _, ref a, ..)) => a, - (3, Junctions::X6(_, _, _, ref a, ..)) => a, - (3, Junctions::X7(_, _, _, ref a, ..)) => a, - (3, Junctions::X8(_, _, _, ref a, ..)) => a, - (4, Junctions::X5(_, _, _, _, ref a)) => a, - (4, Junctions::X6(_, _, _, _, ref a, ..)) => a, - (4, Junctions::X7(_, _, _, _, ref a, ..)) => a, - (4, Junctions::X8(_, _, _, _, ref a, ..)) => a, - (5, Junctions::X6(_, _, _, _, _, ref a)) => a, - (5, Junctions::X7(_, _, _, _, _, ref a, ..)) => a, - (5, Junctions::X8(_, _, _, _, _, ref a, ..)) => a, - (6, Junctions::X7(_, _, _, _, _, _, ref a)) => a, - (6, Junctions::X8(_, _, _, _, _, _, ref a, ..)) => a, - (7, Junctions::X8(_, _, _, _, _, _, _, ref a)) => a, - _ => return None, - }) - } - - /// Returns a mutable reference to the junction at index `i`, or `None` if the location doesn't - /// contain that many elements. - pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { - Some(match (i, self) { - (0, Junctions::X1(ref mut a)) => a, - (0, Junctions::X2(ref mut a, ..)) => a, - (0, Junctions::X3(ref mut a, ..)) => a, - (0, Junctions::X4(ref mut a, ..)) => a, - (0, Junctions::X5(ref mut a, ..)) => a, - (0, Junctions::X6(ref mut a, ..)) => a, - (0, Junctions::X7(ref mut a, ..)) => a, - (0, Junctions::X8(ref mut a, ..)) => a, - (1, Junctions::X2(_, ref mut a)) => a, - (1, Junctions::X3(_, ref mut a, ..)) => a, - (1, Junctions::X4(_, ref mut a, ..)) => a, - (1, Junctions::X5(_, ref mut a, ..)) => a, - (1, Junctions::X6(_, ref mut a, ..)) => a, - (1, Junctions::X7(_, ref mut a, ..)) => a, - (1, Junctions::X8(_, ref mut a, ..)) => a, - (2, Junctions::X3(_, _, ref mut a)) => a, - (2, Junctions::X4(_, _, ref mut a, ..)) => a, - (2, Junctions::X5(_, _, ref mut a, ..)) => a, - (2, Junctions::X6(_, _, ref mut a, ..)) => a, - (2, Junctions::X7(_, _, ref mut a, ..)) => a, - (2, Junctions::X8(_, _, ref mut a, ..)) => a, - (3, Junctions::X4(_, _, _, ref mut a)) => a, - (3, Junctions::X5(_, _, _, ref mut a, ..)) => a, - (3, Junctions::X6(_, _, _, ref mut a, ..)) => a, - (3, Junctions::X7(_, _, _, ref mut a, ..)) => a, - (3, Junctions::X8(_, _, _, ref mut a, ..)) => a, - (4, Junctions::X5(_, _, _, _, ref mut a)) => a, - (4, Junctions::X6(_, _, _, _, ref mut a, ..)) => a, - (4, Junctions::X7(_, _, _, _, ref mut a, ..)) => a, - (4, Junctions::X8(_, _, _, _, ref mut a, ..)) => a, - (5, Junctions::X6(_, _, _, _, _, ref mut a)) => a, - (5, Junctions::X7(_, _, _, _, _, ref mut a, ..)) => a, - (5, Junctions::X8(_, _, _, _, _, ref mut a, ..)) => a, - (6, Junctions::X7(_, _, _, _, _, _, ref mut a)) => a, - (6, Junctions::X8(_, _, _, _, _, _, ref mut a, ..)) => a, - (7, Junctions::X8(_, _, _, _, _, _, _, ref mut a)) => a, - _ => return None, - }) - } - - /// Returns a reference iterator over the junctions. - pub fn iter(&self) -> JunctionsRefIterator { - JunctionsRefIterator { junctions: self, next: 0, back: 0 } - } - - /// Returns a reference iterator over the junctions in reverse. - #[deprecated(note = "Please use iter().rev()")] - pub fn iter_rev(&self) -> impl Iterator + '_ { - self.iter().rev() - } - - /// Consumes `self` and returns an iterator over the junctions in reverse. - #[deprecated(note = "Please use into_iter().rev()")] - pub fn into_iter_rev(self) -> impl Iterator { - self.into_iter().rev() - } - - /// Ensures that self begins with `prefix` and that it has a single `Junction` item following. - /// If so, returns a reference to this `Junction` item. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*}; - /// let mut m = X3(Parachain(2), PalletInstance(3), OnlyChild); - /// assert_eq!(m.match_and_split(&X2(Parachain(2), PalletInstance(3))), Some(&OnlyChild)); - /// assert_eq!(m.match_and_split(&X1(Parachain(2))), None); - /// ``` - pub fn match_and_split(&self, prefix: &Junctions) -> Option<&Junction> { - if prefix.len() + 1 != self.len() || !self.starts_with(prefix) { - return None - } - self.at(prefix.len()) - } - - /// Returns whether `self` begins with or is equal to `prefix`. - /// - /// # Example - /// ```rust - /// # use staging_xcm::v2::{Junctions::*, Junction::*}; - /// let mut j = X3(Parachain(2), PalletInstance(3), OnlyChild); - /// assert!(j.starts_with(&X2(Parachain(2), PalletInstance(3)))); - /// assert!(j.starts_with(&j)); - /// assert!(j.starts_with(&X1(Parachain(2)))); - /// assert!(!j.starts_with(&X1(Parachain(999)))); - /// assert!(!j.starts_with(&X4(Parachain(2), PalletInstance(3), OnlyChild, OnlyChild))); - /// ``` - pub fn starts_with(&self, prefix: &Junctions) -> bool { - if self.len() < prefix.len() { - return false - } - prefix.iter().zip(self.iter()).all(|(l, r)| l == r) - } -} - -impl TryFrom for Junctions { - type Error = (); - fn try_from(x: MultiLocation) -> result::Result { - if x.parents > 0 { - Err(()) - } else { - Ok(x.interior) - } - } -} - -#[cfg(test)] -mod tests { - use super::{Ancestor, AncestorThen, Junctions::*, MultiLocation, Parent, ParentThen}; - use crate::opaque::v2::{Junction::*, NetworkId::*}; - use codec::{Decode, Encode}; - - #[test] - fn inverted_works() { - let ancestry: MultiLocation = (Parachain(1000), PalletInstance(42)).into(); - let target = (Parent, PalletInstance(69)).into(); - let expected = (Parent, PalletInstance(42)).into(); - let inverted = ancestry.inverted(&target).unwrap(); - assert_eq!(inverted, expected); - - let ancestry: MultiLocation = (Parachain(1000), PalletInstance(42), GeneralIndex(1)).into(); - let target = (Parent, Parent, PalletInstance(69), GeneralIndex(2)).into(); - let expected = (Parent, Parent, PalletInstance(42), GeneralIndex(1)).into(); - let inverted = ancestry.inverted(&target).unwrap(); - assert_eq!(inverted, expected); - } - - #[test] - fn simplify_basic_works() { - let mut location: MultiLocation = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - let context = X2(Parachain(1000), PalletInstance(42)); - let expected = GeneralIndex(69).into(); - location.simplify(&context); - assert_eq!(location, expected); - - let mut location: MultiLocation = (Parent, PalletInstance(42), GeneralIndex(69)).into(); - let context = X1(PalletInstance(42)); - let expected = GeneralIndex(69).into(); - location.simplify(&context); - assert_eq!(location, expected); - - let mut location: MultiLocation = (Parent, PalletInstance(42), GeneralIndex(69)).into(); - let context = X2(Parachain(1000), PalletInstance(42)); - let expected = GeneralIndex(69).into(); - location.simplify(&context); - assert_eq!(location, expected); - - let mut location: MultiLocation = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - let context = X3(OnlyChild, Parachain(1000), PalletInstance(42)); - let expected = GeneralIndex(69).into(); - location.simplify(&context); - assert_eq!(location, expected); - } - - #[test] - fn simplify_incompatible_location_fails() { - let mut location: MultiLocation = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - let context = X3(Parachain(1000), PalletInstance(42), GeneralIndex(42)); - let expected = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - location.simplify(&context); - assert_eq!(location, expected); - - let mut location: MultiLocation = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - let context = X1(Parachain(1000)); - let expected = - (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); - location.simplify(&context); - assert_eq!(location, expected); - } - - #[test] - fn reanchor_works() { - let mut id: MultiLocation = (Parent, Parachain(1000), GeneralIndex(42)).into(); - let ancestry = Parachain(2000).into(); - let target = (Parent, Parachain(1000)).into(); - let expected = GeneralIndex(42).into(); - id.reanchor(&target, &ancestry).unwrap(); - assert_eq!(id, expected); - } - - #[test] - fn encode_and_decode_works() { - let m = MultiLocation { - parents: 1, - interior: X2(Parachain(42), AccountIndex64 { network: Any, index: 23 }), - }; - let encoded = m.encode(); - assert_eq!(encoded, [1, 2, 0, 168, 2, 0, 92].to_vec()); - let decoded = MultiLocation::decode(&mut &encoded[..]); - assert_eq!(decoded, Ok(m)); - } - - #[test] - fn match_and_split_works() { - let m = MultiLocation { - parents: 1, - interior: X2(Parachain(42), AccountIndex64 { network: Any, index: 23 }), - }; - assert_eq!(m.match_and_split(&MultiLocation { parents: 1, interior: Here }), None); - assert_eq!( - m.match_and_split(&MultiLocation { parents: 1, interior: X1(Parachain(42)) }), - Some(&AccountIndex64 { network: Any, index: 23 }) - ); - assert_eq!(m.match_and_split(&m), None); - } - - #[test] - fn starts_with_works() { - let full: MultiLocation = - (Parent, Parachain(1000), AccountId32 { network: Any, id: [0; 32] }).into(); - let identity: MultiLocation = full.clone(); - let prefix: MultiLocation = (Parent, Parachain(1000)).into(); - let wrong_parachain: MultiLocation = (Parent, Parachain(1001)).into(); - let wrong_account: MultiLocation = - (Parent, Parachain(1000), AccountId32 { network: Any, id: [1; 32] }).into(); - let no_parents: MultiLocation = (Parachain(1000)).into(); - let too_many_parents: MultiLocation = (Parent, Parent, Parachain(1000)).into(); - - assert!(full.starts_with(&identity)); - assert!(full.starts_with(&prefix)); - assert!(!full.starts_with(&wrong_parachain)); - assert!(!full.starts_with(&wrong_account)); - assert!(!full.starts_with(&no_parents)); - assert!(!full.starts_with(&too_many_parents)); - } - - #[test] - fn append_with_works() { - let acc = AccountIndex64 { network: Any, index: 23 }; - let mut m = MultiLocation { parents: 1, interior: X1(Parachain(42)) }; - assert_eq!(m.append_with(X2(PalletInstance(3), acc.clone())), Ok(())); - assert_eq!( - m, - MultiLocation { - parents: 1, - interior: X3(Parachain(42), PalletInstance(3), acc.clone()) - } - ); - - // cannot append to create overly long multilocation - let acc = AccountIndex64 { network: Any, index: 23 }; - let m = MultiLocation { - parents: 254, - interior: X5(Parachain(42), OnlyChild, OnlyChild, OnlyChild, OnlyChild), - }; - let suffix = X4(PalletInstance(3), acc.clone(), OnlyChild, OnlyChild); - assert_eq!(m.clone().append_with(suffix.clone()), Err(suffix)); - } - - #[test] - fn prepend_with_works() { - let mut m = MultiLocation { - parents: 1, - interior: X2(Parachain(42), AccountIndex64 { network: Any, index: 23 }), - }; - assert_eq!(m.prepend_with(MultiLocation { parents: 1, interior: X1(OnlyChild) }), Ok(())); - assert_eq!( - m, - MultiLocation { - parents: 1, - interior: X2(Parachain(42), AccountIndex64 { network: Any, index: 23 }) - } - ); - - // cannot prepend to create overly long multilocation - let mut m = MultiLocation { parents: 254, interior: X1(Parachain(42)) }; - let prefix = MultiLocation { parents: 2, interior: Here }; - assert_eq!(m.prepend_with(prefix.clone()), Err(prefix)); - - let prefix = MultiLocation { parents: 1, interior: Here }; - assert_eq!(m.prepend_with(prefix), Ok(())); - assert_eq!(m, MultiLocation { parents: 255, interior: X1(Parachain(42)) }); - } - - #[test] - fn double_ended_ref_iteration_works() { - let m = X3(Parachain(1000), Parachain(3), PalletInstance(5)); - let mut iter = m.iter(); - - let first = iter.next().unwrap(); - assert_eq!(first, &Parachain(1000)); - let third = iter.next_back().unwrap(); - assert_eq!(third, &PalletInstance(5)); - let second = iter.next_back().unwrap(); - assert_eq!(iter.next(), None); - assert_eq!(iter.next_back(), None); - assert_eq!(second, &Parachain(3)); - - let res = Here - .pushed_with(first.clone()) - .unwrap() - .pushed_with(second.clone()) - .unwrap() - .pushed_with(third.clone()) - .unwrap(); - assert_eq!(m, res); - - // make sure there's no funny business with the 0 indexing - let m = Here; - let mut iter = m.iter(); - - assert_eq!(iter.next(), None); - assert_eq!(iter.next_back(), None); - } - - #[test] - fn conversion_from_other_types_works() { - fn takes_multilocation>(_arg: Arg) {} - - takes_multilocation(Parent); - takes_multilocation(Here); - takes_multilocation(X1(Parachain(42))); - takes_multilocation((255, PalletInstance(8))); - takes_multilocation((Ancestor(5), Parachain(1), PalletInstance(3))); - takes_multilocation((Ancestor(2), Here)); - takes_multilocation(AncestorThen( - 3, - X2(Parachain(43), AccountIndex64 { network: Any, index: 155 }), - )); - takes_multilocation((Parent, AccountId32 { network: Any, id: [0; 32] })); - takes_multilocation((Parent, Here)); - takes_multilocation(ParentThen(X1(Parachain(75)))); - takes_multilocation([Parachain(100), PalletInstance(3)]); - } -} diff --git a/polkadot/xcm/src/v2/traits.rs b/polkadot/xcm/src/v2/traits.rs deleted file mode 100644 index 815495b81271..000000000000 --- a/polkadot/xcm/src/v2/traits.rs +++ /dev/null @@ -1,363 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Cross-Consensus Message format data structures. - -use crate::v3::Error as NewError; -use codec::{Decode, Encode}; -use core::result; -use scale_info::TypeInfo; - -use super::*; - -// A simple trait to get the weight of some object. -pub trait GetWeight { - fn weight(&self) -> sp_weights::Weight; -} - -#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Error { - // Errors that happen due to instructions being executed. These alone are defined in the - // XCM specification. - /// An arithmetic overflow happened. - #[codec(index = 0)] - Overflow, - /// The instruction is intentionally unsupported. - #[codec(index = 1)] - Unimplemented, - /// Origin Register does not contain a value value for a reserve transfer notification. - #[codec(index = 2)] - UntrustedReserveLocation, - /// Origin Register does not contain a value value for a teleport notification. - #[codec(index = 3)] - UntrustedTeleportLocation, - /// `MultiLocation` value too large to descend further. - #[codec(index = 4)] - MultiLocationFull, - /// `MultiLocation` value ascend more parents than known ancestors of local location. - #[codec(index = 5)] - MultiLocationNotInvertible, - /// The Origin Register does not contain a valid value for instruction. - #[codec(index = 6)] - BadOrigin, - /// The location parameter is not a valid value for the instruction. - #[codec(index = 7)] - InvalidLocation, - /// The given asset is not handled. - #[codec(index = 8)] - AssetNotFound, - /// An asset transaction (like withdraw or deposit) failed (typically due to type conversions). - #[codec(index = 9)] - FailedToTransactAsset(#[codec(skip)] &'static str), - /// An asset cannot be withdrawn, potentially due to lack of ownership, availability or rights. - #[codec(index = 10)] - NotWithdrawable, - /// An asset cannot be deposited under the ownership of a particular location. - #[codec(index = 11)] - LocationCannotHold, - /// Attempt to send a message greater than the maximum supported by the transport protocol. - #[codec(index = 12)] - ExceedsMaxMessageSize, - /// The given message cannot be translated into a format supported by the destination. - #[codec(index = 13)] - DestinationUnsupported, - /// Destination is routable, but there is some issue with the transport mechanism. - #[codec(index = 14)] - Transport(#[codec(skip)] &'static str), - /// Destination is known to be unroutable. - #[codec(index = 15)] - Unroutable, - /// Used by `ClaimAsset` when the given claim could not be recognized/found. - #[codec(index = 16)] - UnknownClaim, - /// Used by `Transact` when the functor cannot be decoded. - #[codec(index = 17)] - FailedToDecode, - /// Used by `Transact` to indicate that the given weight limit could be breached by the - /// functor. - #[codec(index = 18)] - MaxWeightInvalid, - /// Used by `BuyExecution` when the Holding Register does not contain payable fees. - #[codec(index = 19)] - NotHoldingFees, - /// Used by `BuyExecution` when the fees declared to purchase weight are insufficient. - #[codec(index = 20)] - TooExpensive, - /// Used by the `Trap` instruction to force an error intentionally. Its code is included. - #[codec(index = 21)] - Trap(u64), - - // Errors that happen prior to instructions being executed. These fall outside of the XCM - // spec. - /// XCM version not able to be handled. - UnhandledXcmVersion, - /// Execution of the XCM would potentially result in a greater weight used than weight limit. - WeightLimitReached(Weight), - /// The XCM did not pass the barrier condition for execution. - /// - /// The barrier condition differs on different chains and in different circumstances, but - /// generally it means that the conditions surrounding the message were not such that the chain - /// considers the message worth spending time executing. Since most chains lift the barrier to - /// execution on appropriate payment, presentation of an NFT voucher, or based on the message - /// origin, it means that none of those were the case. - Barrier, - /// The weight of an XCM message is not computable ahead of execution. - WeightNotComputable, -} - -impl TryFrom for Error { - type Error = (); - fn try_from(new_error: NewError) -> result::Result { - use NewError::*; - Ok(match new_error { - Overflow => Self::Overflow, - Unimplemented => Self::Unimplemented, - UntrustedReserveLocation => Self::UntrustedReserveLocation, - UntrustedTeleportLocation => Self::UntrustedTeleportLocation, - LocationFull => Self::MultiLocationFull, - LocationNotInvertible => Self::MultiLocationNotInvertible, - BadOrigin => Self::BadOrigin, - InvalidLocation => Self::InvalidLocation, - AssetNotFound => Self::AssetNotFound, - FailedToTransactAsset(s) => Self::FailedToTransactAsset(s), - NotWithdrawable => Self::NotWithdrawable, - LocationCannotHold => Self::LocationCannotHold, - ExceedsMaxMessageSize => Self::ExceedsMaxMessageSize, - DestinationUnsupported => Self::DestinationUnsupported, - Transport(s) => Self::Transport(s), - Unroutable => Self::Unroutable, - UnknownClaim => Self::UnknownClaim, - FailedToDecode => Self::FailedToDecode, - MaxWeightInvalid => Self::MaxWeightInvalid, - NotHoldingFees => Self::NotHoldingFees, - TooExpensive => Self::TooExpensive, - Trap(i) => Self::Trap(i), - _ => return Err(()), - }) - } -} - -impl From for Error { - fn from(e: SendError) -> Self { - match e { - SendError::NotApplicable(..) | SendError::Unroutable => Error::Unroutable, - SendError::Transport(s) => Error::Transport(s), - SendError::DestinationUnsupported => Error::DestinationUnsupported, - SendError::ExceedsMaxMessageSize => Error::ExceedsMaxMessageSize, - } - } -} - -pub type Result = result::Result<(), Error>; - -/// Outcome of an XCM execution. -#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum Outcome { - /// Execution completed successfully; given weight was used. - Complete(Weight), - /// Execution started, but did not complete successfully due to the given error; given weight - /// was used. - Incomplete(Weight, Error), - /// Execution did not start due to the given error. - Error(Error), -} - -impl Outcome { - pub fn ensure_complete(self) -> Result { - match self { - Outcome::Complete(_) => Ok(()), - Outcome::Incomplete(_, e) => Err(e), - Outcome::Error(e) => Err(e), - } - } - pub fn ensure_execution(self) -> result::Result { - match self { - Outcome::Complete(w) => Ok(w), - Outcome::Incomplete(w, _) => Ok(w), - Outcome::Error(e) => Err(e), - } - } - /// How much weight was used by the XCM execution attempt. - pub fn weight_used(&self) -> Weight { - match self { - Outcome::Complete(w) => *w, - Outcome::Incomplete(w, _) => *w, - Outcome::Error(_) => 0, - } - } -} - -/// Type of XCM message executor. -pub trait ExecuteXcm { - /// Execute some XCM `message` from `origin` using no more than `weight_limit` weight. The - /// weight limit is a basic hard-limit and the implementation may place further restrictions or - /// requirements on weight and other aspects. - fn execute_xcm( - origin: impl Into, - message: Xcm, - weight_limit: Weight, - ) -> Outcome { - let origin = origin.into(); - log::debug!( - target: "xcm::execute_xcm", - "origin: {:?}, message: {:?}, weight_limit: {:?}", - origin, - message, - weight_limit, - ); - Self::execute_xcm_in_credit(origin, message, weight_limit, 0) - } - - /// Execute some XCM `message` from `origin` using no more than `weight_limit` weight. - /// - /// Some amount of `weight_credit` may be provided which, depending on the implementation, may - /// allow execution without associated payment. - fn execute_xcm_in_credit( - origin: impl Into, - message: Xcm, - weight_limit: Weight, - weight_credit: Weight, - ) -> Outcome; -} - -impl ExecuteXcm for () { - fn execute_xcm_in_credit( - _origin: impl Into, - _message: Xcm, - _weight_limit: Weight, - _weight_credit: Weight, - ) -> Outcome { - Outcome::Error(Error::Unimplemented) - } -} - -/// Error result value when attempting to send an XCM message. -#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, scale_info::TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -pub enum SendError { - /// The message and destination combination was not recognized as being reachable. - /// - /// This is not considered fatal: if there are alternative transport routes available, then - /// they may be attempted. For this reason, the destination and message are contained. - NotApplicable(MultiLocation, Xcm<()>), - /// Destination is routable, but there is some issue with the transport mechanism. This is - /// considered fatal. - /// A human-readable explanation of the specific issue is provided. - Transport(#[codec(skip)] &'static str), - /// Destination is known to be unroutable. This is considered fatal. - Unroutable, - /// The given message cannot be translated into a format that the destination can be expected - /// to interpret. - DestinationUnsupported, - /// Message could not be sent due to its size exceeding the maximum allowed by the transport - /// layer. - ExceedsMaxMessageSize, -} - -/// Result value when attempting to send an XCM message. -pub type SendResult = result::Result<(), SendError>; - -/// Utility for sending an XCM message. -/// -/// These can be amalgamated in tuples to form sophisticated routing systems. In tuple format, each -/// router might return `NotApplicable` to pass the execution to the next sender item. Note that -/// each `NotApplicable` might alter the destination and the XCM message for to the next router. -/// -/// -/// # Example -/// ```rust -/// # use staging_xcm::v2::prelude::*; -/// # use codec::Encode; -/// -/// /// A sender that only passes the message through and does nothing. -/// struct Sender1; -/// impl SendXcm for Sender1 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { -/// return Err(SendError::NotApplicable(destination.into(), message)) -/// } -/// } -/// -/// /// A sender that accepts a message that has two junctions, otherwise stops the routing. -/// struct Sender2; -/// impl SendXcm for Sender2 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { -/// let destination = destination.into(); -/// if destination.parents == 0 && destination.interior.len() == 2 { -/// Ok(()) -/// } else { -/// Err(SendError::Unroutable) -/// } -/// } -/// } -/// -/// /// A sender that accepts a message from a parent, passing through otherwise. -/// struct Sender3; -/// impl SendXcm for Sender3 { -/// fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { -/// let destination = destination.into(); -/// match destination { -/// MultiLocation { parents: 1, interior: Here } => Ok(()), -/// _ => Err(SendError::NotApplicable(destination, message)), -/// } -/// } -/// } -/// -/// // A call to send via XCM. We don't really care about this. -/// # fn main() { -/// let call: Vec = ().encode(); -/// let message = Xcm(vec![Instruction::Transact { -/// origin_type: OriginKind::Superuser, -/// require_weight_at_most: 0, -/// call: call.into(), -/// }]); -/// -/// assert!( -/// // Sender2 will block this. -/// <(Sender1, Sender2, Sender3) as SendXcm>::send_xcm(Parent, message.clone()) -/// .is_err() -/// ); -/// -/// assert!( -/// // Sender3 will catch this. -/// <(Sender1, Sender3) as SendXcm>::send_xcm(Parent, message.clone()) -/// .is_ok() -/// ); -/// # } -/// ``` -pub trait SendXcm { - /// Send an XCM `message` to a given `destination`. - /// - /// If it is not a destination which can be reached with this type but possibly could by others, - /// then it *MUST* return `NotApplicable`. Any other error will cause the tuple implementation - /// to exit early without trying other type fields. - fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult; -} - -#[impl_trait_for_tuples::impl_for_tuples(30)] -impl SendXcm for Tuple { - fn send_xcm(destination: impl Into, message: Xcm<()>) -> SendResult { - for_tuples!( #( - // we shadow `destination` and `message` in each expansion for the next one. - let (destination, message) = match Tuple::send_xcm(destination, message) { - Err(SendError::NotApplicable(d, m)) => (d, m), - o @ _ => return o, - }; - )* ); - Err(SendError::NotApplicable(destination.into(), message)) - } -} diff --git a/polkadot/xcm/src/v3/junction.rs b/polkadot/xcm/src/v3/junction.rs index 24348bf2e672..24e9c16bf699 100644 --- a/polkadot/xcm/src/v3/junction.rs +++ b/polkadot/xcm/src/v3/junction.rs @@ -18,10 +18,6 @@ use super::{Junctions, MultiLocation}; use crate::{ - v2::{ - BodyId as OldBodyId, BodyPart as OldBodyPart, Junction as OldJunction, - NetworkId as OldNetworkId, - }, v4::{Junction as NewJunction, NetworkId as NewNetworkId}, VersionedLocation, }; @@ -80,30 +76,6 @@ pub enum NetworkId { PolkadotBulletin, } -impl From for Option { - fn from(old: OldNetworkId) -> Option { - use OldNetworkId::*; - match old { - Any => None, - Named(_) => None, - Polkadot => Some(NetworkId::Polkadot), - Kusama => Some(NetworkId::Kusama), - } - } -} - -impl TryFrom for NetworkId { - type Error = (); - fn try_from(old: OldNetworkId) -> Result { - use OldNetworkId::*; - match old { - Any | Named(_) => Err(()), - Polkadot => Ok(NetworkId::Polkadot), - Kusama => Ok(NetworkId::Kusama), - } - } -} - impl From for Option { fn from(new: NewNetworkId) -> Self { Some(NetworkId::from(new)) @@ -175,32 +147,6 @@ pub enum BodyId { Treasury, } -impl TryFrom for BodyId { - type Error = (); - fn try_from(value: OldBodyId) -> Result { - use OldBodyId::*; - Ok(match value { - Unit => Self::Unit, - Named(n) => - if n.len() == 4 { - let mut r = [0u8; 4]; - r.copy_from_slice(&n[..]); - Self::Moniker(r) - } else { - return Err(()) - }, - Index(n) => Self::Index(n), - Executive => Self::Executive, - Technical => Self::Technical, - Legislative => Self::Legislative, - Judicial => Self::Judicial, - Defense => Self::Defense, - Administration => Self::Administration, - Treasury => Self::Treasury, - }) - } -} - /// A part of a pluralistic body. #[derive( Copy, @@ -262,20 +208,6 @@ impl BodyPart { } } -impl TryFrom for BodyPart { - type Error = (); - fn try_from(value: OldBodyPart) -> Result { - use OldBodyPart::*; - Ok(match value { - Voice => Self::Voice, - Members { count } => Self::Members { count }, - Fraction { nom, denom } => Self::Fraction { nom, denom }, - AtLeastProportion { nom, denom } => Self::AtLeastProportion { nom, denom }, - MoreThanProportion { nom, denom } => Self::MoreThanProportion { nom, denom }, - }) - } -} - /// A single item in a path to describe the relative location of a consensus system. /// /// Each item assumes a pre-existing location as its context and is defined in terms of it. @@ -409,36 +341,6 @@ impl From for Junction { } } -impl TryFrom for Junction { - type Error = (); - fn try_from(value: OldJunction) -> Result { - use OldJunction::*; - Ok(match value { - Parachain(id) => Self::Parachain(id), - AccountId32 { network, id } => Self::AccountId32 { network: network.into(), id }, - AccountIndex64 { network, index } => - Self::AccountIndex64 { network: network.into(), index }, - AccountKey20 { network, key } => Self::AccountKey20 { network: network.into(), key }, - PalletInstance(index) => Self::PalletInstance(index), - GeneralIndex(id) => Self::GeneralIndex(id), - GeneralKey(key) => match key.len() { - len @ 0..=32 => Self::GeneralKey { - length: len as u8, - data: { - let mut data = [0u8; 32]; - data[..len].copy_from_slice(&key[..]); - data - }, - }, - _ => return Err(()), - }, - OnlyChild => Self::OnlyChild, - Plurality { id, part } => - Self::Plurality { id: id.try_into()?, part: part.try_into()? }, - }) - } -} - impl TryFrom for Junction { type Error = (); @@ -496,30 +398,3 @@ impl Junction { } } } - -#[cfg(test)] -mod tests { - use super::*; - use alloc::vec; - - #[test] - fn junction_round_trip_works() { - let j = Junction::GeneralKey { length: 32, data: [1u8; 32] }; - let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); - assert_eq!(j, k); - - let j = OldJunction::GeneralKey(vec![1u8; 32].try_into().unwrap()); - let k = OldJunction::try_from(Junction::try_from(j.clone()).unwrap()).unwrap(); - assert_eq!(j, k); - - let j = Junction::from(BoundedVec::try_from(vec![1u8, 2, 3, 4]).unwrap()); - let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); - assert_eq!(j, k); - let s: BoundedSlice<_, _> = (&k).try_into().unwrap(); - assert_eq!(s, &[1u8, 2, 3, 4][..]); - - let j = OldJunction::GeneralKey(vec![1u8, 2, 3, 4].try_into().unwrap()); - let k = OldJunction::try_from(Junction::try_from(j.clone()).unwrap()).unwrap(); - assert_eq!(j, k); - } -} diff --git a/polkadot/xcm/src/v3/mod.rs b/polkadot/xcm/src/v3/mod.rs index ff64c98e15b3..b60209a440c6 100644 --- a/polkadot/xcm/src/v3/mod.rs +++ b/polkadot/xcm/src/v3/mod.rs @@ -16,11 +16,6 @@ //! Version 3 of the Cross-Consensus Message format data structures. -#[allow(deprecated)] -use super::v2::{ - Instruction as OldInstruction, OriginKind as OldOriginKind, Response as OldResponse, - WeightLimit as OldWeightLimit, Xcm as OldXcm, -}; use super::v4::{ Instruction as NewInstruction, PalletInfo as NewPalletInfo, QueryResponseInfo as NewQueryResponseInfo, Response as NewResponse, Xcm as NewXcm, @@ -56,43 +51,6 @@ pub use traits::{ SendError, SendResult, SendXcm, Weight, XcmHash, }; -/// Basically just the XCM (more general) version of `ParachainDispatchOrigin`. -#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] -#[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] -pub enum OriginKind { - /// Origin should just be the native dispatch origin representation for the sender in the - /// local runtime framework. For Cumulus/Frame chains this is the `Parachain` or `Relay` origin - /// if coming from a chain, though there may be others if the `MultiLocation` XCM origin has a - /// primary/native dispatch origin form. - Native, - - /// Origin should just be the standard account-based origin with the sovereign account of - /// the sender. For Cumulus/Frame chains, this is the `Signed` origin. - SovereignAccount, - - /// Origin should be the super-user. For Cumulus/Frame chains, this is the `Root` origin. - /// This will not usually be an available option. - Superuser, - - /// Origin should be interpreted as an XCM native origin and the `MultiLocation` should be - /// encoded directly in the dispatch origin unchanged. For Cumulus/Frame chains, this will be - /// the `pallet_xcm::Origin::Xcm` type. - Xcm, -} - -impl From for OriginKind { - fn from(old: OldOriginKind) -> Self { - use OldOriginKind::*; - match old { - Native => Self::Native, - SovereignAccount => Self::SovereignAccount, - Superuser => Self::Superuser, - Xcm => Self::Xcm, - } - } -} - /// This module's XCM version. pub const VERSION: super::Version = 3; @@ -456,14 +414,29 @@ impl From for Option { } } -impl From for WeightLimit { - fn from(x: OldWeightLimit) -> Self { - use OldWeightLimit::*; - match x { - Limited(w) => Self::Limited(Weight::from_parts(w, DEFAULT_PROOF_SIZE)), - Unlimited => Self::Unlimited, - } - } +/// Basically just the XCM (more general) version of `ParachainDispatchOrigin`. +#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] +#[scale_info(replace_segment("staging_xcm", "xcm"))] +#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] +pub enum OriginKind { + /// Origin should just be the native dispatch origin representation for the sender in the + /// local runtime framework. For Cumulus/Frame chains this is the `Parachain` or `Relay` origin + /// if coming from a chain, though there may be others if the `MultiLocation` XCM origin has a + /// primary/native dispatch origin form. + Native, + + /// Origin should just be the standard account-based origin with the sovereign account of + /// the sender. For Cumulus/Frame chains, this is the `Signed` origin. + SovereignAccount, + + /// Origin should be the super-user. For Cumulus/Frame chains, this is the `Root` origin. + /// This will not usually be an available option. + Superuser, + + /// Origin should be interpreted as an XCM native origin and the `MultiLocation` should be + /// encoded directly in the dispatch origin unchanged. For Cumulus/Frame chains, this will be + /// the `pallet_xcm::Origin::Xcm` type. + Xcm, } /// Contextual data pertaining to a specific list of XCM instructions. @@ -819,6 +792,7 @@ pub enum Instruction { /// Kind: *Command* /// /// Errors: + #[builder(pays_fees)] BuyExecution { fees: MultiAsset, weight_limit: WeightLimit }, /// Refund any surplus weight previously bought with `BuyExecution`. @@ -1327,31 +1301,6 @@ pub mod opaque { pub type Instruction = super::Instruction<()>; } -// Convert from a v2 response to a v3 response. -impl TryFrom for Response { - type Error = (); - fn try_from(old_response: OldResponse) -> result::Result { - match old_response { - OldResponse::Assets(assets) => Ok(Self::Assets(assets.try_into()?)), - OldResponse::Version(version) => Ok(Self::Version(version)), - OldResponse::ExecutionResult(error) => Ok(Self::ExecutionResult(match error { - Some((i, e)) => Some((i, e.try_into()?)), - None => None, - })), - OldResponse::Null => Ok(Self::Null), - } - } -} - -// Convert from a v2 XCM to a v3 XCM. -#[allow(deprecated)] -impl TryFrom> for Xcm { - type Error = (); - fn try_from(old_xcm: OldXcm) -> result::Result { - Ok(Xcm(old_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) - } -} - // Convert from a v4 XCM to a v3 XCM. impl TryFrom> for Xcm { type Error = (); @@ -1501,109 +1450,6 @@ impl TryFrom> for Instruction { } } -/// Default value for the proof size weight component when converting from V2. Set at 64 KB. -/// NOTE: Make sure this is removed after we properly account for PoV weights. -const DEFAULT_PROOF_SIZE: u64 = 64 * 1024; - -// Convert from a v2 instruction to a v3 instruction. -impl TryFrom> for Instruction { - type Error = (); - fn try_from(old_instruction: OldInstruction) -> result::Result { - use OldInstruction::*; - Ok(match old_instruction { - WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), - ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), - ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), - QueryResponse { query_id, response, max_weight } => Self::QueryResponse { - query_id, - response: response.try_into()?, - max_weight: Weight::from_parts(max_weight, DEFAULT_PROOF_SIZE), - querier: None, - }, - TransferAsset { assets, beneficiary } => Self::TransferAsset { - assets: assets.try_into()?, - beneficiary: beneficiary.try_into()?, - }, - TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { - assets: assets.try_into()?, - dest: dest.try_into()?, - xcm: xcm.try_into()?, - }, - HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => - Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, - HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, - HrmpChannelClosing { initiator, sender, recipient } => - Self::HrmpChannelClosing { initiator, sender, recipient }, - Transact { origin_type, require_weight_at_most, call } => Self::Transact { - origin_kind: origin_type.into(), - require_weight_at_most: Weight::from_parts( - require_weight_at_most, - DEFAULT_PROOF_SIZE, - ), - call: call.into(), - }, - ReportError { query_id, dest, max_response_weight } => { - let response_info = QueryResponseInfo { - destination: dest.try_into()?, - query_id, - max_weight: Weight::from_parts(max_response_weight, DEFAULT_PROOF_SIZE), - }; - Self::ReportError(response_info) - }, - DepositAsset { assets, max_assets, beneficiary } => Self::DepositAsset { - assets: (assets, max_assets).try_into()?, - beneficiary: beneficiary.try_into()?, - }, - DepositReserveAsset { assets, max_assets, dest, xcm } => { - let assets = (assets, max_assets).try_into()?; - Self::DepositReserveAsset { assets, dest: dest.try_into()?, xcm: xcm.try_into()? } - }, - ExchangeAsset { give, receive } => { - let give = give.try_into()?; - let want = receive.try_into()?; - Self::ExchangeAsset { give, want, maximal: true } - }, - InitiateReserveWithdraw { assets, reserve, xcm } => Self::InitiateReserveWithdraw { - assets: assets.try_into()?, - reserve: reserve.try_into()?, - xcm: xcm.try_into()?, - }, - InitiateTeleport { assets, dest, xcm } => Self::InitiateTeleport { - assets: assets.try_into()?, - dest: dest.try_into()?, - xcm: xcm.try_into()?, - }, - QueryHolding { query_id, dest, assets, max_response_weight } => { - let response_info = QueryResponseInfo { - destination: dest.try_into()?, - query_id, - max_weight: Weight::from_parts(max_response_weight, DEFAULT_PROOF_SIZE), - }; - Self::ReportHolding { response_info, assets: assets.try_into()? } - }, - BuyExecution { fees, weight_limit } => - Self::BuyExecution { fees: fees.try_into()?, weight_limit: weight_limit.into() }, - ClearOrigin => Self::ClearOrigin, - DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), - RefundSurplus => Self::RefundSurplus, - SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), - SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), - ClearError => Self::ClearError, - ClaimAsset { assets, ticket } => { - let assets = assets.try_into()?; - let ticket = ticket.try_into()?; - Self::ClaimAsset { assets, ticket } - }, - Trap(code) => Self::Trap(code), - SubscribeVersion { query_id, max_response_weight } => Self::SubscribeVersion { - query_id, - max_response_weight: Weight::from_parts(max_response_weight, DEFAULT_PROOF_SIZE), - }, - UnsubscribeVersion => Self::UnsubscribeVersion, - }) - } -} - #[cfg(test)] mod tests { use super::{prelude::*, *}; diff --git a/polkadot/xcm/src/v3/multiasset.rs b/polkadot/xcm/src/v3/multiasset.rs index 56b46b1d921e..e8bd3e167f61 100644 --- a/polkadot/xcm/src/v3/multiasset.rs +++ b/polkadot/xcm/src/v3/multiasset.rs @@ -27,18 +27,10 @@ //! filtering an XCM holding account. use super::{InteriorMultiLocation, MultiLocation}; -use crate::{ - v2::{ - AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, - MultiAsset as OldMultiAsset, MultiAssetFilter as OldMultiAssetFilter, - MultiAssets as OldMultiAssets, WildFungibility as OldWildFungibility, - WildMultiAsset as OldWildMultiAsset, - }, - v4::{ - Asset as NewMultiAsset, AssetFilter as NewMultiAssetFilter, AssetId as NewAssetId, - AssetInstance as NewAssetInstance, Assets as NewMultiAssets, Fungibility as NewFungibility, - WildAsset as NewWildMultiAsset, WildFungibility as NewWildFungibility, - }, +use crate::v4::{ + Asset as NewMultiAsset, AssetFilter as NewMultiAssetFilter, AssetId as NewAssetId, + AssetInstance as NewAssetInstance, Assets as NewMultiAssets, Fungibility as NewFungibility, + WildAsset as NewWildMultiAsset, WildFungibility as NewWildFungibility, }; use alloc::{vec, vec::Vec}; use bounded_collections::{BoundedVec, ConstU32}; @@ -85,22 +77,6 @@ pub enum AssetInstance { Array32([u8; 32]), } -impl TryFrom for AssetInstance { - type Error = (); - fn try_from(value: OldAssetInstance) -> Result { - use OldAssetInstance::*; - Ok(match value { - Undefined => Self::Undefined, - Index(n) => Self::Index(n), - Array4(n) => Self::Array4(n), - Array8(n) => Self::Array8(n), - Array16(n) => Self::Array16(n), - Array32(n) => Self::Array32(n), - Blob(_) => return Err(()), - }) - } -} - impl TryFrom for AssetInstance { type Error = (); fn try_from(value: NewAssetInstance) -> Result { @@ -340,17 +316,6 @@ impl> From for Fungibility { } } -impl TryFrom for Fungibility { - type Error = (); - fn try_from(value: OldFungibility) -> Result { - use OldFungibility::*; - Ok(match value { - Fungible(n) => Self::Fungible(n), - NonFungible(i) => Self::NonFungible(i.try_into()?), - }) - } -} - impl TryFrom for Fungibility { type Error = (); fn try_from(value: NewFungibility) -> Result { @@ -387,17 +352,6 @@ pub enum WildFungibility { NonFungible, } -impl TryFrom for WildFungibility { - type Error = (); - fn try_from(value: OldWildFungibility) -> Result { - use OldWildFungibility::*; - Ok(match value { - Fungible => Self::Fungible, - NonFungible => Self::NonFungible, - }) - } -} - impl TryFrom for WildFungibility { type Error = (); fn try_from(value: NewWildFungibility) -> Result { @@ -447,22 +401,6 @@ impl From<[u8; 32]> for AssetId { } } -impl TryFrom for AssetId { - type Error = (); - fn try_from(old: OldAssetId) -> Result { - use OldAssetId::*; - Ok(match old { - Concrete(l) => Self::Concrete(l.try_into()?), - Abstract(v) if v.len() <= 32 => { - let mut r = [0u8; 32]; - r[..v.len()].copy_from_slice(&v[..]); - Self::Abstract(r) - }, - _ => return Err(()), - }) - } -} - impl TryFrom for AssetId { type Error = (); fn try_from(new: NewAssetId) -> Result { @@ -601,13 +539,6 @@ impl MultiAsset { } } -impl TryFrom for MultiAsset { - type Error = (); - fn try_from(old: OldMultiAsset) -> Result { - Ok(Self { id: old.id.try_into()?, fun: old.fun.try_into()? }) - } -} - impl TryFrom for MultiAsset { type Error = (); fn try_from(new: NewMultiAsset) -> Result { @@ -657,18 +588,6 @@ impl Decode for MultiAssets { } } -impl TryFrom for MultiAssets { - type Error = (); - fn try_from(old: OldMultiAssets) -> Result { - let v = old - .drain() - .into_iter() - .map(MultiAsset::try_from) - .collect::, ()>>()?; - Ok(MultiAssets(v)) - } -} - impl TryFrom for MultiAssets { type Error = (); fn try_from(new: NewMultiAssets) -> Result { @@ -882,17 +801,6 @@ pub enum WildMultiAsset { }, } -impl TryFrom for WildMultiAsset { - type Error = (); - fn try_from(old: OldWildMultiAsset) -> Result { - use OldWildMultiAsset::*; - Ok(match old { - AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, - All => Self::All, - }) - } -} - impl TryFrom for WildMultiAsset { type Error = (); fn try_from(new: NewWildMultiAsset) -> Result { @@ -907,19 +815,6 @@ impl TryFrom for WildMultiAsset { } } -impl TryFrom<(OldWildMultiAsset, u32)> for WildMultiAsset { - type Error = (); - fn try_from(old: (OldWildMultiAsset, u32)) -> Result { - use OldWildMultiAsset::*; - let count = old.1; - Ok(match old.0 { - AllOf { id, fun } => - Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, - All => Self::AllCounted(count), - }) - } -} - impl WildMultiAsset { /// Returns true if `self` is a super-set of the given `inner` asset. pub fn contains(&self, inner: &MultiAsset) -> bool { @@ -1079,16 +974,6 @@ impl MultiAssetFilter { } } -impl TryFrom for MultiAssetFilter { - type Error = (); - fn try_from(old: OldMultiAssetFilter) -> Result { - Ok(match old { - OldMultiAssetFilter::Definite(x) => Self::Definite(x.try_into()?), - OldMultiAssetFilter::Wild(x) => Self::Wild(x.try_into()?), - }) - } -} - impl TryFrom for MultiAssetFilter { type Error = (); fn try_from(new: NewMultiAssetFilter) -> Result { @@ -1100,19 +985,6 @@ impl TryFrom for MultiAssetFilter { } } -impl TryFrom<(OldMultiAssetFilter, u32)> for MultiAssetFilter { - type Error = (); - fn try_from(old: (OldMultiAssetFilter, u32)) -> Result { - let count = old.1; - Ok(match old.0 { - OldMultiAssetFilter::Definite(x) if count >= x.len() as u32 => - Self::Definite(x.try_into()?), - OldMultiAssetFilter::Wild(x) => Self::Wild((x, count).try_into()?), - _ => return Err(()), - }) - } -} - #[cfg(test)] mod tests { use super::super::prelude::*; diff --git a/polkadot/xcm/src/v3/multilocation.rs b/polkadot/xcm/src/v3/multilocation.rs index e51981204d96..8f18312046f8 100644 --- a/polkadot/xcm/src/v3/multilocation.rs +++ b/polkadot/xcm/src/v3/multilocation.rs @@ -17,9 +17,7 @@ //! XCM `MultiLocation` datatype. use super::{Junction, Junctions}; -use crate::{ - v2::MultiLocation as OldMultiLocation, v4::Location as NewMultiLocation, VersionedLocation, -}; +use crate::{v4::Location as NewMultiLocation, VersionedLocation}; use codec::{Decode, Encode, MaxEncodedLen}; use core::result; use scale_info::TypeInfo; @@ -464,13 +462,6 @@ impl MultiLocation { } } -impl TryFrom for MultiLocation { - type Error = (); - fn try_from(x: OldMultiLocation) -> result::Result { - Ok(MultiLocation { parents: x.parents, interior: x.interior.try_into()? }) - } -} - impl TryFrom for Option { type Error = (); fn try_from(new: NewMultiLocation) -> result::Result { @@ -759,37 +750,4 @@ mod tests { let expected = MultiLocation::new(2, (GlobalConsensus(Kusama), Parachain(42))); assert_eq!(para_to_remote_para.chain_location(), expected); } - - #[test] - fn conversion_from_other_types_works() { - use crate::v2; - - fn takes_multilocation>(_arg: Arg) {} - - takes_multilocation(Parent); - takes_multilocation(Here); - takes_multilocation(X1(Parachain(42))); - takes_multilocation((Ancestor(255), PalletInstance(8))); - takes_multilocation((Ancestor(5), Parachain(1), PalletInstance(3))); - takes_multilocation((Ancestor(2), Here)); - takes_multilocation(AncestorThen( - 3, - X2(Parachain(43), AccountIndex64 { network: None, index: 155 }), - )); - takes_multilocation((Parent, AccountId32 { network: None, id: [0; 32] })); - takes_multilocation((Parent, Here)); - takes_multilocation(ParentThen(X1(Parachain(75)))); - takes_multilocation([Parachain(100), PalletInstance(3)]); - - assert_eq!( - v2::MultiLocation::from(v2::Junctions::Here).try_into(), - Ok(MultiLocation::here()) - ); - assert_eq!(v2::MultiLocation::from(v2::Parent).try_into(), Ok(MultiLocation::parent())); - assert_eq!( - v2::MultiLocation::from((v2::Parent, v2::Parent, v2::Junction::GeneralIndex(42u128),)) - .try_into(), - Ok(MultiLocation { parents: 2, interior: X1(GeneralIndex(42u128)) }), - ); - } } diff --git a/polkadot/xcm/src/v3/traits.rs b/polkadot/xcm/src/v3/traits.rs index 34c46453b9a8..1c8620708922 100644 --- a/polkadot/xcm/src/v3/traits.rs +++ b/polkadot/xcm/src/v3/traits.rs @@ -16,20 +16,19 @@ //! Cross-Consensus Message format data structures. -use crate::v2::Error as OldError; -use codec::{Decode, Encode, MaxEncodedLen}; +use crate::v5::Error as NewError; use core::result; use scale_info::TypeInfo; pub use sp_weights::Weight; -use super::*; - // A simple trait to get the weight of some object. pub trait GetWeight { fn weight(&self) -> sp_weights::Weight; } +use super::*; + /// Error codes used in XCM. The first errors codes have explicit indices and are part of the XCM /// format. Those trailing are merely part of the XCM implementation; there is no expectation that /// they will retain the same index over time. @@ -166,25 +165,17 @@ pub enum Error { ExceedsStackLimit, } -impl MaxEncodedLen for Error { - fn max_encoded_len() -> usize { - // TODO: max_encoded_len doesn't quite work here as it tries to take notice of the fields - // marked `codec(skip)`. We can hard-code it with the right answer for now. - 1 - } -} - -impl TryFrom for Error { +impl TryFrom for Error { type Error = (); - fn try_from(old_error: OldError) -> result::Result { - use OldError::*; - Ok(match old_error { + fn try_from(new_error: NewError) -> result::Result { + use NewError::*; + Ok(match new_error { Overflow => Self::Overflow, Unimplemented => Self::Unimplemented, UntrustedReserveLocation => Self::UntrustedReserveLocation, UntrustedTeleportLocation => Self::UntrustedTeleportLocation, - MultiLocationFull => Self::LocationFull, - MultiLocationNotInvertible => Self::LocationNotInvertible, + LocationFull => Self::LocationFull, + LocationNotInvertible => Self::LocationNotInvertible, BadOrigin => Self::BadOrigin, InvalidLocation => Self::InvalidLocation, AssetNotFound => Self::AssetNotFound, @@ -201,11 +192,32 @@ impl TryFrom for Error { NotHoldingFees => Self::NotHoldingFees, TooExpensive => Self::TooExpensive, Trap(i) => Self::Trap(i), + ExpectationFalse => Self::ExpectationFalse, + PalletNotFound => Self::PalletNotFound, + NameMismatch => Self::NameMismatch, + VersionIncompatible => Self::VersionIncompatible, + HoldingWouldOverflow => Self::HoldingWouldOverflow, + ExportError => Self::ExportError, + ReanchorFailed => Self::ReanchorFailed, + NoDeal => Self::NoDeal, + FeesNotMet => Self::FeesNotMet, + LockError => Self::LockError, + NoPermission => Self::NoPermission, + Unanchored => Self::Unanchored, + NotDepositable => Self::NotDepositable, _ => return Err(()), }) } } +impl MaxEncodedLen for Error { + fn max_encoded_len() -> usize { + // TODO: max_encoded_len doesn't quite work here as it tries to take notice of the fields + // marked `codec(skip)`. We can hard-code it with the right answer for now. + 1 + } +} + impl From for Error { fn from(e: SendError) -> Self { match e { diff --git a/polkadot/xcm/src/v4/asset.rs b/polkadot/xcm/src/v4/asset.rs index 41f1f82f828c..d7a9297d6932 100644 --- a/polkadot/xcm/src/v4/asset.rs +++ b/polkadot/xcm/src/v4/asset.rs @@ -27,10 +27,17 @@ //! holding account. use super::{InteriorLocation, Location, Reanchorable}; -use crate::v3::{ - AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, - MultiAsset as OldAsset, MultiAssetFilter as OldAssetFilter, MultiAssets as OldAssets, - WildFungibility as OldWildFungibility, WildMultiAsset as OldWildAsset, +use crate::{ + v3::{ + AssetId as OldAssetId, AssetInstance as OldAssetInstance, Fungibility as OldFungibility, + MultiAsset as OldAsset, MultiAssetFilter as OldAssetFilter, MultiAssets as OldAssets, + WildFungibility as OldWildFungibility, WildMultiAsset as OldWildAsset, + }, + v5::{ + Asset as NewAsset, AssetFilter as NewAssetFilter, AssetId as NewAssetId, + AssetInstance as NewAssetInstance, Assets as NewAssets, Fungibility as NewFungibility, + WildAsset as NewWildAsset, WildFungibility as NewWildFungibility, + }, }; use alloc::{vec, vec::Vec}; use bounded_collections::{BoundedVec, ConstU32}; @@ -90,6 +97,21 @@ impl TryFrom for AssetInstance { } } +impl TryFrom for AssetInstance { + type Error = (); + fn try_from(value: NewAssetInstance) -> Result { + use NewAssetInstance::*; + Ok(match value { + Undefined => Self::Undefined, + Index(n) => Self::Index(n), + Array4(n) => Self::Array4(n), + Array8(n) => Self::Array8(n), + Array16(n) => Self::Array16(n), + Array32(n) => Self::Array32(n), + }) + } +} + impl From<()> for AssetInstance { fn from(_: ()) -> Self { Self::Undefined @@ -244,6 +266,17 @@ impl TryFrom for u128 { } } +impl TryFrom for Fungibility { + type Error = (); + fn try_from(value: NewFungibility) -> Result { + use NewFungibility::*; + Ok(match value { + Fungible(n) => Self::Fungible(n), + NonFungible(i) => Self::NonFungible(i.try_into()?), + }) + } +} + /// Classification of whether an asset is fungible or not, along with a mandatory amount or /// instance. #[derive( @@ -357,6 +390,17 @@ impl TryFrom for WildFungibility { } } +impl TryFrom for WildFungibility { + type Error = (); + fn try_from(value: NewWildFungibility) -> Result { + use NewWildFungibility::*; + Ok(match value { + Fungible => Self::Fungible, + NonFungible => Self::NonFungible, + }) + } +} + /// Location to identify an asset. #[derive( Clone, @@ -391,6 +435,13 @@ impl TryFrom for AssetId { } } +impl TryFrom for AssetId { + type Error = (); + fn try_from(new: NewAssetId) -> Result { + Ok(Self(new.0.try_into()?)) + } +} + impl AssetId { /// Prepend a `Location` to an asset id, giving it a new root location. pub fn prepend_with(&mut self, prepend: &Location) -> Result<(), ()> { @@ -526,6 +577,13 @@ impl TryFrom for Asset { } } +impl TryFrom for Asset { + type Error = (); + fn try_from(new: NewAsset) -> Result { + Ok(Self { id: new.id.try_into()?, fun: new.fun.try_into()? }) + } +} + /// A `Vec` of `Asset`s. /// /// There are a number of invariants which the construction and mutation functions must ensure are @@ -579,6 +637,18 @@ impl TryFrom for Assets { } } +impl TryFrom for Assets { + type Error = (); + fn try_from(new: NewAssets) -> Result { + let v = new + .into_inner() + .into_iter() + .map(Asset::try_from) + .collect::, ()>>()?; + Ok(Assets(v)) + } +} + impl From> for Assets { fn from(mut assets: Vec) -> Self { let mut res = Vec::with_capacity(assets.len()); @@ -795,6 +865,20 @@ impl TryFrom for WildAsset { } } +impl TryFrom for WildAsset { + type Error = (); + fn try_from(new: NewWildAsset) -> Result { + use NewWildAsset::*; + Ok(match new { + AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, + AllOfCounted { id, fun, count } => + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + All => Self::All, + AllCounted(count) => Self::AllCounted(count), + }) + } +} + impl WildAsset { /// Returns true if `self` is a super-set of the given `inner` asset. pub fn contains(&self, inner: &Asset) -> bool { @@ -944,6 +1028,17 @@ impl AssetFilter { } } +impl TryFrom for AssetFilter { + type Error = (); + fn try_from(new: NewAssetFilter) -> Result { + use NewAssetFilter::*; + Ok(match new { + Definite(x) => Self::Definite(x.try_into()?), + Wild(x) => Self::Wild(x.try_into()?), + }) + } +} + impl TryFrom for AssetFilter { type Error = (); fn try_from(old: OldAssetFilter) -> Result { diff --git a/polkadot/xcm/src/v4/junction.rs b/polkadot/xcm/src/v4/junction.rs index 36fb616d2dc5..c6e83214328e 100644 --- a/polkadot/xcm/src/v4/junction.rs +++ b/polkadot/xcm/src/v4/junction.rs @@ -20,6 +20,7 @@ use super::Location; pub use crate::v3::{BodyId, BodyPart}; use crate::{ v3::{Junction as OldJunction, NetworkId as OldNetworkId}, + v5::{Junction as NewJunction, NetworkId as NewNetworkId}, VersionedLocation, }; use bounded_collections::{BoundedSlice, BoundedVec, ConstU32}; @@ -72,7 +73,6 @@ pub enum Junction { /// An instanced, indexed pallet that forms a constituent part of the context. /// /// Generally used when the context is a Frame-based chain. - // TODO XCMv4 inner should be `Compact`. PalletInstance(u8), /// A non-descript index within the context location. /// @@ -103,6 +103,28 @@ pub enum Junction { GlobalConsensus(NetworkId), } +impl From for Option { + fn from(new: NewNetworkId) -> Self { + Some(NetworkId::from(new)) + } +} + +impl From for NetworkId { + fn from(new: NewNetworkId) -> Self { + use NewNetworkId::*; + match new { + ByGenesis(hash) => Self::ByGenesis(hash), + ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash }, + Polkadot => Self::Polkadot, + Kusama => Self::Kusama, + Ethereum { chain_id } => Self::Ethereum { chain_id }, + BitcoinCore => Self::BitcoinCore, + BitcoinCash => Self::BitcoinCash, + PolkadotBulletin => Self::PolkadotBulletin, + } + } +} + /// A global identifier of a data structure existing within consensus. /// /// Maintenance note: Networks with global consensus and which are practically bridgeable within the @@ -253,6 +275,29 @@ impl TryFrom for Junction { } } +impl TryFrom for Junction { + type Error = (); + + fn try_from(value: NewJunction) -> Result { + use NewJunction::*; + Ok(match value { + Parachain(id) => Self::Parachain(id), + AccountId32 { network: maybe_network, id } => + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, + AccountIndex64 { network: maybe_network, index } => + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, + AccountKey20 { network: maybe_network, key } => + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + PalletInstance(index) => Self::PalletInstance(index), + GeneralIndex(id) => Self::GeneralIndex(id), + GeneralKey { length, data } => Self::GeneralKey { length, data }, + OnlyChild => Self::OnlyChild, + Plurality { id, part } => Self::Plurality { id, part }, + GlobalConsensus(network) => Self::GlobalConsensus(network.into()), + }) + } +} + impl Junction { /// Convert `self` into a `Location` containing 0 parents. /// diff --git a/polkadot/xcm/src/v4/location.rs b/polkadot/xcm/src/v4/location.rs index f2c302495c73..3a44b0696be4 100644 --- a/polkadot/xcm/src/v4/location.rs +++ b/polkadot/xcm/src/v4/location.rs @@ -17,7 +17,7 @@ //! XCM `Location` datatype. use super::{traits::Reanchorable, Junction, Junctions}; -use crate::{v3::MultiLocation as OldLocation, VersionedLocation}; +use crate::{v3::MultiLocation as OldLocation, v5::Location as NewLocation, VersionedLocation}; use codec::{Decode, Encode, MaxEncodedLen}; use core::result; use scale_info::TypeInfo; @@ -489,6 +489,20 @@ impl TryFrom for Location { } } +impl TryFrom for Option { + type Error = (); + fn try_from(new: NewLocation) -> result::Result { + Ok(Some(Location::try_from(new)?)) + } +} + +impl TryFrom for Location { + type Error = (); + fn try_from(new: NewLocation) -> result::Result { + Ok(Location { parents: new.parent_count(), interior: new.interior().clone().try_into()? }) + } +} + /// A unit struct which can be converted into a `Location` of `parents` value 1. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Parent; diff --git a/polkadot/xcm/src/v4/mod.rs b/polkadot/xcm/src/v4/mod.rs index a2b12dcc54ce..545b75a99ff3 100644 --- a/polkadot/xcm/src/v4/mod.rs +++ b/polkadot/xcm/src/v4/mod.rs @@ -17,9 +17,15 @@ //! Version 4 of the Cross-Consensus Message format data structures. pub use super::v3::GetWeight; -use super::v3::{ - Instruction as OldInstruction, PalletInfo as OldPalletInfo, - QueryResponseInfo as OldQueryResponseInfo, Response as OldResponse, Xcm as OldXcm, +use super::{ + v3::{ + Instruction as OldInstruction, PalletInfo as OldPalletInfo, + QueryResponseInfo as OldQueryResponseInfo, Response as OldResponse, Xcm as OldXcm, + }, + v5::{ + Instruction as NewInstruction, PalletInfo as NewPalletInfo, + QueryResponseInfo as NewQueryResponseInfo, Response as NewResponse, Xcm as NewXcm, + }, }; use crate::DoubleEncoded; use alloc::{vec, vec::Vec}; @@ -30,6 +36,7 @@ use codec::{ }; use core::{fmt::Debug, result}; use derivative::Derivative; +use frame_support::dispatch::GetDispatchInfo; use scale_info::TypeInfo; mod asset; @@ -50,7 +57,7 @@ pub use traits::{ SendError, SendResult, SendXcm, Weight, XcmHash, }; // These parts of XCM v3 are unchanged in XCM v4, and are re-imported here. -pub use super::v3::{MaybeErrorCode, OriginKind, WeightLimit}; +pub use super::v3::{MaxDispatchErrorLen, MaybeErrorCode, OriginKind, WeightLimit}; /// This module's XCM version. pub const VERSION: super::Version = 4; @@ -222,9 +229,6 @@ pub mod prelude { parameter_types! { pub MaxPalletNameLen: u32 = 48; - /// Maximum size of the encoded error code coming from a `Dispatch` result, used for - /// `MaybeErrorCode`. This is not (yet) enforced, so it's just an indication of expectation. - pub MaxDispatchErrorLen: u32 = 128; pub MaxPalletsInfo: u32 = 64; } @@ -258,6 +262,22 @@ impl TryInto for PalletInfo { } } +impl TryInto for PalletInfo { + type Error = (); + + fn try_into(self) -> result::Result { + NewPalletInfo::new( + self.index, + self.name.into_inner(), + self.module_name.into_inner(), + self.major, + self.minor, + self.patch, + ) + .map_err(|_| ()) + } +} + impl PalletInfo { pub fn new( index: u32, @@ -322,6 +342,36 @@ impl TryFrom for Response { } } +impl TryFrom for Response { + type Error = (); + + fn try_from(new: NewResponse) -> result::Result { + use NewResponse::*; + Ok(match new { + Null => Self::Null, + Assets(assets) => Self::Assets(assets.try_into()?), + ExecutionResult(result) => Self::ExecutionResult( + result + .map(|(num, new_error)| (num, new_error.try_into())) + .map(|(num, result)| result.map(|inner| (num, inner))) + .transpose()?, + ), + Version(version) => Self::Version(version), + PalletsInfo(pallet_info) => { + let inner = pallet_info + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?; + Self::PalletsInfo( + BoundedVec::::try_from(inner).map_err(|_| ())?, + ) + }, + DispatchResult(maybe_error) => + Self::DispatchResult(maybe_error.try_into().map_err(|_| ())?), + }) + } +} + /// Information regarding the composition of a query response. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] pub struct QueryResponseInfo { @@ -334,6 +384,18 @@ pub struct QueryResponseInfo { pub max_weight: Weight, } +impl TryFrom for QueryResponseInfo { + type Error = (); + + fn try_from(new: NewQueryResponseInfo) -> result::Result { + Ok(Self { + destination: new.destination.try_into()?, + query_id: new.query_id, + max_weight: new.max_weight, + }) + } +} + impl TryFrom for QueryResponseInfo { type Error = (); @@ -690,6 +752,7 @@ pub enum Instruction { /// Kind: *Command* /// /// Errors: + #[builder(pays_fees)] BuyExecution { fees: Asset, weight_limit: WeightLimit }, /// Refund any surplus weight previously bought with `BuyExecution`. @@ -1206,6 +1269,166 @@ impl TryFrom> for Xcm { } } +// Convert from a v5 XCM to a v4 XCM. +impl TryFrom> for Xcm { + type Error = (); + fn try_from(new_xcm: NewXcm) -> result::Result { + Ok(Xcm(new_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) + } +} + +// Convert from a v5 instruction to a v4 instruction. +impl TryFrom> for Instruction { + type Error = (); + fn try_from(new_instruction: NewInstruction) -> result::Result { + use NewInstruction::*; + Ok(match new_instruction { + WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), + ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), + ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + Self::QueryResponse { + query_id, + querier: querier.try_into()?, + response: response.try_into()?, + max_weight, + }, + QueryResponse { query_id, response, max_weight, querier: None } => + Self::QueryResponse { + query_id, + querier: None, + response: response.try_into()?, + max_weight, + }, + TransferAsset { assets, beneficiary } => Self::TransferAsset { + assets: assets.try_into()?, + beneficiary: beneficiary.try_into()?, + }, + TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { + assets: assets.try_into()?, + dest: dest.try_into()?, + xcm: xcm.try_into()?, + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + Self::HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, mut call } => { + let require_weight_at_most = call.take_decoded()?.get_dispatch_info().call_weight; + Self::Transact { origin_kind, require_weight_at_most, call: call.into() } + }, + ReportError(response_info) => Self::ReportError(QueryResponseInfo { + query_id: response_info.query_id, + destination: response_info.destination.try_into().map_err(|_| ())?, + max_weight: response_info.max_weight, + }), + DepositAsset { assets, beneficiary } => { + let beneficiary = beneficiary.try_into()?; + let assets = assets.try_into()?; + Self::DepositAsset { assets, beneficiary } + }, + DepositReserveAsset { assets, dest, xcm } => { + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + let assets = assets.try_into()?; + Self::DepositReserveAsset { assets, dest, xcm } + }, + ExchangeAsset { give, want, maximal } => { + let give = give.try_into()?; + let want = want.try_into()?; + Self::ExchangeAsset { give, want, maximal } + }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let reserve = reserve.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateReserveWithdraw { assets, reserve, xcm } + }, + InitiateTeleport { assets, dest, xcm } => { + // No `max_assets` here, so if there's a connt, then we cannot translate. + let assets = assets.try_into()?; + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateTeleport { assets, dest, xcm } + }, + ReportHolding { response_info, assets } => { + let response_info = QueryResponseInfo { + destination: response_info.destination.try_into().map_err(|_| ())?, + query_id: response_info.query_id, + max_weight: response_info.max_weight, + }; + Self::ReportHolding { response_info, assets: assets.try_into()? } + }, + BuyExecution { fees, weight_limit } => { + let fees = fees.try_into()?; + let weight_limit = weight_limit.into(); + Self::BuyExecution { fees, weight_limit } + }, + ClearOrigin => Self::ClearOrigin, + DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), + RefundSurplus => Self::RefundSurplus, + SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), + SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), + ClearError => Self::ClearError, + ClaimAsset { assets, ticket } => { + let assets = assets.try_into()?; + let ticket = ticket.try_into()?; + Self::ClaimAsset { assets, ticket } + }, + Trap(code) => Self::Trap(code), + SubscribeVersion { query_id, max_response_weight } => + Self::SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => Self::UnsubscribeVersion, + BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), + ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), + ExpectOrigin(maybe_origin) => + Self::ExpectOrigin(maybe_origin.map(|origin| origin.try_into()).transpose()?), + ExpectError(maybe_error) => Self::ExpectError( + maybe_error + .map(|(num, new_error)| (num, new_error.try_into())) + .map(|(num, result)| result.map(|inner| (num, inner))) + .transpose()?, + ), + ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), + QueryPallet { module_name, response_info } => + Self::QueryPallet { module_name, response_info: response_info.try_into()? }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => + Self::ReportTransactStatus(response_info.try_into()?), + ClearTransactStatus => Self::ClearTransactStatus, + UniversalOrigin(junction) => Self::UniversalOrigin(junction.try_into()?), + ExportMessage { network, destination, xcm } => Self::ExportMessage { + network: network.into(), + destination: destination.try_into()?, + xcm: xcm.try_into()?, + }, + LockAsset { asset, unlocker } => + Self::LockAsset { asset: asset.try_into()?, unlocker: unlocker.try_into()? }, + UnlockAsset { asset, target } => + Self::UnlockAsset { asset: asset.try_into()?, target: target.try_into()? }, + NoteUnlockable { asset, owner } => + Self::NoteUnlockable { asset: asset.try_into()?, owner: owner.try_into()? }, + RequestUnlock { asset, locker } => + Self::RequestUnlock { asset: asset.try_into()?, locker: locker.try_into()? }, + SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, + SetTopic(topic) => Self::SetTopic(topic), + ClearTopic => Self::ClearTopic, + AliasOrigin(location) => Self::AliasOrigin(location.try_into()?), + UnpaidExecution { weight_limit, check_origin } => Self::UnpaidExecution { + weight_limit, + check_origin: check_origin.map(|origin| origin.try_into()).transpose()?, + }, + InitiateTransfer { .. } | PayFees { .. } | SetAssetClaimer { .. } => { + log::debug!(target: "xcm::v5tov4", "`{new_instruction:?}` not supported by v4"); + return Err(()); + }, + }) + } +} + // Convert from a v3 instruction to a v4 instruction impl TryFrom> for Instruction { type Error = (); diff --git a/polkadot/xcm/src/v5/asset.rs b/polkadot/xcm/src/v5/asset.rs new file mode 100644 index 000000000000..d0d9a7cedff0 --- /dev/null +++ b/polkadot/xcm/src/v5/asset.rs @@ -0,0 +1,1155 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Cross-Consensus Message format asset data structures. +//! +//! This encompasses four types for representing assets: +//! - `Asset`: A description of a single asset, either an instance of a non-fungible or some amount +//! of a fungible. +//! - `Assets`: A collection of `Asset`s. These are stored in a `Vec` and sorted with fungibles +//! first. +//! - `Wild`: A single asset wildcard, this can either be "all" assets, or all assets of a specific +//! kind. +//! - `AssetFilter`: A combination of `Wild` and `Assets` designed for efficiently filtering an XCM +//! holding account. + +use super::{InteriorLocation, Location, Reanchorable}; +use crate::v4::{ + Asset as OldAsset, AssetFilter as OldAssetFilter, AssetId as OldAssetId, + AssetInstance as OldAssetInstance, Assets as OldAssets, Fungibility as OldFungibility, + WildAsset as OldWildAsset, WildFungibility as OldWildFungibility, +}; +use alloc::{vec, vec::Vec}; +use bounded_collections::{BoundedVec, ConstU32}; +use codec::{self as codec, Decode, Encode, MaxEncodedLen}; +use core::cmp::Ordering; +use scale_info::TypeInfo; + +/// A general identifier for an instance of a non-fungible asset class. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum AssetInstance { + /// Undefined - used if the non-fungible asset class has only one instance. + Undefined, + + /// A compact index. Technically this could be greater than `u128`, but this implementation + /// supports only values up to `2**128 - 1`. + Index(#[codec(compact)] u128), + + /// A 4-byte fixed-length datum. + Array4([u8; 4]), + + /// An 8-byte fixed-length datum. + Array8([u8; 8]), + + /// A 16-byte fixed-length datum. + Array16([u8; 16]), + + /// A 32-byte fixed-length datum. + Array32([u8; 32]), +} + +impl TryFrom for AssetInstance { + type Error = (); + fn try_from(value: OldAssetInstance) -> Result { + use OldAssetInstance::*; + Ok(match value { + Undefined => Self::Undefined, + Index(n) => Self::Index(n), + Array4(n) => Self::Array4(n), + Array8(n) => Self::Array8(n), + Array16(n) => Self::Array16(n), + Array32(n) => Self::Array32(n), + }) + } +} + +impl From<()> for AssetInstance { + fn from(_: ()) -> Self { + Self::Undefined + } +} + +impl From<[u8; 4]> for AssetInstance { + fn from(x: [u8; 4]) -> Self { + Self::Array4(x) + } +} + +impl From<[u8; 8]> for AssetInstance { + fn from(x: [u8; 8]) -> Self { + Self::Array8(x) + } +} + +impl From<[u8; 16]> for AssetInstance { + fn from(x: [u8; 16]) -> Self { + Self::Array16(x) + } +} + +impl From<[u8; 32]> for AssetInstance { + fn from(x: [u8; 32]) -> Self { + Self::Array32(x) + } +} + +impl From for AssetInstance { + fn from(x: u8) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u16) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u32) -> Self { + Self::Index(x as u128) + } +} + +impl From for AssetInstance { + fn from(x: u64) -> Self { + Self::Index(x as u128) + } +} + +impl TryFrom for () { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Undefined => Ok(()), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 4] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array4(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 8] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array8(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 16] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array16(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for [u8; 32] { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Array32(x) => Ok(x), + _ => Err(()), + } + } +} + +impl TryFrom for u8 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u16 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u32 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u64 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => x.try_into().map_err(|_| ()), + _ => Err(()), + } + } +} + +impl TryFrom for u128 { + type Error = (); + fn try_from(x: AssetInstance) -> Result { + match x { + AssetInstance::Index(x) => Ok(x), + _ => Err(()), + } + } +} + +/// Classification of whether an asset is fungible or not, along with a mandatory amount or +/// instance. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum Fungibility { + /// A fungible asset; we record a number of units, as a `u128` in the inner item. + Fungible(#[codec(compact)] u128), + /// A non-fungible asset. We record the instance identifier in the inner item. Only one asset + /// of each instance identifier may ever be in existence at once. + NonFungible(AssetInstance), +} + +#[derive(Decode)] +enum UncheckedFungibility { + Fungible(#[codec(compact)] u128), + NonFungible(AssetInstance), +} + +impl Decode for Fungibility { + fn decode(input: &mut I) -> Result { + match UncheckedFungibility::decode(input)? { + UncheckedFungibility::Fungible(a) if a != 0 => Ok(Self::Fungible(a)), + UncheckedFungibility::NonFungible(i) => Ok(Self::NonFungible(i)), + UncheckedFungibility::Fungible(_) => + Err("Fungible asset of zero amount is not allowed".into()), + } + } +} + +impl Fungibility { + pub fn is_kind(&self, w: WildFungibility) -> bool { + use Fungibility::*; + use WildFungibility::{Fungible as WildFungible, NonFungible as WildNonFungible}; + matches!((self, w), (Fungible(_), WildFungible) | (NonFungible(_), WildNonFungible)) + } +} + +impl From for Fungibility { + fn from(amount: i32) -> Fungibility { + debug_assert_ne!(amount, 0); + Fungibility::Fungible(amount as u128) + } +} + +impl From for Fungibility { + fn from(amount: u128) -> Fungibility { + debug_assert_ne!(amount, 0); + Fungibility::Fungible(amount) + } +} + +impl> From for Fungibility { + fn from(instance: T) -> Fungibility { + Fungibility::NonFungible(instance.into()) + } +} + +impl TryFrom for Fungibility { + type Error = (); + fn try_from(value: OldFungibility) -> Result { + use OldFungibility::*; + Ok(match value { + Fungible(n) => Self::Fungible(n), + NonFungible(i) => Self::NonFungible(i.try_into()?), + }) + } +} + +/// Classification of whether an asset is fungible or not. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum WildFungibility { + /// The asset is fungible. + Fungible, + /// The asset is not fungible. + NonFungible, +} + +impl TryFrom for WildFungibility { + type Error = (); + fn try_from(value: OldWildFungibility) -> Result { + use OldWildFungibility::*; + Ok(match value { + Fungible => Self::Fungible, + NonFungible => Self::NonFungible, + }) + } +} + +/// Location to identify an asset. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub struct AssetId(pub Location); + +impl> From for AssetId { + fn from(x: T) -> Self { + Self(x.into()) + } +} + +impl TryFrom for AssetId { + type Error = (); + fn try_from(old: OldAssetId) -> Result { + Ok(Self(old.0.try_into()?)) + } +} + +impl AssetId { + /// Prepend a `Location` to an asset id, giving it a new root location. + pub fn prepend_with(&mut self, prepend: &Location) -> Result<(), ()> { + self.0.prepend_with(prepend.clone()).map_err(|_| ())?; + Ok(()) + } + + /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding + /// `Asset` value. + pub fn into_asset(self, fun: Fungibility) -> Asset { + Asset { fun, id: self } + } + + /// Use the value of `self` along with a `fun` fungibility specifier to create the corresponding + /// `WildAsset` wildcard (`AllOf`) value. + pub fn into_wild(self, fun: WildFungibility) -> WildAsset { + WildAsset::AllOf { fun, id: self } + } +} + +impl Reanchorable for AssetId { + type Error = (); + + /// Mutate the asset to represent the same value from the perspective of a new `target` + /// location. The local chain's location is provided in `context`. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.0.reanchor(target, context)?; + Ok(()) + } + + fn reanchored(mut self, target: &Location, context: &InteriorLocation) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(()), + } + } +} + +/// Either an amount of a single fungible asset, or a single well-identified non-fungible asset. +#[derive( + Clone, + Eq, + PartialEq, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub struct Asset { + /// The overall asset identity (aka *class*, in the case of a non-fungible). + pub id: AssetId, + /// The fungibility of the asset, which contains either the amount (in the case of a fungible + /// asset) or the *instance ID*, the secondary asset identifier. + pub fun: Fungibility, +} + +impl PartialOrd for Asset { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Asset { + fn cmp(&self, other: &Self) -> Ordering { + match (&self.fun, &other.fun) { + (Fungibility::Fungible(..), Fungibility::NonFungible(..)) => Ordering::Less, + (Fungibility::NonFungible(..), Fungibility::Fungible(..)) => Ordering::Greater, + _ => (&self.id, &self.fun).cmp(&(&other.id, &other.fun)), + } + } +} + +impl, B: Into> From<(A, B)> for Asset { + fn from((id, fun): (A, B)) -> Asset { + Asset { fun: fun.into(), id: id.into() } + } +} + +impl Asset { + pub fn is_fungible(&self, maybe_id: Option) -> bool { + use Fungibility::*; + matches!(self.fun, Fungible(..)) && maybe_id.map_or(true, |i| i == self.id) + } + + pub fn is_non_fungible(&self, maybe_id: Option) -> bool { + use Fungibility::*; + matches!(self.fun, NonFungible(..)) && maybe_id.map_or(true, |i| i == self.id) + } + + /// Prepend a `Location` to a concrete asset, giving it a new root location. + pub fn prepend_with(&mut self, prepend: &Location) -> Result<(), ()> { + self.id.prepend_with(prepend) + } + + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + use Fungibility::*; + if self.id == inner.id { + match (&self.fun, &inner.fun) { + (Fungible(a), Fungible(i)) if a >= i => return true, + (NonFungible(a), NonFungible(i)) if a == i => return true, + _ => (), + } + } + false + } +} + +impl Reanchorable for Asset { + type Error = (); + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.id.reanchor(target, context) + } + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + fn reanchored(mut self, target: &Location, context: &InteriorLocation) -> Result { + self.id.reanchor(target, context)?; + Ok(self) + } +} + +impl TryFrom for Asset { + type Error = (); + fn try_from(old: OldAsset) -> Result { + Ok(Self { id: old.id.try_into()?, fun: old.fun.try_into()? }) + } +} + +/// A `Vec` of `Asset`s. +/// +/// There are a number of invariants which the construction and mutation functions must ensure are +/// maintained: +/// - It may contain no items of duplicate asset class; +/// - All items must be ordered; +/// - The number of items should grow no larger than `MAX_ITEMS_IN_ASSETS`. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + TypeInfo, + Default, + serde::Serialize, + serde::Deserialize, +)] +pub struct Assets(Vec); + +/// Maximum number of items we expect in a single `Assets` value. Note this is not (yet) +/// enforced, and just serves to provide a sensible `max_encoded_len` for `Assets`. +pub const MAX_ITEMS_IN_ASSETS: usize = 20; + +impl MaxEncodedLen for Assets { + fn max_encoded_len() -> usize { + Asset::max_encoded_len() * MAX_ITEMS_IN_ASSETS + } +} + +impl Decode for Assets { + fn decode(input: &mut I) -> Result { + let bounded_instructions = + BoundedVec::>::decode(input)?; + Self::from_sorted_and_deduplicated(bounded_instructions.into_inner()) + .map_err(|()| "Out of order".into()) + } +} + +impl TryFrom for Assets { + type Error = (); + fn try_from(old: OldAssets) -> Result { + let v = old + .into_inner() + .into_iter() + .map(Asset::try_from) + .collect::, ()>>()?; + Ok(Assets(v)) + } +} + +impl From> for Assets { + fn from(mut assets: Vec) -> Self { + let mut res = Vec::with_capacity(assets.len()); + if !assets.is_empty() { + assets.sort(); + let mut iter = assets.into_iter(); + if let Some(first) = iter.next() { + let last = iter.fold(first, |a, b| -> Asset { + match (a, b) { + ( + Asset { fun: Fungibility::Fungible(a_amount), id: a_id }, + Asset { fun: Fungibility::Fungible(b_amount), id: b_id }, + ) if a_id == b_id => Asset { + id: a_id, + fun: Fungibility::Fungible(a_amount.saturating_add(b_amount)), + }, + ( + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + Asset { fun: Fungibility::NonFungible(b_instance), id: b_id }, + ) if a_id == b_id && a_instance == b_instance => + Asset { fun: Fungibility::NonFungible(a_instance), id: a_id }, + (to_push, to_remember) => { + res.push(to_push); + to_remember + }, + } + }); + res.push(last); + } + } + Self(res) + } +} + +impl> From for Assets { + fn from(x: T) -> Self { + Self(vec![x.into()]) + } +} + +impl Assets { + /// A new (empty) value. + pub fn new() -> Self { + Self(Vec::new()) + } + + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// Returns `Ok` if the operation succeeds and `Err` if `r` is out of order or had duplicates. + /// If you can't guarantee that `r` is sorted and deduplicated, then use + /// `From::>::from` which is infallible. + pub fn from_sorted_and_deduplicated(r: Vec) -> Result { + if r.is_empty() { + return Ok(Self(Vec::new())) + } + r.iter().skip(1).try_fold(&r[0], |a, b| -> Result<&Asset, ()> { + if a.id < b.id || a < b && (a.is_non_fungible(None) || b.is_non_fungible(None)) { + Ok(b) + } else { + Err(()) + } + })?; + Ok(Self(r)) + } + + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// In release mode, this skips any checks to ensure that `r` is correct, making it a + /// negligible-cost operation. Generally though you should avoid using it unless you have a + /// strict proof that `r` is valid. + #[cfg(test)] + pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { + Self::from_sorted_and_deduplicated(r).expect("Invalid input r is not sorted/deduped") + } + /// Create a new instance of `Assets` from a `Vec` whose contents are sorted + /// and which contain no duplicates. + /// + /// In release mode, this skips any checks to ensure that `r` is correct, making it a + /// negligible-cost operation. Generally though you should avoid using it unless you have a + /// strict proof that `r` is valid. + /// + /// In test mode, this checks anyway and panics on fail. + #[cfg(not(test))] + pub fn from_sorted_and_deduplicated_skip_checks(r: Vec) -> Self { + Self(r) + } + + /// Add some asset onto the list, saturating. This is quite a laborious operation since it + /// maintains the ordering. + pub fn push(&mut self, a: Asset) { + for asset in self.0.iter_mut().filter(|x| x.id == a.id) { + match (&a.fun, &mut asset.fun) { + (Fungibility::Fungible(amount), Fungibility::Fungible(balance)) => { + *balance = balance.saturating_add(*amount); + return + }, + (Fungibility::NonFungible(inst1), Fungibility::NonFungible(inst2)) + if inst1 == inst2 => + return, + _ => (), + } + } + self.0.push(a); + self.0.sort(); + } + + /// Returns `true` if this definitely represents no asset. + pub fn is_none(&self) -> bool { + self.0.is_empty() + } + + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + self.0.iter().any(|i| i.contains(inner)) + } + + /// Consume `self` and return the inner vec. + #[deprecated = "Use `into_inner()` instead"] + pub fn drain(self) -> Vec { + self.0 + } + + /// Consume `self` and return the inner vec. + pub fn into_inner(self) -> Vec { + self.0 + } + + /// Return a reference to the inner vec. + pub fn inner(&self) -> &Vec { + &self.0 + } + + /// Return the number of distinct asset instances contained. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Prepend a `Location` to any concrete asset items, giving it a new root location. + pub fn prepend_with(&mut self, prefix: &Location) -> Result<(), ()> { + self.0.iter_mut().try_for_each(|i| i.prepend_with(prefix))?; + self.0.sort(); + Ok(()) + } + + /// Return a reference to an item at a specific index or `None` if it doesn't exist. + pub fn get(&self, index: usize) -> Option<&Asset> { + self.0.get(index) + } +} + +impl Reanchorable for Assets { + type Error = (); + + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + self.0.iter_mut().try_for_each(|i| i.reanchor(target, context))?; + self.0.sort(); + Ok(()) + } + + fn reanchored(mut self, target: &Location, context: &InteriorLocation) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(()), + } + } +} + +/// A wildcard representing a set of assets. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum WildAsset { + /// All assets in Holding. + All, + /// All assets in Holding of a given fungibility and ID. + AllOf { id: AssetId, fun: WildFungibility }, + /// All assets in Holding, up to `u32` individual assets (different instances of non-fungibles + /// are separate assets). + AllCounted(#[codec(compact)] u32), + /// All assets in Holding of a given fungibility and ID up to `count` individual assets + /// (different instances of non-fungibles are separate assets). + AllOfCounted { + id: AssetId, + fun: WildFungibility, + #[codec(compact)] + count: u32, + }, +} + +impl TryFrom for WildAsset { + type Error = (); + fn try_from(old: OldWildAsset) -> Result { + use OldWildAsset::*; + Ok(match old { + AllOf { id, fun } => Self::AllOf { id: id.try_into()?, fun: fun.try_into()? }, + All => Self::All, + AllOfCounted { id, fun, count } => + Self::AllOfCounted { id: id.try_into()?, fun: fun.try_into()?, count }, + AllCounted(count) => Self::AllCounted(count), + }) + } +} + +impl WildAsset { + /// Returns true if `self` is a super-set of the given `inner` asset. + pub fn contains(&self, inner: &Asset) -> bool { + use WildAsset::*; + match self { + AllOfCounted { count: 0, .. } | AllCounted(0) => false, + AllOf { fun, id } | AllOfCounted { id, fun, .. } => + inner.fun.is_kind(*fun) && &inner.id == id, + All | AllCounted(_) => true, + } + } + + /// Returns true if the wild element of `self` matches `inner`. + /// + /// Note that for `Counted` variants of wildcards, then it will disregard the count except for + /// always returning `false` when equal to 0. + #[deprecated = "Use `contains` instead"] + pub fn matches(&self, inner: &Asset) -> bool { + self.contains(inner) + } + + /// Mutate the asset to represent the same value from the perspective of a new `target` + /// location. The local chain's location is provided in `context`. + pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + use WildAsset::*; + match self { + AllOf { ref mut id, .. } | AllOfCounted { ref mut id, .. } => + id.reanchor(target, context), + All | AllCounted(_) => Ok(()), + } + } + + /// Maximum count of assets allowed to match, if any. + pub fn count(&self) -> Option { + use WildAsset::*; + match self { + AllOfCounted { count, .. } | AllCounted(count) => Some(*count), + All | AllOf { .. } => None, + } + } + + /// Explicit limit on number of assets allowed to match, if any. + pub fn limit(&self) -> Option { + self.count() + } + + /// Consume self and return the equivalent version but counted and with the `count` set to the + /// given parameter. + pub fn counted(self, count: u32) -> Self { + use WildAsset::*; + match self { + AllOfCounted { fun, id, .. } | AllOf { fun, id } => AllOfCounted { fun, id, count }, + All | AllCounted(_) => AllCounted(count), + } + } +} + +impl, B: Into> From<(A, B)> for WildAsset { + fn from((id, fun): (A, B)) -> WildAsset { + WildAsset::AllOf { fun: fun.into(), id: id.into() } + } +} + +/// `Asset` collection, defined either by a number of `Assets` or a single wildcard. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum AssetFilter { + /// Specify the filter as being everything contained by the given `Assets` inner. + Definite(Assets), + /// Specify the filter as the given `WildAsset` wildcard. + Wild(WildAsset), +} + +impl> From for AssetFilter { + fn from(x: T) -> Self { + Self::Wild(x.into()) + } +} + +impl From for AssetFilter { + fn from(x: Asset) -> Self { + Self::Definite(vec![x].into()) + } +} + +impl From> for AssetFilter { + fn from(x: Vec) -> Self { + Self::Definite(x.into()) + } +} + +impl From for AssetFilter { + fn from(x: Assets) -> Self { + Self::Definite(x) + } +} + +impl AssetFilter { + /// Returns true if `inner` would be matched by `self`. + /// + /// Note that for `Counted` variants of wildcards, then it will disregard the count except for + /// always returning `false` when equal to 0. + pub fn matches(&self, inner: &Asset) -> bool { + match self { + AssetFilter::Definite(ref assets) => assets.contains(inner), + AssetFilter::Wild(ref wild) => wild.contains(inner), + } + } + + /// Mutate the location of the asset identifier if concrete, giving it the same location + /// relative to a `target` context. The local context is provided as `context`. + pub fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + match self { + AssetFilter::Definite(ref mut assets) => assets.reanchor(target, context), + AssetFilter::Wild(ref mut wild) => wild.reanchor(target, context), + } + } + + /// Maximum count of assets it is possible to match, if known. + pub fn count(&self) -> Option { + use AssetFilter::*; + match self { + Definite(x) => Some(x.len() as u32), + Wild(x) => x.count(), + } + } + + /// Explicit limit placed on the number of items, if any. + pub fn limit(&self) -> Option { + use AssetFilter::*; + match self { + Definite(_) => None, + Wild(x) => x.limit(), + } + } +} + +impl TryFrom for AssetFilter { + type Error = (); + fn try_from(old: OldAssetFilter) -> Result { + Ok(match old { + OldAssetFilter::Definite(x) => Self::Definite(x.try_into()?), + OldAssetFilter::Wild(x) => Self::Wild(x.try_into()?), + }) + } +} + +/// Matches assets based on inner `AssetFilter` and tags them for a specific type of asset transfer. +/// Please note: the transfer type is specific to each particular `(asset, source, dest)` +/// combination, so it should always be built in the context of `source` after knowing `dest`. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + Encode, + Decode, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum AssetTransferFilter { + /// teleport assets matching `AssetFilter` to a specific destination + Teleport(AssetFilter), + /// reserve-transfer assets matching `AssetFilter` to a specific destination, using the local + /// chain as reserve + ReserveDeposit(AssetFilter), + /// reserve-transfer assets matching `AssetFilter` to a specific destination, using the + /// destination as reserve + ReserveWithdraw(AssetFilter), +} + +impl AssetTransferFilter { + /// Returns reference to inner `AssetFilter` ignoring the transfer type. + pub fn inner(&self) -> &AssetFilter { + match self { + AssetTransferFilter::Teleport(inner) => inner, + AssetTransferFilter::ReserveDeposit(inner) => inner, + AssetTransferFilter::ReserveWithdraw(inner) => inner, + } + } +} + +#[cfg(test)] +mod tests { + use super::super::prelude::*; + + #[test] + fn conversion_works() { + let _: Assets = (Here, 1u128).into(); + } + + #[test] + fn from_sorted_and_deduplicated_works() { + use super::*; + use alloc::vec; + + let empty = vec![]; + let r = Assets::from_sorted_and_deduplicated(empty); + assert_eq!(r, Ok(Assets(vec![]))); + + let dup_fun = vec![(Here, 100).into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(dup_fun); + assert!(r.is_err()); + + let dup_nft = vec![(Here, *b"notgood!").into(), (Here, *b"notgood!").into()]; + let r = Assets::from_sorted_and_deduplicated(dup_nft); + assert!(r.is_err()); + + let good_fun = vec![(Here, 10).into(), (Parent, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(good_fun.clone()); + assert_eq!(r, Ok(Assets(good_fun))); + + let bad_fun = vec![(Parent, 10).into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(bad_fun); + assert!(r.is_err()); + + let good_nft = vec![(Here, ()).into(), (Here, *b"good").into()]; + let r = Assets::from_sorted_and_deduplicated(good_nft.clone()); + assert_eq!(r, Ok(Assets(good_nft))); + + let bad_nft = vec![(Here, *b"bad!").into(), (Here, ()).into()]; + let r = Assets::from_sorted_and_deduplicated(bad_nft); + assert!(r.is_err()); + + let mixed_good = vec![(Here, 10).into(), (Here, *b"good").into()]; + let r = Assets::from_sorted_and_deduplicated(mixed_good.clone()); + assert_eq!(r, Ok(Assets(mixed_good))); + + let mixed_bad = vec![(Here, *b"bad!").into(), (Here, 10).into()]; + let r = Assets::from_sorted_and_deduplicated(mixed_bad); + assert!(r.is_err()); + } + + #[test] + fn reanchor_preserves_sorting() { + use super::*; + use alloc::vec; + + let reanchor_context: Junctions = Parachain(2000).into(); + let dest = Location::new(1, []); + + let asset_1: Asset = (Location::new(0, [PalletInstance(50), GeneralIndex(1)]), 10).into(); + let mut asset_1_reanchored = asset_1.clone(); + assert!(asset_1_reanchored.reanchor(&dest, &reanchor_context).is_ok()); + assert_eq!( + asset_1_reanchored, + (Location::new(0, [Parachain(2000), PalletInstance(50), GeneralIndex(1)]), 10).into() + ); + + let asset_2: Asset = (Location::new(1, []), 10).into(); + let mut asset_2_reanchored = asset_2.clone(); + assert!(asset_2_reanchored.reanchor(&dest, &reanchor_context).is_ok()); + assert_eq!(asset_2_reanchored, (Location::new(0, []), 10).into()); + + let asset_3: Asset = (Location::new(1, [Parachain(1000)]), 10).into(); + let mut asset_3_reanchored = asset_3.clone(); + assert!(asset_3_reanchored.reanchor(&dest, &reanchor_context).is_ok()); + assert_eq!(asset_3_reanchored, (Location::new(0, [Parachain(1000)]), 10).into()); + + let mut assets: Assets = vec![asset_1.clone(), asset_2.clone(), asset_3.clone()].into(); + assert_eq!(assets.clone(), vec![asset_1.clone(), asset_2.clone(), asset_3.clone()].into()); + + // decoding respects limits and sorting + assert!(assets.using_encoded(|mut enc| Assets::decode(&mut enc).map(|_| ())).is_ok()); + + assert!(assets.reanchor(&dest, &reanchor_context).is_ok()); + assert_eq!(assets.0, vec![asset_2_reanchored, asset_3_reanchored, asset_1_reanchored]); + + // decoding respects limits and sorting + assert!(assets.using_encoded(|mut enc| Assets::decode(&mut enc).map(|_| ())).is_ok()); + } + + #[test] + fn prepend_preserves_sorting() { + use super::*; + use alloc::vec; + + let prefix = Location::new(0, [Parachain(1000)]); + + let asset_1: Asset = (Location::new(0, [PalletInstance(50), GeneralIndex(1)]), 10).into(); + let mut asset_1_prepended = asset_1.clone(); + assert!(asset_1_prepended.prepend_with(&prefix).is_ok()); + // changes interior X2->X3 + assert_eq!( + asset_1_prepended, + (Location::new(0, [Parachain(1000), PalletInstance(50), GeneralIndex(1)]), 10).into() + ); + + let asset_2: Asset = (Location::new(1, [PalletInstance(50), GeneralIndex(1)]), 10).into(); + let mut asset_2_prepended = asset_2.clone(); + assert!(asset_2_prepended.prepend_with(&prefix).is_ok()); + // changes parent + assert_eq!( + asset_2_prepended, + (Location::new(0, [PalletInstance(50), GeneralIndex(1)]), 10).into() + ); + + let asset_3: Asset = (Location::new(2, [PalletInstance(50), GeneralIndex(1)]), 10).into(); + let mut asset_3_prepended = asset_3.clone(); + assert!(asset_3_prepended.prepend_with(&prefix).is_ok()); + // changes parent + assert_eq!( + asset_3_prepended, + (Location::new(1, [PalletInstance(50), GeneralIndex(1)]), 10).into() + ); + + // `From` impl does sorting. + let mut assets: Assets = vec![asset_1, asset_2, asset_3].into(); + // decoding respects limits and sorting + assert!(assets.using_encoded(|mut enc| Assets::decode(&mut enc).map(|_| ())).is_ok()); + + // let's do `prepend_with` + assert!(assets.prepend_with(&prefix).is_ok()); + assert_eq!(assets.0, vec![asset_2_prepended, asset_1_prepended, asset_3_prepended]); + + // decoding respects limits and sorting + assert!(assets.using_encoded(|mut enc| Assets::decode(&mut enc).map(|_| ())).is_ok()); + } + + #[test] + fn decoding_respects_limit() { + use super::*; + + // Having lots of one asset will work since they are deduplicated + let lots_of_one_asset: Assets = + vec![(GeneralIndex(1), 1u128).into(); MAX_ITEMS_IN_ASSETS + 1].into(); + let encoded = lots_of_one_asset.encode(); + assert!(Assets::decode(&mut &encoded[..]).is_ok()); + + // Fewer assets than the limit works + let mut few_assets: Assets = Vec::new().into(); + for i in 0..MAX_ITEMS_IN_ASSETS { + few_assets.push((GeneralIndex(i as u128), 1u128).into()); + } + let encoded = few_assets.encode(); + assert!(Assets::decode(&mut &encoded[..]).is_ok()); + + // Having lots of different assets will not work + let mut too_many_different_assets: Assets = Vec::new().into(); + for i in 0..MAX_ITEMS_IN_ASSETS + 1 { + too_many_different_assets.push((GeneralIndex(i as u128), 1u128).into()); + } + let encoded = too_many_different_assets.encode(); + assert!(Assets::decode(&mut &encoded[..]).is_err()); + } +} diff --git a/polkadot/xcm/src/v5/junction.rs b/polkadot/xcm/src/v5/junction.rs new file mode 100644 index 000000000000..952b61cd9ffe --- /dev/null +++ b/polkadot/xcm/src/v5/junction.rs @@ -0,0 +1,321 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Support data structures for `Location`, primarily the `Junction` datatype. + +use super::Location; +pub use crate::v4::{BodyId, BodyPart}; +use crate::{ + v4::{Junction as OldJunction, NetworkId as OldNetworkId}, + VersionedLocation, +}; +use bounded_collections::{BoundedSlice, BoundedVec, ConstU32}; +use codec::{self, Decode, Encode, MaxEncodedLen}; +use hex_literal::hex; +use scale_info::TypeInfo; +use serde::{Deserialize, Serialize}; + +/// A single item in a path to describe the relative location of a consensus system. +/// +/// Each item assumes a pre-existing location as its context and is defined in terms of it. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + Serialize, + Deserialize, +)] +pub enum Junction { + /// An indexed parachain belonging to and operated by the context. + /// + /// Generally used when the context is a Polkadot Relay-chain. + Parachain(#[codec(compact)] u32), + /// A 32-byte identifier for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// Generally used when the context is a Substrate-based chain. + AccountId32 { network: Option, id: [u8; 32] }, + /// An 8-byte index for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// May be used when the context is a Frame-based chain and includes e.g. an indices pallet. + AccountIndex64 { + network: Option, + #[codec(compact)] + index: u64, + }, + /// A 20-byte identifier for an account of a specific network that is respected as a sovereign + /// endpoint within the context. + /// + /// May be used when the context is an Ethereum or Bitcoin chain or smart-contract. + AccountKey20 { network: Option, key: [u8; 20] }, + /// An instanced, indexed pallet that forms a constituent part of the context. + /// + /// Generally used when the context is a Frame-based chain. + PalletInstance(u8), + /// A non-descript index within the context location. + /// + /// Usage will vary widely owing to its generality. + /// + /// NOTE: Try to avoid using this and instead use a more specific item. + GeneralIndex(#[codec(compact)] u128), + /// A nondescript array datum, 32 bytes, acting as a key within the context + /// location. + /// + /// Usage will vary widely owing to its generality. + /// + /// NOTE: Try to avoid using this and instead use a more specific item. + // Note this is implemented as an array with a length rather than using `BoundedVec` owing to + // the bound for `Copy`. + GeneralKey { length: u8, data: [u8; 32] }, + /// The unambiguous child. + /// + /// Not currently used except as a fallback when deriving context. + OnlyChild, + /// A pluralistic body existing within consensus. + /// + /// Typical to be used to represent a governance origin of a chain, but could in principle be + /// used to represent things such as multisigs also. + Plurality { id: BodyId, part: BodyPart }, + /// A global network capable of externalizing its own consensus. This is not generally + /// meaningful outside of the universal level. + GlobalConsensus(NetworkId), +} + +/// The genesis hash of the Westend testnet. Used to identify it. +pub const WESTEND_GENESIS_HASH: [u8; 32] = + hex!["e143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e"]; + +/// The genesis hash of the Rococo testnet. Used to identify it. +pub const ROCOCO_GENESIS_HASH: [u8; 32] = + hex!["6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e"]; + +/// Dummy genesis hash used instead of defunct networks like Wococo (and soon Rococo). +pub const DUMMY_GENESIS_HASH: [u8; 32] = [0; 32]; + +/// A global identifier of a data structure existing within consensus. +/// +/// Maintenance note: Networks with global consensus and which are practically bridgeable within the +/// Polkadot ecosystem are given preference over explicit naming in this enumeration. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + Serialize, + Deserialize, +)] +pub enum NetworkId { + /// Network specified by the first 32 bytes of its genesis block. + ByGenesis([u8; 32]), + /// Network defined by the first 32-bytes of the hash and number of some block it contains. + ByFork { block_number: u64, block_hash: [u8; 32] }, + /// The Polkadot mainnet Relay-chain. + Polkadot, + /// The Kusama canary-net Relay-chain. + Kusama, + /// An Ethereum network specified by its chain ID. + Ethereum { + /// The EIP-155 chain ID. + #[codec(compact)] + chain_id: u64, + }, + /// The Bitcoin network, including hard-forks supported by Bitcoin Core development team. + BitcoinCore, + /// The Bitcoin network, including hard-forks supported by Bitcoin Cash developers. + BitcoinCash, + /// The Polkadot Bulletin chain. + PolkadotBulletin, +} + +impl From for Option { + fn from(old: OldNetworkId) -> Self { + Some(NetworkId::from(old)) + } +} + +impl From for NetworkId { + fn from(old: OldNetworkId) -> Self { + use OldNetworkId::*; + match old { + ByGenesis(hash) => Self::ByGenesis(hash), + ByFork { block_number, block_hash } => Self::ByFork { block_number, block_hash }, + Polkadot => Self::Polkadot, + Kusama => Self::Kusama, + Westend => Self::ByGenesis(WESTEND_GENESIS_HASH), + Rococo => Self::ByGenesis(ROCOCO_GENESIS_HASH), + Wococo => Self::ByGenesis(DUMMY_GENESIS_HASH), + Ethereum { chain_id } => Self::Ethereum { chain_id }, + BitcoinCore => Self::BitcoinCore, + BitcoinCash => Self::BitcoinCash, + PolkadotBulletin => Self::PolkadotBulletin, + } + } +} + +impl From for Junction { + fn from(n: NetworkId) -> Self { + Self::GlobalConsensus(n) + } +} + +impl From<[u8; 32]> for Junction { + fn from(id: [u8; 32]) -> Self { + Self::AccountId32 { network: None, id } + } +} + +impl From>> for Junction { + fn from(key: BoundedVec>) -> Self { + key.as_bounded_slice().into() + } +} + +impl<'a> From>> for Junction { + fn from(key: BoundedSlice<'a, u8, ConstU32<32>>) -> Self { + let mut data = [0u8; 32]; + data[..key.len()].copy_from_slice(&key[..]); + Self::GeneralKey { length: key.len() as u8, data } + } +} + +impl<'a> TryFrom<&'a Junction> for BoundedSlice<'a, u8, ConstU32<32>> { + type Error = (); + fn try_from(key: &'a Junction) -> Result { + match key { + Junction::GeneralKey { length, data } => + BoundedSlice::try_from(&data[..data.len().min(*length as usize)]).map_err(|_| ()), + _ => Err(()), + } + } +} + +impl From<[u8; 20]> for Junction { + fn from(key: [u8; 20]) -> Self { + Self::AccountKey20 { network: None, key } + } +} + +impl From for Junction { + fn from(index: u64) -> Self { + Self::AccountIndex64 { network: None, index } + } +} + +impl From for Junction { + fn from(id: u128) -> Self { + Self::GeneralIndex(id) + } +} + +impl TryFrom for Junction { + type Error = (); + fn try_from(value: OldJunction) -> Result { + use OldJunction::*; + Ok(match value { + Parachain(id) => Self::Parachain(id), + AccountId32 { network: maybe_network, id } => + Self::AccountId32 { network: maybe_network.map(|network| network.into()), id }, + AccountIndex64 { network: maybe_network, index } => + Self::AccountIndex64 { network: maybe_network.map(|network| network.into()), index }, + AccountKey20 { network: maybe_network, key } => + Self::AccountKey20 { network: maybe_network.map(|network| network.into()), key }, + PalletInstance(index) => Self::PalletInstance(index), + GeneralIndex(id) => Self::GeneralIndex(id), + GeneralKey { length, data } => Self::GeneralKey { length, data }, + OnlyChild => Self::OnlyChild, + Plurality { id, part } => Self::Plurality { id, part }, + GlobalConsensus(network) => Self::GlobalConsensus(network.into()), + }) + } +} + +impl Junction { + /// Convert `self` into a `Location` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub fn into_location(self) -> Location { + Location::new(0, [self]) + } + + /// Convert `self` into a `Location` containing `n` parents. + /// + /// Similar to `Self::into_location`, with the added ability to specify the number of parent + /// junctions. + pub fn into_exterior(self, n: u8) -> Location { + Location::new(n, [self]) + } + + /// Convert `self` into a `VersionedLocation` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub fn into_versioned(self) -> VersionedLocation { + self.into_location().into_versioned() + } + + /// Remove the `NetworkId` value. + pub fn remove_network_id(&mut self) { + use Junction::*; + match self { + AccountId32 { ref mut network, .. } | + AccountIndex64 { ref mut network, .. } | + AccountKey20 { ref mut network, .. } => *network = None, + _ => {}, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + #[test] + fn junction_round_trip_works() { + let j = Junction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + + let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + + let j = Junction::from(BoundedVec::try_from(vec![1u8, 2, 3, 4]).unwrap()); + let k = Junction::try_from(OldJunction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + let s: BoundedSlice<_, _> = (&k).try_into().unwrap(); + assert_eq!(s, &[1u8, 2, 3, 4][..]); + + let j = OldJunction::GeneralKey { length: 32, data: [1u8; 32] }; + let k = OldJunction::try_from(Junction::try_from(j).unwrap()).unwrap(); + assert_eq!(j, k); + } +} diff --git a/polkadot/xcm/src/v5/junctions.rs b/polkadot/xcm/src/v5/junctions.rs new file mode 100644 index 000000000000..dc93c541d19d --- /dev/null +++ b/polkadot/xcm/src/v5/junctions.rs @@ -0,0 +1,723 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! XCM `Junctions`/`InteriorLocation` datatype. + +use super::{Junction, Location, NetworkId}; +use alloc::sync::Arc; +use codec::{Decode, Encode, MaxEncodedLen}; +use core::{mem, ops::Range, result}; +use scale_info::TypeInfo; + +/// Maximum number of `Junction`s that a `Junctions` can contain. +pub(crate) const MAX_JUNCTIONS: usize = 8; + +/// Non-parent junctions that can be constructed, up to the length of 8. This specific `Junctions` +/// implementation uses a Rust `enum` in order to make pattern matching easier. +/// +/// Parent junctions cannot be constructed with this type. Refer to `Location` for +/// instructions on constructing parent junctions. +#[derive( + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + Debug, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub enum Junctions { + /// The interpreting consensus system. + Here, + /// A relative path comprising 1 junction. + X1(Arc<[Junction; 1]>), + /// A relative path comprising 2 junctions. + X2(Arc<[Junction; 2]>), + /// A relative path comprising 3 junctions. + X3(Arc<[Junction; 3]>), + /// A relative path comprising 4 junctions. + X4(Arc<[Junction; 4]>), + /// A relative path comprising 5 junctions. + X5(Arc<[Junction; 5]>), + /// A relative path comprising 6 junctions. + X6(Arc<[Junction; 6]>), + /// A relative path comprising 7 junctions. + X7(Arc<[Junction; 7]>), + /// A relative path comprising 8 junctions. + X8(Arc<[Junction; 8]>), +} + +macro_rules! impl_junctions { + ($count:expr, $variant:ident) => { + impl From<[Junction; $count]> for Junctions { + fn from(junctions: [Junction; $count]) -> Self { + Self::$variant(Arc::new(junctions)) + } + } + impl PartialEq<[Junction; $count]> for Junctions { + fn eq(&self, rhs: &[Junction; $count]) -> bool { + self.as_slice() == rhs + } + } + }; +} + +impl_junctions!(1, X1); +impl_junctions!(2, X2); +impl_junctions!(3, X3); +impl_junctions!(4, X4); +impl_junctions!(5, X5); +impl_junctions!(6, X6); +impl_junctions!(7, X7); +impl_junctions!(8, X8); + +pub struct JunctionsIterator { + junctions: Junctions, + range: Range, +} + +impl Iterator for JunctionsIterator { + type Item = Junction; + fn next(&mut self) -> Option { + self.junctions.at(self.range.next()?).cloned() + } +} + +impl DoubleEndedIterator for JunctionsIterator { + fn next_back(&mut self) -> Option { + self.junctions.at(self.range.next_back()?).cloned() + } +} + +pub struct JunctionsRefIterator<'a> { + junctions: &'a Junctions, + range: Range, +} + +impl<'a> Iterator for JunctionsRefIterator<'a> { + type Item = &'a Junction; + fn next(&mut self) -> Option<&'a Junction> { + self.junctions.at(self.range.next()?) + } +} + +impl<'a> DoubleEndedIterator for JunctionsRefIterator<'a> { + fn next_back(&mut self) -> Option<&'a Junction> { + self.junctions.at(self.range.next_back()?) + } +} +impl<'a> IntoIterator for &'a Junctions { + type Item = &'a Junction; + type IntoIter = JunctionsRefIterator<'a>; + fn into_iter(self) -> Self::IntoIter { + JunctionsRefIterator { junctions: self, range: 0..self.len() } + } +} + +impl IntoIterator for Junctions { + type Item = Junction; + type IntoIter = JunctionsIterator; + fn into_iter(self) -> Self::IntoIter { + JunctionsIterator { range: 0..self.len(), junctions: self } + } +} + +impl Junctions { + /// Convert `self` into a `Location` containing 0 parents. + /// + /// Similar to `Into::into`, except that this method can be used in a const evaluation context. + pub const fn into_location(self) -> Location { + Location { parents: 0, interior: self } + } + + /// Convert `self` into a `Location` containing `n` parents. + /// + /// Similar to `Self::into_location`, with the added ability to specify the number of parent + /// junctions. + pub const fn into_exterior(self, n: u8) -> Location { + Location { parents: n, interior: self } + } + + /// Casts `self` into a slice containing `Junction`s. + pub fn as_slice(&self) -> &[Junction] { + match self { + Junctions::Here => &[], + Junctions::X1(ref a) => &a[..], + Junctions::X2(ref a) => &a[..], + Junctions::X3(ref a) => &a[..], + Junctions::X4(ref a) => &a[..], + Junctions::X5(ref a) => &a[..], + Junctions::X6(ref a) => &a[..], + Junctions::X7(ref a) => &a[..], + Junctions::X8(ref a) => &a[..], + } + } + + /// Casts `self` into a mutable slice containing `Junction`s. + pub fn as_slice_mut(&mut self) -> &mut [Junction] { + match self { + Junctions::Here => &mut [], + Junctions::X1(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X2(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X3(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X4(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X5(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X6(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X7(ref mut a) => &mut Arc::make_mut(a)[..], + Junctions::X8(ref mut a) => &mut Arc::make_mut(a)[..], + } + } + + /// Remove the `NetworkId` value in any `Junction`s. + pub fn remove_network_id(&mut self) { + self.for_each_mut(Junction::remove_network_id); + } + + /// Treating `self` as the universal context, return the location of the local consensus system + /// from the point of view of the given `target`. + pub fn invert_target(&self, target: &Location) -> Result { + let mut itself = self.clone(); + let mut junctions = Self::Here; + for _ in 0..target.parent_count() { + junctions = junctions + .pushed_front_with(itself.take_last().unwrap_or(Junction::OnlyChild)) + .map_err(|_| ())?; + } + let parents = target.interior().len() as u8; + Ok(Location::new(parents, junctions)) + } + + /// Execute a function `f` on every junction. We use this since we cannot implement a mutable + /// `Iterator` without unsafe code. + pub fn for_each_mut(&mut self, x: impl FnMut(&mut Junction)) { + self.as_slice_mut().iter_mut().for_each(x) + } + + /// Extract the network ID treating this value as a universal location. + /// + /// This will return an `Err` if the first item is not a `GlobalConsensus`, which would indicate + /// that this value is not a universal location. + pub fn global_consensus(&self) -> Result { + if let Some(Junction::GlobalConsensus(network)) = self.first() { + Ok(*network) + } else { + Err(()) + } + } + + /// Extract the network ID and the interior consensus location, treating this value as a + /// universal location. + /// + /// This will return an `Err` if the first item is not a `GlobalConsensus`, which would indicate + /// that this value is not a universal location. + pub fn split_global(self) -> Result<(NetworkId, Junctions), ()> { + match self.split_first() { + (location, Some(Junction::GlobalConsensus(network))) => Ok((network, location)), + _ => return Err(()), + } + } + + /// Treat `self` as a universal location and the context of `relative`, returning the universal + /// location of relative. + /// + /// This will return an error if `relative` has as many (or more) parents than there are + /// junctions in `self`, implying that relative refers into a different global consensus. + pub fn within_global(mut self, relative: Location) -> Result { + if self.len() <= relative.parent_count() as usize { + return Err(()) + } + for _ in 0..relative.parent_count() { + self.take_last(); + } + for j in relative.interior() { + self.push(*j).map_err(|_| ())?; + } + Ok(self) + } + + /// Consumes `self` and returns how `viewer` would address it locally. + pub fn relative_to(mut self, viewer: &Junctions) -> Location { + let mut i = 0; + while match (self.first(), viewer.at(i)) { + (Some(x), Some(y)) => x == y, + _ => false, + } { + self = self.split_first().0; + // NOTE: Cannot overflow as loop can only iterate at most `MAX_JUNCTIONS` times. + i += 1; + } + // AUDIT NOTES: + // - above loop ensures that `i <= viewer.len()`. + // - `viewer.len()` is at most `MAX_JUNCTIONS`, so won't overflow a `u8`. + Location::new((viewer.len() - i) as u8, self) + } + + /// Returns first junction, or `None` if the location is empty. + pub fn first(&self) -> Option<&Junction> { + self.as_slice().first() + } + + /// Returns last junction, or `None` if the location is empty. + pub fn last(&self) -> Option<&Junction> { + self.as_slice().last() + } + + /// Splits off the first junction, returning the remaining suffix (first item in tuple) and the + /// first element (second item in tuple) or `None` if it was empty. + pub fn split_first(self) -> (Junctions, Option) { + match self { + Junctions::Here => (Junctions::Here, None), + Junctions::X1(xs) => { + let [a] = *xs; + (Junctions::Here, Some(a)) + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + ([b].into(), Some(a)) + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + ([b, c].into(), Some(a)) + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + ([b, c, d].into(), Some(a)) + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + ([b, c, d, e].into(), Some(a)) + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + ([b, c, d, e, f].into(), Some(a)) + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + ([b, c, d, e, f, g].into(), Some(a)) + }, + Junctions::X8(xs) => { + let [a, b, c, d, e, f, g, h] = *xs; + ([b, c, d, e, f, g, h].into(), Some(a)) + }, + } + } + + /// Splits off the last junction, returning the remaining prefix (first item in tuple) and the + /// last element (second item in tuple) or `None` if it was empty. + pub fn split_last(self) -> (Junctions, Option) { + match self { + Junctions::Here => (Junctions::Here, None), + Junctions::X1(xs) => { + let [a] = *xs; + (Junctions::Here, Some(a)) + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + ([a].into(), Some(b)) + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + ([a, b].into(), Some(c)) + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + ([a, b, c].into(), Some(d)) + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + ([a, b, c, d].into(), Some(e)) + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + ([a, b, c, d, e].into(), Some(f)) + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + ([a, b, c, d, e, f].into(), Some(g)) + }, + Junctions::X8(xs) => { + let [a, b, c, d, e, f, g, h] = *xs; + ([a, b, c, d, e, f, g].into(), Some(h)) + }, + } + } + + /// Removes the first element from `self`, returning it (or `None` if it was empty). + pub fn take_first(&mut self) -> Option { + let mut d = Junctions::Here; + mem::swap(&mut *self, &mut d); + let (tail, head) = d.split_first(); + *self = tail; + head + } + + /// Removes the last element from `self`, returning it (or `None` if it was empty). + pub fn take_last(&mut self) -> Option { + let mut d = Junctions::Here; + mem::swap(&mut *self, &mut d); + let (head, tail) = d.split_last(); + *self = head; + tail + } + + /// Mutates `self` to be appended with `new` or returns an `Err` with `new` if would overflow. + pub fn push(&mut self, new: impl Into) -> result::Result<(), Junction> { + let new = new.into(); + let mut dummy = Junctions::Here; + mem::swap(self, &mut dummy); + match dummy.pushed_with(new) { + Ok(s) => { + *self = s; + Ok(()) + }, + Err((s, j)) => { + *self = s; + Err(j) + }, + } + } + + /// Mutates `self` to be prepended with `new` or returns an `Err` with `new` if would overflow. + pub fn push_front(&mut self, new: impl Into) -> result::Result<(), Junction> { + let new = new.into(); + let mut dummy = Junctions::Here; + mem::swap(self, &mut dummy); + match dummy.pushed_front_with(new) { + Ok(s) => { + *self = s; + Ok(()) + }, + Err((s, j)) => { + *self = s; + Err(j) + }, + } + } + + /// Consumes `self` and returns a `Junctions` suffixed with `new`, or an `Err` with the + /// original value of `self` and `new` in case of overflow. + pub fn pushed_with(self, new: impl Into) -> result::Result { + let new = new.into(); + Ok(match self { + Junctions::Here => [new].into(), + Junctions::X1(xs) => { + let [a] = *xs; + [a, new].into() + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + [a, b, new].into() + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + [a, b, c, new].into() + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + [a, b, c, d, new].into() + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + [a, b, c, d, e, new].into() + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + [a, b, c, d, e, f, new].into() + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + [a, b, c, d, e, f, g, new].into() + }, + s => Err((s, new))?, + }) + } + + /// Consumes `self` and returns a `Junctions` prefixed with `new`, or an `Err` with the + /// original value of `self` and `new` in case of overflow. + pub fn pushed_front_with( + self, + new: impl Into, + ) -> result::Result { + let new = new.into(); + Ok(match self { + Junctions::Here => [new].into(), + Junctions::X1(xs) => { + let [a] = *xs; + [new, a].into() + }, + Junctions::X2(xs) => { + let [a, b] = *xs; + [new, a, b].into() + }, + Junctions::X3(xs) => { + let [a, b, c] = *xs; + [new, a, b, c].into() + }, + Junctions::X4(xs) => { + let [a, b, c, d] = *xs; + [new, a, b, c, d].into() + }, + Junctions::X5(xs) => { + let [a, b, c, d, e] = *xs; + [new, a, b, c, d, e].into() + }, + Junctions::X6(xs) => { + let [a, b, c, d, e, f] = *xs; + [new, a, b, c, d, e, f].into() + }, + Junctions::X7(xs) => { + let [a, b, c, d, e, f, g] = *xs; + [new, a, b, c, d, e, f, g].into() + }, + s => Err((s, new))?, + }) + } + + /// Mutate `self` so that it is suffixed with `suffix`. + /// + /// Does not modify `self` and returns `Err` with `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions, Junction::*, Location}; + /// # fn main() { + /// let mut m = Junctions::from([Parachain(21)]); + /// assert_eq!(m.append_with([PalletInstance(3)]), Ok(())); + /// assert_eq!(m, [Parachain(21), PalletInstance(3)]); + /// # } + /// ``` + pub fn append_with(&mut self, suffix: impl Into) -> Result<(), Junctions> { + let suffix = suffix.into(); + if self.len().saturating_add(suffix.len()) > MAX_JUNCTIONS { + return Err(suffix) + } + for j in suffix.into_iter() { + self.push(j).expect("Already checked the sum of the len()s; qed") + } + Ok(()) + } + + /// Returns the number of junctions in `self`. + pub fn len(&self) -> usize { + self.as_slice().len() + } + + /// Returns the junction at index `i`, or `None` if the location doesn't contain that many + /// elements. + pub fn at(&self, i: usize) -> Option<&Junction> { + self.as_slice().get(i) + } + + /// Returns a mutable reference to the junction at index `i`, or `None` if the location doesn't + /// contain that many elements. + pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { + self.as_slice_mut().get_mut(i) + } + + /// Returns a reference iterator over the junctions. + pub fn iter(&self) -> JunctionsRefIterator { + JunctionsRefIterator { junctions: self, range: 0..self.len() } + } + + /// Ensures that self begins with `prefix` and that it has a single `Junction` item following. + /// If so, returns a reference to this `Junction` item. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions, Junction::*}; + /// # fn main() { + /// let mut m = Junctions::from([Parachain(2), PalletInstance(3), OnlyChild]); + /// assert_eq!(m.match_and_split(&[Parachain(2), PalletInstance(3)].into()), Some(&OnlyChild)); + /// assert_eq!(m.match_and_split(&[Parachain(2)].into()), None); + /// # } + /// ``` + pub fn match_and_split(&self, prefix: &Junctions) -> Option<&Junction> { + if prefix.len() + 1 != self.len() { + return None + } + for i in 0..prefix.len() { + if prefix.at(i) != self.at(i) { + return None + } + } + return self.at(prefix.len()) + } + + pub fn starts_with(&self, prefix: &Junctions) -> bool { + prefix.len() <= self.len() && prefix.iter().zip(self.iter()).all(|(x, y)| x == y) + } +} + +impl TryFrom for Junctions { + type Error = Location; + fn try_from(x: Location) -> result::Result { + if x.parent_count() > 0 { + Err(x) + } else { + Ok(x.interior().clone()) + } + } +} + +impl> From for Junctions { + fn from(x: T) -> Self { + [x.into()].into() + } +} + +impl From<[Junction; 0]> for Junctions { + fn from(_: [Junction; 0]) -> Self { + Self::Here + } +} + +impl From<()> for Junctions { + fn from(_: ()) -> Self { + Self::Here + } +} + +xcm_procedural::impl_conversion_functions_for_junctions_v5!(); + +#[cfg(test)] +mod tests { + use super::{super::prelude::*, *}; + + #[test] + fn inverting_works() { + let context: InteriorLocation = (Parachain(1000), PalletInstance(42)).into(); + let target = (Parent, PalletInstance(69)).into(); + let expected = (Parent, PalletInstance(42)).into(); + let inverted = context.invert_target(&target).unwrap(); + assert_eq!(inverted, expected); + + let context: InteriorLocation = + (Parachain(1000), PalletInstance(42), GeneralIndex(1)).into(); + let target = (Parent, Parent, PalletInstance(69), GeneralIndex(2)).into(); + let expected = (Parent, Parent, PalletInstance(42), GeneralIndex(1)).into(); + let inverted = context.invert_target(&target).unwrap(); + assert_eq!(inverted, expected); + } + + #[test] + fn relative_to_works() { + use NetworkId::*; + assert_eq!( + Junctions::from([Polkadot.into()]).relative_to(&Junctions::from([Kusama.into()])), + (Parent, Polkadot).into() + ); + let base = Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1)]); + + // Ancestors. + assert_eq!(Here.relative_to(&base), (Parent, Parent, Parent).into()); + assert_eq!(Junctions::from([Kusama.into()]).relative_to(&base), (Parent, Parent).into()); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1)]).relative_to(&base), + (Parent,).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1)]).relative_to(&base), + Here.into() + ); + + // Ancestors with one child. + assert_eq!( + Junctions::from([Polkadot.into()]).relative_to(&base), + (Parent, Parent, Parent, Polkadot).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(2)]).relative_to(&base), + (Parent, Parent, Parachain(2)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(2)]).relative_to(&base), + (Parent, PalletInstance(2)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(1), [1u8; 32].into()]) + .relative_to(&base), + ([1u8; 32],).into() + ); + + // Ancestors with grandchildren. + assert_eq!( + Junctions::from([Polkadot.into(), Parachain(1)]).relative_to(&base), + (Parent, Parent, Parent, Polkadot, Parachain(1)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(2), PalletInstance(1)]).relative_to(&base), + (Parent, Parent, Parachain(2), PalletInstance(1)).into() + ); + assert_eq!( + Junctions::from([Kusama.into(), Parachain(1), PalletInstance(2), [1u8; 32].into()]) + .relative_to(&base), + (Parent, PalletInstance(2), [1u8; 32]).into() + ); + assert_eq!( + Junctions::from([ + Kusama.into(), + Parachain(1), + PalletInstance(1), + [1u8; 32].into(), + 1u128.into() + ]) + .relative_to(&base), + ([1u8; 32], 1u128).into() + ); + } + + #[test] + fn global_consensus_works() { + use NetworkId::*; + assert_eq!(Junctions::from([Polkadot.into()]).global_consensus(), Ok(Polkadot)); + assert_eq!(Junctions::from([Kusama.into(), 1u64.into()]).global_consensus(), Ok(Kusama)); + assert_eq!(Here.global_consensus(), Err(())); + assert_eq!(Junctions::from([1u64.into()]).global_consensus(), Err(())); + assert_eq!(Junctions::from([1u64.into(), Kusama.into()]).global_consensus(), Err(())); + } + + #[test] + fn test_conversion() { + use super::{Junction::*, NetworkId::*}; + let x: Junctions = GlobalConsensus(Polkadot).into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot)])); + let x: Junctions = Polkadot.into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot)])); + let x: Junctions = (Polkadot, Kusama).into(); + assert_eq!(x, Junctions::from([GlobalConsensus(Polkadot), GlobalConsensus(Kusama)])); + } + + #[test] + fn encode_decode_junctions_works() { + let original = Junctions::from([ + Polkadot.into(), + Kusama.into(), + 1u64.into(), + GlobalConsensus(Polkadot), + Parachain(123), + PalletInstance(45), + ]); + let encoded = original.encode(); + assert_eq!(encoded, &[6, 9, 2, 9, 3, 2, 0, 4, 9, 2, 0, 237, 1, 4, 45]); + let decoded = Junctions::decode(&mut &encoded[..]).unwrap(); + assert_eq!(decoded, original); + } +} diff --git a/polkadot/xcm/src/v5/location.rs b/polkadot/xcm/src/v5/location.rs new file mode 100644 index 000000000000..38e8ecdd15ca --- /dev/null +++ b/polkadot/xcm/src/v5/location.rs @@ -0,0 +1,755 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! XCM `Location` datatype. + +use super::{traits::Reanchorable, Junction, Junctions}; +use crate::{v4::Location as OldLocation, VersionedLocation}; +use codec::{Decode, Encode, MaxEncodedLen}; +use core::result; +use scale_info::TypeInfo; + +/// A relative path between state-bearing consensus systems. +/// +/// A location in a consensus system is defined as an *isolatable state machine* held within global +/// consensus. The location in question need not have a sophisticated consensus algorithm of its +/// own; a single account within Ethereum, for example, could be considered a location. +/// +/// A very-much non-exhaustive list of types of location include: +/// - A (normal, layer-1) block chain, e.g. the Bitcoin mainnet or a parachain. +/// - A layer-0 super-chain, e.g. the Polkadot Relay chain. +/// - A layer-2 smart contract, e.g. an ERC-20 on Ethereum. +/// - A logical functional component of a chain, e.g. a single instance of a pallet on a Frame-based +/// Substrate chain. +/// - An account. +/// +/// A `Location` is a *relative identifier*, meaning that it can only be used to define the +/// relative path between two locations, and cannot generally be used to refer to a location +/// universally. It is comprised of an integer number of parents specifying the number of times to +/// "escape" upwards into the containing consensus system and then a number of *junctions*, each +/// diving down and specifying some interior portion of state (which may be considered a +/// "sub-consensus" system). +/// +/// This specific `Location` implementation uses a `Junctions` datatype which is a Rust `enum` +/// in order to make pattern matching easier. There are occasions where it is important to ensure +/// that a value is strictly an interior location, in those cases, `Junctions` may be used. +/// +/// The `Location` value of `Null` simply refers to the interpreting consensus system. +#[derive( + Clone, + Decode, + Encode, + Eq, + PartialEq, + Ord, + PartialOrd, + Debug, + TypeInfo, + MaxEncodedLen, + serde::Serialize, + serde::Deserialize, +)] +pub struct Location { + /// The number of parent junctions at the beginning of this `Location`. + pub parents: u8, + /// The interior (i.e. non-parent) junctions that this `Location` contains. + pub interior: Junctions, +} + +impl Default for Location { + fn default() -> Self { + Self::here() + } +} + +/// A relative location which is constrained to be an interior location of the context. +/// +/// See also `Location`. +pub type InteriorLocation = Junctions; + +impl Location { + /// Creates a new `Location` with the given number of parents and interior junctions. + pub fn new(parents: u8, interior: impl Into) -> Location { + Location { parents, interior: interior.into() } + } + + /// Consume `self` and return the equivalent `VersionedLocation` value. + pub const fn into_versioned(self) -> VersionedLocation { + VersionedLocation::V5(self) + } + + /// Creates a new `Location` with 0 parents and a `Here` interior. + /// + /// The resulting `Location` can be interpreted as the "current consensus system". + pub const fn here() -> Location { + Location { parents: 0, interior: Junctions::Here } + } + + /// Creates a new `Location` which evaluates to the parent context. + pub const fn parent() -> Location { + Location { parents: 1, interior: Junctions::Here } + } + + /// Creates a new `Location` with `parents` and an empty (`Here`) interior. + pub const fn ancestor(parents: u8) -> Location { + Location { parents, interior: Junctions::Here } + } + + /// Whether the `Location` has no parents and has a `Here` interior. + pub fn is_here(&self) -> bool { + self.parents == 0 && self.interior.len() == 0 + } + + /// Remove the `NetworkId` value in any interior `Junction`s. + pub fn remove_network_id(&mut self) { + self.interior.remove_network_id(); + } + + /// Return a reference to the interior field. + pub fn interior(&self) -> &Junctions { + &self.interior + } + + /// Return a mutable reference to the interior field. + pub fn interior_mut(&mut self) -> &mut Junctions { + &mut self.interior + } + + /// Returns the number of `Parent` junctions at the beginning of `self`. + pub const fn parent_count(&self) -> u8 { + self.parents + } + + /// Returns the parent count and the interior [`Junctions`] as a tuple. + /// + /// To be used when pattern matching, for example: + /// + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location}; + /// fn get_parachain_id(loc: &Location) -> Option { + /// match loc.unpack() { + /// (0, [Parachain(id)]) => Some(*id), + /// _ => None + /// } + /// } + /// ``` + pub fn unpack(&self) -> (u8, &[Junction]) { + (self.parents, self.interior.as_slice()) + } + + /// Returns boolean indicating whether `self` contains only the specified amount of + /// parents and no interior junctions. + pub const fn contains_parents_only(&self, count: u8) -> bool { + matches!(self.interior, Junctions::Here) && self.parents == count + } + + /// Returns the number of parents and junctions in `self`. + pub fn len(&self) -> usize { + self.parent_count() as usize + self.interior.len() + } + + /// Returns the first interior junction, or `None` if the location is empty or contains only + /// parents. + pub fn first_interior(&self) -> Option<&Junction> { + self.interior.first() + } + + /// Returns last junction, or `None` if the location is empty or contains only parents. + pub fn last(&self) -> Option<&Junction> { + self.interior.last() + } + + /// Splits off the first interior junction, returning the remaining suffix (first item in tuple) + /// and the first element (second item in tuple) or `None` if it was empty. + pub fn split_first_interior(self) -> (Location, Option) { + let Location { parents, interior: junctions } = self; + let (suffix, first) = junctions.split_first(); + let location = Location { parents, interior: suffix }; + (location, first) + } + + /// Splits off the last interior junction, returning the remaining prefix (first item in tuple) + /// and the last element (second item in tuple) or `None` if it was empty or if `self` only + /// contains parents. + pub fn split_last_interior(self) -> (Location, Option) { + let Location { parents, interior: junctions } = self; + let (prefix, last) = junctions.split_last(); + let location = Location { parents, interior: prefix }; + (location, last) + } + + /// Mutates `self`, suffixing its interior junctions with `new`. Returns `Err` with `new` in + /// case of overflow. + pub fn push_interior(&mut self, new: impl Into) -> result::Result<(), Junction> { + self.interior.push(new) + } + + /// Mutates `self`, prefixing its interior junctions with `new`. Returns `Err` with `new` in + /// case of overflow. + pub fn push_front_interior( + &mut self, + new: impl Into, + ) -> result::Result<(), Junction> { + self.interior.push_front(new) + } + + /// Consumes `self` and returns a `Location` suffixed with `new`, or an `Err` with + /// the original value of `self` in case of overflow. + pub fn pushed_with_interior( + self, + new: impl Into, + ) -> result::Result { + match self.interior.pushed_with(new) { + Ok(i) => Ok(Location { interior: i, parents: self.parents }), + Err((i, j)) => Err((Location { interior: i, parents: self.parents }, j)), + } + } + + /// Consumes `self` and returns a `Location` prefixed with `new`, or an `Err` with the + /// original value of `self` in case of overflow. + pub fn pushed_front_with_interior( + self, + new: impl Into, + ) -> result::Result { + match self.interior.pushed_front_with(new) { + Ok(i) => Ok(Location { interior: i, parents: self.parents }), + Err((i, j)) => Err((Location { interior: i, parents: self.parents }, j)), + } + } + + /// Returns the junction at index `i`, or `None` if the location is a parent or if the location + /// does not contain that many elements. + pub fn at(&self, i: usize) -> Option<&Junction> { + let num_parents = self.parents as usize; + if i < num_parents { + return None + } + self.interior.at(i - num_parents) + } + + /// Returns a mutable reference to the junction at index `i`, or `None` if the location is a + /// parent or if it doesn't contain that many elements. + pub fn at_mut(&mut self, i: usize) -> Option<&mut Junction> { + let num_parents = self.parents as usize; + if i < num_parents { + return None + } + self.interior.at_mut(i - num_parents) + } + + /// Decrements the parent count by 1. + pub fn dec_parent(&mut self) { + self.parents = self.parents.saturating_sub(1); + } + + /// Removes the first interior junction from `self`, returning it + /// (or `None` if it was empty or if `self` contains only parents). + pub fn take_first_interior(&mut self) -> Option { + self.interior.take_first() + } + + /// Removes the last element from `interior`, returning it (or `None` if it was empty or if + /// `self` only contains parents). + pub fn take_last(&mut self) -> Option { + self.interior.take_last() + } + + /// Ensures that `self` has the same number of parents as `prefix`, its junctions begins with + /// the junctions of `prefix` and that it has a single `Junction` item following. + /// If so, returns a reference to this `Junction` item. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location}; + /// # fn main() { + /// let mut m = Location::new(1, [PalletInstance(3), OnlyChild]); + /// assert_eq!( + /// m.match_and_split(&Location::new(1, [PalletInstance(3)])), + /// Some(&OnlyChild), + /// ); + /// assert_eq!(m.match_and_split(&Location::new(1, Here)), None); + /// # } + /// ``` + pub fn match_and_split(&self, prefix: &Location) -> Option<&Junction> { + if self.parents != prefix.parents { + return None + } + self.interior.match_and_split(&prefix.interior) + } + + pub fn starts_with(&self, prefix: &Location) -> bool { + self.parents == prefix.parents && self.interior.starts_with(&prefix.interior) + } + + /// Mutate `self` so that it is suffixed with `suffix`. + /// + /// Does not modify `self` and returns `Err` with `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parachain(21), 69u64).into(); + /// assert_eq!(m.append_with((Parent, PalletInstance(3))), Ok(())); + /// assert_eq!(m, Location::new(1, [Parachain(21), PalletInstance(3)])); + /// # } + /// ``` + pub fn append_with(&mut self, suffix: impl Into) -> Result<(), Self> { + let prefix = core::mem::replace(self, suffix.into()); + match self.prepend_with(prefix) { + Ok(()) => Ok(()), + Err(prefix) => Err(core::mem::replace(self, prefix)), + } + } + + /// Consume `self` and return its value suffixed with `suffix`. + /// + /// Returns `Err` with the original value of `self` and `suffix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parachain(21), 69u64).into(); + /// let r = m.appended_with((Parent, PalletInstance(3))).unwrap(); + /// assert_eq!(r, Location::new(1, [Parachain(21), PalletInstance(3)])); + /// # } + /// ``` + pub fn appended_with(mut self, suffix: impl Into) -> Result { + match self.append_with(suffix) { + Ok(()) => Ok(self), + Err(suffix) => Err((self, suffix)), + } + } + + /// Mutate `self` so that it is prefixed with `prefix`. + /// + /// Does not modify `self` and returns `Err` with `prefix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let mut m: Location = (Parent, Parent, PalletInstance(3)).into(); + /// assert_eq!(m.prepend_with((Parent, Parachain(21), OnlyChild)), Ok(())); + /// assert_eq!(m, Location::new(1, [PalletInstance(3)])); + /// # } + /// ``` + pub fn prepend_with(&mut self, prefix: impl Into) -> Result<(), Self> { + // prefix self (suffix) + // P .. P I .. I p .. p i .. i + let mut prefix = prefix.into(); + let prepend_interior = prefix.interior.len().saturating_sub(self.parents as usize); + let final_interior = self.interior.len().saturating_add(prepend_interior); + if final_interior > super::junctions::MAX_JUNCTIONS { + return Err(prefix) + } + let suffix_parents = (self.parents as usize).saturating_sub(prefix.interior.len()); + let final_parents = (prefix.parents as usize).saturating_add(suffix_parents); + if final_parents > 255 { + return Err(prefix) + } + + // cancel out the final item on the prefix interior for one of the suffix's parents. + while self.parents > 0 && prefix.take_last().is_some() { + self.dec_parent(); + } + + // now we have either removed all suffix's parents or prefix interior. + // this means we can combine the prefix's and suffix's remaining parents/interior since + // we know that with at least one empty, the overall order will be respected: + // prefix self (suffix) + // P .. P (I) p .. p i .. i => P + p .. (no I) i + // -- or -- + // P .. P I .. I (p) i .. i => P (no p) .. I + i + + self.parents = self.parents.saturating_add(prefix.parents); + for j in prefix.interior.into_iter().rev() { + self.push_front_interior(j) + .expect("final_interior no greater than MAX_JUNCTIONS; qed"); + } + Ok(()) + } + + /// Consume `self` and return its value prefixed with `prefix`. + /// + /// Returns `Err` with the original value of `self` and `prefix` in case of overflow. + /// + /// # Example + /// ```rust + /// # use staging_xcm::v5::{Junctions::*, Junction::*, Location, Parent}; + /// # fn main() { + /// let m: Location = (Parent, Parent, PalletInstance(3)).into(); + /// let r = m.prepended_with((Parent, Parachain(21), OnlyChild)).unwrap(); + /// assert_eq!(r, Location::new(1, [PalletInstance(3)])); + /// # } + /// ``` + pub fn prepended_with(mut self, prefix: impl Into) -> Result { + match self.prepend_with(prefix) { + Ok(()) => Ok(self), + Err(prefix) => Err((self, prefix)), + } + } + + /// Remove any unneeded parents/junctions in `self` based on the given context it will be + /// interpreted in. + pub fn simplify(&mut self, context: &Junctions) { + if context.len() < self.parents as usize { + // Not enough context + return + } + while self.parents > 0 { + let maybe = context.at(context.len() - (self.parents as usize)); + match (self.interior.first(), maybe) { + (Some(i), Some(j)) if i == j => { + self.interior.take_first(); + self.parents -= 1; + }, + _ => break, + } + } + } + + /// Return the Location subsection identifying the chain that `self` points to. + pub fn chain_location(&self) -> Location { + let mut clone = self.clone(); + // start popping junctions until we reach chain identifier + while let Some(j) = clone.last() { + if matches!(j, Junction::Parachain(_) | Junction::GlobalConsensus(_)) { + // return chain subsection + return clone + } else { + (clone, _) = clone.split_last_interior(); + } + } + Location::new(clone.parents, Junctions::Here) + } +} + +impl Reanchorable for Location { + type Error = Self; + + /// Mutate `self` so that it represents the same location from the point of view of `target`. + /// The context of `self` is provided as `context`. + /// + /// Does not modify `self` in case of overflow. + fn reanchor(&mut self, target: &Location, context: &InteriorLocation) -> Result<(), ()> { + // TODO: https://github.com/paritytech/polkadot/issues/4489 Optimize this. + + // 1. Use our `context` to figure out how the `target` would address us. + let inverted_target = context.invert_target(target)?; + + // 2. Prepend `inverted_target` to `self` to get self's location from the perspective of + // `target`. + self.prepend_with(inverted_target).map_err(|_| ())?; + + // 3. Given that we know some of `target` context, ensure that any parents in `self` are + // strictly needed. + self.simplify(target.interior()); + + Ok(()) + } + + /// Consume `self` and return a new value representing the same location from the point of view + /// of `target`. The context of `self` is provided as `context`. + /// + /// Returns the original `self` in case of overflow. + fn reanchored(mut self, target: &Location, context: &InteriorLocation) -> Result { + match self.reanchor(target, context) { + Ok(()) => Ok(self), + Err(()) => Err(self), + } + } +} + +impl TryFrom for Option { + type Error = (); + fn try_from(value: OldLocation) -> result::Result { + Ok(Some(Location::try_from(value)?)) + } +} + +impl TryFrom for Location { + type Error = (); + fn try_from(x: OldLocation) -> result::Result { + Ok(Location { parents: x.parents, interior: x.interior.try_into()? }) + } +} + +/// A unit struct which can be converted into a `Location` of `parents` value 1. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct Parent; +impl From for Location { + fn from(_: Parent) -> Self { + Location { parents: 1, interior: Junctions::Here } + } +} + +/// A tuple struct which can be converted into a `Location` of `parents` value 1 with the inner +/// interior. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct ParentThen(pub Junctions); +impl From for Location { + fn from(ParentThen(interior): ParentThen) -> Self { + Location { parents: 1, interior } + } +} + +/// A unit struct which can be converted into a `Location` of the inner `parents` value. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct Ancestor(pub u8); +impl From for Location { + fn from(Ancestor(parents): Ancestor) -> Self { + Location { parents, interior: Junctions::Here } + } +} + +/// A unit struct which can be converted into a `Location` of the inner `parents` value and the +/// inner interior. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] +pub struct AncestorThen(pub u8, pub Interior); +impl> From> for Location { + fn from(AncestorThen(parents, interior): AncestorThen) -> Self { + Location { parents, interior: interior.into() } + } +} + +impl From<[u8; 32]> for Location { + fn from(bytes: [u8; 32]) -> Self { + let junction: Junction = bytes.into(); + junction.into() + } +} + +impl From for Location { + fn from(id: sp_runtime::AccountId32) -> Self { + Junction::AccountId32 { network: None, id: id.into() }.into() + } +} + +xcm_procedural::impl_conversion_functions_for_location_v5!(); + +#[cfg(test)] +mod tests { + use crate::v5::prelude::*; + use codec::{Decode, Encode}; + + #[test] + fn conversion_works() { + let x: Location = Parent.into(); + assert_eq!(x, Location { parents: 1, interior: Here }); + // let x: Location = (Parent,).into(); + // assert_eq!(x, Location { parents: 1, interior: Here }); + // let x: Location = (Parent, Parent).into(); + // assert_eq!(x, Location { parents: 2, interior: Here }); + let x: Location = (Parent, Parent, OnlyChild).into(); + assert_eq!(x, Location { parents: 2, interior: OnlyChild.into() }); + let x: Location = OnlyChild.into(); + assert_eq!(x, Location { parents: 0, interior: OnlyChild.into() }); + let x: Location = (OnlyChild,).into(); + assert_eq!(x, Location { parents: 0, interior: OnlyChild.into() }); + } + + #[test] + fn simplify_basic_works() { + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = (Parent, PalletInstance(42), GeneralIndex(69)).into(); + let context = [PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = (Parent, PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [OnlyChild, Parachain(1000), PalletInstance(42)].into(); + let expected = GeneralIndex(69).into(); + location.simplify(&context); + assert_eq!(location, expected); + } + + #[test] + fn simplify_incompatible_location_fails() { + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000), PalletInstance(42), GeneralIndex(42)].into(); + let expected = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + location.simplify(&context); + assert_eq!(location, expected); + + let mut location: Location = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + let context = [Parachain(1000)].into(); + let expected = + (Parent, Parent, Parachain(1000), PalletInstance(42), GeneralIndex(69)).into(); + location.simplify(&context); + assert_eq!(location, expected); + } + + #[test] + fn reanchor_works() { + let mut id: Location = (Parent, Parachain(1000), GeneralIndex(42)).into(); + let context = Parachain(2000).into(); + let target = (Parent, Parachain(1000)).into(); + let expected = GeneralIndex(42).into(); + id.reanchor(&target, &context).unwrap(); + assert_eq!(id, expected); + } + + #[test] + fn encode_and_decode_works() { + let m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + let encoded = m.encode(); + assert_eq!(encoded, [1, 2, 0, 168, 2, 0, 92].to_vec()); + let decoded = Location::decode(&mut &encoded[..]); + assert_eq!(decoded, Ok(m)); + } + + #[test] + fn match_and_split_works() { + let m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + assert_eq!(m.match_and_split(&Location { parents: 1, interior: Here }), None); + assert_eq!( + m.match_and_split(&Location { parents: 1, interior: [Parachain(42)].into() }), + Some(&AccountIndex64 { network: None, index: 23 }) + ); + assert_eq!(m.match_and_split(&m), None); + } + + #[test] + fn append_with_works() { + let acc = AccountIndex64 { network: None, index: 23 }; + let mut m = Location { parents: 1, interior: [Parachain(42)].into() }; + assert_eq!(m.append_with([PalletInstance(3), acc]), Ok(())); + assert_eq!( + m, + Location { parents: 1, interior: [Parachain(42), PalletInstance(3), acc].into() } + ); + + // cannot append to create overly long location + let acc = AccountIndex64 { network: None, index: 23 }; + let m = Location { + parents: 254, + interior: [Parachain(42), OnlyChild, OnlyChild, OnlyChild, OnlyChild].into(), + }; + let suffix: Location = (PalletInstance(3), acc, OnlyChild, OnlyChild).into(); + assert_eq!(m.clone().append_with(suffix.clone()), Err(suffix)); + } + + #[test] + fn prepend_with_works() { + let mut m = Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into(), + }; + assert_eq!(m.prepend_with(Location { parents: 1, interior: [OnlyChild].into() }), Ok(())); + assert_eq!( + m, + Location { + parents: 1, + interior: [Parachain(42), AccountIndex64 { network: None, index: 23 }].into() + } + ); + + // cannot prepend to create overly long location + let mut m = Location { parents: 254, interior: [Parachain(42)].into() }; + let prefix = Location { parents: 2, interior: Here }; + assert_eq!(m.prepend_with(prefix.clone()), Err(prefix)); + + let prefix = Location { parents: 1, interior: Here }; + assert_eq!(m.prepend_with(prefix.clone()), Ok(())); + assert_eq!(m, Location { parents: 255, interior: [Parachain(42)].into() }); + } + + #[test] + fn double_ended_ref_iteration_works() { + let m: Junctions = [Parachain(1000), Parachain(3), PalletInstance(5)].into(); + let mut iter = m.iter(); + + let first = iter.next().unwrap(); + assert_eq!(first, &Parachain(1000)); + let third = iter.next_back().unwrap(); + assert_eq!(third, &PalletInstance(5)); + let second = iter.next_back().unwrap(); + assert_eq!(iter.next(), None); + assert_eq!(iter.next_back(), None); + assert_eq!(second, &Parachain(3)); + + let res = Here + .pushed_with(*first) + .unwrap() + .pushed_with(*second) + .unwrap() + .pushed_with(*third) + .unwrap(); + assert_eq!(m, res); + + // make sure there's no funny business with the 0 indexing + let m = Here; + let mut iter = m.iter(); + + assert_eq!(iter.next(), None); + assert_eq!(iter.next_back(), None); + } + + #[test] + fn conversion_from_other_types_works() { + use crate::v4; + + fn takes_location>(_arg: Arg) {} + + takes_location(Parent); + takes_location(Here); + takes_location([Parachain(42)]); + takes_location((Ancestor(255), PalletInstance(8))); + takes_location((Ancestor(5), Parachain(1), PalletInstance(3))); + takes_location((Ancestor(2), Here)); + takes_location(AncestorThen( + 3, + [Parachain(43), AccountIndex64 { network: None, index: 155 }], + )); + takes_location((Parent, AccountId32 { network: None, id: [0; 32] })); + takes_location((Parent, Here)); + takes_location(ParentThen([Parachain(75)].into())); + takes_location([Parachain(100), PalletInstance(3)]); + + assert_eq!(v4::Location::from(v4::Junctions::Here).try_into(), Ok(Location::here())); + assert_eq!(v4::Location::from(v4::Parent).try_into(), Ok(Location::parent())); + assert_eq!( + v4::Location::from((v4::Parent, v4::Parent, v4::Junction::GeneralIndex(42u128),)) + .try_into(), + Ok(Location { parents: 2, interior: [GeneralIndex(42u128)].into() }), + ); + } +} diff --git a/polkadot/xcm/src/v5/mod.rs b/polkadot/xcm/src/v5/mod.rs new file mode 100644 index 000000000000..d455fa48adae --- /dev/null +++ b/polkadot/xcm/src/v5/mod.rs @@ -0,0 +1,1585 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Version 5 of the Cross-Consensus Message format data structures. + +pub use super::v3::GetWeight; +use super::v4::{ + Instruction as OldInstruction, PalletInfo as OldPalletInfo, + QueryResponseInfo as OldQueryResponseInfo, Response as OldResponse, Xcm as OldXcm, +}; +use crate::DoubleEncoded; +use alloc::{vec, vec::Vec}; +use bounded_collections::{parameter_types, BoundedVec}; +use codec::{ + self, decode_vec_with_len, Compact, Decode, Encode, Error as CodecError, Input as CodecInput, + MaxEncodedLen, +}; +use core::{fmt::Debug, result}; +use derivative::Derivative; +use scale_info::TypeInfo; + +mod asset; +mod junction; +pub(crate) mod junctions; +mod location; +mod traits; + +pub use asset::{ + Asset, AssetFilter, AssetId, AssetInstance, AssetTransferFilter, Assets, Fungibility, + WildAsset, WildFungibility, MAX_ITEMS_IN_ASSETS, +}; +pub use junction::{ + BodyId, BodyPart, Junction, NetworkId, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH, +}; +pub use junctions::Junctions; +pub use location::{Ancestor, AncestorThen, InteriorLocation, Location, Parent, ParentThen}; +pub use traits::{ + send_xcm, validate_send, Error, ExecuteXcm, Outcome, PreparedMessage, Reanchorable, Result, + SendError, SendResult, SendXcm, Weight, XcmHash, +}; +// These parts of XCM v4 are unchanged in XCM v5, and are re-imported here. +pub use super::v4::{MaxDispatchErrorLen, MaybeErrorCode, OriginKind, WeightLimit}; + +pub const VERSION: super::Version = 5; + +/// An identifier for a query. +pub type QueryId = u64; + +#[derive(Derivative, Default, Encode, TypeInfo)] +#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] +#[codec(encode_bound())] +#[codec(decode_bound())] +#[scale_info(bounds(), skip_type_params(Call))] +pub struct Xcm(pub Vec>); + +pub const MAX_INSTRUCTIONS_TO_DECODE: u8 = 100; + +environmental::environmental!(instructions_count: u8); + +impl Decode for Xcm { + fn decode(input: &mut I) -> core::result::Result { + instructions_count::using_once(&mut 0, || { + let number_of_instructions: u32 = >::decode(input)?.into(); + instructions_count::with(|count| { + *count = count.saturating_add(number_of_instructions as u8); + if *count > MAX_INSTRUCTIONS_TO_DECODE { + return Err(CodecError::from("Max instructions exceeded")) + } + Ok(()) + }) + .expect("Called in `using` context and thus can not return `None`; qed")?; + let decoded_instructions = decode_vec_with_len(input, number_of_instructions as usize)?; + Ok(Self(decoded_instructions)) + }) + } +} + +impl Xcm { + /// Create an empty instance. + pub fn new() -> Self { + Self(vec![]) + } + + /// Return `true` if no instructions are held in `self`. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Return the number of instructions held in `self`. + pub fn len(&self) -> usize { + self.0.len() + } + + /// Return a reference to the inner value. + pub fn inner(&self) -> &[Instruction] { + &self.0 + } + + /// Return a mutable reference to the inner value. + pub fn inner_mut(&mut self) -> &mut Vec> { + &mut self.0 + } + + /// Consume and return the inner value. + pub fn into_inner(self) -> Vec> { + self.0 + } + + /// Return an iterator over references to the items. + pub fn iter(&self) -> impl Iterator> { + self.0.iter() + } + + /// Return an iterator over mutable references to the items. + pub fn iter_mut(&mut self) -> impl Iterator> { + self.0.iter_mut() + } + + /// Consume and return an iterator over the items. + pub fn into_iter(self) -> impl Iterator> { + self.0.into_iter() + } + + /// Consume and either return `self` if it contains some instructions, or if it's empty, then + /// instead return the result of `f`. + pub fn or_else(self, f: impl FnOnce() -> Self) -> Self { + if self.0.is_empty() { + f() + } else { + self + } + } + + /// Return the first instruction, if any. + pub fn first(&self) -> Option<&Instruction> { + self.0.first() + } + + /// Return the last instruction, if any. + pub fn last(&self) -> Option<&Instruction> { + self.0.last() + } + + /// Return the only instruction, contained in `Self`, iff only one exists (`None` otherwise). + pub fn only(&self) -> Option<&Instruction> { + if self.0.len() == 1 { + self.0.first() + } else { + None + } + } + + /// Return the only instruction, contained in `Self`, iff only one exists (returns `self` + /// otherwise). + pub fn into_only(mut self) -> core::result::Result, Self> { + if self.0.len() == 1 { + self.0.pop().ok_or(self) + } else { + Err(self) + } + } +} + +impl From>> for Xcm { + fn from(c: Vec>) -> Self { + Self(c) + } +} + +impl From> for Vec> { + fn from(c: Xcm) -> Self { + c.0 + } +} + +/// A prelude for importing all types typically used when interacting with XCM messages. +pub mod prelude { + mod contents { + pub use super::super::{ + send_xcm, validate_send, Ancestor, AncestorThen, Asset, + AssetFilter::{self, *}, + AssetId, + AssetInstance::{self, *}, + Assets, BodyId, BodyPart, Error as XcmError, ExecuteXcm, + Fungibility::{self, *}, + Instruction::*, + InteriorLocation, + Junction::{self, *}, + Junctions::{self, Here}, + Location, MaybeErrorCode, + NetworkId::{self, *}, + OriginKind, Outcome, PalletInfo, Parent, ParentThen, PreparedMessage, QueryId, + QueryResponseInfo, Reanchorable, Response, Result as XcmResult, SendError, SendResult, + SendXcm, Weight, + WeightLimit::{self, *}, + WildAsset::{self, *}, + WildFungibility::{self, Fungible as WildFungible, NonFungible as WildNonFungible}, + XcmContext, XcmHash, XcmWeightInfo, VERSION as XCM_VERSION, + }; + } + pub use super::{Instruction, Xcm}; + pub use contents::*; + pub mod opaque { + pub use super::{ + super::opaque::{Instruction, Xcm}, + contents::*, + }; + } +} + +parameter_types! { + pub MaxPalletNameLen: u32 = 48; + pub MaxPalletsInfo: u32 = 64; +} + +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] +pub struct PalletInfo { + #[codec(compact)] + pub index: u32, + pub name: BoundedVec, + pub module_name: BoundedVec, + #[codec(compact)] + pub major: u32, + #[codec(compact)] + pub minor: u32, + #[codec(compact)] + pub patch: u32, +} + +impl TryInto for PalletInfo { + type Error = (); + + fn try_into(self) -> result::Result { + OldPalletInfo::new( + self.index, + self.name.into_inner(), + self.module_name.into_inner(), + self.major, + self.minor, + self.patch, + ) + .map_err(|_| ()) + } +} + +impl PalletInfo { + pub fn new( + index: u32, + name: Vec, + module_name: Vec, + major: u32, + minor: u32, + patch: u32, + ) -> result::Result { + let name = BoundedVec::try_from(name).map_err(|_| Error::Overflow)?; + let module_name = BoundedVec::try_from(module_name).map_err(|_| Error::Overflow)?; + + Ok(Self { index, name, module_name, major, minor, patch }) + } +} + +/// Response data to a query. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] +pub enum Response { + /// No response. Serves as a neutral default. + Null, + /// Some assets. + Assets(Assets), + /// The outcome of an XCM instruction. + ExecutionResult(Option<(u32, Error)>), + /// An XCM version. + Version(super::Version), + /// The index, instance name, pallet name and version of some pallets. + PalletsInfo(BoundedVec), + /// The status of a dispatch attempt using `Transact`. + DispatchResult(MaybeErrorCode), +} + +impl Default for Response { + fn default() -> Self { + Self::Null + } +} + +impl TryFrom for Response { + type Error = (); + + fn try_from(old: OldResponse) -> result::Result { + use OldResponse::*; + Ok(match old { + Null => Self::Null, + Assets(assets) => Self::Assets(assets.try_into()?), + ExecutionResult(result) => Self::ExecutionResult( + result + .map(|(num, old_error)| (num, old_error.try_into())) + .map(|(num, result)| result.map(|inner| (num, inner))) + .transpose()?, + ), + Version(version) => Self::Version(version), + PalletsInfo(pallet_info) => { + let inner = pallet_info + .into_iter() + .map(TryInto::try_into) + .collect::, _>>()?; + Self::PalletsInfo( + BoundedVec::::try_from(inner).map_err(|_| ())?, + ) + }, + DispatchResult(maybe_error) => Self::DispatchResult(maybe_error), + }) + } +} + +/// Information regarding the composition of a query response. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] +pub struct QueryResponseInfo { + /// The destination to which the query response message should be send. + pub destination: Location, + /// The `query_id` field of the `QueryResponse` message. + #[codec(compact)] + pub query_id: QueryId, + /// The `max_weight` field of the `QueryResponse` message. + pub max_weight: Weight, +} + +impl TryFrom for QueryResponseInfo { + type Error = (); + + fn try_from(old: OldQueryResponseInfo) -> result::Result { + Ok(Self { + destination: old.destination.try_into()?, + query_id: old.query_id, + max_weight: old.max_weight, + }) + } +} + +/// Contextual data pertaining to a specific list of XCM instructions. +#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug)] +pub struct XcmContext { + /// The current value of the Origin register of the `XCVM`. + pub origin: Option, + /// The identity of the XCM; this may be a hash of its versioned encoding but could also be + /// a high-level identity set by an appropriate barrier. + pub message_id: XcmHash, + /// The current value of the Topic register of the `XCVM`. + pub topic: Option<[u8; 32]>, +} + +impl XcmContext { + /// Constructor which sets the message ID to the supplied parameter and leaves the origin and + /// topic unset. + pub fn with_message_id(message_id: XcmHash) -> XcmContext { + XcmContext { origin: None, message_id, topic: None } + } +} + +/// Cross-Consensus Message: A message from one consensus system to another. +/// +/// Consensus systems that may send and receive messages include blockchains and smart contracts. +/// +/// All messages are delivered from a known *origin*, expressed as a `Location`. +/// +/// This is the inner XCM format and is version-sensitive. Messages are typically passed using the +/// outer XCM format, known as `VersionedXcm`. +#[derive( + Derivative, + Encode, + Decode, + TypeInfo, + xcm_procedural::XcmWeightInfoTrait, + xcm_procedural::Builder, +)] +#[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] +#[codec(encode_bound())] +#[codec(decode_bound())] +#[scale_info(bounds(), skip_type_params(Call))] +pub enum Instruction { + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place them into the Holding + /// Register. + /// + /// - `assets`: The asset(s) to be withdrawn into holding. + /// + /// Kind: *Command*. + /// + /// Errors: + #[builder(loads_holding)] + WithdrawAsset(Assets), + + /// Asset(s) (`assets`) have been received into the ownership of this system on the `origin` + /// system and equivalent derivatives should be placed into the Holding Register. + /// + /// - `assets`: The asset(s) that are minted into holding. + /// + /// Safety: `origin` must be trusted to have received and be storing `assets` such that they + /// may later be withdrawn should this system send a corresponding message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + #[builder(loads_holding)] + ReserveAssetDeposited(Assets), + + /// Asset(s) (`assets`) have been destroyed on the `origin` system and equivalent assets should + /// be created and placed into the Holding Register. + /// + /// - `assets`: The asset(s) that are minted into the Holding Register. + /// + /// Safety: `origin` must be trusted to have irrevocably destroyed the corresponding `assets` + /// prior as a consequence of sending this message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + #[builder(loads_holding)] + ReceiveTeleportedAsset(Assets), + + /// Respond with information that the local system is expecting. + /// + /// - `query_id`: The identifier of the query that resulted in this message being sent. + /// - `response`: The message content. + /// - `max_weight`: The maximum weight that handling this response should take. + /// - `querier`: The location responsible for the initiation of the response, if there is one. + /// In general this will tend to be the same location as the receiver of this message. NOTE: + /// As usual, this is interpreted from the perspective of the receiving consensus system. + /// + /// Safety: Since this is information only, there are no immediate concerns. However, it should + /// be remembered that even if the Origin behaves reasonably, it can always be asked to make + /// a response to a third-party chain who may or may not be expecting the response. Therefore + /// the `querier` should be checked to match the expected value. + /// + /// Kind: *Information*. + /// + /// Errors: + QueryResponse { + #[codec(compact)] + query_id: QueryId, + response: Response, + max_weight: Weight, + querier: Option, + }, + + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets + /// under the ownership of `beneficiary`. + /// + /// - `assets`: The asset(s) to be withdrawn. + /// - `beneficiary`: The new owner for the assets. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + TransferAsset { assets: Assets, beneficiary: Location }, + + /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place equivalent assets + /// under the ownership of `dest` within this consensus system (i.e. its sovereign account). + /// + /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given + /// `xcm`. + /// + /// - `assets`: The asset(s) to be withdrawn. + /// - `dest`: The location whose sovereign account will own the assets and thus the effective + /// beneficiary for the assets and the notification target for the reserve asset deposit + /// message. + /// - `xcm`: The instructions that should follow the `ReserveAssetDeposited` instruction, which + /// is sent onwards to `dest`. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + TransferReserveAsset { assets: Assets, dest: Location, xcm: Xcm<()> }, + + /// Apply the encoded transaction `call`, whose dispatch-origin should be `origin` as expressed + /// by the kind of origin `origin_kind`. + /// + /// The Transact Status Register is set according to the result of dispatching the call. + /// + /// - `origin_kind`: The means of expressing the message origin as a dispatch origin. + /// - `call`: The encoded transaction to be applied. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + Transact { origin_kind: OriginKind, call: DoubleEncoded }, + + /// A message to notify about a new incoming HRMP channel. This message is meant to be sent by + /// the relay-chain to a para. + /// + /// - `sender`: The sender in the to-be opened channel. Also, the initiator of the channel + /// opening. + /// - `max_message_size`: The maximum size of a message proposed by the sender. + /// - `max_capacity`: The maximum number of messages that can be queued in the channel. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + HrmpNewChannelOpenRequest { + #[codec(compact)] + sender: u32, + #[codec(compact)] + max_message_size: u32, + #[codec(compact)] + max_capacity: u32, + }, + + /// A message to notify about that a previously sent open channel request has been accepted by + /// the recipient. That means that the channel will be opened during the next relay-chain + /// session change. This message is meant to be sent by the relay-chain to a para. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + /// + /// Errors: + HrmpChannelAccepted { + // NOTE: We keep this as a structured item to a) keep it consistent with the other Hrmp + // items; and b) because the field's meaning is not obvious/mentioned from the item name. + #[codec(compact)] + recipient: u32, + }, + + /// A message to notify that the other party in an open channel decided to close it. In + /// particular, `initiator` is going to close the channel opened from `sender` to the + /// `recipient`. The close will be enacted at the next relay-chain session change. This message + /// is meant to be sent by the relay-chain to a para. + /// + /// Safety: The message should originate directly from the relay-chain. + /// + /// Kind: *System Notification* + /// + /// Errors: + HrmpChannelClosing { + #[codec(compact)] + initiator: u32, + #[codec(compact)] + sender: u32, + #[codec(compact)] + recipient: u32, + }, + + /// Clear the origin. + /// + /// This may be used by the XCM author to ensure that later instructions cannot command the + /// authority of the origin (e.g. if they are being relayed from an untrusted source, as often + /// the case with `ReserveAssetDeposited`). + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + ClearOrigin, + + /// Mutate the origin to some interior location. + /// + /// Kind: *Command* + /// + /// Errors: + DescendOrigin(InteriorLocation), + + /// Immediately report the contents of the Error Register to the given destination via XCM. + /// + /// A `QueryResponse` message of type `ExecutionOutcome` is sent to the described destination. + /// + /// - `response_info`: Information for making the response. + /// + /// Kind: *Command* + /// + /// Errors: + ReportError(QueryResponseInfo), + + /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under + /// the ownership of `beneficiary` within this consensus system. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `beneficiary`: The new owner for the assets. + /// + /// Kind: *Command* + /// + /// Errors: + DepositAsset { assets: AssetFilter, beneficiary: Location }, + + /// Remove the asset(s) (`assets`) from the Holding Register and place equivalent assets under + /// the ownership of `dest` within this consensus system (i.e. deposit them into its sovereign + /// account). + /// + /// Send an onward XCM message to `dest` of `ReserveAssetDeposited` with the given `effects`. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `dest`: The location whose sovereign account will own the assets and thus the effective + /// beneficiary for the assets and the notification target for the reserve asset deposit + /// message. + /// - `xcm`: The orders that should follow the `ReserveAssetDeposited` instruction which is + /// sent onwards to `dest`. + /// + /// Kind: *Command* + /// + /// Errors: + DepositReserveAsset { assets: AssetFilter, dest: Location, xcm: Xcm<()> }, + + /// Remove the asset(s) (`want`) from the Holding Register and replace them with alternative + /// assets. + /// + /// The minimum amount of assets to be received into the Holding Register for the order not to + /// fail may be stated. + /// + /// - `give`: The maximum amount of assets to remove from holding. + /// - `want`: The minimum amount of assets which `give` should be exchanged for. + /// - `maximal`: If `true`, then prefer to give as much as possible up to the limit of `give` + /// and receive accordingly more. If `false`, then prefer to give as little as possible in + /// order to receive as little as possible while receiving at least `want`. + /// + /// Kind: *Command* + /// + /// Errors: + ExchangeAsset { give: AssetFilter, want: Assets, maximal: bool }, + + /// Remove the asset(s) (`assets`) from holding and send a `WithdrawAsset` XCM message to a + /// reserve location. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `reserve`: A valid location that acts as a reserve for all asset(s) in `assets`. The + /// sovereign account of this consensus system *on the reserve location* will have + /// appropriate assets withdrawn and `effects` will be executed on them. There will typically + /// be only one valid location on any given asset/chain combination. + /// - `xcm`: The instructions to execute on the assets once withdrawn *on the reserve + /// location*. + /// + /// Kind: *Command* + /// + /// Errors: + InitiateReserveWithdraw { assets: AssetFilter, reserve: Location, xcm: Xcm<()> }, + + /// Remove the asset(s) (`assets`) from holding and send a `ReceiveTeleportedAsset` XCM message + /// to a `dest` location. + /// + /// - `assets`: The asset(s) to remove from holding. + /// - `dest`: A valid location that respects teleports coming from this location. + /// - `xcm`: The instructions to execute on the assets once arrived *on the destination + /// location*. + /// + /// NOTE: The `dest` location *MUST* respect this origin as a valid teleportation origin for + /// all `assets`. If it does not, then the assets may be lost. + /// + /// Kind: *Command* + /// + /// Errors: + InitiateTeleport { assets: AssetFilter, dest: Location, xcm: Xcm<()> }, + + /// Report to a given destination the contents of the Holding Register. + /// + /// A `QueryResponse` message of type `Assets` is sent to the described destination. + /// + /// - `response_info`: Information for making the response. + /// - `assets`: A filter for the assets that should be reported back. The assets reported back + /// will be, asset-wise, *the lesser of this value and the holding register*. No wildcards + /// will be used when reporting assets back. + /// + /// Kind: *Command* + /// + /// Errors: + ReportHolding { response_info: QueryResponseInfo, assets: AssetFilter }, + + /// Pay for the execution of some XCM `xcm` and `orders` with up to `weight` + /// picoseconds of execution time, paying for this with up to `fees` from the Holding Register. + /// + /// - `fees`: The asset(s) to remove from the Holding Register to pay for fees. + /// - `weight_limit`: The maximum amount of weight to purchase; this must be at least the + /// expected maximum weight of the total XCM to be executed for the + /// `AllowTopLevelPaidExecutionFrom` barrier to allow the XCM be executed. + /// + /// Kind: *Command* + /// + /// Errors: + #[builder(pays_fees)] + BuyExecution { fees: Asset, weight_limit: WeightLimit }, + + /// Refund any surplus weight previously bought with `BuyExecution`. + /// + /// Kind: *Command* + /// + /// Errors: None. + RefundSurplus, + + /// Set the Error Handler Register. This is code that should be called in the case of an error + /// happening. + /// + /// An error occurring within execution of this code will _NOT_ result in the error register + /// being set, nor will an error handler be called due to it. The error handler and appendix + /// may each still be set. + /// + /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing + /// weight however includes only the difference between the previous handler and the new + /// handler, which can reasonably be negative, which would result in a surplus. + /// + /// Kind: *Command* + /// + /// Errors: None. + SetErrorHandler(Xcm), + + /// Set the Appendix Register. This is code that should be called after code execution + /// (including the error handler if any) is finished. This will be called regardless of whether + /// an error occurred. + /// + /// Any error occurring due to execution of this code will result in the error register being + /// set, and the error handler (if set) firing. + /// + /// The apparent weight of this instruction is inclusive of the inner `Xcm`; the executing + /// weight however includes only the difference between the previous appendix and the new + /// appendix, which can reasonably be negative, which would result in a surplus. + /// + /// Kind: *Command* + /// + /// Errors: None. + SetAppendix(Xcm), + + /// Clear the Error Register. + /// + /// Kind: *Command* + /// + /// Errors: None. + ClearError, + + /// Set asset claimer for all the trapped assets during the execution. + /// + /// - `location`: The claimer of any assets potentially trapped during the execution of current + /// XCM. It can be an arbitrary location, not necessarily the caller or origin. + /// + /// Kind: *Command* + /// + /// Errors: None. + SetAssetClaimer { location: Location }, + /// Create some assets which are being held on behalf of the origin. + /// + /// - `assets`: The assets which are to be claimed. This must match exactly with the assets + /// claimable by the origin of the ticket. + /// - `ticket`: The ticket of the asset; this is an abstract identifier to help locate the + /// asset. + /// + /// Kind: *Command* + /// + /// Errors: + #[builder(loads_holding)] + ClaimAsset { assets: Assets, ticket: Location }, + + /// Always throws an error of type `Trap`. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `Trap`: All circumstances, whose inner value is the same as this item's inner value. + Trap(#[codec(compact)] u64), + + /// Ask the destination system to respond with the most recent version of XCM that they + /// support in a `QueryResponse` instruction. Any changes to this should also elicit similar + /// responses when they happen. + /// + /// - `query_id`: An identifier that will be replicated into the returned XCM message. + /// - `max_response_weight`: The maximum amount of weight that the `QueryResponse` item which + /// is sent as a reply may take to execute. NOTE: If this is unexpectedly large then the + /// response may not execute at all. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible* + SubscribeVersion { + #[codec(compact)] + query_id: QueryId, + max_response_weight: Weight, + }, + + /// Cancel the effect of a previous `SubscribeVersion` instruction. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible* + UnsubscribeVersion, + + /// Reduce Holding by up to the given assets. + /// + /// Holding is reduced by as much as possible up to the assets in the parameter. It is not an + /// error if the Holding does not contain the assets (to make this an error, use `ExpectAsset` + /// prior). + /// + /// Kind: *Command* + /// + /// Errors: *Infallible* + BurnAsset(Assets), + + /// Throw an error if Holding does not contain at least the given assets. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If Holding Register does not contain the assets in the parameter. + ExpectAsset(Assets), + + /// Ensure that the Origin Register equals some given value and throw an error if not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If Origin Register is not equal to the parameter. + ExpectOrigin(Option), + + /// Ensure that the Error Register equals some given value and throw an error if not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If the value of the Error Register is not equal to the parameter. + ExpectError(Option<(u32, Error)>), + + /// Ensure that the Transact Status Register equals some given value and throw an error if + /// not. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: If the value of the Transact Status Register is not equal to the + /// parameter. + ExpectTransactStatus(MaybeErrorCode), + + /// Query the existence of a particular pallet type. + /// + /// - `module_name`: The module name of the pallet to query. + /// - `response_info`: Information for making the response. + /// + /// Sends a `QueryResponse` to Origin whose data field `PalletsInfo` containing the information + /// of all pallets on the local chain whose name is equal to `name`. This is empty in the case + /// that the local chain is not based on Substrate Frame. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + QueryPallet { module_name: Vec, response_info: QueryResponseInfo }, + + /// Ensure that a particular pallet with a particular version exists. + /// + /// - `index: Compact`: The index which identifies the pallet. An error if no pallet exists at + /// this index. + /// - `name: Vec`: Name which must be equal to the name of the pallet. + /// - `module_name: Vec`: Module name which must be equal to the name of the module in + /// which the pallet exists. + /// - `crate_major: Compact`: Version number which must be equal to the major version of the + /// crate which implements the pallet. + /// - `min_crate_minor: Compact`: Version number which must be at most the minor version of the + /// crate which implements the pallet. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `ExpectationFalse`: In case any of the expectations are broken. + ExpectPallet { + #[codec(compact)] + index: u32, + name: Vec, + module_name: Vec, + #[codec(compact)] + crate_major: u32, + #[codec(compact)] + min_crate_minor: u32, + }, + + /// Send a `QueryResponse` message containing the value of the Transact Status Register to some + /// destination. + /// + /// - `query_response_info`: The information needed for constructing and sending the + /// `QueryResponse` message. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + ReportTransactStatus(QueryResponseInfo), + + /// Set the Transact Status Register to its default, cleared, value. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: *Infallible*. + ClearTransactStatus, + + /// Set the Origin Register to be some child of the Universal Ancestor. + /// + /// Safety: Should only be usable if the Origin is trusted to represent the Universal Ancestor + /// child in general. In general, no Origin should be able to represent the Universal Ancestor + /// child which is the root of the local consensus system since it would by extension + /// allow it to act as any location within the local consensus. + /// + /// The `Junction` parameter should generally be a `GlobalConsensus` variant since it is only + /// these which are children of the Universal Ancestor. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + UniversalOrigin(Junction), + + /// Send a message on to Non-Local Consensus system. + /// + /// This will tend to utilize some extra-consensus mechanism, the obvious one being a bridge. + /// A fee may be charged; this may be determined based on the contents of `xcm`. It will be + /// taken from the Holding register. + /// + /// - `network`: The remote consensus system to which the message should be exported. + /// - `destination`: The location relative to the remote consensus system to which the message + /// should be sent on arrival. + /// - `xcm`: The message to be exported. + /// + /// As an example, to export a message for execution on Statemine (parachain #1000 in the + /// Kusama network), you would call with `network: NetworkId::Kusama` and + /// `destination: [Parachain(1000)].into()`. Alternatively, to export a message for execution + /// on Polkadot, you would call with `network: NetworkId:: Polkadot` and `destination: Here`. + /// + /// Kind: *Command* + /// + /// Errors: *Fallible*. + ExportMessage { network: NetworkId, destination: InteriorLocation, xcm: Xcm<()> }, + + /// Lock the locally held asset and prevent further transfer or withdrawal. + /// + /// This restriction may be removed by the `UnlockAsset` instruction being called with an + /// Origin of `unlocker` and a `target` equal to the current `Origin`. + /// + /// If the locking is successful, then a `NoteUnlockable` instruction is sent to `unlocker`. + /// + /// - `asset`: The asset(s) which should be locked. + /// - `unlocker`: The value which the Origin must be for a corresponding `UnlockAsset` + /// instruction to work. + /// + /// Kind: *Command*. + /// + /// Errors: + LockAsset { asset: Asset, unlocker: Location }, + + /// Remove the lock over `asset` on this chain and (if nothing else is preventing it) allow the + /// asset to be transferred. + /// + /// - `asset`: The asset to be unlocked. + /// - `target`: The owner of the asset on the local chain. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + /// Errors: + UnlockAsset { asset: Asset, target: Location }, + + /// Asset (`asset`) has been locked on the `origin` system and may not be transferred. It may + /// only be unlocked with the receipt of the `UnlockAsset` instruction from this chain. + /// + /// - `asset`: The asset(s) which are now unlockable from this origin. + /// - `owner`: The owner of the asset on the chain in which it was locked. This may be a + /// location specific to the origin network. + /// + /// Safety: `origin` must be trusted to have locked the corresponding `asset` + /// prior as a consequence of sending this message. + /// + /// Kind: *Trusted Indication*. + /// + /// Errors: + NoteUnlockable { asset: Asset, owner: Location }, + + /// Send an `UnlockAsset` instruction to the `locker` for the given `asset`. + /// + /// This may fail if the local system is making use of the fact that the asset is locked or, + /// of course, if there is no record that the asset actually is locked. + /// + /// - `asset`: The asset(s) to be unlocked. + /// - `locker`: The location from which a previous `NoteUnlockable` was sent and to which an + /// `UnlockAsset` should be sent. + /// + /// Kind: *Command*. + /// + /// Errors: + RequestUnlock { asset: Asset, locker: Location }, + + /// Sets the Fees Mode Register. + /// + /// - `jit_withdraw`: The fees mode item; if set to `true` then fees for any instructions are + /// withdrawn as needed using the same mechanism as `WithdrawAssets`. + /// + /// Kind: *Command*. + /// + /// Errors: + SetFeesMode { jit_withdraw: bool }, + + /// Set the Topic Register. + /// + /// The 32-byte array identifier in the parameter is not guaranteed to be + /// unique; if such a property is desired, it is up to the code author to + /// enforce uniqueness. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: + SetTopic([u8; 32]), + + /// Clear the Topic Register. + /// + /// Kind: *Command* + /// + /// Errors: None. + ClearTopic, + + /// Alter the current Origin to another given origin. + /// + /// Kind: *Command* + /// + /// Errors: If the existing state would not allow such a change. + AliasOrigin(Location), + + /// A directive to indicate that the origin expects free execution of the message. + /// + /// At execution time, this instruction just does a check on the Origin register. + /// However, at the barrier stage messages starting with this instruction can be disregarded if + /// the origin is not acceptable for free execution or the `weight_limit` is `Limited` and + /// insufficient. + /// + /// Kind: *Indication* + /// + /// Errors: If the given origin is `Some` and not equal to the current Origin register. + UnpaidExecution { weight_limit: WeightLimit, check_origin: Option }, + + /// Pay Fees. + /// + /// Successor to `BuyExecution`. + /// Defined in fellowship RFC 105. + #[builder(pays_fees)] + PayFees { asset: Asset }, + + /// Initiates cross-chain transfer as follows: + /// + /// Assets in the holding register are matched using the given list of `AssetTransferFilter`s, + /// they are then transferred based on their specified transfer type: + /// + /// - teleport: burn local assets and append a `ReceiveTeleportedAsset` XCM instruction to the + /// XCM program to be sent onward to the `destination` location, + /// + /// - reserve deposit: place assets under the ownership of `destination` within this consensus + /// system (i.e. its sovereign account), and append a `ReserveAssetDeposited` XCM instruction + /// to the XCM program to be sent onward to the `destination` location, + /// + /// - reserve withdraw: burn local assets and append a `WithdrawAsset` XCM instruction to the + /// XCM program to be sent onward to the `destination` location, + /// + /// The onward XCM is then appended a `ClearOrigin` to allow safe execution of any following + /// custom XCM instructions provided in `remote_xcm`. + /// + /// The onward XCM also contains either a `PayFees` or `UnpaidExecution` instruction based + /// on the presence of the `remote_fees` parameter (see below). + /// + /// If an XCM program requires going through multiple hops, it can compose this instruction to + /// be used at every chain along the path, describing that specific leg of the flow. + /// + /// Parameters: + /// - `destination`: The location of the program next hop. + /// - `remote_fees`: If set to `Some(asset_xfer_filter)`, the single asset matching + /// `asset_xfer_filter` in the holding register will be transferred first in the remote XCM + /// program, followed by a `PayFees(fee)`, then rest of transfers follow. This guarantees + /// `remote_xcm` will successfully pass a `AllowTopLevelPaidExecutionFrom` barrier. If set to + /// `None`, a `UnpaidExecution` instruction is appended instead. Please note that these + /// assets are **reserved** for fees, they are sent to the fees register rather than holding. + /// Best practice is to only add here enough to cover fees, and transfer the rest through the + /// `assets` parameter. + /// - `preserve_origin`: Specifies whether the original origin should be preserved or cleared, + /// using the instructions `AliasOrigin` or `ClearOrigin` respectively. + /// - `assets`: List of asset filters matched against existing assets in holding. These are + /// transferred over to `destination` using the specified transfer type, and deposited to + /// holding on `destination`. + /// - `remote_xcm`: Custom instructions that will be executed on the `destination` chain. Note + /// that these instructions will be executed after a `ClearOrigin` so their origin will be + /// `None`. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + InitiateTransfer { + destination: Location, + remote_fees: Option, + preserve_origin: bool, + assets: Vec, + remote_xcm: Xcm<()>, + }, +} + +impl Xcm { + pub fn into(self) -> Xcm { + Xcm::from(self) + } + pub fn from(xcm: Xcm) -> Self { + Self(xcm.0.into_iter().map(Instruction::::from).collect()) + } +} + +impl Instruction { + pub fn into(self) -> Instruction { + Instruction::from(self) + } + pub fn from(xcm: Instruction) -> Self { + use Instruction::*; + match xcm { + WithdrawAsset(assets) => WithdrawAsset(assets), + ReserveAssetDeposited(assets) => ReserveAssetDeposited(assets), + ReceiveTeleportedAsset(assets) => ReceiveTeleportedAsset(assets), + QueryResponse { query_id, response, max_weight, querier } => + QueryResponse { query_id, response, max_weight, querier }, + TransferAsset { assets, beneficiary } => TransferAsset { assets, beneficiary }, + TransferReserveAsset { assets, dest, xcm } => + TransferReserveAsset { assets, dest, xcm }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, call } => Transact { origin_kind, call: call.into() }, + ReportError(response_info) => ReportError(response_info), + DepositAsset { assets, beneficiary } => DepositAsset { assets, beneficiary }, + DepositReserveAsset { assets, dest, xcm } => DepositReserveAsset { assets, dest, xcm }, + ExchangeAsset { give, want, maximal } => ExchangeAsset { give, want, maximal }, + InitiateReserveWithdraw { assets, reserve, xcm } => + InitiateReserveWithdraw { assets, reserve, xcm }, + InitiateTeleport { assets, dest, xcm } => InitiateTeleport { assets, dest, xcm }, + ReportHolding { response_info, assets } => ReportHolding { response_info, assets }, + BuyExecution { fees, weight_limit } => BuyExecution { fees, weight_limit }, + ClearOrigin => ClearOrigin, + DescendOrigin(who) => DescendOrigin(who), + RefundSurplus => RefundSurplus, + SetErrorHandler(xcm) => SetErrorHandler(xcm.into()), + SetAppendix(xcm) => SetAppendix(xcm.into()), + ClearError => ClearError, + SetAssetClaimer { location } => SetAssetClaimer { location }, + ClaimAsset { assets, ticket } => ClaimAsset { assets, ticket }, + Trap(code) => Trap(code), + SubscribeVersion { query_id, max_response_weight } => + SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => UnsubscribeVersion, + BurnAsset(assets) => BurnAsset(assets), + ExpectAsset(assets) => ExpectAsset(assets), + ExpectOrigin(origin) => ExpectOrigin(origin), + ExpectError(error) => ExpectError(error), + ExpectTransactStatus(transact_status) => ExpectTransactStatus(transact_status), + QueryPallet { module_name, response_info } => + QueryPallet { module_name, response_info }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => ReportTransactStatus(response_info), + ClearTransactStatus => ClearTransactStatus, + UniversalOrigin(j) => UniversalOrigin(j), + ExportMessage { network, destination, xcm } => + ExportMessage { network, destination, xcm }, + LockAsset { asset, unlocker } => LockAsset { asset, unlocker }, + UnlockAsset { asset, target } => UnlockAsset { asset, target }, + NoteUnlockable { asset, owner } => NoteUnlockable { asset, owner }, + RequestUnlock { asset, locker } => RequestUnlock { asset, locker }, + SetFeesMode { jit_withdraw } => SetFeesMode { jit_withdraw }, + SetTopic(topic) => SetTopic(topic), + ClearTopic => ClearTopic, + AliasOrigin(location) => AliasOrigin(location), + UnpaidExecution { weight_limit, check_origin } => + UnpaidExecution { weight_limit, check_origin }, + PayFees { asset } => PayFees { asset }, + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm }, + } + } +} + +// TODO: Automate Generation +impl> GetWeight for Instruction { + fn weight(&self) -> Weight { + use Instruction::*; + match self { + WithdrawAsset(assets) => W::withdraw_asset(assets), + ReserveAssetDeposited(assets) => W::reserve_asset_deposited(assets), + ReceiveTeleportedAsset(assets) => W::receive_teleported_asset(assets), + QueryResponse { query_id, response, max_weight, querier } => + W::query_response(query_id, response, max_weight, querier), + TransferAsset { assets, beneficiary } => W::transfer_asset(assets, beneficiary), + TransferReserveAsset { assets, dest, xcm } => + W::transfer_reserve_asset(&assets, dest, xcm), + Transact { origin_kind, call } => W::transact(origin_kind, call), + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + W::hrmp_new_channel_open_request(sender, max_message_size, max_capacity), + HrmpChannelAccepted { recipient } => W::hrmp_channel_accepted(recipient), + HrmpChannelClosing { initiator, sender, recipient } => + W::hrmp_channel_closing(initiator, sender, recipient), + ClearOrigin => W::clear_origin(), + DescendOrigin(who) => W::descend_origin(who), + ReportError(response_info) => W::report_error(&response_info), + DepositAsset { assets, beneficiary } => W::deposit_asset(assets, beneficiary), + DepositReserveAsset { assets, dest, xcm } => + W::deposit_reserve_asset(assets, dest, xcm), + ExchangeAsset { give, want, maximal } => W::exchange_asset(give, want, maximal), + InitiateReserveWithdraw { assets, reserve, xcm } => + W::initiate_reserve_withdraw(assets, reserve, xcm), + InitiateTeleport { assets, dest, xcm } => W::initiate_teleport(assets, dest, xcm), + ReportHolding { response_info, assets } => W::report_holding(&response_info, &assets), + BuyExecution { fees, weight_limit } => W::buy_execution(fees, weight_limit), + RefundSurplus => W::refund_surplus(), + SetErrorHandler(xcm) => W::set_error_handler(xcm), + SetAppendix(xcm) => W::set_appendix(xcm), + ClearError => W::clear_error(), + SetAssetClaimer { location } => W::set_asset_claimer(location), + ClaimAsset { assets, ticket } => W::claim_asset(assets, ticket), + Trap(code) => W::trap(code), + SubscribeVersion { query_id, max_response_weight } => + W::subscribe_version(query_id, max_response_weight), + UnsubscribeVersion => W::unsubscribe_version(), + BurnAsset(assets) => W::burn_asset(assets), + ExpectAsset(assets) => W::expect_asset(assets), + ExpectOrigin(origin) => W::expect_origin(origin), + ExpectError(error) => W::expect_error(error), + ExpectTransactStatus(transact_status) => W::expect_transact_status(transact_status), + QueryPallet { module_name, response_info } => + W::query_pallet(module_name, response_info), + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), + ReportTransactStatus(response_info) => W::report_transact_status(response_info), + ClearTransactStatus => W::clear_transact_status(), + UniversalOrigin(j) => W::universal_origin(j), + ExportMessage { network, destination, xcm } => + W::export_message(network, destination, xcm), + LockAsset { asset, unlocker } => W::lock_asset(asset, unlocker), + UnlockAsset { asset, target } => W::unlock_asset(asset, target), + NoteUnlockable { asset, owner } => W::note_unlockable(asset, owner), + RequestUnlock { asset, locker } => W::request_unlock(asset, locker), + SetFeesMode { jit_withdraw } => W::set_fees_mode(jit_withdraw), + SetTopic(topic) => W::set_topic(topic), + ClearTopic => W::clear_topic(), + AliasOrigin(location) => W::alias_origin(location), + UnpaidExecution { weight_limit, check_origin } => + W::unpaid_execution(weight_limit, check_origin), + PayFees { asset } => W::pay_fees(asset), + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => + W::initiate_transfer(destination, remote_fees, preserve_origin, assets, remote_xcm), + } + } +} + +pub mod opaque { + /// The basic concrete type of `Xcm`, which doesn't make any assumptions about the + /// format of a call other than it is pre-encoded. + pub type Xcm = super::Xcm<()>; + + /// The basic concrete type of `Instruction`, which doesn't make any assumptions about the + /// format of a call other than it is pre-encoded. + pub type Instruction = super::Instruction<()>; +} + +// Convert from a v4 XCM to a v5 XCM +impl TryFrom> for Xcm { + type Error = (); + fn try_from(old_xcm: OldXcm) -> result::Result { + Ok(Xcm(old_xcm.0.into_iter().map(TryInto::try_into).collect::>()?)) + } +} + +// Convert from a v4 instruction to a v5 instruction +impl TryFrom> for Instruction { + type Error = (); + fn try_from(old_instruction: OldInstruction) -> result::Result { + use OldInstruction::*; + Ok(match old_instruction { + WithdrawAsset(assets) => Self::WithdrawAsset(assets.try_into()?), + ReserveAssetDeposited(assets) => Self::ReserveAssetDeposited(assets.try_into()?), + ReceiveTeleportedAsset(assets) => Self::ReceiveTeleportedAsset(assets.try_into()?), + QueryResponse { query_id, response, max_weight, querier: Some(querier) } => + Self::QueryResponse { + query_id, + querier: querier.try_into()?, + response: response.try_into()?, + max_weight, + }, + QueryResponse { query_id, response, max_weight, querier: None } => + Self::QueryResponse { + query_id, + querier: None, + response: response.try_into()?, + max_weight, + }, + TransferAsset { assets, beneficiary } => Self::TransferAsset { + assets: assets.try_into()?, + beneficiary: beneficiary.try_into()?, + }, + TransferReserveAsset { assets, dest, xcm } => Self::TransferReserveAsset { + assets: assets.try_into()?, + dest: dest.try_into()?, + xcm: xcm.try_into()?, + }, + HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity } => + Self::HrmpNewChannelOpenRequest { sender, max_message_size, max_capacity }, + HrmpChannelAccepted { recipient } => Self::HrmpChannelAccepted { recipient }, + HrmpChannelClosing { initiator, sender, recipient } => + Self::HrmpChannelClosing { initiator, sender, recipient }, + Transact { origin_kind, require_weight_at_most: _, call } => + Self::Transact { origin_kind, call: call.into() }, + ReportError(response_info) => Self::ReportError(QueryResponseInfo { + query_id: response_info.query_id, + destination: response_info.destination.try_into().map_err(|_| ())?, + max_weight: response_info.max_weight, + }), + DepositAsset { assets, beneficiary } => { + let beneficiary = beneficiary.try_into()?; + let assets = assets.try_into()?; + Self::DepositAsset { assets, beneficiary } + }, + DepositReserveAsset { assets, dest, xcm } => { + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + let assets = assets.try_into()?; + Self::DepositReserveAsset { assets, dest, xcm } + }, + ExchangeAsset { give, want, maximal } => { + let give = give.try_into()?; + let want = want.try_into()?; + Self::ExchangeAsset { give, want, maximal } + }, + InitiateReserveWithdraw { assets, reserve, xcm } => { + let assets = assets.try_into()?; + let reserve = reserve.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateReserveWithdraw { assets, reserve, xcm } + }, + InitiateTeleport { assets, dest, xcm } => { + let assets = assets.try_into()?; + let dest = dest.try_into()?; + let xcm = xcm.try_into()?; + Self::InitiateTeleport { assets, dest, xcm } + }, + ReportHolding { response_info, assets } => { + let response_info = QueryResponseInfo { + destination: response_info.destination.try_into().map_err(|_| ())?, + query_id: response_info.query_id, + max_weight: response_info.max_weight, + }; + Self::ReportHolding { response_info, assets: assets.try_into()? } + }, + BuyExecution { fees, weight_limit } => { + let fees = fees.try_into()?; + let weight_limit = weight_limit.into(); + Self::BuyExecution { fees, weight_limit } + }, + ClearOrigin => Self::ClearOrigin, + DescendOrigin(who) => Self::DescendOrigin(who.try_into()?), + RefundSurplus => Self::RefundSurplus, + SetErrorHandler(xcm) => Self::SetErrorHandler(xcm.try_into()?), + SetAppendix(xcm) => Self::SetAppendix(xcm.try_into()?), + ClearError => Self::ClearError, + ClaimAsset { assets, ticket } => { + let assets = assets.try_into()?; + let ticket = ticket.try_into()?; + Self::ClaimAsset { assets, ticket } + }, + Trap(code) => Self::Trap(code), + SubscribeVersion { query_id, max_response_weight } => + Self::SubscribeVersion { query_id, max_response_weight }, + UnsubscribeVersion => Self::UnsubscribeVersion, + BurnAsset(assets) => Self::BurnAsset(assets.try_into()?), + ExpectAsset(assets) => Self::ExpectAsset(assets.try_into()?), + ExpectOrigin(maybe_location) => Self::ExpectOrigin( + maybe_location.map(|location| location.try_into()).transpose().map_err(|_| ())?, + ), + ExpectError(maybe_error) => Self::ExpectError( + maybe_error + .map(|(num, old_error)| (num, old_error.try_into())) + .map(|(num, result)| result.map(|inner| (num, inner))) + .transpose() + .map_err(|_| ())?, + ), + ExpectTransactStatus(maybe_error_code) => Self::ExpectTransactStatus(maybe_error_code), + QueryPallet { module_name, response_info } => Self::QueryPallet { + module_name, + response_info: response_info.try_into().map_err(|_| ())?, + }, + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + Self::ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, + ReportTransactStatus(response_info) => + Self::ReportTransactStatus(response_info.try_into().map_err(|_| ())?), + ClearTransactStatus => Self::ClearTransactStatus, + UniversalOrigin(junction) => + Self::UniversalOrigin(junction.try_into().map_err(|_| ())?), + ExportMessage { network, destination, xcm } => Self::ExportMessage { + network: network.into(), + destination: destination.try_into().map_err(|_| ())?, + xcm: xcm.try_into().map_err(|_| ())?, + }, + LockAsset { asset, unlocker } => Self::LockAsset { + asset: asset.try_into().map_err(|_| ())?, + unlocker: unlocker.try_into().map_err(|_| ())?, + }, + UnlockAsset { asset, target } => Self::UnlockAsset { + asset: asset.try_into().map_err(|_| ())?, + target: target.try_into().map_err(|_| ())?, + }, + NoteUnlockable { asset, owner } => Self::NoteUnlockable { + asset: asset.try_into().map_err(|_| ())?, + owner: owner.try_into().map_err(|_| ())?, + }, + RequestUnlock { asset, locker } => Self::RequestUnlock { + asset: asset.try_into().map_err(|_| ())?, + locker: locker.try_into().map_err(|_| ())?, + }, + SetFeesMode { jit_withdraw } => Self::SetFeesMode { jit_withdraw }, + SetTopic(topic) => Self::SetTopic(topic), + ClearTopic => Self::ClearTopic, + AliasOrigin(location) => Self::AliasOrigin(location.try_into().map_err(|_| ())?), + UnpaidExecution { weight_limit, check_origin } => Self::UnpaidExecution { + weight_limit, + check_origin: check_origin + .map(|location| location.try_into()) + .transpose() + .map_err(|_| ())?, + }, + }) + } +} + +#[cfg(test)] +mod tests { + use super::{prelude::*, *}; + use crate::v4::{ + AssetFilter as OldAssetFilter, Junctions::Here as OldHere, WildAsset as OldWildAsset, + }; + + #[test] + fn basic_roundtrip_works() { + let xcm = Xcm::<()>(vec![TransferAsset { + assets: (Here, 1u128).into(), + beneficiary: Here.into(), + }]); + let old_xcm = OldXcm::<()>(vec![OldInstruction::TransferAsset { + assets: (OldHere, 1u128).into(), + beneficiary: OldHere.into(), + }]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn teleport_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + ReceiveTeleportedAsset((Here, 1u128).into()), + ClearOrigin, + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm: OldXcm<()> = OldXcm::<()>(vec![ + OldInstruction::ReceiveTeleportedAsset((OldHere, 1u128).into()), + OldInstruction::ClearOrigin, + OldInstruction::DepositAsset { + assets: crate::v4::AssetFilter::Wild(crate::v4::WildAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn reserve_deposit_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + ReserveAssetDeposited((Here, 1u128).into()), + ClearOrigin, + BuyExecution { + fees: (Here, 1u128).into(), + weight_limit: Some(Weight::from_parts(1, 1)).into(), + }, + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::ReserveAssetDeposited((OldHere, 1u128).into()), + OldInstruction::ClearOrigin, + OldInstruction::BuyExecution { + fees: (OldHere, 1u128).into(), + weight_limit: WeightLimit::Limited(Weight::from_parts(1, 1)), + }, + OldInstruction::DepositAsset { + assets: crate::v4::AssetFilter::Wild(crate::v4::WildAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn deposit_asset_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + WithdrawAsset((Here, 1u128).into()), + DepositAsset { assets: Wild(AllCounted(1)), beneficiary: Here.into() }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::WithdrawAsset((OldHere, 1u128).into()), + OldInstruction::DepositAsset { + assets: OldAssetFilter::Wild(OldWildAsset::AllCounted(1)), + beneficiary: OldHere.into(), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn deposit_reserve_asset_roundtrip_works() { + let xcm = Xcm::<()>(vec![ + WithdrawAsset((Here, 1u128).into()), + DepositReserveAsset { + assets: Wild(AllCounted(1)), + dest: Here.into(), + xcm: Xcm::<()>(vec![]), + }, + ]); + let old_xcm = OldXcm::<()>(vec![ + OldInstruction::WithdrawAsset((OldHere, 1u128).into()), + OldInstruction::DepositReserveAsset { + assets: OldAssetFilter::Wild(OldWildAsset::AllCounted(1)), + dest: OldHere.into(), + xcm: OldXcm::<()>(vec![]), + }, + ]); + assert_eq!(old_xcm, OldXcm::<()>::try_from(xcm.clone()).unwrap()); + let new_xcm: Xcm<()> = old_xcm.try_into().unwrap(); + assert_eq!(new_xcm, xcm); + } + + #[test] + fn decoding_respects_limit() { + let max_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize]); + let encoded = max_xcm.encode(); + assert!(Xcm::<()>::decode(&mut &encoded[..]).is_ok()); + + let big_xcm = Xcm::<()>(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE as usize + 1]); + let encoded = big_xcm.encode(); + assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); + + let nested_xcm = Xcm::<()>(vec![ + DepositReserveAsset { + assets: All.into(), + dest: Here.into(), + xcm: max_xcm, + }; + (MAX_INSTRUCTIONS_TO_DECODE / 2) as usize + ]); + let encoded = nested_xcm.encode(); + assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); + + let even_more_nested_xcm = Xcm::<()>(vec![SetAppendix(nested_xcm); 64]); + let encoded = even_more_nested_xcm.encode(); + assert_eq!(encoded.len(), 342530); + // This should not decode since the limit is 100 + assert_eq!(MAX_INSTRUCTIONS_TO_DECODE, 100, "precondition"); + assert!(Xcm::<()>::decode(&mut &encoded[..]).is_err()); + } +} diff --git a/polkadot/xcm/src/v5/traits.rs b/polkadot/xcm/src/v5/traits.rs new file mode 100644 index 000000000000..1f5041ca8d84 --- /dev/null +++ b/polkadot/xcm/src/v5/traits.rs @@ -0,0 +1,525 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Cross-Consensus Message format data structures. + +pub use crate::v3::{Error as OldError, SendError, XcmHash}; +use codec::{Decode, Encode}; +use core::result; +use scale_info::TypeInfo; + +pub use sp_weights::Weight; + +use super::*; + +/// Error codes used in XCM. The first errors codes have explicit indices and are part of the XCM +/// format. Those trailing are merely part of the XCM implementation; there is no expectation that +/// they will retain the same index over time. +#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] +#[scale_info(replace_segment("staging_xcm", "xcm"))] +#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] +pub enum Error { + // Errors that happen due to instructions being executed. These alone are defined in the + // XCM specification. + /// An arithmetic overflow happened. + #[codec(index = 0)] + Overflow, + /// The instruction is intentionally unsupported. + #[codec(index = 1)] + Unimplemented, + /// Origin Register does not contain a value value for a reserve transfer notification. + #[codec(index = 2)] + UntrustedReserveLocation, + /// Origin Register does not contain a value value for a teleport notification. + #[codec(index = 3)] + UntrustedTeleportLocation, + /// `MultiLocation` value too large to descend further. + #[codec(index = 4)] + LocationFull, + /// `MultiLocation` value ascend more parents than known ancestors of local location. + #[codec(index = 5)] + LocationNotInvertible, + /// The Origin Register does not contain a valid value for instruction. + #[codec(index = 6)] + BadOrigin, + /// The location parameter is not a valid value for the instruction. + #[codec(index = 7)] + InvalidLocation, + /// The given asset is not handled. + #[codec(index = 8)] + AssetNotFound, + /// An asset transaction (like withdraw or deposit) failed (typically due to type conversions). + #[codec(index = 9)] + FailedToTransactAsset(#[codec(skip)] &'static str), + /// An asset cannot be withdrawn, potentially due to lack of ownership, availability or rights. + #[codec(index = 10)] + NotWithdrawable, + /// An asset cannot be deposited under the ownership of a particular location. + #[codec(index = 11)] + LocationCannotHold, + /// Attempt to send a message greater than the maximum supported by the transport protocol. + #[codec(index = 12)] + ExceedsMaxMessageSize, + /// The given message cannot be translated into a format supported by the destination. + #[codec(index = 13)] + DestinationUnsupported, + /// Destination is routable, but there is some issue with the transport mechanism. + #[codec(index = 14)] + Transport(#[codec(skip)] &'static str), + /// Destination is known to be unroutable. + #[codec(index = 15)] + Unroutable, + /// Used by `ClaimAsset` when the given claim could not be recognized/found. + #[codec(index = 16)] + UnknownClaim, + /// Used by `Transact` when the functor cannot be decoded. + #[codec(index = 17)] + FailedToDecode, + /// Used by `Transact` to indicate that the given weight limit could be breached by the + /// functor. + #[codec(index = 18)] + MaxWeightInvalid, + /// Used by `BuyExecution` when the Holding Register does not contain payable fees. + #[codec(index = 19)] + NotHoldingFees, + /// Used by `BuyExecution` when the fees declared to purchase weight are insufficient. + #[codec(index = 20)] + TooExpensive, + /// Used by the `Trap` instruction to force an error intentionally. Its code is included. + #[codec(index = 21)] + Trap(u64), + /// Used by `ExpectAsset`, `ExpectError` and `ExpectOrigin` when the expectation was not true. + #[codec(index = 22)] + ExpectationFalse, + /// The provided pallet index was not found. + #[codec(index = 23)] + PalletNotFound, + /// The given pallet's name is different to that expected. + #[codec(index = 24)] + NameMismatch, + /// The given pallet's version has an incompatible version to that expected. + #[codec(index = 25)] + VersionIncompatible, + /// The given operation would lead to an overflow of the Holding Register. + #[codec(index = 26)] + HoldingWouldOverflow, + /// The message was unable to be exported. + #[codec(index = 27)] + ExportError, + /// `MultiLocation` value failed to be reanchored. + #[codec(index = 28)] + ReanchorFailed, + /// No deal is possible under the given constraints. + #[codec(index = 29)] + NoDeal, + /// Fees were required which the origin could not pay. + #[codec(index = 30)] + FeesNotMet, + /// Some other error with locking. + #[codec(index = 31)] + LockError, + /// The state was not in a condition where the operation was valid to make. + #[codec(index = 32)] + NoPermission, + /// The universal location of the local consensus is improper. + #[codec(index = 33)] + Unanchored, + /// An asset cannot be deposited, probably because (too much of) it already exists. + #[codec(index = 34)] + NotDepositable, + /// Too many assets matched the given asset filter. + #[codec(index = 35)] + TooManyAssets, + + // Errors that happen prior to instructions being executed. These fall outside of the XCM + // spec. + /// XCM version not able to be handled. + UnhandledXcmVersion, + /// Execution of the XCM would potentially result in a greater weight used than weight limit. + WeightLimitReached(Weight), + /// The XCM did not pass the barrier condition for execution. + /// + /// The barrier condition differs on different chains and in different circumstances, but + /// generally it means that the conditions surrounding the message were not such that the chain + /// considers the message worth spending time executing. Since most chains lift the barrier to + /// execution on appropriate payment, presentation of an NFT voucher, or based on the message + /// origin, it means that none of those were the case. + Barrier, + /// The weight of an XCM message is not computable ahead of execution. + WeightNotComputable, + /// Recursion stack limit reached + // TODO(https://github.com/paritytech/polkadot-sdk/issues/6199): This should have a fixed index since + // we use it in `FrameTransactionalProcessor` // which is used in instructions. + // Or we should create a different error for that. + ExceedsStackLimit, +} + +impl TryFrom for Error { + type Error = (); + fn try_from(old_error: OldError) -> result::Result { + use OldError::*; + Ok(match old_error { + Overflow => Self::Overflow, + Unimplemented => Self::Unimplemented, + UntrustedReserveLocation => Self::UntrustedReserveLocation, + UntrustedTeleportLocation => Self::UntrustedTeleportLocation, + LocationFull => Self::LocationFull, + LocationNotInvertible => Self::LocationNotInvertible, + BadOrigin => Self::BadOrigin, + InvalidLocation => Self::InvalidLocation, + AssetNotFound => Self::AssetNotFound, + FailedToTransactAsset(s) => Self::FailedToTransactAsset(s), + NotWithdrawable => Self::NotWithdrawable, + LocationCannotHold => Self::LocationCannotHold, + ExceedsMaxMessageSize => Self::ExceedsMaxMessageSize, + DestinationUnsupported => Self::DestinationUnsupported, + Transport(s) => Self::Transport(s), + Unroutable => Self::Unroutable, + UnknownClaim => Self::UnknownClaim, + FailedToDecode => Self::FailedToDecode, + MaxWeightInvalid => Self::MaxWeightInvalid, + NotHoldingFees => Self::NotHoldingFees, + TooExpensive => Self::TooExpensive, + Trap(i) => Self::Trap(i), + ExpectationFalse => Self::ExpectationFalse, + PalletNotFound => Self::PalletNotFound, + NameMismatch => Self::NameMismatch, + VersionIncompatible => Self::VersionIncompatible, + HoldingWouldOverflow => Self::HoldingWouldOverflow, + ExportError => Self::ExportError, + ReanchorFailed => Self::ReanchorFailed, + NoDeal => Self::NoDeal, + FeesNotMet => Self::FeesNotMet, + LockError => Self::LockError, + NoPermission => Self::NoPermission, + Unanchored => Self::Unanchored, + NotDepositable => Self::NotDepositable, + UnhandledXcmVersion => Self::UnhandledXcmVersion, + WeightLimitReached(weight) => Self::WeightLimitReached(weight), + Barrier => Self::Barrier, + WeightNotComputable => Self::WeightNotComputable, + ExceedsStackLimit => Self::ExceedsStackLimit, + }) + } +} + +impl MaxEncodedLen for Error { + fn max_encoded_len() -> usize { + // TODO: max_encoded_len doesn't quite work here as it tries to take notice of the fields + // marked `codec(skip)`. We can hard-code it with the right answer for now. + 1 + } +} + +impl From for Error { + fn from(e: SendError) -> Self { + match e { + SendError::NotApplicable | SendError::Unroutable | SendError::MissingArgument => + Error::Unroutable, + SendError::Transport(s) => Error::Transport(s), + SendError::DestinationUnsupported => Error::DestinationUnsupported, + SendError::ExceedsMaxMessageSize => Error::ExceedsMaxMessageSize, + SendError::Fees => Error::FeesNotMet, + } + } +} + +pub type Result = result::Result<(), Error>; + +/// Outcome of an XCM execution. +#[derive(Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] +pub enum Outcome { + /// Execution completed successfully; given weight was used. + Complete { used: Weight }, + /// Execution started, but did not complete successfully due to the given error; given weight + /// was used. + Incomplete { used: Weight, error: Error }, + /// Execution did not start due to the given error. + Error { error: Error }, +} + +impl Outcome { + pub fn ensure_complete(self) -> Result { + match self { + Outcome::Complete { .. } => Ok(()), + Outcome::Incomplete { error, .. } => Err(error), + Outcome::Error { error, .. } => Err(error), + } + } + pub fn ensure_execution(self) -> result::Result { + match self { + Outcome::Complete { used, .. } => Ok(used), + Outcome::Incomplete { used, .. } => Ok(used), + Outcome::Error { error, .. } => Err(error), + } + } + /// How much weight was used by the XCM execution attempt. + pub fn weight_used(&self) -> Weight { + match self { + Outcome::Complete { used, .. } => *used, + Outcome::Incomplete { used, .. } => *used, + Outcome::Error { .. } => Weight::zero(), + } + } +} + +impl From for Outcome { + fn from(error: Error) -> Self { + Self::Error { error } + } +} + +pub trait PreparedMessage { + fn weight_of(&self) -> Weight; +} + +/// Type of XCM message executor. +pub trait ExecuteXcm { + type Prepared: PreparedMessage; + fn prepare(message: Xcm) -> result::Result>; + fn execute( + origin: impl Into, + pre: Self::Prepared, + id: &mut XcmHash, + weight_credit: Weight, + ) -> Outcome; + fn prepare_and_execute( + origin: impl Into, + message: Xcm, + id: &mut XcmHash, + weight_limit: Weight, + weight_credit: Weight, + ) -> Outcome { + let pre = match Self::prepare(message) { + Ok(x) => x, + Err(_) => return Outcome::Error { error: Error::WeightNotComputable }, + }; + let xcm_weight = pre.weight_of(); + if xcm_weight.any_gt(weight_limit) { + return Outcome::Error { error: Error::WeightLimitReached(xcm_weight) } + } + Self::execute(origin, pre, id, weight_credit) + } + + /// Deduct some `fees` to the sovereign account of the given `location` and place them as per + /// the convention for fees. + fn charge_fees(location: impl Into, fees: Assets) -> Result; +} + +pub enum Weightless {} +impl PreparedMessage for Weightless { + fn weight_of(&self) -> Weight { + unreachable!() + } +} + +impl ExecuteXcm for () { + type Prepared = Weightless; + fn prepare(message: Xcm) -> result::Result> { + Err(message) + } + fn execute(_: impl Into, _: Self::Prepared, _: &mut XcmHash, _: Weight) -> Outcome { + unreachable!() + } + fn charge_fees(_location: impl Into, _fees: Assets) -> Result { + Err(Error::Unimplemented) + } +} + +pub trait Reanchorable: Sized { + /// Type to return in case of an error. + type Error: Debug; + + /// Mutate `self` so that it represents the same location from the point of view of `target`. + /// The context of `self` is provided as `context`. + /// + /// Does not modify `self` in case of overflow. + fn reanchor( + &mut self, + target: &Location, + context: &InteriorLocation, + ) -> core::result::Result<(), ()>; + + /// Consume `self` and return a new value representing the same location from the point of view + /// of `target`. The context of `self` is provided as `context`. + /// + /// Returns the original `self` in case of overflow. + fn reanchored( + self, + target: &Location, + context: &InteriorLocation, + ) -> core::result::Result; +} + +/// Result value when attempting to send an XCM message. +pub type SendResult = result::Result<(T, Assets), SendError>; + +/// Utility for sending an XCM message to a given location. +/// +/// These can be amalgamated in tuples to form sophisticated routing systems. In tuple format, each +/// router might return `NotApplicable` to pass the execution to the next sender item. Note that +/// each `NotApplicable` might alter the destination and the XCM message for to the next router. +/// +/// # Example +/// ```rust +/// # use codec::Encode; +/// # use staging_xcm::v5::{prelude::*, Weight}; +/// # use staging_xcm::VersionedXcm; +/// # use std::convert::Infallible; +/// +/// /// A sender that only passes the message through and does nothing. +/// struct Sender1; +/// impl SendXcm for Sender1 { +/// type Ticket = Infallible; +/// fn validate(_: &mut Option, _: &mut Option>) -> SendResult { +/// Err(SendError::NotApplicable) +/// } +/// fn deliver(_: Infallible) -> Result { +/// unreachable!() +/// } +/// } +/// +/// /// A sender that accepts a message that has two junctions, otherwise stops the routing. +/// struct Sender2; +/// impl SendXcm for Sender2 { +/// type Ticket = (); +/// fn validate(destination: &mut Option, message: &mut Option>) -> SendResult<()> { +/// match destination.as_ref().ok_or(SendError::MissingArgument)?.unpack() { +/// (0, [j1, j2]) => Ok(((), Assets::new())), +/// _ => Err(SendError::Unroutable), +/// } +/// } +/// fn deliver(_: ()) -> Result { +/// Ok([0; 32]) +/// } +/// } +/// +/// /// A sender that accepts a message from a parent, passing through otherwise. +/// struct Sender3; +/// impl SendXcm for Sender3 { +/// type Ticket = (); +/// fn validate(destination: &mut Option, message: &mut Option>) -> SendResult<()> { +/// match destination.as_ref().ok_or(SendError::MissingArgument)?.unpack() { +/// (1, []) => Ok(((), Assets::new())), +/// _ => Err(SendError::NotApplicable), +/// } +/// } +/// fn deliver(_: ()) -> Result { +/// Ok([0; 32]) +/// } +/// } +/// +/// // A call to send via XCM. We don't really care about this. +/// # fn main() { +/// let call: Vec = ().encode(); +/// let message = Xcm(vec![Instruction::Transact { +/// origin_kind: OriginKind::Superuser, +/// call: call.into(), +/// }]); +/// let message_hash = message.using_encoded(sp_io::hashing::blake2_256); +/// +/// // Sender2 will block this. +/// assert!(send_xcm::<(Sender1, Sender2, Sender3)>(Parent.into(), message.clone()).is_err()); +/// +/// // Sender3 will catch this. +/// assert!(send_xcm::<(Sender1, Sender3)>(Parent.into(), message.clone()).is_ok()); +/// # } +/// ``` +pub trait SendXcm { + /// Intermediate value which connects the two phases of the send operation. + type Ticket; + + /// Check whether the given `_message` is deliverable to the given `_destination` and if so + /// determine the cost which will be paid by this chain to do so, returning a `Validated` token + /// which can be used to enact delivery. + /// + /// The `destination` and `message` must be `Some` (or else an error will be returned) and they + /// may only be consumed if the `Err` is not `NotApplicable`. + /// + /// If it is not a destination which can be reached with this type but possibly could by others, + /// then this *MUST* return `NotApplicable`. Any other error will cause the tuple + /// implementation to exit early without trying other type fields. + fn validate( + destination: &mut Option, + message: &mut Option>, + ) -> SendResult; + + /// Actually carry out the delivery operation for a previously validated message sending. + fn deliver(ticket: Self::Ticket) -> result::Result; +} + +#[impl_trait_for_tuples::impl_for_tuples(30)] +impl SendXcm for Tuple { + for_tuples! { type Ticket = (#( Option ),* ); } + + fn validate( + destination: &mut Option, + message: &mut Option>, + ) -> SendResult { + let mut maybe_cost: Option = None; + let one_ticket: Self::Ticket = (for_tuples! { #( + if maybe_cost.is_some() { + None + } else { + match Tuple::validate(destination, message) { + Err(SendError::NotApplicable) => None, + Err(e) => { return Err(e) }, + Ok((v, c)) => { + maybe_cost = Some(c); + Some(v) + }, + } + } + ),* }); + if let Some(cost) = maybe_cost { + Ok((one_ticket, cost)) + } else { + Err(SendError::NotApplicable) + } + } + + fn deliver(one_ticket: Self::Ticket) -> result::Result { + for_tuples!( #( + if let Some(validated) = one_ticket.Tuple { + return Tuple::deliver(validated); + } + )* ); + Err(SendError::Unroutable) + } +} + +/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps +/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +pub fn validate_send(dest: Location, msg: Xcm<()>) -> SendResult { + T::validate(&mut Some(dest), &mut Some(msg)) +} + +/// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps +/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// +/// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message +/// could not be sent. +/// +/// Generally you'll want to validate and get the price first to ensure that the sender can pay it +/// before actually doing the delivery. +pub fn send_xcm( + dest: Location, + msg: Xcm<()>, +) -> result::Result<(XcmHash, Assets), SendError> { + let (ticket, price) = T::validate(&mut Some(dest), &mut Some(msg))?; + let hash = T::deliver(ticket)?; + Ok((hash, price)) +} diff --git a/polkadot/xcm/xcm-builder/src/barriers.rs b/polkadot/xcm/xcm-builder/src/barriers.rs index c995361ea8a3..56a8493ef0ab 100644 --- a/polkadot/xcm/xcm-builder/src/barriers.rs +++ b/polkadot/xcm/xcm-builder/src/barriers.rs @@ -108,6 +108,7 @@ impl> ShouldExecute for AllowTopLevelPaidExecutionFrom *weight_limit = Limited(max_weight); Ok(()) }, + PayFees { .. } => Ok(()), _ => Err(ProcessMessageError::Overweight(max_weight)), })?; Ok(()) diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index bec3bdcb05a0..3d68d8ed16ae 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -108,7 +108,7 @@ pub use nonfungible_adapter::{ }; mod origin_aliases; -pub use origin_aliases::AliasForeignAccountId32; +pub use origin_aliases::*; mod origin_conversion; pub use origin_conversion::{ diff --git a/polkadot/xcm/xcm-builder/src/origin_aliases.rs b/polkadot/xcm/xcm-builder/src/origin_aliases.rs index d568adc3127c..5bc8f0ca32b9 100644 --- a/polkadot/xcm/xcm-builder/src/origin_aliases.rs +++ b/polkadot/xcm/xcm-builder/src/origin_aliases.rs @@ -17,7 +17,7 @@ //! Implementation for `ContainsPair`. use core::marker::PhantomData; -use frame_support::traits::{Contains, ContainsPair}; +use frame_support::traits::{Contains, ContainsPair, Get}; use xcm::latest::prelude::*; /// Alias a Foreign `AccountId32` with a local `AccountId32` if the foreign `AccountId32` matches @@ -38,3 +38,34 @@ impl> ContainsPair false } } + +/// Alias a descendant location of the original origin. +pub struct AliasChildLocation; +impl ContainsPair for AliasChildLocation { + fn contains(origin: &Location, target: &Location) -> bool { + return target.starts_with(origin) + } +} + +/// Alias a location if it passes `Filter` and the original origin is root of `Origin`. +/// +/// This can be used to allow (trusted) system chains root to alias into other locations. +/// **Warning**: do not use with untrusted `Origin` chains. +pub struct AliasOriginRootUsingFilter(PhantomData<(Origin, Filter)>); +impl ContainsPair for AliasOriginRootUsingFilter +where + Origin: Get, + Filter: Contains, +{ + fn contains(origin: &Location, target: &Location) -> bool { + // check that `origin` is a root location + match origin.unpack() { + (1, [Parachain(_)]) | + (2, [GlobalConsensus(_)]) | + (2, [GlobalConsensus(_), Parachain(_)]) => (), + _ => return false, + }; + // check that `origin` matches `Origin` and `target` matches `Filter` + return Origin::get().eq(origin) && Filter::contains(target) + } +} diff --git a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs index 2e6f8c5fb566..8dafbf66adf0 100644 --- a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs +++ b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs @@ -18,7 +18,10 @@ use codec::{Decode, FullCodec, MaxEncodedLen}; use core::{fmt::Debug, marker::PhantomData}; -use frame_support::traits::{ProcessMessage, ProcessMessageError}; +use frame_support::{ + dispatch::GetDispatchInfo, + traits::{ProcessMessage, ProcessMessageError}, +}; use scale_info::TypeInfo; use sp_weights::{Weight, WeightMeter}; use xcm::prelude::*; @@ -32,7 +35,7 @@ pub struct ProcessXcmMessage( impl< MessageOrigin: Into + FullCodec + MaxEncodedLen + Clone + Eq + PartialEq + TypeInfo + Debug, XcmExecutor: ExecuteXcm, - Call, + Call: Decode + GetDispatchInfo, > ProcessMessage for ProcessXcmMessage { type Origin = MessageOrigin; @@ -125,7 +128,7 @@ mod tests { traits::{ProcessMessageError, ProcessMessageError::*}, }; use polkadot_test_runtime::*; - use xcm::{v3, v4, VersionedXcm}; + use xcm::{v3, v4, v5, VersionedXcm}; const ORIGIN: Junction = Junction::OnlyChild; /// The processor to use for tests. @@ -137,13 +140,15 @@ mod tests { // ClearOrigin works. assert!(process(v3_xcm(true)).unwrap()); assert!(process(v4_xcm(true)).unwrap()); + assert!(process(v5_xcm(true)).unwrap()); } #[test] fn process_message_trivial_fails() { // Trap makes it fail. assert!(!process(v3_xcm(false)).unwrap()); - assert!(!process(v3_xcm(false)).unwrap()); + assert!(!process(v4_xcm(false)).unwrap()); + assert!(!process(v5_xcm(false)).unwrap()); } #[test] @@ -179,7 +184,7 @@ mod tests { type Processor = ProcessXcmMessage; - let xcm = VersionedXcm::V4(xcm::latest::Xcm::<()>(vec![ + let xcm = VersionedXcm::from(xcm::latest::Xcm::<()>(vec![ xcm::latest::Instruction::<()>::ClearOrigin, ])); assert_err!( @@ -235,6 +240,15 @@ mod tests { VersionedXcm::V4(v4::Xcm::(vec![instr])) } + fn v5_xcm(success: bool) -> VersionedXcm { + let instr = if success { + v5::Instruction::::ClearOrigin + } else { + v5::Instruction::::Trap(1) + }; + VersionedXcm::V5(v5::Xcm::(vec![instr])) + } + fn process(msg: VersionedXcm) -> Result { process_raw(msg.encode().as_slice()) } diff --git a/polkadot/xcm/xcm-builder/src/tests/aliases.rs b/polkadot/xcm/xcm-builder/src/tests/aliases.rs index 89c17b09396d..dc8b016a6aa4 100644 --- a/polkadot/xcm/xcm-builder/src/tests/aliases.rs +++ b/polkadot/xcm/xcm-builder/src/tests/aliases.rs @@ -88,3 +88,164 @@ fn alias_origin_should_work() { ); assert_eq!(r, Outcome::Complete { used: Weight::from_parts(10, 10) }); } + +#[test] +fn alias_child_location() { + // parents differ + assert!(!AliasChildLocation::contains( + &Location::new(0, Parachain(1)), + &Location::new(1, Parachain(1)), + )); + assert!(!AliasChildLocation::contains( + &Location::new(0, Here), + &Location::new(1, Parachain(1)), + )); + assert!(!AliasChildLocation::contains(&Location::new(1, Here), &Location::new(2, Here),)); + + // interiors differ + assert!(!AliasChildLocation::contains( + &Location::new(1, Parachain(1)), + &Location::new(1, OnlyChild), + )); + assert!(!AliasChildLocation::contains( + &Location::new(1, Parachain(1)), + &Location::new(1, Parachain(12)), + )); + assert!(!AliasChildLocation::contains( + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [0; 32] }]), + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [1; 32] }]), + )); + assert!(!AliasChildLocation::contains( + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [0; 32] }]), + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [1; 32] }]), + )); + + // child to parent not allowed + assert!(!AliasChildLocation::contains( + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [0; 32] }]), + &Location::new(1, [Parachain(1)]), + )); + assert!(!AliasChildLocation::contains( + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [0; 32] }]), + &Location::new(1, Here), + )); + + // parent to child should work + assert!(AliasChildLocation::contains( + &Location::new(1, Here), + &Location::new(1, [Parachain(1), AccountId32 { network: None, id: [1; 32] }]), + )); + assert!( + AliasChildLocation::contains(&Location::new(1, Here), &Location::new(1, Parachain(1)),) + ); + assert!(AliasChildLocation::contains( + &Location::new(0, Here), + &Location::new(0, PalletInstance(42)), + )); + assert!(AliasChildLocation::contains( + &Location::new(2, GlobalConsensus(Kusama)), + &Location::new(2, [GlobalConsensus(Kusama), Parachain(42), GeneralIndex(12)]), + )); +} + +#[test] +fn alias_trusted_root_location() { + const ALICE: [u8; 32] = [111u8; 32]; + const BOB: [u8; 32] = [222u8; 32]; + const BOB_ON_ETH: [u8; 20] = [222u8; 20]; + + parameter_types! { + pub AliceOnAssetHub: Location = Location::new(1, [Parachain(1000), AccountId32 { id: ALICE, network: None }]); + pub SystemAssetHubLocation: Location = Location::new(1, [Parachain(1000)]); + } + + struct MatchSiblingAccounts; + impl Contains for MatchSiblingAccounts { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (1, [Parachain(_), AccountId32 { .. }])) + } + } + + struct MatchOtherGlobalConsensus; + impl Contains for MatchOtherGlobalConsensus { + fn contains(location: &Location) -> bool { + matches!(location.unpack(), (2, [GlobalConsensus(_)]) | (2, [GlobalConsensus(_), _])) + } + } + + type AliceOnAssetHubAliasesSiblingAccounts = + AliasOriginRootUsingFilter; + type AssetHubAliasesSiblingAccounts = + AliasOriginRootUsingFilter; + type AssetHubAliasesOtherGlobalConsensus = + AliasOriginRootUsingFilter; + + // Fails if origin is not the root of a chain. + assert!(!AliceOnAssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000), AccountId32 { id: ALICE, network: None }]), + &Location::new(1, [Parachain(1000), AccountId32 { id: BOB, network: None }]), + )); + assert!(!AliceOnAssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000), AccountId32 { id: ALICE, network: None }]), + &Location::new(2, [GlobalConsensus(NetworkId::Ethereum { chain_id: 1 })]), + )); + assert!(!AliceOnAssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000), AccountId32 { id: ALICE, network: None }]), + &Location::new( + 2, + [ + GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }), + AccountKey20 { key: BOB_ON_ETH, network: None } + ] + ), + )); + // Fails if origin doesn't match. + assert!(!AssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1001)]), + &Location::new(1, [Parachain(1000), AccountId32 { id: BOB, network: None }]), + )); + assert!(!AssetHubAliasesOtherGlobalConsensus::contains( + &Location::new(1, [Parachain(1001)]), + &Location::new( + 2, + [ + GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }), + AccountKey20 { key: BOB_ON_ETH, network: None } + ] + ), + )); + // Fails if filter doesn't match. + assert!(!AssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000)]), + &Location::new(2, [GlobalConsensus(NetworkId::Ethereum { chain_id: 1 })]), + )); + assert!(!AssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000)]), + &Location::new( + 2, + [ + GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }), + AccountKey20 { key: BOB_ON_ETH, network: None } + ] + ), + )); + assert!(!AssetHubAliasesOtherGlobalConsensus::contains( + &Location::new(1, [Parachain(1000)]), + &Location::new(1, [Parachain(1000), AccountId32 { id: BOB, network: None }]), + )); + // Works when origin is a chain that matches Origin and filter also matches. + assert!(AssetHubAliasesSiblingAccounts::contains( + &Location::new(1, [Parachain(1000)]), + &Location::new(1, [Parachain(1000), AccountId32 { id: BOB, network: None }]), + )); + assert!(AssetHubAliasesOtherGlobalConsensus::contains( + &Location::new(1, [Parachain(1000)]), + &Location::new( + 2, + [ + GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }), + AccountKey20 { key: BOB_ON_ETH, network: None } + ] + ), + )); +} diff --git a/polkadot/xcm/xcm-builder/src/tests/transacting.rs b/polkadot/xcm/xcm-builder/src/tests/transacting.rs index a85c8b9986c8..8963e7147fdc 100644 --- a/polkadot/xcm/xcm-builder/src/tests/transacting.rs +++ b/polkadot/xcm/xcm-builder/src/tests/transacting.rs @@ -22,7 +22,6 @@ fn transacting_should_work() { let message = Xcm::(vec![Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }]); let mut hash = fake_message_hash(&message); @@ -43,7 +42,6 @@ fn transacting_should_respect_max_weight_requirement() { let message = Xcm::(vec![Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(40, 40), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }]); let mut hash = fake_message_hash(&message); @@ -55,10 +53,7 @@ fn transacting_should_respect_max_weight_requirement() { weight_limit, Weight::zero(), ); - assert_eq!( - r, - Outcome::Incomplete { used: Weight::from_parts(50, 50), error: XcmError::MaxWeightInvalid } - ); + assert_eq!(r, Outcome::Complete { used: Weight::from_parts(60, 60) }); } #[test] @@ -67,7 +62,6 @@ fn transacting_should_refund_weight() { let message = Xcm::(vec![Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), Some(Weight::from_parts(30, 30))) .encode() .into(), @@ -98,7 +92,6 @@ fn paid_transacting_should_refund_payment_for_unused_weight() { BuyExecution { fees, weight_limit: Limited(Weight::from_parts(100, 100)) }, Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), // call estimated at 50 but only takes 10. call: TestCall::Any(Weight::from_parts(50, 50), Some(Weight::from_parts(10, 10))) .encode() @@ -130,7 +123,6 @@ fn report_successful_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }, ReportTransactStatus(QueryResponseInfo { @@ -166,7 +158,6 @@ fn report_failed_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::OnlyRoot(Weight::from_parts(50, 50), None).encode().into(), }, ReportTransactStatus(QueryResponseInfo { @@ -202,7 +193,6 @@ fn expect_successful_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }, ExpectTransactStatus(MaybeErrorCode::Success), @@ -221,7 +211,6 @@ fn expect_successful_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::OnlyRoot(Weight::from_parts(50, 50), None).encode().into(), }, ExpectTransactStatus(MaybeErrorCode::Success), @@ -248,7 +237,6 @@ fn expect_failed_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::OnlyRoot(Weight::from_parts(50, 50), None).encode().into(), }, ExpectTransactStatus(vec![2].into()), @@ -267,7 +255,6 @@ fn expect_failed_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::Any(Weight::from_parts(50, 50), None).encode().into(), }, ExpectTransactStatus(vec![2].into()), @@ -294,7 +281,6 @@ fn clear_transact_status_should_work() { let message = Xcm::(vec![ Transact { origin_kind: OriginKind::Native, - require_weight_at_most: Weight::from_parts(50, 50), call: TestCall::OnlyRoot(Weight::from_parts(50, 50), None).encode().into(), }, ClearTransactStatus, diff --git a/polkadot/xcm/xcm-builder/src/weight.rs b/polkadot/xcm/xcm-builder/src/weight.rs index 7861fdcc2e57..f8c0275d0f54 100644 --- a/polkadot/xcm/xcm-builder/src/weight.rs +++ b/polkadot/xcm/xcm-builder/src/weight.rs @@ -43,26 +43,28 @@ impl, C: Decode + GetDispatchInfo, M: Get> WeightBounds let mut instructions_left = M::get(); Self::weight_with_limit(message, &mut instructions_left) } - fn instr_weight(instruction: &Instruction) -> Result { + fn instr_weight(instruction: &mut Instruction) -> Result { Self::instr_weight_with_limit(instruction, &mut u32::max_value()) } } impl, C: Decode + GetDispatchInfo, M> FixedWeightBounds { - fn weight_with_limit(message: &Xcm, instrs_limit: &mut u32) -> Result { + fn weight_with_limit(message: &mut Xcm, instrs_limit: &mut u32) -> Result { let mut r: Weight = Weight::zero(); *instrs_limit = instrs_limit.checked_sub(message.0.len() as u32).ok_or(())?; - for m in message.0.iter() { - r = r.checked_add(&Self::instr_weight_with_limit(m, instrs_limit)?).ok_or(())?; + for instruction in message.0.iter_mut() { + r = r + .checked_add(&Self::instr_weight_with_limit(instruction, instrs_limit)?) + .ok_or(())?; } Ok(r) } fn instr_weight_with_limit( - instruction: &Instruction, + instruction: &mut Instruction, instrs_limit: &mut u32, ) -> Result { let instr_weight = match instruction { - Transact { require_weight_at_most, .. } => *require_weight_at_most, + Transact { ref mut call, .. } => call.ensure_decoded()?.get_dispatch_info().call_weight, SetErrorHandler(xcm) | SetAppendix(xcm) => Self::weight_with_limit(xcm, instrs_limit)?, _ => Weight::zero(), }; @@ -83,7 +85,7 @@ where let mut instructions_left = M::get(); Self::weight_with_limit(message, &mut instructions_left) } - fn instr_weight(instruction: &Instruction) -> Result { + fn instr_weight(instruction: &mut Instruction) -> Result { Self::instr_weight_with_limit(instruction, &mut u32::max_value()) } } @@ -95,20 +97,22 @@ where M: Get, Instruction: xcm::latest::GetWeight, { - fn weight_with_limit(message: &Xcm, instrs_limit: &mut u32) -> Result { + fn weight_with_limit(message: &mut Xcm, instrs_limit: &mut u32) -> Result { let mut r: Weight = Weight::zero(); *instrs_limit = instrs_limit.checked_sub(message.0.len() as u32).ok_or(())?; - for m in message.0.iter() { - r = r.checked_add(&Self::instr_weight_with_limit(m, instrs_limit)?).ok_or(())?; + for instruction in message.0.iter_mut() { + r = r + .checked_add(&Self::instr_weight_with_limit(instruction, instrs_limit)?) + .ok_or(())?; } Ok(r) } fn instr_weight_with_limit( - instruction: &Instruction, + instruction: &mut Instruction, instrs_limit: &mut u32, ) -> Result { let instr_weight = match instruction { - Transact { require_weight_at_most, .. } => *require_weight_at_most, + Transact { ref mut call, .. } => call.ensure_decoded()?.get_dispatch_info().call_weight, SetErrorHandler(xcm) | SetAppendix(xcm) => Self::weight_with_limit(xcm, instrs_limit)?, _ => Weight::zero(), }; @@ -227,7 +231,7 @@ impl< log::trace!(target: "xcm::weight", "UsingComponents::buy_weight weight: {:?}, payment: {:?}, context: {:?}", weight, payment, context); let amount = WeightToFee::weight_to_fee(&weight); let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?; - let required = (AssetId(AssetIdValue::get()), u128_amount).into(); + let required = Asset { id: AssetId(AssetIdValue::get()), fun: Fungible(u128_amount) }; let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?; self.0 = self.0.saturating_add(weight); self.1 = self.1.saturating_add(amount); diff --git a/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs b/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs index e95473c5407e..9b918fd7eeed 100644 --- a/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs +++ b/polkadot/xcm/xcm-executor/integration-tests/src/lib.rs @@ -17,7 +17,7 @@ #![cfg(test)] use codec::Encode; -use frame_support::{dispatch::GetDispatchInfo, weights::Weight}; +use frame_support::weights::Weight; use polkadot_test_client::{ BlockBuilderExt, ClientBlockImportExt, DefaultTestClientBuilderExt, InitPolkadotBlockBuilder, TestClientBuilder, TestClientBuilderExt, @@ -79,11 +79,7 @@ fn transact_recursion_limit_works() { Xcm(vec![ WithdrawAsset((Here, 1_000).into()), BuyExecution { fees: (Here, 1).into(), weight_limit: Unlimited }, - Transact { - origin_kind: OriginKind::Native, - require_weight_at_most: call.get_dispatch_info().call_weight, - call: call.encode().into(), - }, + Transact { origin_kind: OriginKind::Native, call: call.encode().into() }, ]) }; let mut call: Option = None; @@ -241,7 +237,7 @@ fn query_response_fires() { assert_eq!( polkadot_test_runtime::Xcm::query(query_id), Some(QueryStatus::Ready { - response: VersionedResponse::V4(Response::ExecutionResult(None)), + response: VersionedResponse::from(Response::ExecutionResult(None)), at: 2u32.into() }), ) diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs index e3addfa3e794..a823dc6fec78 100644 --- a/polkadot/xcm/xcm-executor/src/lib.rs +++ b/polkadot/xcm/xcm-executor/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ use sp_core::defer; use sp_io::hashing::blake2_128; use sp_weights::Weight; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, AssetTransferFilter}; pub mod traits; use traits::{ @@ -47,6 +47,9 @@ pub use assets::AssetsInHolding; mod config; pub use config::Config; +#[cfg(test)] +mod tests; + /// A struct to specify how fees are being paid. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct FeesMode { @@ -83,13 +86,17 @@ pub struct XcmExecutor { appendix_weight: Weight, transact_status: MaybeErrorCode, fees_mode: FeesMode, + fees: AssetsInHolding, /// Asset provided in last `BuyExecution` instruction (if any) in current XCM program. Same /// asset type will be used for paying any potential delivery fees incurred by the program. - asset_used_for_fees: Option, + asset_used_in_buy_execution: Option, + /// Stores the current message's weight. + message_weight: Weight, + asset_claimer: Option, _config: PhantomData, } -#[cfg(feature = "runtime-benchmarks")] +#[cfg(any(test, feature = "runtime-benchmarks"))] impl XcmExecutor { pub fn holding(&self) -> &AssetsInHolding { &self.holding @@ -175,12 +182,24 @@ impl XcmExecutor { pub fn set_fees_mode(&mut self, v: FeesMode) { self.fees_mode = v } + pub fn fees(&self) -> &AssetsInHolding { + &self.fees + } + pub fn set_fees(&mut self, value: AssetsInHolding) { + self.fees = value; + } pub fn topic(&self) -> &Option<[u8; 32]> { &self.context.topic } pub fn set_topic(&mut self, v: Option<[u8; 32]>) { self.context.topic = v; } + pub fn asset_claimer(&self) -> Option { + self.asset_claimer.clone() + } + pub fn set_message_weight(&mut self, weight: Weight) { + self.message_weight = weight; + } } pub struct WeighedMessage(Weight, Xcm); @@ -249,6 +268,7 @@ impl ExecuteXcm for XcmExecutor XcmExecutor { appendix_weight: Weight::zero(), transact_status: Default::default(), fees_mode: FeesMode { jit_withdraw: false }, - asset_used_for_fees: None, + fees: AssetsInHolding::new(), + asset_used_in_buy_execution: None, + message_weight: Weight::zero(), + asset_claimer: None, _config: PhantomData, } } @@ -346,9 +369,12 @@ impl XcmExecutor { original_origin = ?self.original_origin, "Trapping assets in holding register", ); - let effective_origin = self.context.origin.as_ref().unwrap_or(&self.original_origin); - let trap_weight = - Config::AssetTrap::drop_assets(effective_origin, self.holding, &self.context); + let claimer = if let Some(asset_claimer) = self.asset_claimer.as_ref() { + asset_claimer + } else { + self.context.origin.as_ref().unwrap_or(&self.original_origin) + }; + let trap_weight = Config::AssetTrap::drop_assets(claimer, self.holding, &self.context); weight_used.saturating_accrue(trap_weight); }; @@ -466,6 +492,11 @@ impl XcmExecutor { self.holding.subsume_assets(w.into()); } } + // If there are any leftover `fees`, merge them with `holding`. + if !self.fees.is_empty() { + let leftover_fees = self.fees.saturating_take(Wild(All)); + self.holding.subsume_assets(leftover_fees); + } tracing::trace!( target: "xcm::refund_surplus", total_refunded = ?self.total_refunded, @@ -490,7 +521,7 @@ impl XcmExecutor { Some(fee) => fee, None => return Ok(()), // No delivery fees need to be paid. }; - // If `BuyExecution` was called, we use that asset for delivery fees as well. + // If `BuyExecution` or `PayFees` was called, we use that asset for delivery fees as well. let asset_to_pay_for_fees = self.calculate_asset_for_delivery_fees(asset_needed_for_fees.clone()); tracing::trace!(target: "xcm::fees", ?asset_to_pay_for_fees); @@ -505,15 +536,31 @@ impl XcmExecutor { tracing::trace!(target: "xcm::fees", ?asset_needed_for_fees); asset_to_pay_for_fees.clone().into() } else { - let assets_taken_from_holding_to_pay_delivery_fees = self - .holding - .try_take(asset_to_pay_for_fees.clone().into()) - .map_err(|e| { - tracing::error!(target: "xcm::fees", ?e, ?asset_to_pay_for_fees, "Failed to take asset_to_pay_for_fees from holding"); - XcmError::NotHoldingFees - })?; - tracing::trace!(target: "xcm::fees", ?assets_taken_from_holding_to_pay_delivery_fees); - let mut iter = assets_taken_from_holding_to_pay_delivery_fees.fungible_assets_iter(); + // This condition exists to support `BuyExecution` while the ecosystem + // transitions to `PayFees`. + let assets_to_pay_delivery_fees: AssetsInHolding = if self.fees.is_empty() { + // Means `BuyExecution` was used, we'll find the fees in the `holding` register. + self.holding + .try_take(asset_to_pay_for_fees.clone().into()) + .map_err(|e| { + tracing::error!(target: "xcm::fees", ?e, ?asset_to_pay_for_fees, + "Holding doesn't hold enough for fees"); + XcmError::NotHoldingFees + })? + .into() + } else { + // Means `PayFees` was used, we'll find the fees in the `fees` register. + self.fees + .try_take(asset_to_pay_for_fees.clone().into()) + .map_err(|e| { + tracing::error!(target: "xcm::fees", ?e, ?asset_to_pay_for_fees, + "Fees register doesn't hold enough for fees"); + XcmError::NotHoldingFees + })? + .into() + }; + tracing::trace!(target: "xcm::fees", ?assets_to_pay_delivery_fees); + let mut iter = assets_to_pay_delivery_fees.fungible_assets_iter(); let asset = iter.next().ok_or(XcmError::NotHoldingFees)?; asset.into() }; @@ -544,41 +591,45 @@ impl XcmExecutor { Ok(()) } - /// Calculates the amount of `self.asset_used_for_fees` required to swap for - /// `asset_needed_for_fees`. + /// Calculates the amount of asset used in `PayFees` or `BuyExecution` that would be + /// charged for swapping to `asset_needed_for_fees`. /// /// The calculation is done by `Config::AssetExchanger`. - /// If `self.asset_used_for_fees` is not set, it will just return `asset_needed_for_fees`. + /// If neither `PayFees` or `BuyExecution` were not used, or no swap is required, + /// it will just return `asset_needed_for_fees`. fn calculate_asset_for_delivery_fees(&self, asset_needed_for_fees: Asset) -> Asset { - if let Some(asset_wanted_for_fees) = &self.asset_used_for_fees { - if *asset_wanted_for_fees != asset_needed_for_fees.id { - match Config::AssetExchanger::quote_exchange_price( - &(asset_wanted_for_fees.clone(), Fungible(0)).into(), - &asset_needed_for_fees.clone().into(), - false, // Minimal. - ) { - Some(necessary_assets) => - // We only use the first asset for fees. - // If this is not enough to swap for the fee asset then it will error later down - // the line. - necessary_assets.get(0).unwrap_or(&asset_needed_for_fees.clone()).clone(), - // If we can't convert, then we return the original asset. - // It will error later in any case. - None => { - tracing::trace!( - target: "xcm::calculate_asset_for_delivery_fees", - ?asset_wanted_for_fees, - "Could not convert fees", - ); - asset_needed_for_fees.clone() - }, - } - } else { - asset_needed_for_fees - } - } else { + let Some(asset_wanted_for_fees) = + // we try to swap first asset in the fees register (should only ever be one), + self.fees.fungible.first_key_value().map(|(id, _)| id).or_else(|| { + // or the one used in BuyExecution + self.asset_used_in_buy_execution.as_ref() + }) + // if it is different than what we need + .filter(|&id| asset_needed_for_fees.id.ne(id)) + else { + // either nothing to swap or we're already holding the right asset + return asset_needed_for_fees + }; + Config::AssetExchanger::quote_exchange_price( + &(asset_wanted_for_fees.clone(), Fungible(0)).into(), + &asset_needed_for_fees.clone().into(), + false, // Minimal. + ) + .and_then(|necessary_assets| { + // We only use the first asset for fees. + // If this is not enough to swap for the fee asset then it will error later down + // the line. + necessary_assets.into_inner().into_iter().next() + }) + .unwrap_or_else(|| { + // If we can't convert, then we return the original asset. + // It will error later in any case. + tracing::trace!( + target: "xcm::calculate_asset_for_delivery_fees", + ?asset_wanted_for_fees, "Could not convert fees", + ); asset_needed_for_fees - } + }) } /// Calculates what `local_querier` would be from the perspective of `destination`. @@ -614,6 +665,74 @@ impl XcmExecutor { self.send(destination, message, fee_reason) } + fn do_reserve_deposit_assets( + assets: AssetsInHolding, + dest: &Location, + remote_xcm: &mut Vec>, + context: Option<&XcmContext>, + ) -> Result { + Self::deposit_assets_with_retry(&assets, dest, context)?; + // Note that we pass `None` as `maybe_failed_bin` and drop any assets which + // cannot be reanchored, because we have already called `deposit_asset` on + // all assets. + let reanchored_assets = Self::reanchored(assets, dest, None); + remote_xcm.push(ReserveAssetDeposited(reanchored_assets.clone())); + + Ok(reanchored_assets) + } + + fn do_reserve_withdraw_assets( + assets: AssetsInHolding, + failed_bin: &mut AssetsInHolding, + reserve: &Location, + remote_xcm: &mut Vec>, + ) -> Result { + // Must ensure that we recognise the assets as being managed by the destination. + #[cfg(not(any(test, feature = "runtime-benchmarks")))] + for asset in assets.assets_iter() { + ensure!( + Config::IsReserve::contains(&asset, &reserve), + XcmError::UntrustedReserveLocation + ); + } + // Note that here we are able to place any assets which could not be + // reanchored back into Holding. + let reanchored_assets = Self::reanchored(assets, reserve, Some(failed_bin)); + remote_xcm.push(WithdrawAsset(reanchored_assets.clone())); + + Ok(reanchored_assets) + } + + fn do_teleport_assets( + assets: AssetsInHolding, + dest: &Location, + remote_xcm: &mut Vec>, + context: &XcmContext, + ) -> Result { + for asset in assets.assets_iter() { + // Must ensure that we have teleport trust with destination for these assets. + #[cfg(not(any(test, feature = "runtime-benchmarks")))] + ensure!( + Config::IsTeleporter::contains(&asset, &dest), + XcmError::UntrustedTeleportLocation + ); + // We should check that the asset can actually be teleported out (for + // this to be in error, there would need to be an accounting violation + // by ourselves, so it's unlikely, but we don't want to allow that kind + // of bug to leak into a trusted chain. + Config::AssetTransactor::can_check_out(dest, &asset, context)?; + } + for asset in assets.assets_iter() { + Config::AssetTransactor::check_out(dest, &asset, context); + } + // Note that we pass `None` as `maybe_failed_bin` and drop any assets which + // cannot be reanchored, because we have already checked all assets out. + let reanchored_assets = Self::reanchored(assets, dest, None); + remote_xcm.push(ReceiveTeleportedAsset(reanchored_assets.clone())); + + Ok(reanchored_assets) + } + fn try_reanchor( reanchorable: T, destination: &Location, @@ -638,11 +757,16 @@ impl XcmExecutor { assets.into_assets_iter().collect::>().into() } - #[cfg(feature = "runtime-benchmarks")] + #[cfg(any(test, feature = "runtime-benchmarks"))] pub fn bench_process(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { self.process(xcm) } + #[cfg(any(test, feature = "runtime-benchmarks"))] + pub fn bench_post_process(self, xcm_weight: Weight) -> Outcome { + self.post_process(xcm_weight) + } + fn process(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { tracing::trace!( target: "xcm::process", @@ -652,7 +776,7 @@ impl XcmExecutor { error_handler_weight = ?self.error_handler_weight, ); let mut result = Ok(()); - for (i, instr) in xcm.0.into_iter().enumerate() { + for (i, mut instr) in xcm.0.into_iter().enumerate() { match &mut result { r @ Ok(()) => { // Initialize the recursion count only the first time we hit this code in our @@ -688,7 +812,7 @@ impl XcmExecutor { } }, Err(ref mut error) => - if let Ok(x) = Config::Weigher::instr_weight(&instr) { + if let Ok(x) = Config::Weigher::instr_weight(&mut instr) { error.weight.saturating_accrue(x) }, } @@ -805,7 +929,7 @@ impl XcmExecutor { Ok(()) }) }, - Transact { origin_kind, require_weight_at_most, mut call } => { + Transact { origin_kind, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. let origin = self.cloned_origin().ok_or_else(|| { tracing::trace!( @@ -862,18 +986,6 @@ impl XcmExecutor { ); let weight = message_call.get_dispatch_info().call_weight; - - if !weight.all_lte(require_weight_at_most) { - tracing::trace!( - target: "xcm::process_instruction::transact", - %weight, - %require_weight_at_most, - "Max weight bigger than require at most", - ); - - return Err(XcmError::MaxWeightInvalid) - } - let maybe_actual_weight = match Config::CallDispatcher::dispatch(message_call, dispatch_origin) { Ok(post_info) => { @@ -898,9 +1010,7 @@ impl XcmExecutor { }; let actual_weight = maybe_actual_weight.unwrap_or(weight); let surplus = weight.saturating_sub(actual_weight); - // We assume that the `Config::Weigher` will count the `require_weight_at_most` - // for the estimate of how much weight this instruction will take. Now that we know - // that it's less, we credit it. + // If the actual weight of the call was less than the specified weight, we credit it. // // We make the adjustment for the total surplus, which is used eventually // reported back to the caller and this ensures that they account for the total @@ -950,7 +1060,7 @@ impl XcmExecutor { let old_holding = self.holding.clone(); let result = Config::TransactionalProcessor::process(|| { let deposited = self.holding.saturating_take(assets); - self.deposit_assets_with_retry(&deposited, &beneficiary) + Self::deposit_assets_with_retry(&deposited, &beneficiary, Some(&self.context)) }); if Config::TransactionalProcessor::IS_TRANSACTIONAL && result.is_err() { self.holding = old_holding; @@ -960,42 +1070,28 @@ impl XcmExecutor { DepositReserveAsset { assets, dest, xcm } => { let old_holding = self.holding.clone(); let result = Config::TransactionalProcessor::process(|| { - // we need to do this take/put cycle to solve wildcards and get exact assets to - // be weighed - let to_weigh = self.holding.saturating_take(assets.clone()); - self.holding.subsume_assets(to_weigh.clone()); - let to_weigh_reanchored = Self::reanchored(to_weigh, &dest, None); - let mut message_to_weigh = - vec![ReserveAssetDeposited(to_weigh_reanchored), ClearOrigin]; - message_to_weigh.extend(xcm.0.clone().into_iter()); - let (_, fee) = - validate_send::(dest.clone(), Xcm(message_to_weigh))?; - let maybe_delivery_fee = fee.get(0).map(|asset_needed_for_fees| { - tracing::trace!( - target: "xcm::DepositReserveAsset", - "Asset provided to pay for fees {:?}, asset required for delivery fees: {:?}", - self.asset_used_for_fees, asset_needed_for_fees, - ); - let asset_to_pay_for_fees = - self.calculate_asset_for_delivery_fees(asset_needed_for_fees.clone()); - // set aside fee to be charged by XcmSender - let delivery_fee = - self.holding.saturating_take(asset_to_pay_for_fees.into()); - tracing::trace!(target: "xcm::DepositReserveAsset", ?delivery_fee); - delivery_fee - }); + let maybe_delivery_fee_from_holding = if self.fees.is_empty() { + self.get_delivery_fee_from_holding(&assets, &dest, &xcm)? + } else { + None + }; + + let mut message = Vec::with_capacity(xcm.len() + 2); // now take assets to deposit (after having taken delivery fees) let deposited = self.holding.saturating_take(assets); tracing::trace!(target: "xcm::DepositReserveAsset", ?deposited, "Assets except delivery fee"); - self.deposit_assets_with_retry(&deposited, &dest)?; - // Note that we pass `None` as `maybe_failed_bin` and drop any assets which - // cannot be reanchored because we have already called `deposit_asset` on all - // assets. - let assets = Self::reanchored(deposited, &dest, None); - let mut message = vec![ReserveAssetDeposited(assets), ClearOrigin]; + Self::do_reserve_deposit_assets( + deposited, + &dest, + &mut message, + Some(&self.context), + )?; + // clear origin for subsequent custom instructions + message.push(ClearOrigin); + // append custom instructions message.extend(xcm.0.into_iter()); - // put back delivery_fee in holding register to be charged by XcmSender - if let Some(delivery_fee) = maybe_delivery_fee { + if let Some(delivery_fee) = maybe_delivery_fee_from_holding { + // Put back delivery_fee in holding register to be charged by XcmSender. self.holding.subsume_assets(delivery_fee); } self.send(dest, Xcm(message), FeeReason::DepositReserveAsset)?; @@ -1010,18 +1106,16 @@ impl XcmExecutor { let old_holding = self.holding.clone(); let result = Config::TransactionalProcessor::process(|| { let assets = self.holding.saturating_take(assets); - // Must ensure that we recognise the assets as being managed by the destination. - #[cfg(not(feature = "runtime-benchmarks"))] - for asset in assets.assets_iter() { - ensure!( - Config::IsReserve::contains(&asset, &reserve), - XcmError::UntrustedReserveLocation - ); - } - // Note that here we are able to place any assets which could not be reanchored - // back into Holding. - let assets = Self::reanchored(assets, &reserve, Some(&mut self.holding)); - let mut message = vec![WithdrawAsset(assets), ClearOrigin]; + let mut message = Vec::with_capacity(xcm.len() + 2); + Self::do_reserve_withdraw_assets( + assets, + &mut self.holding, + &reserve, + &mut message, + )?; + // clear origin for subsequent custom instructions + message.push(ClearOrigin); + // append custom instructions message.extend(xcm.0.into_iter()); self.send(reserve, Xcm(message), FeeReason::InitiateReserveWithdraw)?; Ok(()) @@ -1033,37 +1127,131 @@ impl XcmExecutor { }, InitiateTeleport { assets, dest, xcm } => { let old_holding = self.holding.clone(); - let result = (|| -> Result<(), XcmError> { - // We must do this first in order to resolve wildcards. + let result = Config::TransactionalProcessor::process(|| { let assets = self.holding.saturating_take(assets); - // Must ensure that we have teleport trust with destination for these assets. - #[cfg(not(feature = "runtime-benchmarks"))] - for asset in assets.assets_iter() { - ensure!( - Config::IsTeleporter::contains(&asset, &dest), - XcmError::UntrustedTeleportLocation - ); - } - for asset in assets.assets_iter() { - // We should check that the asset can actually be teleported out (for this - // to be in error, there would need to be an accounting violation by - // ourselves, so it's unlikely, but we don't want to allow that kind of bug - // to leak into a trusted chain. - Config::AssetTransactor::can_check_out(&dest, &asset, &self.context)?; - } - // Note that we pass `None` as `maybe_failed_bin` and drop any assets which - // cannot be reanchored because we have already checked all assets out. - let reanchored_assets = Self::reanchored(assets.clone(), &dest, None); - let mut message = vec![ReceiveTeleportedAsset(reanchored_assets), ClearOrigin]; + let mut message = Vec::with_capacity(xcm.len() + 2); + Self::do_teleport_assets(assets, &dest, &mut message, &self.context)?; + // clear origin for subsequent custom instructions + message.push(ClearOrigin); + // append custom instructions message.extend(xcm.0.into_iter()); self.send(dest.clone(), Xcm(message), FeeReason::InitiateTeleport)?; + Ok(()) + }); + if Config::TransactionalProcessor::IS_TRANSACTIONAL && result.is_err() { + self.holding = old_holding; + } + result + }, + InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => { + let old_holding = self.holding.clone(); + let result = Config::TransactionalProcessor::process(|| { + let mut message = Vec::with_capacity(assets.len() + remote_xcm.len() + 2); + + // We need to transfer the fees and buy execution on remote chain _BEFORE_ + // transferring the other assets. This is required to satisfy the + // `MAX_ASSETS_FOR_BUY_EXECUTION` limit in the `AllowTopLevelPaidExecutionFrom` + // barrier. + if let Some(remote_fees) = remote_fees { + let reanchored_fees = match remote_fees { + AssetTransferFilter::Teleport(fees_filter) => { + let teleport_fees = self + .holding + .try_take(fees_filter) + .map_err(|_| XcmError::NotHoldingFees)?; + Self::do_teleport_assets( + teleport_fees, + &destination, + &mut message, + &self.context, + )? + }, + AssetTransferFilter::ReserveDeposit(fees_filter) => { + let reserve_deposit_fees = self + .holding + .try_take(fees_filter) + .map_err(|_| XcmError::NotHoldingFees)?; + Self::do_reserve_deposit_assets( + reserve_deposit_fees, + &destination, + &mut message, + Some(&self.context), + )? + }, + AssetTransferFilter::ReserveWithdraw(fees_filter) => { + let reserve_withdraw_fees = self + .holding + .try_take(fees_filter) + .map_err(|_| XcmError::NotHoldingFees)?; + Self::do_reserve_withdraw_assets( + reserve_withdraw_fees, + &mut self.holding, + &destination, + &mut message, + )? + }, + }; + ensure!(reanchored_fees.len() == 1, XcmError::TooManyAssets); + let fees = + reanchored_fees.into_inner().pop().ok_or(XcmError::NotHoldingFees)?; + // move these assets to the fees register for covering execution and paying + // any subsequent fees + message.push(PayFees { asset: fees }); + } else { + // unpaid execution + message + .push(UnpaidExecution { weight_limit: Unlimited, check_origin: None }); + } - for asset in assets.assets_iter() { - Config::AssetTransactor::check_out(&dest, &asset, &self.context); + // add any extra asset transfers + for asset_filter in assets { + match asset_filter { + AssetTransferFilter::Teleport(assets) => Self::do_teleport_assets( + self.holding.saturating_take(assets), + &destination, + &mut message, + &self.context, + )?, + AssetTransferFilter::ReserveDeposit(assets) => + Self::do_reserve_deposit_assets( + self.holding.saturating_take(assets), + &destination, + &mut message, + Some(&self.context), + )?, + AssetTransferFilter::ReserveWithdraw(assets) => + Self::do_reserve_withdraw_assets( + self.holding.saturating_take(assets), + &mut self.holding, + &destination, + &mut message, + )?, + }; } + if preserve_origin { + // preserve current origin for subsequent user-controlled instructions on + // remote chain + let original_origin = self + .origin_ref() + .cloned() + .and_then(|origin| { + Self::try_reanchor(origin, &destination) + .map(|(reanchored, _)| reanchored) + .ok() + }) + .ok_or(XcmError::BadOrigin)?; + message.push(AliasOrigin(original_origin)); + } else { + // clear origin for subsequent user-controlled instructions on remote chain + message.push(ClearOrigin); + } + // append custom instructions + message.extend(remote_xcm.0.into_iter()); + // send the onward XCM + self.send(destination, Xcm(message), FeeReason::InitiateTransfer)?; Ok(()) - })(); - if result.is_err() { + }); + if Config::TransactionalProcessor::IS_TRANSACTIONAL && result.is_err() { self.holding = old_holding; } result @@ -1090,24 +1278,61 @@ impl XcmExecutor { let old_holding = self.holding.clone(); // Save the asset being used for execution fees, so we later know what should be // used for delivery fees. - self.asset_used_for_fees = Some(fees.id.clone()); - tracing::trace!(target: "xcm::executor::BuyExecution", asset_used_for_fees = ?self.asset_used_for_fees); + self.asset_used_in_buy_execution = Some(fees.id.clone()); + tracing::trace!( + target: "xcm::executor::BuyExecution", + asset_used_in_buy_execution = ?self.asset_used_in_buy_execution + ); // pay for `weight` using up to `fees` of the holding register. let max_fee = self.holding.try_take(fees.clone().into()).map_err(|e| { - tracing::error!(target: "xcm::process_instruction::buy_execution", ?e, ?fees, "Failed to take fees from holding"); + tracing::error!(target: "xcm::process_instruction::buy_execution", ?e, ?fees, + "Failed to take fees from holding"); XcmError::NotHoldingFees })?; - let result = || -> Result<(), XcmError> { + let result = Config::TransactionalProcessor::process(|| { let unspent = self.trader.buy_weight(weight, max_fee, &self.context)?; self.holding.subsume_assets(unspent); Ok(()) - }(); + }); if result.is_err() { self.holding = old_holding; } result }, + PayFees { asset } => { + // Message was not weighed, there is nothing to pay. + if self.message_weight == Weight::zero() { + tracing::warn!( + target: "xcm::executor::PayFees", + "Message was not weighed or weight was 0. Nothing will be charged.", + ); + return Ok(()); + } + // Record old holding in case we need to rollback. + let old_holding = self.holding.clone(); + // The max we're willing to pay for fees is decided by the `asset` operand. + tracing::trace!( + target: "xcm::executor::PayFees", + asset_for_fees = ?asset, + message_weight = ?self.message_weight, + ); + let max_fee = + self.holding.try_take(asset.into()).map_err(|_| XcmError::NotHoldingFees)?; + // Pay for execution fees. + let result = Config::TransactionalProcessor::process(|| { + let unspent = + self.trader.buy_weight(self.message_weight, max_fee, &self.context)?; + // Move unspent to the `fees` register. + self.fees.subsume_assets(unspent); + Ok(()) + }); + if Config::TransactionalProcessor::IS_TRANSACTIONAL && result.is_err() { + // Rollback. + self.holding = old_holding; + } + result + }, RefundSurplus => self.refund_surplus(), SetErrorHandler(mut handler) => { let handler_weight = Config::Weigher::weight(&mut handler) @@ -1129,6 +1354,10 @@ impl XcmExecutor { self.error = None; Ok(()) }, + SetAssetClaimer { location } => { + self.asset_claimer = Some(location); + Ok(()) + }, ClaimAsset { assets, ticket } => { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; self.ensure_can_subsume_assets(assets.len())?; @@ -1338,7 +1567,7 @@ impl XcmExecutor { ExchangeAsset { give, want, maximal } => { let old_holding = self.holding.clone(); let give = self.holding.saturating_take(give); - let result = (|| -> Result<(), XcmError> { + let result = Config::TransactionalProcessor::process(|| { self.ensure_can_subsume_assets(want.len())?; let exchange_result = Config::AssetExchanger::exchange_asset( self.origin_ref(), @@ -1352,7 +1581,7 @@ impl XcmExecutor { } else { Err(XcmError::NoDeal) } - })(); + }); if result.is_err() { self.holding = old_holding; } @@ -1414,16 +1643,15 @@ impl XcmExecutor { /// This function can write into storage and also return an error at the same time, it should /// always be called within a transactional context. fn deposit_assets_with_retry( - &mut self, to_deposit: &AssetsInHolding, beneficiary: &Location, + context: Option<&XcmContext>, ) -> Result<(), XcmError> { let mut failed_deposits = Vec::with_capacity(to_deposit.len()); let mut deposit_result = Ok(()); for asset in to_deposit.assets_iter() { - deposit_result = - Config::AssetTransactor::deposit_asset(&asset, &beneficiary, Some(&self.context)); + deposit_result = Config::AssetTransactor::deposit_asset(&asset, &beneficiary, context); // if deposit failed for asset, mark it for retry after depositing the others. if deposit_result.is_err() { failed_deposits.push(asset); @@ -1441,8 +1669,43 @@ impl XcmExecutor { // retry previously failed deposits, this time short-circuiting on any error. for asset in failed_deposits { - Config::AssetTransactor::deposit_asset(&asset, &beneficiary, Some(&self.context))?; + Config::AssetTransactor::deposit_asset(&asset, &beneficiary, context)?; } Ok(()) } + + /// Gets the necessary delivery fee to send a reserve transfer message to `destination` from + /// holding. + /// + /// Will be removed once the transition from `BuyExecution` to `PayFees` is complete. + fn get_delivery_fee_from_holding( + &mut self, + assets: &AssetFilter, + destination: &Location, + xcm: &Xcm<()>, + ) -> Result, XcmError> { + // we need to do this take/put cycle to solve wildcards and get exact assets to + // be weighed + let to_weigh = self.holding.saturating_take(assets.clone()); + self.holding.subsume_assets(to_weigh.clone()); + let to_weigh_reanchored = Self::reanchored(to_weigh, &destination, None); + let mut message_to_weigh = vec![ReserveAssetDeposited(to_weigh_reanchored), ClearOrigin]; + message_to_weigh.extend(xcm.0.clone().into_iter()); + let (_, fee) = + validate_send::(destination.clone(), Xcm(message_to_weigh))?; + let maybe_delivery_fee = fee.get(0).map(|asset_needed_for_fees| { + tracing::trace!( + target: "xcm::fees::DepositReserveAsset", + "Asset provided to pay for fees {:?}, asset required for delivery fees: {:?}", + self.asset_used_in_buy_execution, asset_needed_for_fees, + ); + let asset_to_pay_for_fees = + self.calculate_asset_for_delivery_fees(asset_needed_for_fees.clone()); + // set aside fee to be charged by XcmSender + let delivery_fee = self.holding.saturating_take(asset_to_pay_for_fees.into()); + tracing::trace!(target: "xcm::fees::DepositReserveAsset", ?delivery_fee); + delivery_fee + }); + Ok(maybe_delivery_fee) + } } diff --git a/polkadot/xcm/xcm-executor/src/tests/initiate_transfer.rs b/polkadot/xcm/xcm-executor/src/tests/initiate_transfer.rs new file mode 100644 index 000000000000..09ed1f44cc4a --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/tests/initiate_transfer.rs @@ -0,0 +1,106 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Unit tests related to the `InitiateTransfer` instruction. +//! +//! See [Fellowship RFC 100](https://github.com/polkadot-fellows/rfCs/pull/100), +//! [Fellowship RFC 122](https://github.com/polkadot-fellows/rfCs/pull/122), and the +//! [specification](https://github.com/polkadot-fellows/xcm-format) for more information. + +use xcm::{latest::AssetTransferFilter, prelude::*}; + +use super::mock::*; + +// The sender and recipient we use across these tests. +const SENDER: [u8; 32] = [0; 32]; +const RECIPIENT: [u8; 32] = [1; 32]; + +#[test] +fn clears_origin() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + let xcm_on_dest = + Xcm(vec![RefundSurplus, DepositAsset { assets: Wild(All), beneficiary: RECIPIENT.into() }]); + let assets: Assets = (Here, 90u128).into(); + let xcm = Xcm::(vec![ + WithdrawAsset((Here, 100u128).into()), + PayFees { asset: (Here, 10u128).into() }, + InitiateTransfer { + destination: Parent.into(), + remote_fees: Some(AssetTransferFilter::ReserveDeposit(assets.into())), + preserve_origin: false, + assets: vec![], + remote_xcm: xcm_on_dest, + }, + ]); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + let res = vm.bench_process(xcm); + assert!(res.is_ok(), "execution error {:?}", res); + + let (dest, sent_message) = sent_xcm().pop().unwrap(); + assert_eq!(dest, Parent.into()); + assert_eq!(sent_message.len(), 5); + let mut instr = sent_message.inner().iter(); + assert!(matches!(instr.next().unwrap(), ReserveAssetDeposited(..))); + assert!(matches!(instr.next().unwrap(), PayFees { .. })); + assert!(matches!(instr.next().unwrap(), ClearOrigin)); + assert!(matches!(instr.next().unwrap(), RefundSurplus)); + assert!(matches!(instr.next().unwrap(), DepositAsset { .. })); +} + +#[test] +fn preserves_origin() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + let xcm_on_dest = + Xcm(vec![RefundSurplus, DepositAsset { assets: Wild(All), beneficiary: RECIPIENT.into() }]); + let assets: Assets = (Here, 90u128).into(); + let xcm = Xcm::(vec![ + WithdrawAsset((Here, 100u128).into()), + PayFees { asset: (Here, 10u128).into() }, + InitiateTransfer { + destination: Parent.into(), + remote_fees: Some(AssetTransferFilter::ReserveDeposit(assets.into())), + preserve_origin: true, + assets: vec![], + remote_xcm: xcm_on_dest, + }, + ]); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + let res = vm.bench_process(xcm); + assert!(res.is_ok(), "execution error {:?}", res); + + let (dest, sent_message) = sent_xcm().pop().unwrap(); + assert_eq!(dest, Parent.into()); + assert_eq!(sent_message.len(), 5); + let mut instr = sent_message.inner().iter(); + assert!(matches!(instr.next().unwrap(), ReserveAssetDeposited(..))); + assert!(matches!(instr.next().unwrap(), PayFees { .. })); + assert!(matches!( + instr.next().unwrap(), + AliasOrigin(origin) if matches!(origin.unpack(), (0, [Parachain(1000), AccountId32 { id: SENDER, network: None }])) + )); + assert!(matches!(instr.next().unwrap(), RefundSurplus)); + assert!(matches!(instr.next().unwrap(), DepositAsset { .. })); +} diff --git a/polkadot/xcm/xcm-executor/src/tests/mock.rs b/polkadot/xcm/xcm-executor/src/tests/mock.rs new file mode 100644 index 000000000000..9cf258331f38 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/tests/mock.rs @@ -0,0 +1,279 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Mock types and XcmConfig for all executor unit tests. + +use alloc::collections::btree_map::BTreeMap; +use codec::{Decode, Encode}; +use core::cell::RefCell; +use frame_support::{ + dispatch::{DispatchInfo, DispatchResultWithPostInfo, GetDispatchInfo, PostDispatchInfo}, + parameter_types, + traits::{Everything, Nothing, ProcessMessageError}, + weights::Weight, +}; +use sp_runtime::traits::Dispatchable; +use xcm::prelude::*; + +use crate::{ + traits::{DropAssets, Properties, ShouldExecute, TransactAsset, WeightBounds, WeightTrader}, + AssetsInHolding, Config, XcmExecutor, +}; + +/// We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we +/// can inspect its fields. +pub fn instantiate_executor( + origin: impl Into, + message: Xcm<::RuntimeCall>, +) -> (XcmExecutor, Weight) { + let mut vm = + XcmExecutor::::new(origin, message.using_encoded(sp_io::hashing::blake2_256)); + let weight = XcmExecutor::::prepare(message.clone()).unwrap().weight_of(); + vm.message_weight = weight; + (vm, weight) +} + +parameter_types! { + pub const MaxAssetsIntoHolding: u32 = 10; + pub const BaseXcmWeight: Weight = Weight::from_parts(1, 1); + pub const MaxInstructions: u32 = 10; + pub UniversalLocation: InteriorLocation = [GlobalConsensus(ByGenesis([0; 32])), Parachain(1000)].into(); +} + +/// Test origin. +#[derive(Debug)] +pub struct TestOrigin; + +/// Test call. +/// +/// Doesn't dispatch anything, has an empty implementation of [`Dispatchable`] that +/// just returns `Ok` with an empty [`PostDispatchInfo`]. +#[derive(Debug, Encode, Decode, Eq, PartialEq, Clone, Copy, scale_info::TypeInfo)] +pub struct TestCall; +impl Dispatchable for TestCall { + type RuntimeOrigin = TestOrigin; + type Config = (); + type Info = (); + type PostInfo = PostDispatchInfo; + + fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithPostInfo { + Ok(PostDispatchInfo::default()) + } +} +impl GetDispatchInfo for TestCall { + fn get_dispatch_info(&self) -> DispatchInfo { + DispatchInfo::default() + } +} + +/// Test weigher that just returns a fixed weight for every program. +pub struct TestWeigher; +impl WeightBounds for TestWeigher { + fn weight(_message: &mut Xcm) -> Result { + Ok(Weight::from_parts(2, 2)) + } + + fn instr_weight(_instruction: &mut Instruction) -> Result { + Ok(Weight::from_parts(2, 2)) + } +} + +thread_local! { + pub static ASSETS: RefCell> = RefCell::new(BTreeMap::new()); + pub static SENT_XCM: RefCell)>> = RefCell::new(Vec::new()); +} + +pub fn add_asset(who: impl Into, what: impl Into) { + ASSETS.with(|a| { + a.borrow_mut() + .entry(who.into()) + .or_insert(AssetsInHolding::new()) + .subsume(what.into()) + }); +} + +pub fn asset_list(who: impl Into) -> Vec { + Assets::from(assets(who)).into_inner() +} + +pub fn assets(who: impl Into) -> AssetsInHolding { + ASSETS.with(|a| a.borrow().get(&who.into()).cloned()).unwrap_or_default() +} + +pub fn get_first_fungible(assets: &AssetsInHolding) -> Option { + assets.fungible_assets_iter().next() +} + +/// Test asset transactor that withdraws from and deposits to a thread local assets storage. +pub struct TestAssetTransactor; +impl TransactAsset for TestAssetTransactor { + fn deposit_asset( + what: &Asset, + who: &Location, + _context: Option<&XcmContext>, + ) -> Result<(), XcmError> { + add_asset(who.clone(), what.clone()); + Ok(()) + } + + fn withdraw_asset( + what: &Asset, + who: &Location, + _context: Option<&XcmContext>, + ) -> Result { + ASSETS.with(|a| { + a.borrow_mut() + .get_mut(who) + .ok_or(XcmError::NotWithdrawable)? + .try_take(what.clone().into()) + .map_err(|_| XcmError::NotWithdrawable) + }) + } +} + +/// Test barrier that just lets everything through. +pub struct TestBarrier; +impl ShouldExecute for TestBarrier { + fn should_execute( + _origin: &Location, + _instructions: &mut [Instruction], + _max_weight: Weight, + _properties: &mut Properties, + ) -> Result<(), ProcessMessageError> { + Ok(()) + } +} + +/// Test weight to fee that just multiplies `Weight.ref_time` and `Weight.proof_size`. +pub struct WeightToFee; +impl WeightToFee { + pub fn weight_to_fee(weight: &Weight) -> u128 { + weight.ref_time() as u128 * weight.proof_size() as u128 + } +} + +/// Test weight trader that just buys weight with the native asset (`Here`) and +/// uses the test `WeightToFee`. +pub struct TestTrader { + weight_bought_so_far: Weight, +} +impl WeightTrader for TestTrader { + fn new() -> Self { + Self { weight_bought_so_far: Weight::zero() } + } + + fn buy_weight( + &mut self, + weight: Weight, + payment: AssetsInHolding, + _context: &XcmContext, + ) -> Result { + let amount = WeightToFee::weight_to_fee(&weight); + let required: Asset = (Here, amount).into(); + let unused = payment.checked_sub(required).map_err(|_| XcmError::TooExpensive)?; + self.weight_bought_so_far.saturating_add(weight); + Ok(unused) + } + + fn refund_weight(&mut self, weight: Weight, _context: &XcmContext) -> Option { + let weight = weight.min(self.weight_bought_so_far); + let amount = WeightToFee::weight_to_fee(&weight); + self.weight_bought_so_far -= weight; + if amount > 0 { + Some((Here, amount).into()) + } else { + None + } + } +} + +/// Account where all dropped assets are deposited. +pub const TRAPPED_ASSETS: [u8; 32] = [255; 32]; + +/// Test asset trap that moves all dropped assets to the `TRAPPED_ASSETS` account. +pub struct TestAssetTrap; +impl DropAssets for TestAssetTrap { + fn drop_assets(_origin: &Location, assets: AssetsInHolding, _context: &XcmContext) -> Weight { + ASSETS.with(|a| { + a.borrow_mut() + .entry(TRAPPED_ASSETS.into()) + .or_insert(AssetsInHolding::new()) + .subsume_assets(assets) + }); + Weight::zero() + } +} + +/// Test sender that always succeeds and puts messages in a dummy queue. +/// +/// It charges `1` for the delivery fee. +pub struct TestSender; +impl SendXcm for TestSender { + type Ticket = (Location, Xcm<()>); + + fn validate( + destination: &mut Option, + message: &mut Option>, + ) -> SendResult { + let ticket = (destination.take().unwrap(), message.take().unwrap()); + let delivery_fee: Asset = (Here, 1u128).into(); + Ok((ticket, delivery_fee.into())) + } + + fn deliver(ticket: Self::Ticket) -> Result { + SENT_XCM.with(|q| q.borrow_mut().push(ticket)); + Ok([0; 32]) + } +} + +/// Gets queued test messages. +pub fn sent_xcm() -> Vec<(Location, Xcm<()>)> { + SENT_XCM.with(|q| (*q.borrow()).clone()) +} + +/// Test XcmConfig that uses all the test implementations in this file. +pub struct XcmConfig; +impl Config for XcmConfig { + type RuntimeCall = TestCall; + type XcmSender = TestSender; + type AssetTransactor = TestAssetTransactor; + type OriginConverter = (); + type IsReserve = (); + type IsTeleporter = (); + type UniversalLocation = UniversalLocation; + type Barrier = TestBarrier; + type Weigher = TestWeigher; + type Trader = TestTrader; + type ResponseHandler = (); + type AssetTrap = TestAssetTrap; + type AssetLocker = (); + type AssetExchanger = (); + type AssetClaims = (); + type SubscriptionService = (); + type PalletInstancesInfo = (); + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = Self::RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; + type TransactionalProcessor = (); + type HrmpNewChannelOpenRequestHandler = (); + type HrmpChannelAcceptedHandler = (); + type HrmpChannelClosingHandler = (); + type XcmRecorder = (); +} diff --git a/polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.rs b/polkadot/xcm/xcm-executor/src/tests/mod.rs similarity index 70% rename from polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.rs rename to polkadot/xcm/xcm-executor/src/tests/mod.rs index 1ed8dd38cbad..5c133871f0bf 100644 --- a/polkadot/xcm/procedural/tests/ui/builder_pattern/no_buy_execution.rs +++ b/polkadot/xcm/xcm-executor/src/tests/mod.rs @@ -14,16 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Test error when there's no `BuyExecution` instruction. - -use xcm_procedural::Builder; - -struct Xcm(pub Vec>); - -#[derive(Builder)] -enum Instruction { - UnpaidExecution { weight_limit: (u32, u32) }, - Transact { call: Call }, -} - -fn main() {} +//! Unit tests for the XCM executor. +//! +//! These exclude any cross-chain functionality. For those, look at the +//! `xcm-emulator` based tests in the cumulus folder. +//! These tests deal with internal state changes of the XCVM. + +mod initiate_transfer; +mod mock; +mod pay_fees; +mod set_asset_claimer; diff --git a/polkadot/xcm/xcm-executor/src/tests/pay_fees.rs b/polkadot/xcm/xcm-executor/src/tests/pay_fees.rs new file mode 100644 index 000000000000..4c196831e6a4 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/tests/pay_fees.rs @@ -0,0 +1,257 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Unit tests related to the `fees` register and `PayFees` instruction. +//! +//! See [Fellowship RFC 105](https://github.com/polkadot-fellows/rfCs/pull/105) +//! and the [specification](https://github.com/polkadot-fellows/xcm-format) for more information. + +use xcm::prelude::*; + +use super::mock::*; + +// The sender and recipient we use across these tests. +const SENDER: [u8; 32] = [0; 32]; +const RECIPIENT: [u8; 32] = [1; 32]; + +// ===== Happy path ===== + +// This is a sort of backwards compatibility test. +// Since `PayFees` is a replacement for `BuyExecution`, we need to make sure it at least +// manages to do the same thing, paying for execution fees. +#[test] +fn works_for_execution_fees() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .deposit_asset(All, RECIPIENT) + .build(); + + let (mut vm, weight) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // Execution fees were 4, so we still have 6 left in the `fees` register. + assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 6u128).into()); + + // The recipient received all the assets in the holding register, so `100` that + // were withdrawn, minus the `10` that were destinated for fee payment. + assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]); + + // Leftover fees get trapped. + assert!(vm.bench_post_process(weight).ensure_complete().is_ok()); + assert_eq!(asset_list(TRAPPED_ASSETS), [(Here, 6u128).into()]) +} + +// This tests the new functionality provided by `PayFees`, being able to pay for +// delivery fees from the `fees` register. +#[test] +fn works_for_delivery_fees() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Information to send messages. + // We don't care about the specifics since we're not actually sending them. + let query_response_info = + QueryResponseInfo { destination: Parent.into(), query_id: 0, max_weight: Weight::zero() }; + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + .pay_fees((Here, 10u128)) + // Send a bunch of messages, each charging delivery fees. + .report_error(query_response_info.clone()) + .report_error(query_response_info.clone()) + .report_error(query_response_info) + .deposit_asset(All, RECIPIENT) + .build(); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // Execution fees were 4, delivery were 3, so we are left with only 3 in the `fees` register. + assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 3u128).into()); + + // The recipient received all the assets in the holding register, so `100` that + // were withdrawn, minus the `10` that were destinated for fee payment. + assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]); + + let querier: Location = + (Parachain(1000), AccountId32 { id: SENDER.into(), network: None }).into(); + let sent_message = Xcm(vec![QueryResponse { + query_id: 0, + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }]); + + // The messages were "sent" successfully. + assert_eq!( + sent_xcm(), + vec![ + (Parent.into(), sent_message.clone()), + (Parent.into(), sent_message.clone()), + (Parent.into(), sent_message.clone()) + ] + ); +} + +// Tests the support for `BuyExecution` while the ecosystem transitions to `PayFees`. +#[test] +fn buy_execution_works_as_before() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + // We can put everything here, since excess will be returned to holding. + // We have to specify `Limited` here to actually work, it's normally + // set in the `AllowTopLevelPaidExecutionFrom` barrier. + .buy_execution((Here, 100u128), Limited(Weight::from_parts(2, 2))) + .deposit_asset(All, RECIPIENT) + .build(); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // `BuyExecution` does not interact with the `fees` register. + assert_eq!(get_first_fungible(vm.fees()), None); + + // The recipient received all the assets in the holding register, so `100` that + // were withdrawn, minus the `4` from paying the execution fees. + assert_eq!(asset_list(RECIPIENT), [(Here, 96u128).into()]); +} + +// Tests the interaction between `PayFees` and `RefundSurplus`. +#[test] +fn fees_can_be_refunded() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .deposit_asset(All, RECIPIENT) + .refund_surplus() + .deposit_asset(All, SENDER) + .build(); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // Nothing was left in the `fees` register since it was refunded. + assert_eq!(get_first_fungible(vm.fees()), None); + + // The recipient received all the assets in the holding register, so `100` that + // were withdrawn, minus the `10` that were destinated for fee payment. + assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]); + + // The sender got back `6` from unused assets. + assert_eq!(asset_list(SENDER), [(Here, 6u128).into()]); +} + +// ===== Unhappy path ===== + +#[test] +fn putting_all_assets_in_pay_fees() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + .pay_fees((Here, 100u128)) // 100% destined for fees, this is not going to end well... + .deposit_asset(All, RECIPIENT) + .build(); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // We destined `100` for fee payment, after `4` for execution fees, we are left with `96`. + assert_eq!(get_first_fungible(vm.fees()).unwrap(), (Here, 96u128).into()); + + // The recipient received no assets since they were all destined for fee payment. + assert_eq!(asset_list(RECIPIENT), []); +} + +#[test] +fn refunding_too_early() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER, (Here, 100u128)); + + // Information to send messages. + // We don't care about the specifics since we're not actually sending them. + let query_response_info = + QueryResponseInfo { destination: Parent.into(), query_id: 0, max_weight: Weight::zero() }; + + // Build xcm. + let xcm = Xcm::::builder() + .withdraw_asset((Here, 100u128)) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .deposit_asset(All, RECIPIENT) + .refund_surplus() + .deposit_asset(All, SENDER) + // `refund_surplus` cleared the `fees` register. + // `holding` is used as a fallback, but we also cleared that. + // The instruction will error and the message won't be sent :(. + .report_error(query_response_info) + .build(); + + let (mut vm, _) = instantiate_executor(SENDER, xcm.clone()); + + // Program fails to run. + assert!(vm.bench_process(xcm).is_err()); + + // Nothing is left in the `holding` register. + assert_eq!(get_first_fungible(vm.holding()), None); + // Nothing was left in the `fees` register since it was refunded. + assert_eq!(get_first_fungible(vm.fees()), None); + + // The recipient received all the assets in the holding register, so `100` that + // were withdrawn, minus the `10` that were destinated for fee payment. + assert_eq!(asset_list(RECIPIENT), [(Here, 90u128).into()]); + + // The sender got back `6` from unused assets. + assert_eq!(asset_list(SENDER), [(Here, 6u128).into()]); + + // No messages were "sent". + assert_eq!(sent_xcm(), Vec::new()); +} diff --git a/polkadot/xcm/xcm-executor/src/tests/set_asset_claimer.rs b/polkadot/xcm/xcm-executor/src/tests/set_asset_claimer.rs new file mode 100644 index 000000000000..bc504b8db2a2 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/tests/set_asset_claimer.rs @@ -0,0 +1,138 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Unit tests related to the `fees` register and `PayFees` instruction. +//! +//! See [Fellowship RFC 105](https://github.com/polkadot-fellows/rfCs/pull/105) +//! and the [specification](https://github.com/polkadot-fellows/xcm-format) for more information. + +use codec::Encode; +use xcm::prelude::*; + +use super::mock::*; +use crate::XcmExecutor; + +#[test] +fn set_asset_claimer() { + let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]); + let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]); + + // Make sure the user has enough funds to withdraw. + add_asset(sender.clone(), (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + // if withdrawing fails we're not missing any corner case. + .withdraw_asset((Here, 100u128)) + .clear_origin() + .set_asset_claimer(bob.clone()) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .build(); + + // We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we + // can inspect its fields. + let mut vm = + XcmExecutor::::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256)); + vm.message_weight = XcmExecutor::::prepare(xcm.clone()).unwrap().weight_of(); + + let result = vm.bench_process(xcm); + assert!(result.is_ok()); + assert_eq!(vm.asset_claimer(), Some(bob)); +} + +#[test] +fn do_not_set_asset_claimer_none() { + let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]); + + // Make sure the user has enough funds to withdraw. + add_asset(sender.clone(), (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + // if withdrawing fails we're not missing any corner case. + .withdraw_asset((Here, 100u128)) + .clear_origin() + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .build(); + + // We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we + // can inspect its fields. + let mut vm = + XcmExecutor::::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256)); + vm.message_weight = XcmExecutor::::prepare(xcm.clone()).unwrap().weight_of(); + + let result = vm.bench_process(xcm); + assert!(result.is_ok()); + assert_eq!(vm.asset_claimer(), None); +} + +#[test] +fn trap_then_set_asset_claimer() { + let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]); + let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]); + + // Make sure the user has enough funds to withdraw. + add_asset(sender.clone(), (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + // if withdrawing fails we're not missing any corner case. + .withdraw_asset((Here, 100u128)) + .clear_origin() + .trap(0u64) + .set_asset_claimer(bob) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .build(); + + // We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we + // can inspect its fields. + let mut vm = + XcmExecutor::::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256)); + vm.message_weight = XcmExecutor::::prepare(xcm.clone()).unwrap().weight_of(); + + let result = vm.bench_process(xcm); + assert!(result.is_err()); + assert_eq!(vm.asset_claimer(), None); +} + +#[test] +fn set_asset_claimer_then_trap() { + let sender = Location::new(0, [AccountId32 { id: [0; 32], network: None }]); + let bob = Location::new(0, [AccountId32 { id: [2; 32], network: None }]); + + // Make sure the user has enough funds to withdraw. + add_asset(sender.clone(), (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + // if withdrawing fails we're not missing any corner case. + .withdraw_asset((Here, 100u128)) + .clear_origin() + .set_asset_claimer(bob.clone()) + .trap(0u64) + .pay_fees((Here, 10u128)) // 10% destined for fees, not more. + .build(); + + // We create an XCVM instance instead of calling `XcmExecutor::<_>::prepare_and_execute` so we + // can inspect its fields. + let mut vm = + XcmExecutor::::new(sender, xcm.using_encoded(sp_io::hashing::blake2_256)); + vm.message_weight = XcmExecutor::::prepare(xcm.clone()).unwrap().weight_of(); + + let result = vm.bench_process(xcm); + assert!(result.is_err()); + assert_eq!(vm.asset_claimer(), Some(bob)); +} diff --git a/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs b/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs index b6e303daaad8..256f47fec4f0 100644 --- a/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs +++ b/polkadot/xcm/xcm-executor/src/traits/fee_manager.rs @@ -39,6 +39,8 @@ pub enum FeeReason { InitiateReserveWithdraw, /// When the `InitiateTeleport` instruction is called. InitiateTeleport, + /// When the `InitiateTransfer` instruction is called. + InitiateTransfer, /// When the `QueryPallet` instruction is called. QueryPallet, /// When the `ExportMessage` instruction is called (and includes the network ID). diff --git a/polkadot/xcm/xcm-executor/src/traits/weight.rs b/polkadot/xcm/xcm-executor/src/traits/weight.rs index 61545c330621..4e41aa5b4753 100644 --- a/polkadot/xcm/xcm-executor/src/traits/weight.rs +++ b/polkadot/xcm/xcm-executor/src/traits/weight.rs @@ -26,7 +26,7 @@ pub trait WeightBounds { /// Return the maximum amount of weight that an attempted execution of this instruction could /// consume. - fn instr_weight(instruction: &Instruction) -> Result; + fn instr_weight(instruction: &mut Instruction) -> Result; } /// Charge for weight in order to execute XCM. diff --git a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs index 4a5de8875007..f0a5be908f69 100644 --- a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs @@ -144,7 +144,7 @@ parameter_types! { pub const BaseXcmWeight: Weight = Weight::from_parts(100, 10); // Random value. pub const MaxInstructions: u32 = 100; pub const NativeTokenPerSecondPerByte: (AssetId, u128, u128) = (AssetId(HereLocation::get()), 1, 1); - pub UniversalLocation: InteriorLocation = [GlobalConsensus(NetworkId::Westend), Parachain(2000)].into(); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(NetworkId::ByGenesis([0; 32])), Parachain(2000)].into(); pub const HereLocation: Location = Location::here(); pub const RelayLocation: Location = Location::parent(); pub const MaxAssetsIntoHolding: u32 = 64; diff --git a/polkadot/xcm/xcm-simulator/example/src/tests.rs b/polkadot/xcm/xcm-simulator/example/src/tests.rs index 34c1feb6e946..bbac44ed8a1f 100644 --- a/polkadot/xcm/xcm-simulator/example/src/tests.rs +++ b/polkadot/xcm/xcm-simulator/example/src/tests.rs @@ -46,7 +46,6 @@ fn dmp() { Parachain(1), Xcm(vec![Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(INITIAL_BALANCE as u64, 1024 * 1024), call: remark.encode().into(), }]), )); @@ -74,7 +73,6 @@ fn ump() { Parent, Xcm(vec![Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(INITIAL_BALANCE as u64, 1024 * 1024), call: remark.encode().into(), }]), )); @@ -102,7 +100,6 @@ fn xcmp() { (Parent, Parachain(2)), Xcm(vec![Transact { origin_kind: OriginKind::SovereignAccount, - require_weight_at_most: Weight::from_parts(INITIAL_BALANCE as u64, 1024 * 1024), call: remark.encode().into(), }]), )); @@ -383,7 +380,6 @@ fn reserve_asset_class_create_and_reserve_transfer() { let message = Xcm(vec![Transact { origin_kind: OriginKind::Xcm, - require_weight_at_most: Weight::from_parts(1_000_000_000, 1024 * 1024), call: parachain::RuntimeCall::from( pallet_uniques::Call::::create { collection: (Parent, 2u64).into(), diff --git a/prdoc/pr_4826.prdoc b/prdoc/pr_4826.prdoc new file mode 100644 index 000000000000..daa4a77e3e8f --- /dev/null +++ b/prdoc/pr_4826.prdoc @@ -0,0 +1,69 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: XCMv5 + +doc: + - audience: [Runtime User, Runtime Dev] + description: | + Added XCMv5. + + This PR brings a new XCM version. + It's an amalgamation of multiple individual PRs: + - https://github.com/paritytech/polkadot-sdk/pull/6228 + - https://github.com/paritytech/polkadot-sdk/pull/6148 + - https://github.com/paritytech/polkadot-sdk/pull/5971 + - https://github.com/paritytech/polkadot-sdk/pull/5876 + - https://github.com/paritytech/polkadot-sdk/pull/5420 + - https://github.com/paritytech/polkadot-sdk/pull/5585 + + XCMv5 reduces the potential for bugs by: + - Removing the need to specify weight in Transact. + - Handling fees in a better way with `PayFees` instead of `BuyExecution`. + - Improves asset claiming with `SetAssetClaimer`. + + It also allows some new use-cases like: + - Sending both teleported and reserve asset transferred assets in the same cross-chain + transfer. + - Preserving the origin when doing cross-chain transfers. Allowing the use of Transact + in the same message as a cross-chain transfer. + + In version 5, it's expected to change usage of `BuyExecution` to `PayFees`. + While `BuyExecution` returns all leftover assets to holding, `PayFees` doesn't. + The only way to get funds back from those sent to `PayFees` is by using `RefundSurplus`. + Because of this, it's meant to be used alongside the new DryRunApi and XcmPaymentApi. + You first dry-run the XCM, get the fees needed, and put them in `PayFees`. + +crates: + - name: staging-xcm + bump: major + - name: staging-xcm-builder + bump: major + - name: staging-xcm-executor + bump: major + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: penpal-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + - name: pallet-xcm-benchmarks + bump: minor + - name: pallet-multisig + bump: minor diff --git a/prdoc/pr_5390.prdoc b/prdoc/pr_5390.prdoc new file mode 100644 index 000000000000..cfe6894324aa --- /dev/null +++ b/prdoc/pr_5390.prdoc @@ -0,0 +1,55 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Remove NetworkIds for testnets Rococo and Westend + +doc: + - audience: [Runtime Dev, Runtime User] + description: | + Implemetation of https://github.com/polkadot-fellows/RFCs/pull/108, in the version 5 of XCM, + Remove `Westend` and `Rococo` from the included `NetworkId`s to improve the stability of the language. + + `NetworkId::Rococo` and `NetworkId::Westend` can just use `NetworkId::ByGenesis` by importing their genesis + block hash + +crates: + - name: staging-xcm + bump: major + - name: pallet-xcm-bridge-hub + bump: patch + - name: snowbridge-pallet-system + bump: patch + - name: asset-hub-rococo-runtime + bump: patch + - name: asset-hub-westend-runtime + bump: patch + - name: bridge-hub-rococo-runtime + bump: patch + - name: bridge-hub-westend-runtime + bump: patch + - name: collectives-westend-runtime + bump: patch + - name: contracts-rococo-runtime + bump: patch + - name: coretime-rococo-runtime + bump: patch + - name: coretime-westend-runtime + bump: patch + - name: glutton-westend-runtime + bump: patch + - name: people-rococo-runtime + bump: patch + - name: people-westend-runtime + bump: patch + - name: penpal-runtime + bump: patch + - name: rococo-parachain-runtime + bump: patch + - name: xcm-runtime-apis + bump: patch + - name: rococo-runtime + bump: patch + - name: westend-runtime + bump: patch + - name: assets-common + bump: patch diff --git a/prdoc/pr_5420.prdoc b/prdoc/pr_5420.prdoc new file mode 100644 index 000000000000..bf8a34569077 --- /dev/null +++ b/prdoc/pr_5420.prdoc @@ -0,0 +1,62 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: XCMv5 - Better fee mechanism + +doc: + - audience: + - Runtime User + - Runtime Dev + description: | + In XCMv5, there's a new instruction, `PayFees`, which is meant to be a replacement for `BuyExecution`. + This instruction takes only one parameter, the `asset` that you are willing to use for fee payment. + There's no parameter for limiting the weight, the amount of the `asset` you put in is the limit of + how much you're willing to pay. + This instruction works much better with delivery fees. + `BuyExecution` will still be around to ensure backwards-compatibility, however, the benefits of the new + instruction are a good incentive to switch. + The proposed workflow is to estimate fees using the `XcmPaymentApi` and `DryRunApi`, then to put those + values in `PayFees` and watch your message go knowing you covered all the necessary fees. + You can add a little bit more just in case if you want. + `RefundSurplus` now gets back all of the assets that were destined for fee payment so you can deposit + them somewhere. + BEWARE, make sure you're not sending any other message after you call `RefundSurplus`, if not, it will + error. + +crates: + - name: staging-xcm-executor + bump: minor + - name: staging-xcm-builder + bump: minor + - name: staging-xcm + bump: major + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + - name: xcm-emulator + bump: major + - name: people-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: asset-hub-rococo-runtime + bump: minor + - name: emulated-integration-tests-common + bump: minor + - name: xcm-procedural + bump: minor + - name: pallet-xcm-benchmarks + bump: minor + - name: snowbridge-pallet-system + bump: patch diff --git a/prdoc/pr_5585.prdoc b/prdoc/pr_5585.prdoc new file mode 100644 index 000000000000..d4b115413d4d --- /dev/null +++ b/prdoc/pr_5585.prdoc @@ -0,0 +1,47 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Added SetAssetClaimer instruction to XCM v5. + +doc: + - audience: Runtime Dev + description: | + Added SetAssetClaimer implementation to XCM v5. With asset_claimer set users can retrieve their trapped assets + at any point in time without the need to go through OpenGov reclaim process. + +crates: +- name: bridge-hub-westend-emulated-chain + bump: minor +- name: asset-hub-westend-integration-tests + bump: minor +- name: asset-hub-rococo-runtime + bump: minor +- name: asset-hub-westend-runtime + bump: minor +- name: bridge-hub-rococo-runtime + bump: minor +- name: bridge-hub-westend-runtime + bump: minor +- name: coretime-rococo-runtime + bump: minor +- name: coretime-westend-runtime + bump: minor +- name: people-rococo-runtime + bump: minor +- name: people-westend-runtime + bump: minor +- name: penpal-runtime + bump: minor +- name: rococo-runtime + bump: minor +- name: westend-runtime + bump: minor +- name: staging-xcm + bump: minor +- name: staging-xcm-executor + bump: minor +- name: pallet-xcm-benchmarks + bump: minor +- name: pallet-multisig + bump: minor + diff --git a/prdoc/pr_5876.prdoc b/prdoc/pr_5876.prdoc new file mode 100644 index 000000000000..4e2b8a5c8aad --- /dev/null +++ b/prdoc/pr_5876.prdoc @@ -0,0 +1,99 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: (XCMv5) implement RFC#100, add new InitiateTransfer instruction + +doc: + - audience: Runtime Dev + description: | + There's a new XCM instruction in v5: InitiateTransfer. + It's meant as a general instruction that will do everything (and more) currently + done by InitiateTeleport, InitiateReserveWithdraw and DepositReserveAsset. + Its main feature is the ability to do cross-chains transfers mixing teleported and + reserve transferred assets. + ```rust + /// Specify which type of asset transfer is required for a particular `(asset, dest)` combination. + pub enum AssetTransferFilter { + /// teleport assets matching `AssetFilter` to `dest` + Teleport(AssetFilter), + /// reserve-transfer assets matching `AssetFilter` to `dest`, using the local chain as reserve + ReserveDeposit(AssetFilter), + /// reserve-transfer assets matching `AssetFilter` to `dest`, using `dest` as reserve + ReserveWithdraw(AssetFilter), + } + /// Cross-chain transfer matching `assets` in the holding register as follows: + /// + /// Assets in the holding register are matched using the given list of `AssetTransferFilter`s, + /// they are then transferred based on their specified transfer type: + /// + /// - teleport: burn local assets and append a `ReceiveTeleportedAsset` XCM instruction to + /// the XCM program to be sent onward to the `dest` location, + /// + /// - reserve deposit: place assets under the ownership of `dest` within this consensus system + /// (i.e. its sovereign account), and append a `ReserveAssetDeposited` XCM instruction + /// to the XCM program to be sent onward to the `dest` location, + /// + /// - reserve withdraw: burn local assets and append a `WithdrawAsset` XCM instruction + /// to the XCM program to be sent onward to the `dest` location, + /// + /// The onward XCM is then appended a `ClearOrigin` to allow safe execution of any following + /// custom XCM instructions provided in `remote_xcm`. + /// + /// The onward XCM also potentially contains a `BuyExecution` instruction based on the presence + /// of the `remote_fees` parameter (see below). + /// + /// If a transfer requires going through multiple hops, an XCM program can compose this instruction + /// to be used at every chain along the path, describing that specific leg of the transfer. + /// + /// Parameters: + /// - `dest`: The location of the transfer next hop. + /// - `remote_fees`: If set to `Some(asset_xfer_filter)`, the single asset matching + /// `asset_xfer_filter` in the holding register will be transferred first in the remote XCM + /// program, followed by a `BuyExecution(fee)`, then rest of transfers follow. + /// This guarantees `remote_xcm` will successfully pass a `AllowTopLevelPaidExecutionFrom` barrier. + /// - `remote_xcm`: Custom instructions that will be executed on the `dest` chain. Note that + /// these instructions will be executed after a `ClearOrigin` so their origin will be `None`. + /// + /// Safety: No concerns. + /// + /// Kind: *Command*. + /// + InitiateTransfer { + destination: Location, + remote_fees: Option, + assets: Vec, + remote_xcm: Xcm<()>, + } + ``` + +crates: + - name: emulated-integration-tests-common + bump: major + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + - name: pallet-xcm-benchmarks + bump: minor + - name: staging-xcm + bump: major + - name: staging-xcm-executor + bump: major diff --git a/prdoc/pr_5971.prdoc b/prdoc/pr_5971.prdoc new file mode 100644 index 000000000000..4b1afc4c268a --- /dev/null +++ b/prdoc/pr_5971.prdoc @@ -0,0 +1,66 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: XCMv5 InitiateTransfer can preserve original origin across chains. + +doc: + - audience: Runtime User + description: | + The new InitiateTransfer instruction can preserve the original origin across chains by + setting `preserve_origin: true` in the instruction itself. + When it's set to true, it will append after the inner XCM, an `AliasOrigin` instruction + instead of the usual `ClearOrigin`. + This instruction will try to alias to the original origin, thus preserving it. + This only works if the chain receiving the transfer supports the aliasing operation. + If not, `preserve_origin: false` works as before and will never fail because of this. + - audience: Runtime Dev + description: | + The new InitiateTransfer instruction can preserve the original origin across chains by + setting `preserve_origin: true` in the instruction itself. + When it's set to true, it will append after the inner XCM, an `AliasOrigin` instruction + instead of the usual `ClearOrigin`. + This instruction will try to alias to the original origin, thus preserving it. + + Beware: This only works if the following two rules are followed by the chain receiving such + a message. + - Alias to interior locations is valid (the exact same behaviour as DescendOrigin) + - AssetHub can alias everything (most importantly sibling accounts and ethereum). + These can be set with the `Aliasers` configuration item, with the following adapters: + - AliasChildLocation + - AliasOriginRootUsingFilter with AssetHub and Everything + An example of the first one can be seen in `asset-hub-westend` and of the second one in + `penpal-runtime`. + +crates: + - name: staging-xcm + bump: minor + - name: staging-xcm-builder + bump: minor + - name: staging-xcm-executor + bump: minor + - name: pallet-xcm-benchmarks + bump: minor + - name: snowbridge-router-primitives + bump: minor + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: penpal-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor diff --git a/prdoc/pr_6228.prdoc b/prdoc/pr_6228.prdoc new file mode 100644 index 000000000000..4512adf01bbb --- /dev/null +++ b/prdoc/pr_6228.prdoc @@ -0,0 +1,50 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Transact without having to specify weight + +doc: + - audience: [Runtime User, Runtime Dev] + description: | + In XCMv5, it's no longer required to pass in the expected weight when using + `Transact`. + This was made to remove a whole class of bugs where the weight specified + was not enough. + +crates: + - name: staging-xcm + bump: major + - name: staging-xcm-executor + bump: major + - name: snowbridge-router-primitives + bump: minor + - name: emulated-integration-tests-common + bump: minor + - name: cumulus-ping + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: asset-hub-rococo-runtime + bump: minor + - name: parachains-runtimes-test-utils + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + - name: pallet-xcm-benchmarks + bump: minor + - name: xcm-simulator-example + bump: minor diff --git a/substrate/frame/examples/multi-block-migrations/src/migrations/v1/weights.rs b/substrate/frame/examples/multi-block-migrations/src/migrations/v1/weights.rs index 6a5cf2ac5936..a436d6a8ab40 100644 --- a/substrate/frame/examples/multi-block-migrations/src/migrations/v1/weights.rs +++ b/substrate/frame/examples/multi-block-migrations/src/migrations/v1/weights.rs @@ -33,7 +33,7 @@ // --pallet // pallet_example_mbm // --extrinsic -// +// // --template // substrate/.maintain/frame-weight-template.hbs // --output diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index ff682c82ce9d..04bedd78cc12 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -130,7 +130,8 @@ use frame_support::traits::BuildGenesisConfig; use frame_support::{ dispatch::{ extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo, - DispatchResult, DispatchResultWithPostInfo, PerDispatchClass, PostDispatchInfo, + DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, PerDispatchClass, + PostDispatchInfo, }, ensure, impl_ensure_origin_with_arg_ignoring_arg, migrations::MultiStepMigrator, @@ -507,6 +508,7 @@ pub mod pallet { type RuntimeCall: Parameter + Dispatchable + Debug + + GetDispatchInfo + From>; /// The aggregated `RuntimeTask` type. From 1f381f606033f3ae67c86dbe57bbb94c96dc3092 Mon Sep 17 00:00:00 2001 From: Ankan <10196091+Ank4n@users.noreply.github.com> Date: Wed, 6 Nov 2024 23:46:57 +0100 Subject: [PATCH 049/166] [Pools] New runtime api that returns the pot accounts associated with the pool (#6357) closes https://github.com/paritytech/polkadot-sdk/issues/6358 Adds the following runtime api to pallet-nomination-pools. `pool_accounts(pool_id)`: Returns `(bonded_account, reward_account)` associated with the `pool_id`. cc: @rossbulat --------- Co-authored-by: command-bot <> Co-authored-by: Branislav Kontur --- polkadot/runtime/westend/src/lib.rs | 15 +++++++++----- prdoc/pr_6357.prdoc | 20 +++++++++++++++++++ substrate/bin/node/runtime/src/lib.rs | 15 +++++++++----- .../nomination-pools/runtime-api/src/lib.rs | 3 +++ substrate/frame/nomination-pools/src/lib.rs | 7 +++++++ 5 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 prdoc/pr_6357.prdoc diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index a9a76dbced10..4c04af111f81 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -46,6 +46,7 @@ use frame_support::{ use frame_system::{EnsureRoot, EnsureSigned}; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_identity::legacy::IdentityInfo; +use pallet_nomination_pools::PoolId; use pallet_session::historical as session_historical; use pallet_transaction_payment::{FeeDetails, FungibleAdapter, RuntimeDispatchInfo}; use polkadot_primitives::{ @@ -2492,15 +2493,15 @@ sp_api::impl_runtime_apis! { NominationPools::api_pending_rewards(member).unwrap_or_default() } - fn points_to_balance(pool_id: pallet_nomination_pools::PoolId, points: Balance) -> Balance { + fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance { NominationPools::api_points_to_balance(pool_id, points) } - fn balance_to_points(pool_id: pallet_nomination_pools::PoolId, new_funds: Balance) -> Balance { + fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance { NominationPools::api_balance_to_points(pool_id, new_funds) } - fn pool_pending_slash(pool_id: pallet_nomination_pools::PoolId) -> Balance { + fn pool_pending_slash(pool_id: PoolId) -> Balance { NominationPools::api_pool_pending_slash(pool_id) } @@ -2508,7 +2509,7 @@ sp_api::impl_runtime_apis! { NominationPools::api_member_pending_slash(member) } - fn pool_needs_delegate_migration(pool_id: pallet_nomination_pools::PoolId) -> bool { + fn pool_needs_delegate_migration(pool_id: PoolId) -> bool { NominationPools::api_pool_needs_delegate_migration(pool_id) } @@ -2520,9 +2521,13 @@ sp_api::impl_runtime_apis! { NominationPools::api_member_total_balance(member) } - fn pool_balance(pool_id: pallet_nomination_pools::PoolId) -> Balance { + fn pool_balance(pool_id: PoolId) -> Balance { NominationPools::api_pool_balance(pool_id) } + + fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) { + NominationPools::api_pool_accounts(pool_id) + } } impl pallet_staking_runtime_api::StakingApi for Runtime { diff --git a/prdoc/pr_6357.prdoc b/prdoc/pr_6357.prdoc new file mode 100644 index 000000000000..b3155b1a6050 --- /dev/null +++ b/prdoc/pr_6357.prdoc @@ -0,0 +1,20 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: New runtime api that returns the associated pool accounts with a nomination pool. + +doc: + - audience: Runtime User + description: | + Each nomination pool has two associated pot accounts: the bonded account, where funds are pooled for staking, and + the reward account. This update introduces a runtime api that clients can query to retrieve these accounts. + +crates: + - name: westend-runtime + bump: minor + - name: kitchensink-runtime + bump: minor + - name: pallet-nomination-pools + bump: minor + - name: pallet-nomination-pools-runtime-api + bump: minor diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 18db43b1c120..5a2ff3ceb7f6 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -83,6 +83,7 @@ use pallet_identity::legacy::IdentityInfo; use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_nfts::PalletFeatures; use pallet_nis::WithMaximumOf; +use pallet_nomination_pools::PoolId; use pallet_revive::{evm::runtime::EthExtra, AddressMapper}; use pallet_session::historical as pallet_session_historical; // Can't use `FungibleAdapter` here until Treasury pallet migrates to fungibles @@ -3004,15 +3005,15 @@ impl_runtime_apis! { NominationPools::api_pending_rewards(who).unwrap_or_default() } - fn points_to_balance(pool_id: pallet_nomination_pools::PoolId, points: Balance) -> Balance { + fn points_to_balance(pool_id: PoolId, points: Balance) -> Balance { NominationPools::api_points_to_balance(pool_id, points) } - fn balance_to_points(pool_id: pallet_nomination_pools::PoolId, new_funds: Balance) -> Balance { + fn balance_to_points(pool_id: PoolId, new_funds: Balance) -> Balance { NominationPools::api_balance_to_points(pool_id, new_funds) } - fn pool_pending_slash(pool_id: pallet_nomination_pools::PoolId) -> Balance { + fn pool_pending_slash(pool_id: PoolId) -> Balance { NominationPools::api_pool_pending_slash(pool_id) } @@ -3020,7 +3021,7 @@ impl_runtime_apis! { NominationPools::api_member_pending_slash(member) } - fn pool_needs_delegate_migration(pool_id: pallet_nomination_pools::PoolId) -> bool { + fn pool_needs_delegate_migration(pool_id: PoolId) -> bool { NominationPools::api_pool_needs_delegate_migration(pool_id) } @@ -3032,9 +3033,13 @@ impl_runtime_apis! { NominationPools::api_member_total_balance(member) } - fn pool_balance(pool_id: pallet_nomination_pools::PoolId) -> Balance { + fn pool_balance(pool_id: PoolId) -> Balance { NominationPools::api_pool_balance(pool_id) } + + fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId) { + NominationPools::api_pool_accounts(pool_id) + } } impl pallet_staking_runtime_api::StakingApi for Runtime { diff --git a/substrate/frame/nomination-pools/runtime-api/src/lib.rs b/substrate/frame/nomination-pools/runtime-api/src/lib.rs index d81ad1dd4954..4138dd22d898 100644 --- a/substrate/frame/nomination-pools/runtime-api/src/lib.rs +++ b/substrate/frame/nomination-pools/runtime-api/src/lib.rs @@ -69,5 +69,8 @@ sp_api::decl_runtime_apis! { /// Total balance contributed to the pool. fn pool_balance(pool_id: PoolId) -> Balance; + + /// Returns the bonded account and reward account associated with the pool_id. + fn pool_accounts(pool_id: PoolId) -> (AccountId, AccountId); } } diff --git a/substrate/frame/nomination-pools/src/lib.rs b/substrate/frame/nomination-pools/src/lib.rs index 177c5da74d4f..201b0af1d608 100644 --- a/substrate/frame/nomination-pools/src/lib.rs +++ b/substrate/frame/nomination-pools/src/lib.rs @@ -4020,6 +4020,13 @@ impl Pallet { T::StakeAdapter::total_balance(Pool::from(Self::generate_bonded_account(pool_id))) .unwrap_or_default() } + + /// Returns the bonded account and reward account associated with the pool_id. + pub fn api_pool_accounts(pool_id: PoolId) -> (T::AccountId, T::AccountId) { + let bonded_account = Self::generate_bonded_account(pool_id); + let reward_account = Self::generate_reward_account(pool_id); + (bonded_account, reward_account) + } } impl sp_staking::OnStakingUpdate> for Pallet { From 27bf54b42dea0f856b0c8b05672775663bbea083 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 Nov 2024 07:57:08 +0000 Subject: [PATCH 050/166] Bump futures from 0.3.30 to 0.3.31 (#6252) Bumps [futures](https://github.com/rust-lang/futures-rs) from 0.3.30 to 0.3.31.
Release notes

Sourced from futures's releases.

0.3.31

  • Fix use after free of task in FuturesUnordered when dropped future panics (#2886)
  • Fix soundness bug in task::waker_ref (#2830) This is a breaking change but allowed because it is soundness bug fix.
  • Fix bugs in AsyncBufRead::read_line and AsyncBufReadExt::lines (#2884)
  • Fix parsing issue in select!/select_biased! (#2832) This is technically a breaking change as it will now reject a very odd undocumented syntax that was previously accidentally accepted.
  • Work around issue due to upstream Waker::will_wake change (#2865)
  • Add stream::Iter::{get_ref,get_mut,into_inner} (#2875)
  • Add future::AlwaysReady (#2825)
  • Relax trait bound on non-constructor methods of io::{BufReader,BufWriter} (#2848)
Changelog

Sourced from futures's changelog.

0.3.31 - 2024-10-05

  • Fix use after free of task in FuturesUnordered when dropped future panics (#2886)
  • Fix soundness bug in task::waker_ref (#2830) This is a breaking change but allowed because it is soundness bug fix.
  • Fix bugs in AsyncBufRead::read_line and AsyncBufReadExt::lines (#2884)
  • Fix parsing issue in select!/select_biased! (#2832) This is technically a breaking change as it will now reject a very odd undocumented syntax that was previously accidentally accepted.
  • Work around issue due to upstream Waker::will_wake change (#2865)
  • Add stream::Iter::{get_ref,get_mut,into_inner} (#2875)
  • Add future::AlwaysReady (#2825)
  • Relax trait bound on non-constructor methods of io::{BufReader,BufWriter} (#2848)
Commits
  • 1e05281 Release 0.3.31
  • 8a8b085 Fix clippy::uninit_vec warning
  • f3fb74d Document how BoxFutures / BoxStreams are often made (#2887)
  • f00e7af Fix use after free of task in FuturesUnordered when dropped future panics (#2...
  • 33c46b3 ci: Work around sanitizer issue on latest Linux kernel
  • 7bf5a72 Fix issues with AsyncBufRead::read_line and AsyncBufReadExt::lines (#2884)
  • 87afaf3 Use #[inline(always)] on clone_arc_raw (#2865)
  • 549b90b Add accessors for the inner of stream::Iter (#2875)
  • 07b004a Add missing symbols (#2883)
  • 86dc069 Various fixes too make the CI green (#2885)
  • Additional commits viewable in compare view

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=futures&package-manager=cargo&previous-version=0.3.30&new-version=0.3.31)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 36 ++++++++++++++++++------------------ Cargo.toml | 2 +- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03350ff38f5d..5f81f77991a7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6758,9 +6758,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" [[package]] name = "futures" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" dependencies = [ "futures-channel", "futures-core", @@ -6783,9 +6783,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", "futures-sink", @@ -6793,15 +6793,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "futures-executor" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" dependencies = [ "futures-core", "futures-task", @@ -6811,9 +6811,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-lite" @@ -6845,9 +6845,9 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -6866,15 +6866,15 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" [[package]] name = "futures-task" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" [[package]] name = "futures-timer" @@ -6888,9 +6888,9 @@ dependencies = [ [[package]] name = "futures-util" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-channel", "futures-core", diff --git a/Cargo.toml b/Cargo.toml index b12469987ed6..c00276724333 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -792,7 +792,7 @@ frame-system-rpc-runtime-api = { path = "substrate/frame/system/rpc/runtime-api" frame-try-runtime = { path = "substrate/frame/try-runtime", default-features = false } fs4 = { version = "0.7.0" } fs_extra = { version = "1.3.0" } -futures = { version = "0.3.30" } +futures = { version = "0.3.31" } futures-channel = { version = "0.3.23" } futures-timer = { version = "3.0.2" } futures-util = { version = "0.3.30", default-features = false } From 1d351bf46109a110a60befd4d2924da8eeaa2f0a Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Thu, 7 Nov 2024 16:05:09 +0800 Subject: [PATCH 051/166] Migrate pallet-election-provider-support-benchmarking benchmark to v2 (#6315) Part of: - #6202. --------- Co-authored-by: GitHub Action Co-authored-by: Guillaume Thiolliere Co-authored-by: Giuseppe Re Co-authored-by: Guillaume Thiolliere --- prdoc/pr_6315.prdoc | 8 ++ .../benchmarking/src/inner.rs | 81 +++++++++++-------- 2 files changed, 55 insertions(+), 34 deletions(-) create mode 100644 prdoc/pr_6315.prdoc diff --git a/prdoc/pr_6315.prdoc b/prdoc/pr_6315.prdoc new file mode 100644 index 000000000000..6fc070b43b35 --- /dev/null +++ b/prdoc/pr_6315.prdoc @@ -0,0 +1,8 @@ +title: Migrate pallet-election-provider-support-benchmarking benchmark to v2 +doc: +- audience: Runtime Dev + description: |- + Migrate pallet-election-provider-support-benchmarking benchmark to v2 +crates: +- name: pallet-election-provider-support-benchmarking + bump: patch diff --git a/substrate/frame/election-provider-support/benchmarking/src/inner.rs b/substrate/frame/election-provider-support/benchmarking/src/inner.rs index 8cca0d459eac..7fb8c1bdb729 100644 --- a/substrate/frame/election-provider-support/benchmarking/src/inner.rs +++ b/substrate/frame/election-provider-support/benchmarking/src/inner.rs @@ -20,17 +20,19 @@ use alloc::vec::Vec; use codec::Decode; -use frame_benchmarking::v1::benchmarks; +use frame_benchmarking::v2::*; use frame_election_provider_support::{NposSolver, PhragMMS, SequentialPhragmen}; - -pub struct Pallet(frame_system::Pallet); -pub trait Config: frame_system::Config {} +use sp_runtime::Perbill; const VOTERS: [u32; 2] = [1_000, 2_000]; const TARGETS: [u32; 2] = [500, 1_000]; const VOTES_PER_VOTER: [u32; 2] = [5, 16]; - const SEED: u32 = 999; + +pub trait Config: frame_system::Config {} + +pub struct Pallet(frame_system::Pallet); + fn set_up_voters_targets( voters_len: u32, targets_len: u32, @@ -54,36 +56,47 @@ fn set_up_voters_targets( (voters, targets) } -benchmarks! { - phragmen { - // number of votes in snapshot. - let v in (VOTERS[0]) .. VOTERS[1]; - // number of targets in snapshot. - let t in (TARGETS[0]) .. TARGETS[1]; - // number of votes per voter (ie the degree). - let d in (VOTES_PER_VOTER[0]) .. VOTES_PER_VOTER[1]; - - let (voters, targets) = set_up_voters_targets::(v, t, d as usize); - }: { - assert!( - SequentialPhragmen:: - ::solve(d as usize, targets, voters).is_ok() - ); +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn phragmen( + // Number of votes in snapshot. + v: Linear<{ VOTERS[0] }, { VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ TARGETS[0] }, { TARGETS[1] }>, + // Number of votes per voter (ie the degree). + d: Linear<{ VOTES_PER_VOTER[0] }, { VOTES_PER_VOTER[1] }>, + ) { + let (voters, targets) = set_up_voters_targets::(v, t, d as _); + let result; + + #[block] + { + result = SequentialPhragmen::::solve(d as _, targets, voters); + } + + assert!(result.is_ok()); } - phragmms { - // number of votes in snapshot. - let v in (VOTERS[0]) .. VOTERS[1]; - // number of targets in snapshot. - let t in (TARGETS[0]) .. TARGETS[1]; - // number of votes per voter (ie the degree). - let d in (VOTES_PER_VOTER[0]) .. VOTES_PER_VOTER[1]; - - let (voters, targets) = set_up_voters_targets::(v, t, d as usize); - }: { - assert!( - PhragMMS:: - ::solve(d as usize, targets, voters).is_ok() - ); + #[benchmark] + fn phragmms( + // Number of votes in snapshot. + v: Linear<{ VOTERS[0] }, { VOTERS[1] }>, + // Number of targets in snapshot. + t: Linear<{ TARGETS[0] }, { TARGETS[1] }>, + // Number of votes per voter (ie the degree). + d: Linear<{ VOTES_PER_VOTER[0] }, { VOTES_PER_VOTER[1] }>, + ) { + let (voters, targets) = set_up_voters_targets::(v, t, d as _); + let result; + + #[block] + { + result = PhragMMS::::solve(d as _, targets, voters); + } + + assert!(result.is_ok()); } } From ec77843c353147059d9d93fb3fd8948b15eb2b6d Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Thu, 7 Nov 2024 11:29:33 +0200 Subject: [PATCH 052/166] fix shared-core-idle-parachain flaky test (#6387) https://github.com/paritytech/polkadot-sdk/issues/6343 --- .gitlab/pipeline/zombienet/polkadot.yml | 2 +- .../functional/0018-shared-core-idle-parachain.zndsl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitlab/pipeline/zombienet/polkadot.yml b/.gitlab/pipeline/zombienet/polkadot.yml index 15d9a5fb5fca..3dab49a118e5 100644 --- a/.gitlab/pipeline/zombienet/polkadot.yml +++ b/.gitlab/pipeline/zombienet/polkadot.yml @@ -241,7 +241,7 @@ zombienet-polkadot-functional-0017-sync-backing: --local-dir="${LOCAL_DIR}/functional" --test="0017-sync-backing.zndsl" -.zombienet-polkadot-functional-0018-shared-core-idle-parachain: +zombienet-polkadot-functional-0018-shared-core-idle-parachain: extends: - .zombienet-polkadot-common before_script: diff --git a/polkadot/zombienet_tests/functional/0018-shared-core-idle-parachain.zndsl b/polkadot/zombienet_tests/functional/0018-shared-core-idle-parachain.zndsl index 80ecf6ae1b9b..dce52505444e 100644 --- a/polkadot/zombienet_tests/functional/0018-shared-core-idle-parachain.zndsl +++ b/polkadot/zombienet_tests/functional/0018-shared-core-idle-parachain.zndsl @@ -8,4 +8,4 @@ validator-0: js-script ./force-register-paras.js with "2000" return is 0 within # assign core 0 to be shared by two paras, but only one exists validator-0: js-script ./assign-core.js with "0,2000,28800,2001,28800" return is 0 within 600 seconds -collator-2000: reports block height is at least 10 within 180 seconds +collator-2000: reports block height is at least 10 within 210 seconds From 3c7b9a0e14dd48dea2ea64313c23261572491009 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Thu, 7 Nov 2024 11:56:28 +0200 Subject: [PATCH 053/166] substrate/zombienet: Fix 0002-validators-warp-sync (#6379) This PR fixes the `0002-validators-warp-sync` zombienet test by matching for a specific error case. The following PR introduced a new error for validators that don't have public addresses available for publishing in the DHT: - https://github.com/paritytech/polkadot-sdk/pull/6298 The log line was moved from `eprintln!("Warning: ...` in sc-cli to the authority discovery where it is printed properly as an error. cc @paritytech/sdk-node Signed-off-by: Alexandru Vasile --- .../test-validators-warp-sync.zndsl | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/substrate/zombienet/0002-validators-warp-sync/test-validators-warp-sync.zndsl b/substrate/zombienet/0002-validators-warp-sync/test-validators-warp-sync.zndsl index bc587b044774..cca1f544b350 100644 --- a/substrate/zombienet/0002-validators-warp-sync/test-validators-warp-sync.zndsl +++ b/substrate/zombienet/0002-validators-warp-sync/test-validators-warp-sync.zndsl @@ -35,7 +35,10 @@ bob: reports block height is at least {{DB_BLOCK_HEIGHT}} within 10 seconds alice: reports substrate_beefy_best_block is at least {{200*180/6}} within 180 seconds bob: reports substrate_beefy_best_block is at least {{200*180/6}} within 180 seconds -alice: count of log lines containing "error" is 0 within 10 seconds +# Validators started without public addresses must emit an error. +# Double check the error is the expected one. +alice: log line matches "No public addresses configured and no global listen addresses found" within 60 seconds +alice: count of log lines containing "error" is 1 within 10 seconds bob: count of log lines containing "verification failed" is 0 within 10 seconds # new blocks were built From 12d9052459ade7fc7588807bf0775d7c7d135e82 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Thu, 7 Nov 2024 12:12:24 +0200 Subject: [PATCH 054/166] Syncing strategy refactoring (part 3) (#5737) # Description This is a continuation of https://github.com/paritytech/polkadot-sdk/pull/5666 that finally fixes https://github.com/paritytech/polkadot-sdk/issues/5333. This should allow developers to create custom syncing strategies or even the whole syncing engine if they so desire. It also moved syncing engine creation and addition of corresponding protocol outside `build_network_advanced` method, which is something Bastian expressed as desired in https://github.com/paritytech/polkadot-sdk/issues/5#issuecomment-1700816458 Here I replaced strategy-specific types and methods in `SyncingStrategy` trait with generic ones. Specifically `SyncingAction` is now used by all strategies instead of strategy-specific types with conversions. `StrategyKey` was an enum with a fixed set of options and now replaced with an opaque type that strategies create privately and send to upper layers as an opaque type. Requests and responses are now handled in a generic way regardless of the strategy, which reduced and simplified strategy API. `PolkadotSyncingStrategy` now lives in its dedicated module (had to edit .gitignore for this) like other strategies. `build_network_advanced` takes generic `SyncingService` as an argument alongside with a few other low-level types (that can probably be extracted in the future as well) without any notion of specifics of the way syncing is actually done. All the protocol and tasks are created outside and not a part of the network anymore. It still adds a bunch of protocols like for light client and some others that should eventually be restructured making `build_network_advanced` just building generic network and not application-specific protocols handling. ## Integration Just like https://github.com/paritytech/polkadot-sdk/pull/5666 introduced `build_polkadot_syncing_strategy`, this PR introduces `build_default_block_downloader`, but for convenience and to avoid typical boilerplate a simpler high-level function `build_default_syncing_engine` is added that will take care of creating typical block downloader, syncing strategy and syncing engine, which is what most users will be using going forward. `build_network` towards the end of the PR was renamed to `build_network_advanced` and `build_network`'s API was reverted to pre-https://github.com/paritytech/polkadot-sdk/pull/5666, so most users will not see much of a difference during upgrade unless they opt-in to use new API. ## Review Notes For `StrategyKey` I was thinking about using something like private type and then storing `TypeId` inside instead of a static string in it, let me know if that would preferred. The biggest change happened to requests that different strategies make and how their responses are handled. The most annoying thing here is that block response decoding, in contrast to all other responses, is dependent on request. This meant request had to be sent throughout the system. While originally `Response` was `Vec`, I didn't want to re-encode/decode request and response just to fit into that API, so I ended up with `Box`. This allows responses to be truly generic and each strategy will know how to downcast it back to the concrete type when handling the response. Import queue refactoring was needed to move `SyncingEngine` construction out of `build_network` that awkwardly implemented for `SyncingService`, but due to `&mut self` wasn't usable on `Arc` for no good reason. `Arc` itself is of course useless, but refactoring to replace it with just `SyncingService` was unfortunately rejected in https://github.com/paritytech/polkadot-sdk/pull/5454 As usual I recommend to review this PR as a series of commits instead of as the final diff, it'll make more sense that way. # Checklist * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. * [x] My PR follows the [labeling requirements]( https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process ) of this project (at minimum one label for `T` required) * External contributors: ask maintainers to put the right label on your PR. * [x] I have made corresponding changes to the documentation (if applicable) --- .gitignore | 1 - cumulus/client/service/src/lib.rs | 19 +- .../lib/src/nodes/manual_seal.rs | 16 +- polkadot/node/service/src/lib.rs | 14 +- prdoc/pr_5737.prdoc | 25 + substrate/bin/node/cli/src/service.rs | 13 +- .../consensus/common/src/import_queue.rs | 14 +- .../common/src/import_queue/basic_queue.rs | 29 +- .../common/src/import_queue/buffered_link.rs | 18 +- .../consensus/common/src/import_queue/mock.rs | 4 +- .../network/sync/src/block_relay_protocol.rs | 7 +- .../network/sync/src/block_request_handler.rs | 5 + substrate/client/network/sync/src/engine.rs | 258 ++------ substrate/client/network/sync/src/mock.rs | 3 + .../network/sync/src/pending_responses.rs | 46 +- .../client/network/sync/src/service/mock.rs | 6 +- .../network/sync/src/service/network.rs | 23 +- .../sync/src/service/syncing_service.rs | 6 +- substrate/client/network/sync/src/strategy.rs | 565 ++---------------- .../network/sync/src/strategy/chain_sync.rs | 313 ++++++---- .../sync/src/strategy/chain_sync/test.rs | 111 +++- .../network/sync/src/strategy/polkadot.rs | 481 +++++++++++++++ .../client/network/sync/src/strategy/state.rs | 134 +++-- .../client/network/sync/src/strategy/warp.rs | 317 +++++++--- substrate/client/network/sync/src/types.rs | 49 +- substrate/client/network/test/src/lib.rs | 21 +- substrate/client/network/test/src/service.rs | 15 +- substrate/client/service/src/builder.rs | 403 ++++++++++--- .../service/src/chain_ops/import_blocks.rs | 36 +- substrate/client/service/src/lib.rs | 10 +- templates/minimal/node/src/service.rs | 20 +- templates/solochain/node/Cargo.toml | 2 +- templates/solochain/node/src/service.rs | 17 +- 33 files changed, 1695 insertions(+), 1306 deletions(-) create mode 100644 prdoc/pr_5737.prdoc create mode 100644 substrate/client/network/sync/src/strategy/polkadot.rs diff --git a/.gitignore b/.gitignore index afa9ed33f4a0..d48287657085 100644 --- a/.gitignore +++ b/.gitignore @@ -30,7 +30,6 @@ artifacts bin/node-template/Cargo.lock nohup.out polkadot_argument_parsing -polkadot.* !docs/sdk/src/polkadot_sdk/polkadot.rs pwasm-alloc/Cargo.lock pwasm-libc/Cargo.lock diff --git a/cumulus/client/service/src/lib.rs b/cumulus/client/service/src/lib.rs index 25b8ee10a931..ae83f2ade3f6 100644 --- a/cumulus/client/service/src/lib.rs +++ b/cumulus/client/service/src/lib.rs @@ -40,10 +40,7 @@ use sc_consensus::{ use sc_network::{config::SyncMode, service::traits::NetworkService, NetworkBackend}; use sc_network_sync::SyncingService; use sc_network_transactions::TransactionsHandlerController; -use sc_service::{ - build_polkadot_syncing_strategy, Configuration, NetworkStarter, SpawnTaskHandle, TaskManager, - WarpSyncConfig, -}; +use sc_service::{Configuration, NetworkStarter, SpawnTaskHandle, TaskManager, WarpSyncConfig}; use sc_telemetry::{log, TelemetryWorkerHandle}; use sc_utils::mpsc::TracingUnboundedSender; use sp_api::ProvideRuntimeApi; @@ -429,7 +426,7 @@ pub struct BuildNetworkParams< pub async fn build_network<'a, Block, Client, RCInterface, IQ, Network>( BuildNetworkParams { parachain_config, - mut net_config, + net_config, client, transaction_pool, para_id, @@ -500,16 +497,6 @@ where parachain_config.prometheus_config.as_ref().map(|config| &config.registry), ); - let syncing_strategy = build_polkadot_syncing_strategy( - parachain_config.protocol_id(), - parachain_config.chain_spec.fork_id(), - &mut net_config, - warp_sync_config, - client.clone(), - &spawn_handle, - parachain_config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - sc_service::build_network(sc_service::BuildNetworkParams { config: parachain_config, net_config, @@ -518,7 +505,7 @@ where spawn_handle, import_queue, block_announce_validator_builder: Some(Box::new(move |_| block_announce_validator)), - syncing_strategy, + warp_sync_config, block_relay: None, metrics, }) diff --git a/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs b/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs index e8043bd7b2aa..b7fc3489da25 100644 --- a/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs +++ b/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs @@ -25,7 +25,7 @@ use cumulus_primitives_core::ParaId; use sc_consensus::{DefaultImportQueue, LongestChain}; use sc_consensus_manual_seal::rpc::{ManualSeal, ManualSealApiServer}; use sc_network::NetworkBackend; -use sc_service::{build_polkadot_syncing_strategy, Configuration, PartialComponents, TaskManager}; +use sc_service::{Configuration, PartialComponents, TaskManager}; use sc_telemetry::TelemetryHandle; use sp_runtime::traits::Header; use std::{marker::PhantomData, sync::Arc}; @@ -85,7 +85,7 @@ impl ManualSealNode { // Since this is a dev node, prevent it from connecting to peers. config.network.default_peers_set.in_peers = 0; config.network.default_peers_set.out_peers = 0; - let mut net_config = sc_network::config::FullNetworkConfiguration::<_, _, Net>::new( + let net_config = sc_network::config::FullNetworkConfiguration::<_, _, Net>::new( &config.network, config.prometheus_config.as_ref().map(|cfg| cfg.registry.clone()), ); @@ -93,16 +93,6 @@ impl ManualSealNode { config.prometheus_config.as_ref().map(|cfg| &cfg.registry), ); - let syncing_strategy = build_polkadot_syncing_strategy( - config.protocol_id(), - config.chain_spec.fork_id(), - &mut net_config, - None, - client.clone(), - &task_manager.spawn_handle(), - config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -112,7 +102,7 @@ impl ManualSealNode { import_queue, net_config, block_announce_validator_builder: None, - syncing_strategy, + warp_sync_config: None, block_relay: None, metrics, })?; diff --git a/polkadot/node/service/src/lib.rs b/polkadot/node/service/src/lib.rs index abba91a38a97..d2424474302a 100644 --- a/polkadot/node/service/src/lib.rs +++ b/polkadot/node/service/src/lib.rs @@ -80,7 +80,7 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration}; use prometheus_endpoint::Registry; #[cfg(feature = "full-node")] use sc_service::KeystoreContainer; -use sc_service::{build_polkadot_syncing_strategy, RpcHandlers, SpawnTaskHandle}; +use sc_service::{RpcHandlers, SpawnTaskHandle}; use sc_telemetry::TelemetryWorker; #[cfg(feature = "full-node")] use sc_telemetry::{Telemetry, TelemetryWorkerHandle}; @@ -1003,16 +1003,6 @@ pub fn new_full< }) }; - let syncing_strategy = build_polkadot_syncing_strategy( - config.protocol_id(), - config.chain_spec.fork_id(), - &mut net_config, - Some(WarpSyncConfig::WithProvider(warp_sync)), - client.clone(), - &task_manager.spawn_handle(), - config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -1022,7 +1012,7 @@ pub fn new_full< spawn_handle: task_manager.spawn_handle(), import_queue, block_announce_validator_builder: None, - syncing_strategy, + warp_sync_config: Some(WarpSyncConfig::WithProvider(warp_sync)), block_relay: None, metrics, })?; diff --git a/prdoc/pr_5737.prdoc b/prdoc/pr_5737.prdoc new file mode 100644 index 000000000000..a122e4574a9c --- /dev/null +++ b/prdoc/pr_5737.prdoc @@ -0,0 +1,25 @@ +title: Make syncing service an argument of `build_network` + +doc: + - audience: Node Dev + description: | + `build_network` is accompanied with lower-level `build_network_advanced` with simpler API that does not create + syncing engine internally, but instead takes a handle to syncing service as an argument. In most cases typical + syncing engine with polkadot syncing strategy and default block downloader can be created with newly introduced + `sc_service::build_default_syncing_engine()` function, but lower-level `build_default_block_downloader` also + exists for those needing more customization. + + These changes allow developers higher than ever control over syncing implementation, but `build_network` is still + available for easier high-level usage. + +crates: + - name: cumulus-client-service + bump: patch + - name: polkadot-service + bump: patch + - name: sc-consensus + bump: major + - name: sc-service + bump: major + - name: sc-network-sync + bump: major diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index 057e0bbdcefc..008cac4ef8a8 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -32,7 +32,6 @@ use frame_system_rpc_runtime_api::AccountNonceApi; use futures::prelude::*; use kitchensink_runtime::RuntimeApi; use node_primitives::Block; -use polkadot_sdk::sc_service::build_polkadot_syncing_strategy; use sc_client_api::{Backend, BlockBackend}; use sc_consensus_babe::{self, SlotProportion}; use sc_network::{ @@ -514,16 +513,6 @@ pub fn new_full_base::Hash>>( Vec::default(), )); - let syncing_strategy = build_polkadot_syncing_strategy( - config.protocol_id(), - config.chain_spec.fork_id(), - &mut net_config, - Some(WarpSyncConfig::WithProvider(warp_sync)), - client.clone(), - &task_manager.spawn_handle(), - config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -533,7 +522,7 @@ pub fn new_full_base::Hash>>( spawn_handle: task_manager.spawn_handle(), import_queue, block_announce_validator_builder: None, - syncing_strategy, + warp_sync_config: Some(WarpSyncConfig::WithProvider(warp_sync)), block_relay: None, metrics, })?; diff --git a/substrate/client/consensus/common/src/import_queue.rs b/substrate/client/consensus/common/src/import_queue.rs index 1baa67398a49..602683907d48 100644 --- a/substrate/client/consensus/common/src/import_queue.rs +++ b/substrate/client/consensus/common/src/import_queue.rs @@ -107,7 +107,7 @@ pub trait Verifier: Send + Sync { /// /// The `import_*` methods can be called in order to send elements for the import queue to verify. pub trait ImportQueueService: Send { - /// Import bunch of blocks, every next block must be an ancestor of the previous block in the + /// Import a bunch of blocks, every next block must be an ancestor of the previous block in the /// list. fn import_blocks(&mut self, origin: BlockOrigin, blocks: Vec>); @@ -132,21 +132,21 @@ pub trait ImportQueue: Send { /// This method should behave in a way similar to `Future::poll`. It can register the current /// task and notify later when more actions are ready to be polled. To continue the comparison, /// it is as if this method always returned `Poll::Pending`. - fn poll_actions(&mut self, cx: &mut futures::task::Context, link: &mut dyn Link); + fn poll_actions(&mut self, cx: &mut futures::task::Context, link: &dyn Link); /// Start asynchronous runner for import queue. /// /// Takes an object implementing [`Link`] which allows the import queue to /// influence the synchronization process. - async fn run(self, link: Box>); + async fn run(self, link: &dyn Link); } /// Hooks that the verification queue can use to influence the synchronization /// algorithm. -pub trait Link: Send { +pub trait Link: Send + Sync { /// Batch of blocks imported, with or without error. fn blocks_processed( - &mut self, + &self, _imported: usize, _count: usize, _results: Vec<(BlockImportResult, B::Hash)>, @@ -155,7 +155,7 @@ pub trait Link: Send { /// Justification import result. fn justification_imported( - &mut self, + &self, _who: RuntimeOrigin, _hash: &B::Hash, _number: NumberFor, @@ -164,7 +164,7 @@ pub trait Link: Send { } /// Request a justification for the given block. - fn request_justification(&mut self, _hash: &B::Hash, _number: NumberFor) {} + fn request_justification(&self, _hash: &B::Hash, _number: NumberFor) {} } /// Block import successful result. diff --git a/substrate/client/consensus/common/src/import_queue/basic_queue.rs b/substrate/client/consensus/common/src/import_queue/basic_queue.rs index 7b371145e2e7..21270859dd75 100644 --- a/substrate/client/consensus/common/src/import_queue/basic_queue.rs +++ b/substrate/client/consensus/common/src/import_queue/basic_queue.rs @@ -177,7 +177,7 @@ impl ImportQueue for BasicQueue { } /// Poll actions from network. - fn poll_actions(&mut self, cx: &mut Context, link: &mut dyn Link) { + fn poll_actions(&mut self, cx: &mut Context, link: &dyn Link) { if self.result_port.poll_actions(cx, link).is_err() { log::error!( target: LOG_TARGET, @@ -190,9 +190,9 @@ impl ImportQueue for BasicQueue { /// /// Takes an object implementing [`Link`] which allows the import queue to /// influence the synchronization process. - async fn run(mut self, mut link: Box>) { + async fn run(mut self, link: &dyn Link) { loop { - if let Err(_) = self.result_port.next_action(&mut *link).await { + if let Err(_) = self.result_port.next_action(link).await { log::error!(target: "sync", "poll_actions: Background import task is no longer alive"); return } @@ -223,7 +223,7 @@ mod worker_messages { async fn block_import_process( mut block_import: BoxBlockImport, verifier: impl Verifier, - mut result_sender: BufferedLinkSender, + result_sender: BufferedLinkSender, mut block_import_receiver: TracingUnboundedReceiver>, metrics: Option, ) { @@ -501,6 +501,7 @@ mod tests { import_queue::Verifier, }; use futures::{executor::block_on, Future}; + use parking_lot::Mutex; use sp_test_primitives::{Block, BlockNumber, Hash, Header}; #[async_trait::async_trait] @@ -558,29 +559,29 @@ mod tests { #[derive(Default)] struct TestLink { - events: Vec, + events: Mutex>, } impl Link for TestLink { fn blocks_processed( - &mut self, + &self, _imported: usize, _count: usize, results: Vec<(Result, BlockImportError>, Hash)>, ) { if let Some(hash) = results.into_iter().find_map(|(r, h)| r.ok().map(|_| h)) { - self.events.push(Event::BlockImported(hash)); + self.events.lock().push(Event::BlockImported(hash)); } } fn justification_imported( - &mut self, + &self, _who: RuntimeOrigin, hash: &Hash, _number: BlockNumber, _success: bool, ) { - self.events.push(Event::JustificationImported(*hash)) + self.events.lock().push(Event::JustificationImported(*hash)) } } @@ -638,7 +639,7 @@ mod tests { hash }; - let mut link = TestLink::default(); + let link = TestLink::default(); // we send a bunch of tasks to the worker let block1 = import_block(1); @@ -653,13 +654,13 @@ mod tests { // we poll the worker until we have processed 9 events block_on(futures::future::poll_fn(|cx| { - while link.events.len() < 9 { + while link.events.lock().len() < 9 { match Future::poll(Pin::new(&mut worker), cx) { Poll::Pending => {}, Poll::Ready(()) => panic!("import queue worker should not conclude."), } - result_port.poll_actions(cx, &mut link).unwrap(); + result_port.poll_actions(cx, &link).unwrap(); } Poll::Ready(()) @@ -667,8 +668,8 @@ mod tests { // all justification tasks must be done before any block import work assert_eq!( - link.events, - vec![ + &*link.events.lock(), + &[ Event::JustificationImported(justification1), Event::JustificationImported(justification2), Event::JustificationImported(justification3), diff --git a/substrate/client/consensus/common/src/import_queue/buffered_link.rs b/substrate/client/consensus/common/src/import_queue/buffered_link.rs index c23a4b0d5d0a..67131b06a32e 100644 --- a/substrate/client/consensus/common/src/import_queue/buffered_link.rs +++ b/substrate/client/consensus/common/src/import_queue/buffered_link.rs @@ -27,13 +27,13 @@ //! # use sc_consensus::import_queue::buffered_link::buffered_link; //! # use sp_test_primitives::Block; //! # struct DummyLink; impl Link for DummyLink {} -//! # let mut my_link = DummyLink; +//! # let my_link = DummyLink; //! let (mut tx, mut rx) = buffered_link::(100_000); //! tx.blocks_processed(0, 0, vec![]); //! //! // Calls `my_link.blocks_processed(0, 0, vec![])` when polled. //! let _fut = futures::future::poll_fn(move |cx| { -//! rx.poll_actions(cx, &mut my_link); +//! rx.poll_actions(cx, &my_link).unwrap(); //! std::task::Poll::Pending::<()> //! }); //! ``` @@ -90,7 +90,7 @@ pub enum BlockImportWorkerMsg { impl Link for BufferedLinkSender { fn blocks_processed( - &mut self, + &self, imported: usize, count: usize, results: Vec<(BlockImportResult, B::Hash)>, @@ -101,7 +101,7 @@ impl Link for BufferedLinkSender { } fn justification_imported( - &mut self, + &self, who: RuntimeOrigin, hash: &B::Hash, number: NumberFor, @@ -111,7 +111,7 @@ impl Link for BufferedLinkSender { let _ = self.tx.unbounded_send(msg); } - fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { + fn request_justification(&self, hash: &B::Hash, number: NumberFor) { let _ = self .tx .unbounded_send(BlockImportWorkerMsg::RequestJustification(*hash, number)); @@ -125,7 +125,7 @@ pub struct BufferedLinkReceiver { impl BufferedLinkReceiver { /// Send action for the synchronization to perform. - pub fn send_actions(&mut self, msg: BlockImportWorkerMsg, link: &mut dyn Link) { + pub fn send_actions(&mut self, msg: BlockImportWorkerMsg, link: &dyn Link) { match msg { BlockImportWorkerMsg::BlocksProcessed(imported, count, results) => link.blocks_processed(imported, count, results), @@ -144,7 +144,7 @@ impl BufferedLinkReceiver { /// it is as if this method always returned `Poll::Pending`. /// /// Returns an error if the corresponding [`BufferedLinkSender`] has been closed. - pub fn poll_actions(&mut self, cx: &mut Context, link: &mut dyn Link) -> Result<(), ()> { + pub fn poll_actions(&mut self, cx: &mut Context, link: &dyn Link) -> Result<(), ()> { loop { let msg = match Stream::poll_next(Pin::new(&mut self.rx), cx) { Poll::Ready(Some(msg)) => msg, @@ -152,12 +152,12 @@ impl BufferedLinkReceiver { Poll::Pending => break Ok(()), }; - self.send_actions(msg, &mut *link); + self.send_actions(msg, link); } } /// Poll next element from import queue and send the corresponding action command over the link. - pub async fn next_action(&mut self, link: &mut dyn Link) -> Result<(), ()> { + pub async fn next_action(&mut self, link: &dyn Link) -> Result<(), ()> { if let Some(msg) = self.rx.next().await { self.send_actions(msg, link); return Ok(()) diff --git a/substrate/client/consensus/common/src/import_queue/mock.rs b/substrate/client/consensus/common/src/import_queue/mock.rs index 64ac532ded85..a238f72568ca 100644 --- a/substrate/client/consensus/common/src/import_queue/mock.rs +++ b/substrate/client/consensus/common/src/import_queue/mock.rs @@ -40,7 +40,7 @@ mockall::mock! { impl ImportQueue for ImportQueue { fn service(&self) -> Box>; fn service_ref(&mut self) -> &mut dyn ImportQueueService; - fn poll_actions<'a>(&mut self, cx: &mut futures::task::Context<'a>, link: &mut dyn Link); - async fn run(self, link: Box>); + fn poll_actions<'a>(&mut self, cx: &mut futures::task::Context<'a>, link: &dyn Link); + async fn run(self, link: &'__mockall_link dyn Link); } } diff --git a/substrate/client/network/sync/src/block_relay_protocol.rs b/substrate/client/network/sync/src/block_relay_protocol.rs index 3c5b3739e822..13639d851b27 100644 --- a/substrate/client/network/sync/src/block_relay_protocol.rs +++ b/substrate/client/network/sync/src/block_relay_protocol.rs @@ -21,7 +21,7 @@ use sc_network::{request_responses::RequestFailure, NetworkBackend, ProtocolName use sc_network_common::sync::message::{BlockData, BlockRequest}; use sc_network_types::PeerId; use sp_runtime::traits::Block as BlockT; -use std::sync::Arc; +use std::{fmt, sync::Arc}; /// The serving side of the block relay protocol. It runs a single instance /// of the server task that processes the incoming protocol messages. @@ -34,7 +34,10 @@ pub trait BlockServer: Send { /// The client side stub to download blocks from peers. This is a handle /// that can be used to initiate concurrent downloads. #[async_trait::async_trait] -pub trait BlockDownloader: Send + Sync { +pub trait BlockDownloader: fmt::Debug + Send + Sync { + /// Protocol name used by block downloader. + fn protocol_name(&self) -> &ProtocolName; + /// Performs the protocol specific sequence to fetch the blocks from the peer. /// Output: if the download succeeds, the response is a `Vec` which is /// in a format specific to the protocol implementation. The block data diff --git a/substrate/client/network/sync/src/block_request_handler.rs b/substrate/client/network/sync/src/block_request_handler.rs index 6e970b399310..80234170bc20 100644 --- a/substrate/client/network/sync/src/block_request_handler.rs +++ b/substrate/client/network/sync/src/block_request_handler.rs @@ -502,6 +502,7 @@ enum HandleRequestError { } /// The full block downloader implementation of [`BlockDownloader]. +#[derive(Debug)] pub struct FullBlockDownloader { protocol_name: ProtocolName, network: NetworkServiceHandle, @@ -576,6 +577,10 @@ impl FullBlockDownloader { #[async_trait::async_trait] impl BlockDownloader for FullBlockDownloader { + fn protocol_name(&self) -> &ProtocolName { + &self.protocol_name + } + async fn download_blocks( &self, who: PeerId, diff --git a/substrate/client/network/sync/src/engine.rs b/substrate/client/network/sync/src/engine.rs index dceea9954c6e..cc2089d1974c 100644 --- a/substrate/client/network/sync/src/engine.rs +++ b/substrate/client/network/sync/src/engine.rs @@ -23,30 +23,22 @@ use crate::{ block_announce_validator::{ BlockAnnounceValidationResult, BlockAnnounceValidator as BlockAnnounceValidatorStream, }, - block_relay_protocol::{BlockDownloader, BlockResponseError}, pending_responses::{PendingResponses, ResponseEvent}, - schema::v1::{StateRequest, StateResponse}, service::{ self, syncing_service::{SyncingService, ToServiceCommand}, }, - strategy::{ - warp::{EncodedProof, WarpProofRequest}, - StrategyKey, SyncingAction, SyncingStrategy, - }, - types::{ - BadPeer, ExtendedPeerInfo, OpaqueStateRequest, OpaqueStateResponse, PeerRequest, SyncEvent, - }, + strategy::{SyncingAction, SyncingStrategy}, + types::{BadPeer, ExtendedPeerInfo, SyncEvent}, LOG_TARGET, }; use codec::{Decode, DecodeAll, Encode}; -use futures::{channel::oneshot, FutureExt, StreamExt}; +use futures::{channel::oneshot, StreamExt}; use log::{debug, error, trace, warn}; use prometheus_endpoint::{ register, Counter, Gauge, MetricSource, Opts, PrometheusError, Registry, SourcedGauge, U64, }; -use prost::Message; use schnellru::{ByLength, LruMap}; use tokio::time::{Interval, MissedTickBehavior}; @@ -55,7 +47,7 @@ use sc_consensus::{import_queue::ImportQueueService, IncomingBlock}; use sc_network::{ config::{FullNetworkConfiguration, NotificationHandshake, ProtocolId, SetConfig}, peer_store::PeerStoreProvider, - request_responses::{IfDisconnected, OutboundFailure, RequestFailure}, + request_responses::{OutboundFailure, RequestFailure}, service::{ traits::{Direction, NotificationConfig, NotificationEvent, ValidationResult}, NotificationMetrics, @@ -66,7 +58,7 @@ use sc_network::{ }; use sc_network_common::{ role::Roles, - sync::message::{BlockAnnounce, BlockAnnouncesHandshake, BlockRequest, BlockState}, + sync::message::{BlockAnnounce, BlockAnnouncesHandshake, BlockState}, }; use sc_network_types::PeerId; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; @@ -102,8 +94,6 @@ mod rep { pub const GENESIS_MISMATCH: Rep = Rep::new_fatal("Genesis mismatch"); /// Peer send us a block announcement that failed at validation. pub const BAD_BLOCK_ANNOUNCEMENT: Rep = Rep::new(-(1 << 12), "Bad block announcement"); - /// We received a message that failed to decode. - pub const BAD_MESSAGE: Rep = Rep::new(-(1 << 12), "Bad message"); /// Peer is on unsupported protocol version. pub const BAD_PROTOCOL: Rep = Rep::new_fatal("Unsupported protocol"); /// Reputation change when a peer refuses a request. @@ -264,10 +254,7 @@ pub struct SyncingEngine { peer_store_handle: Arc, /// Pending responses - pending_responses: PendingResponses, - - /// Block downloader - block_downloader: Arc>, + pending_responses: PendingResponses, /// Handle to import queue. import_queue: Box>, @@ -291,12 +278,11 @@ where network_metrics: NotificationMetrics, net_config: &FullNetworkConfiguration::Hash, N>, protocol_id: ProtocolId, - fork_id: &Option, + fork_id: Option<&str>, block_announce_validator: Box + Send>, syncing_strategy: Box>, network_service: service::network::NetworkServiceHandle, import_queue: Box>, - block_downloader: Arc>, peer_store_handle: Arc, ) -> Result<(Self, SyncingService, N::NotificationProtocolConfig), ClientError> where @@ -417,7 +403,6 @@ where None }, pending_responses: PendingResponses::new(), - block_downloader, import_queue, }, SyncingService::new(tx, num_connected, is_major_syncing), @@ -583,57 +568,42 @@ where } fn process_strategy_actions(&mut self) -> Result<(), ClientError> { - for action in self.strategy.actions()? { + for action in self.strategy.actions(&self.network_service)? { match action { - SyncingAction::SendBlockRequest { peer_id, key, request } => { - // Sending block request implies dropping obsolete pending response as we are - // not interested in it anymore (see [`SyncingAction::SendBlockRequest`]). - let removed = self.pending_responses.remove(peer_id, key); - self.send_block_request(peer_id, key, request.clone()); - - if removed { - warn!( - target: LOG_TARGET, - "Processed `ChainSyncAction::SendBlockRequest` to {} from {:?} with {:?}. \ - Stale response removed!", - peer_id, - key, - request, - ) - } else { + SyncingAction::StartRequest { peer_id, key, request, remove_obsolete } => { + if !self.peers.contains_key(&peer_id) { trace!( target: LOG_TARGET, - "Processed `ChainSyncAction::SendBlockRequest` to {} from {:?} with {:?}.", - peer_id, - key, - request, - ) + "Cannot start request with strategy key {key:?} to unknown peer \ + {peer_id}", + ); + debug_assert!(false); + continue; } + if remove_obsolete { + if self.pending_responses.remove(peer_id, key) { + warn!( + target: LOG_TARGET, + "Processed `SyncingAction::StartRequest` to {peer_id} with \ + strategy key {key:?}. Stale response removed!", + ) + } else { + trace!( + target: LOG_TARGET, + "Processed `SyncingAction::StartRequest` to {peer_id} with \ + strategy key {key:?}.", + ) + } + } + + self.pending_responses.insert(peer_id, key, request); }, SyncingAction::CancelRequest { peer_id, key } => { let removed = self.pending_responses.remove(peer_id, key); trace!( target: LOG_TARGET, - "Processed {action:?}, response removed: {removed}.", - ); - }, - SyncingAction::SendStateRequest { peer_id, key, protocol_name, request } => { - self.send_state_request(peer_id, key, protocol_name, request); - - trace!( - target: LOG_TARGET, - "Processed `ChainSyncAction::SendStateRequest` to {peer_id}.", - ); - }, - SyncingAction::SendWarpProofRequest { peer_id, key, protocol_name, request } => { - self.send_warp_proof_request(peer_id, key, protocol_name, request.clone()); - - trace!( - target: LOG_TARGET, - "Processed `ChainSyncAction::SendWarpProofRequest` to {}, request: {:?}.", - peer_id, - request, + "Processed `SyncingAction::CancelRequest`, response removed: {removed}.", ); }, SyncingAction::DropPeer(BadPeer(peer_id, rep)) => { @@ -1000,160 +970,12 @@ where Ok(()) } - fn send_block_request(&mut self, peer_id: PeerId, key: StrategyKey, request: BlockRequest) { - if !self.peers.contains_key(&peer_id) { - trace!(target: LOG_TARGET, "Cannot send block request to unknown peer {peer_id}"); - debug_assert!(false); - return; - } - - let downloader = self.block_downloader.clone(); - - self.pending_responses.insert( - peer_id, - key, - PeerRequest::Block(request.clone()), - async move { downloader.download_blocks(peer_id, request).await }.boxed(), - ); - } - - fn send_state_request( - &mut self, - peer_id: PeerId, - key: StrategyKey, - protocol_name: ProtocolName, - request: OpaqueStateRequest, - ) { - if !self.peers.contains_key(&peer_id) { - trace!(target: LOG_TARGET, "Cannot send state request to unknown peer {peer_id}"); - debug_assert!(false); - return; - } - - let (tx, rx) = oneshot::channel(); - - self.pending_responses.insert(peer_id, key, PeerRequest::State, rx.boxed()); - - match Self::encode_state_request(&request) { - Ok(data) => { - self.network_service.start_request( - peer_id, - protocol_name, - data, - tx, - IfDisconnected::ImmediateError, - ); - }, - Err(err) => { - log::warn!( - target: LOG_TARGET, - "Failed to encode state request {request:?}: {err:?}", - ); - }, - } - } - - fn send_warp_proof_request( - &mut self, - peer_id: PeerId, - key: StrategyKey, - protocol_name: ProtocolName, - request: WarpProofRequest, - ) { - if !self.peers.contains_key(&peer_id) { - trace!(target: LOG_TARGET, "Cannot send warp proof request to unknown peer {peer_id}"); - debug_assert!(false); - return; - } - - let (tx, rx) = oneshot::channel(); - - self.pending_responses.insert(peer_id, key, PeerRequest::WarpProof, rx.boxed()); - - self.network_service.start_request( - peer_id, - protocol_name, - request.encode(), - tx, - IfDisconnected::ImmediateError, - ); - } - - fn encode_state_request(request: &OpaqueStateRequest) -> Result, String> { - let request: &StateRequest = request.0.downcast_ref().ok_or_else(|| { - "Failed to downcast opaque state response during encoding, this is an \ - implementation bug." - .to_string() - })?; - - Ok(request.encode_to_vec()) - } - - fn decode_state_response(response: &[u8]) -> Result { - let response = StateResponse::decode(response) - .map_err(|error| format!("Failed to decode state response: {error}"))?; - - Ok(OpaqueStateResponse(Box::new(response))) - } - - fn process_response_event(&mut self, response_event: ResponseEvent) { - let ResponseEvent { peer_id, key, request, response } = response_event; + fn process_response_event(&mut self, response_event: ResponseEvent) { + let ResponseEvent { peer_id, key, response: response_result } = response_event; - match response { - Ok(Ok((resp, _))) => match request { - PeerRequest::Block(req) => { - match self.block_downloader.block_response_into_blocks(&req, resp) { - Ok(blocks) => { - self.strategy.on_block_response(peer_id, key, req, blocks); - }, - Err(BlockResponseError::DecodeFailed(e)) => { - debug!( - target: LOG_TARGET, - "Failed to decode block response from peer {:?}: {:?}.", - peer_id, - e - ); - self.network_service.report_peer(peer_id, rep::BAD_MESSAGE); - self.network_service.disconnect_peer( - peer_id, - self.block_announce_protocol_name.clone(), - ); - return; - }, - Err(BlockResponseError::ExtractionFailed(e)) => { - debug!( - target: LOG_TARGET, - "Failed to extract blocks from peer response {:?}: {:?}.", - peer_id, - e - ); - self.network_service.report_peer(peer_id, rep::BAD_MESSAGE); - return; - }, - } - }, - PeerRequest::State => { - let response = match Self::decode_state_response(&resp[..]) { - Ok(proto) => proto, - Err(e) => { - debug!( - target: LOG_TARGET, - "Failed to decode state response from peer {peer_id:?}: {e:?}.", - ); - self.network_service.report_peer(peer_id, rep::BAD_MESSAGE); - self.network_service.disconnect_peer( - peer_id, - self.block_announce_protocol_name.clone(), - ); - return; - }, - }; - - self.strategy.on_state_response(peer_id, key, response); - }, - PeerRequest::WarpProof => { - self.strategy.on_warp_proof_response(&peer_id, key, EncodedProof(resp)); - }, + match response_result { + Ok(Ok((response, protocol_name))) => { + self.strategy.on_generic_response(&peer_id, key, protocol_name, response); }, Ok(Err(e)) => { debug!(target: LOG_TARGET, "Request to peer {peer_id:?} failed: {e:?}."); @@ -1214,7 +1036,7 @@ where /// Get config for the block announcement protocol fn get_block_announce_proto_config::Hash>>( protocol_id: ProtocolId, - fork_id: &Option, + fork_id: Option<&str>, roles: Roles, best_number: NumberFor, best_hash: B::Hash, @@ -1225,7 +1047,7 @@ where ) -> (N::NotificationProtocolConfig, Box) { let block_announces_protocol = { let genesis_hash = genesis_hash.as_ref(); - if let Some(ref fork_id) = fork_id { + if let Some(fork_id) = fork_id { format!( "/{}/{}/block-announces/1", array_bytes::bytes2hex("", genesis_hash), diff --git a/substrate/client/network/sync/src/mock.rs b/substrate/client/network/sync/src/mock.rs index 741fa7139583..bf25156f9703 100644 --- a/substrate/client/network/sync/src/mock.rs +++ b/substrate/client/network/sync/src/mock.rs @@ -27,10 +27,13 @@ use sc_network_types::PeerId; use sp_runtime::traits::Block as BlockT; mockall::mock! { + #[derive(Debug)] pub BlockDownloader {} #[async_trait::async_trait] impl BlockDownloaderT for BlockDownloader { + fn protocol_name(&self) -> &ProtocolName; + async fn download_blocks( &self, who: PeerId, diff --git a/substrate/client/network/sync/src/pending_responses.rs b/substrate/client/network/sync/src/pending_responses.rs index 7d2d598a2e06..46e6ae626328 100644 --- a/substrate/client/network/sync/src/pending_responses.rs +++ b/substrate/client/network/sync/src/pending_responses.rs @@ -19,7 +19,7 @@ //! [`PendingResponses`] is responsible for keeping track of pending responses and //! polling them. [`Stream`] implemented by [`PendingResponses`] never terminates. -use crate::{strategy::StrategyKey, types::PeerRequest, LOG_TARGET}; +use crate::{strategy::StrategyKey, LOG_TARGET}; use futures::{ channel::oneshot, future::BoxFuture, @@ -27,61 +27,49 @@ use futures::{ FutureExt, StreamExt, }; use log::error; +use std::any::Any; use sc_network::{request_responses::RequestFailure, types::ProtocolName}; use sc_network_types::PeerId; -use sp_runtime::traits::Block as BlockT; use std::task::{Context, Poll, Waker}; use tokio_stream::StreamMap; /// Response result. -type ResponseResult = Result, ProtocolName), RequestFailure>, oneshot::Canceled>; +type ResponseResult = + Result, ProtocolName), RequestFailure>, oneshot::Canceled>; /// A future yielding [`ResponseResult`]. -type ResponseFuture = BoxFuture<'static, ResponseResult>; +pub(crate) type ResponseFuture = BoxFuture<'static, ResponseResult>; /// An event we receive once a pending response future resolves. -pub(crate) struct ResponseEvent { +pub(crate) struct ResponseEvent { pub peer_id: PeerId, pub key: StrategyKey, - pub request: PeerRequest, pub response: ResponseResult, } /// Stream taking care of polling pending responses. -pub(crate) struct PendingResponses { +pub(crate) struct PendingResponses { /// Pending responses - pending_responses: - StreamMap<(PeerId, StrategyKey), BoxStream<'static, (PeerRequest, ResponseResult)>>, + pending_responses: StreamMap<(PeerId, StrategyKey), BoxStream<'static, ResponseResult>>, /// Waker to implement never terminating stream waker: Option, } -impl PendingResponses { +impl PendingResponses { pub fn new() -> Self { Self { pending_responses: StreamMap::new(), waker: None } } - pub fn insert( - &mut self, - peer_id: PeerId, - key: StrategyKey, - request: PeerRequest, - response_future: ResponseFuture, - ) { - let request_type = request.get_type(); - + pub fn insert(&mut self, peer_id: PeerId, key: StrategyKey, response_future: ResponseFuture) { if self .pending_responses - .insert( - (peer_id, key), - Box::pin(async move { (request, response_future.await) }.into_stream()), - ) + .insert((peer_id, key), Box::pin(response_future.into_stream())) .is_some() { error!( target: LOG_TARGET, - "Discarded pending response from peer {peer_id}, request type: {request_type:?}.", + "Discarded pending response from peer {peer_id}, strategy key: {key:?}.", ); debug_assert!(false); } @@ -112,21 +100,21 @@ impl PendingResponses { } } -impl Stream for PendingResponses { - type Item = ResponseEvent; +impl Stream for PendingResponses { + type Item = ResponseEvent; fn poll_next( mut self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> { match self.pending_responses.poll_next_unpin(cx) { - Poll::Ready(Some(((peer_id, key), (request, response)))) => { + Poll::Ready(Some(((peer_id, key), response))) => { // We need to manually remove the stream, because `StreamMap` doesn't know yet that // it's going to yield `None`, so may not remove it before the next request is made // to the same peer. self.pending_responses.remove(&(peer_id, key)); - Poll::Ready(Some(ResponseEvent { peer_id, key, request, response })) + Poll::Ready(Some(ResponseEvent { peer_id, key, response })) }, Poll::Ready(None) | Poll::Pending => { self.waker = Some(cx.waker().clone()); @@ -138,7 +126,7 @@ impl Stream for PendingResponses { } // As [`PendingResponses`] never terminates, we can easily implement [`FusedStream`] for it. -impl FusedStream for PendingResponses { +impl FusedStream for PendingResponses { fn is_terminated(&self) -> bool { false } diff --git a/substrate/client/network/sync/src/service/mock.rs b/substrate/client/network/sync/src/service/mock.rs index 141edc7c8841..300aa076515f 100644 --- a/substrate/client/network/sync/src/service/mock.rs +++ b/substrate/client/network/sync/src/service/mock.rs @@ -45,19 +45,19 @@ mockall::mock! { impl sc_consensus::Link for ChainSyncInterface { fn blocks_processed( - &mut self, + &self, imported: usize, count: usize, results: Vec<(Result>, BlockImportError>, B::Hash)>, ); fn justification_imported( - &mut self, + &self, who: PeerId, hash: &B::Hash, number: NumberFor, success: bool, ); - fn request_justification(&mut self, hash: &B::Hash, number: NumberFor); + fn request_justification(&self, hash: &B::Hash, number: NumberFor); } } diff --git a/substrate/client/network/sync/src/service/network.rs b/substrate/client/network/sync/src/service/network.rs index e848b5f62c1b..139e1a986a92 100644 --- a/substrate/client/network/sync/src/service/network.rs +++ b/substrate/client/network/sync/src/service/network.rs @@ -39,9 +39,11 @@ impl Network for T where T: NetworkPeers + NetworkRequest {} /// calls the `NetworkService` on its behalf. pub struct NetworkServiceProvider { rx: TracingUnboundedReceiver, + handle: NetworkServiceHandle, } /// Commands that `ChainSync` wishes to send to `NetworkService` +#[derive(Debug)] pub enum ToServiceCommand { /// Call `NetworkPeers::disconnect_peer()` DisconnectPeer(PeerId, ProtocolName), @@ -61,7 +63,7 @@ pub enum ToServiceCommand { /// Handle that is (temporarily) passed to `ChainSync` so it can /// communicate with `NetworkService` through `SyncingEngine` -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct NetworkServiceHandle { tx: TracingUnboundedSender, } @@ -99,15 +101,23 @@ impl NetworkServiceHandle { impl NetworkServiceProvider { /// Create new `NetworkServiceProvider` - pub fn new() -> (Self, NetworkServiceHandle) { + pub fn new() -> Self { let (tx, rx) = tracing_unbounded("mpsc_network_service_provider", 100_000); - (Self { rx }, NetworkServiceHandle::new(tx)) + Self { rx, handle: NetworkServiceHandle::new(tx) } + } + + /// Get handle to talk to the provider + pub fn handle(&self) -> NetworkServiceHandle { + self.handle.clone() } /// Run the `NetworkServiceProvider` - pub async fn run(mut self, service: Arc) { - while let Some(inner) = self.rx.next().await { + pub async fn run(self, service: Arc) { + let Self { mut rx, handle } = self; + drop(handle); + + while let Some(inner) = rx.next().await { match inner { ToServiceCommand::DisconnectPeer(peer, protocol_name) => service.disconnect_peer(peer, protocol_name), @@ -129,7 +139,8 @@ mod tests { // and then reported #[tokio::test] async fn disconnect_and_report_peer() { - let (provider, handle) = NetworkServiceProvider::new(); + let provider = NetworkServiceProvider::new(); + let handle = provider.handle(); let peer = PeerId::random(); let proto = ProtocolName::from("test-protocol"); diff --git a/substrate/client/network/sync/src/service/syncing_service.rs b/substrate/client/network/sync/src/service/syncing_service.rs index 08a2b36118a9..b56af2b9976a 100644 --- a/substrate/client/network/sync/src/service/syncing_service.rs +++ b/substrate/client/network/sync/src/service/syncing_service.rs @@ -177,7 +177,7 @@ impl SyncStatusProvider for SyncingService { impl Link for SyncingService { fn blocks_processed( - &mut self, + &self, imported: usize, count: usize, results: Vec<(Result>, BlockImportError>, B::Hash)>, @@ -188,7 +188,7 @@ impl Link for SyncingService { } fn justification_imported( - &mut self, + &self, who: PeerId, hash: &B::Hash, number: NumberFor, @@ -199,7 +199,7 @@ impl Link for SyncingService { .unbounded_send(ToServiceCommand::JustificationImported(who, *hash, number, success)); } - fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { + fn request_justification(&self, hash: &B::Hash, number: NumberFor) { let _ = self.tx.unbounded_send(ToServiceCommand::RequestJustification(*hash, number)); } } diff --git a/substrate/client/network/sync/src/strategy.rs b/substrate/client/network/sync/src/strategy.rs index 81998b7576bb..cdc6de1f8c65 100644 --- a/substrate/client/network/sync/src/strategy.rs +++ b/substrate/client/network/sync/src/strategy.rs @@ -16,50 +16,35 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! [`PolkadotSyncingStrategy`] is a proxy between [`crate::engine::SyncingEngine`] -//! and specific syncing algorithms. +//! [`SyncingStrategy`] defines an interface [`crate::engine::SyncingEngine`] uses as a specific +//! syncing algorithm. +//! +//! A few different strategies are provided by Substrate out of the box with custom strategies +//! possible too. pub mod chain_sync; mod disconnected_peers; +pub mod polkadot; mod state; pub mod state_sync; pub mod warp; use crate::{ - block_request_handler::MAX_BLOCKS_IN_RESPONSE, - types::{BadPeer, OpaqueStateRequest, OpaqueStateResponse, SyncStatus}, - LOG_TARGET, + pending_responses::ResponseFuture, + service::network::NetworkServiceHandle, + types::{BadPeer, SyncStatus}, }; -use chain_sync::{ChainSync, ChainSyncMode}; -use log::{debug, error, info}; -use prometheus_endpoint::Registry; -use sc_client_api::{BlockBackend, ProofProvider}; use sc_consensus::{BlockImportError, BlockImportStatus, IncomingBlock}; use sc_network::ProtocolName; -use sc_network_common::sync::{ - message::{BlockAnnounce, BlockData, BlockRequest}, - SyncMode, -}; +use sc_network_common::sync::message::BlockAnnounce; use sc_network_types::PeerId; -use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata}; +use sp_blockchain::Error as ClientError; use sp_consensus::BlockOrigin; use sp_runtime::{ - traits::{Block as BlockT, Header, NumberFor}, + traits::{Block as BlockT, NumberFor}, Justifications, }; -use state::{StateStrategy, StateStrategyAction}; -use std::{collections::HashMap, sync::Arc}; -use warp::{EncodedProof, WarpProofRequest, WarpSync, WarpSyncAction, WarpSyncConfig}; - -/// Corresponding `ChainSync` mode. -fn chain_sync_mode(sync_mode: SyncMode) -> ChainSyncMode { - match sync_mode { - SyncMode::Full => ChainSyncMode::Full, - SyncMode::LightState { skip_proofs, storage_chain_mode } => - ChainSyncMode::LightState { skip_proofs, storage_chain_mode }, - SyncMode::Warp => ChainSyncMode::Full, - } -} +use std::any::Any; /// Syncing strategy for syncing engine to use pub trait SyncingStrategy: Send @@ -101,29 +86,16 @@ where /// Report a justification import (successful or not). fn on_justification_import(&mut self, hash: B::Hash, number: NumberFor, success: bool); - /// Process block response. - fn on_block_response( - &mut self, - peer_id: PeerId, - key: StrategyKey, - request: BlockRequest, - blocks: Vec>, - ); - - /// Process state response. - fn on_state_response( - &mut self, - peer_id: PeerId, - key: StrategyKey, - response: OpaqueStateResponse, - ); - - /// Process warp proof response. - fn on_warp_proof_response( + /// Process generic response. + /// + /// Strategy has to create opaque response and should be to downcast it back into concrete type + /// internally. Failure to downcast is an implementation bug. + fn on_generic_response( &mut self, peer_id: &PeerId, key: StrategyKey, - response: EncodedProof, + protocol_name: ProtocolName, + response: Box, ); /// A batch of blocks that have been processed, with or without errors. @@ -160,52 +132,32 @@ where /// Get actions that should be performed by the owner on the strategy's behalf #[must_use] - fn actions(&mut self) -> Result>, ClientError>; -} - -/// Syncing configuration containing data for all strategies. -#[derive(Clone, Debug)] -pub struct SyncingConfig { - /// Syncing mode. - pub mode: SyncMode, - /// The number of parallel downloads to guard against slow peers. - pub max_parallel_downloads: u32, - /// Maximum number of blocks to request. - pub max_blocks_per_request: u32, - /// Prometheus metrics registry. - pub metrics_registry: Option, - /// Protocol name used to send out state requests - pub state_request_protocol_name: ProtocolName, + fn actions( + &mut self, + // TODO: Consider making this internal property of the strategy + network_service: &NetworkServiceHandle, + ) -> Result>, ClientError>; } /// The key identifying a specific strategy for responses routing. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum StrategyKey { - /// Warp sync initiated this request. - Warp, - /// State sync initiated this request. - State, - /// `ChainSync` initiated this request. - ChainSync, +pub struct StrategyKey(&'static str); + +impl StrategyKey { + /// Instantiate opaque strategy key. + pub const fn new(key: &'static str) -> Self { + Self(key) + } } -#[derive(Debug)] pub enum SyncingAction { - /// Send block request to peer. Always implies dropping a stale block request to the same peer. - SendBlockRequest { peer_id: PeerId, key: StrategyKey, request: BlockRequest }, - /// Send state request to peer. - SendStateRequest { - peer_id: PeerId, - key: StrategyKey, - protocol_name: ProtocolName, - request: OpaqueStateRequest, - }, - /// Send warp proof request to peer. - SendWarpProofRequest { + /// Start request to peer. + StartRequest { peer_id: PeerId, key: StrategyKey, - protocol_name: ProtocolName, - request: WarpProofRequest, + request: ResponseFuture, + // Whether to remove obsolete pending responses. + remove_obsolete: bool, }, /// Drop stale request. CancelRequest { peer_id: PeerId, key: StrategyKey }, @@ -228,441 +180,16 @@ impl SyncingAction { fn is_finished(&self) -> bool { matches!(self, SyncingAction::Finished) } -} - -impl From> for SyncingAction { - fn from(action: WarpSyncAction) -> Self { - match action { - WarpSyncAction::SendWarpProofRequest { peer_id, protocol_name, request } => - SyncingAction::SendWarpProofRequest { - peer_id, - key: StrategyKey::Warp, - protocol_name, - request, - }, - WarpSyncAction::SendBlockRequest { peer_id, request } => - SyncingAction::SendBlockRequest { peer_id, key: StrategyKey::Warp, request }, - WarpSyncAction::DropPeer(bad_peer) => SyncingAction::DropPeer(bad_peer), - WarpSyncAction::Finished => SyncingAction::Finished, - } - } -} - -impl From> for SyncingAction { - fn from(action: StateStrategyAction) -> Self { - match action { - StateStrategyAction::SendStateRequest { peer_id, protocol_name, request } => - SyncingAction::SendStateRequest { - peer_id, - key: StrategyKey::State, - protocol_name, - request, - }, - StateStrategyAction::DropPeer(bad_peer) => SyncingAction::DropPeer(bad_peer), - StateStrategyAction::ImportBlocks { origin, blocks } => - SyncingAction::ImportBlocks { origin, blocks }, - StateStrategyAction::Finished => SyncingAction::Finished, - } - } -} - -/// Proxy to specific syncing strategies used in Polkadot. -pub struct PolkadotSyncingStrategy { - /// Initial syncing configuration. - config: SyncingConfig, - /// Client used by syncing strategies. - client: Arc, - /// Warp strategy. - warp: Option>, - /// State strategy. - state: Option>, - /// `ChainSync` strategy.` - chain_sync: Option>, - /// Connected peers and their best blocks used to seed a new strategy when switching to it in - /// `PolkadotSyncingStrategy::proceed_to_next`. - peer_best_blocks: HashMap)>, -} - -impl SyncingStrategy for PolkadotSyncingStrategy -where - B: BlockT, - Client: HeaderBackend - + BlockBackend - + HeaderMetadata - + ProofProvider - + Send - + Sync - + 'static, -{ - fn add_peer(&mut self, peer_id: PeerId, best_hash: B::Hash, best_number: NumberFor) { - self.peer_best_blocks.insert(peer_id, (best_hash, best_number)); - - self.warp.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); - self.state.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); - self.chain_sync.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); - } - - fn remove_peer(&mut self, peer_id: &PeerId) { - self.warp.as_mut().map(|s| s.remove_peer(peer_id)); - self.state.as_mut().map(|s| s.remove_peer(peer_id)); - self.chain_sync.as_mut().map(|s| s.remove_peer(peer_id)); - - self.peer_best_blocks.remove(peer_id); - } - - fn on_validated_block_announce( - &mut self, - is_best: bool, - peer_id: PeerId, - announce: &BlockAnnounce, - ) -> Option<(B::Hash, NumberFor)> { - let new_best = if let Some(ref mut warp) = self.warp { - warp.on_validated_block_announce(is_best, peer_id, announce) - } else if let Some(ref mut state) = self.state { - state.on_validated_block_announce(is_best, peer_id, announce) - } else if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.on_validated_block_announce(is_best, peer_id, announce) - } else { - error!(target: LOG_TARGET, "No syncing strategy is active."); - debug_assert!(false); - Some((announce.header.hash(), *announce.header.number())) - }; - - if let Some(new_best) = new_best { - if let Some(best) = self.peer_best_blocks.get_mut(&peer_id) { - *best = new_best; - } else { - debug!( - target: LOG_TARGET, - "Cannot update `peer_best_blocks` as peer {peer_id} is not known to `Strategy` \ - (already disconnected?)", - ); - } - } - - new_best - } - - fn set_sync_fork_request(&mut self, peers: Vec, hash: &B::Hash, number: NumberFor) { - // Fork requests are only handled by `ChainSync`. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.set_sync_fork_request(peers.clone(), hash, number); - } - } - - fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { - // Justifications can only be requested via `ChainSync`. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.request_justification(hash, number); - } - } - - fn clear_justification_requests(&mut self) { - // Justification requests can only be cleared by `ChainSync`. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.clear_justification_requests(); - } - } - - fn on_justification_import(&mut self, hash: B::Hash, number: NumberFor, success: bool) { - // Only `ChainSync` is interested in justification import. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.on_justification_import(hash, number, success); - } - } - - fn on_block_response( - &mut self, - peer_id: PeerId, - key: StrategyKey, - request: BlockRequest, - blocks: Vec>, - ) { - if let (StrategyKey::Warp, Some(ref mut warp)) = (key, &mut self.warp) { - warp.on_block_response(peer_id, request, blocks); - } else if let (StrategyKey::ChainSync, Some(ref mut chain_sync)) = - (key, &mut self.chain_sync) - { - chain_sync.on_block_response(peer_id, key, request, blocks); - } else { - error!( - target: LOG_TARGET, - "`on_block_response()` called with unexpected key {key:?} \ - or corresponding strategy is not active.", - ); - debug_assert!(false); - } - } - - fn on_state_response( - &mut self, - peer_id: PeerId, - key: StrategyKey, - response: OpaqueStateResponse, - ) { - if let (StrategyKey::State, Some(ref mut state)) = (key, &mut self.state) { - state.on_state_response(peer_id, response); - } else if let (StrategyKey::ChainSync, Some(ref mut chain_sync)) = - (key, &mut self.chain_sync) - { - chain_sync.on_state_response(peer_id, key, response); - } else { - error!( - target: LOG_TARGET, - "`on_state_response()` called with unexpected key {key:?} \ - or corresponding strategy is not active.", - ); - debug_assert!(false); - } - } - - fn on_warp_proof_response( - &mut self, - peer_id: &PeerId, - key: StrategyKey, - response: EncodedProof, - ) { - if let (StrategyKey::Warp, Some(ref mut warp)) = (key, &mut self.warp) { - warp.on_warp_proof_response(peer_id, response); - } else { - error!( - target: LOG_TARGET, - "`on_warp_proof_response()` called with unexpected key {key:?} \ - or warp strategy is not active", - ); - debug_assert!(false); - } - } - - fn on_blocks_processed( - &mut self, - imported: usize, - count: usize, - results: Vec<(Result>, BlockImportError>, B::Hash)>, - ) { - // Only `StateStrategy` and `ChainSync` are interested in block processing notifications. - if let Some(ref mut state) = self.state { - state.on_blocks_processed(imported, count, results); - } else if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.on_blocks_processed(imported, count, results); - } - } - - fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor) { - // Only `ChainSync` is interested in block finalization notifications. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.on_block_finalized(hash, number); - } - } - - fn update_chain_info(&mut self, best_hash: &B::Hash, best_number: NumberFor) { - // This is relevant to `ChainSync` only. - if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.update_chain_info(best_hash, best_number); - } - } - - fn is_major_syncing(&self) -> bool { - self.warp.is_some() || - self.state.is_some() || - match self.chain_sync { - Some(ref s) => s.status().state.is_major_syncing(), - None => unreachable!("At least one syncing strategy is active; qed"), - } - } - - fn num_peers(&self) -> usize { - self.peer_best_blocks.len() - } - - fn status(&self) -> SyncStatus { - // This function presumes that strategies are executed serially and must be refactored - // once we have parallel strategies. - if let Some(ref warp) = self.warp { - warp.status() - } else if let Some(ref state) = self.state { - state.status() - } else if let Some(ref chain_sync) = self.chain_sync { - chain_sync.status() - } else { - unreachable!("At least one syncing strategy is always active; qed") - } - } - - fn num_downloaded_blocks(&self) -> usize { - self.chain_sync - .as_ref() - .map_or(0, |chain_sync| chain_sync.num_downloaded_blocks()) - } - - fn num_sync_requests(&self) -> usize { - self.chain_sync.as_ref().map_or(0, |chain_sync| chain_sync.num_sync_requests()) - } - - fn actions(&mut self) -> Result>, ClientError> { - // This function presumes that strategies are executed serially and must be refactored once - // we have parallel strategies. - let actions: Vec<_> = if let Some(ref mut warp) = self.warp { - warp.actions().map(Into::into).collect() - } else if let Some(ref mut state) = self.state { - state.actions().map(Into::into).collect() - } else if let Some(ref mut chain_sync) = self.chain_sync { - chain_sync.actions()? - } else { - unreachable!("At least one syncing strategy is always active; qed") - }; - - if actions.iter().any(SyncingAction::is_finished) { - self.proceed_to_next()?; - } - - Ok(actions) - } -} - -impl PolkadotSyncingStrategy -where - B: BlockT, - Client: HeaderBackend - + BlockBackend - + HeaderMetadata - + ProofProvider - + Send - + Sync - + 'static, -{ - /// Initialize a new syncing strategy. - pub fn new( - mut config: SyncingConfig, - client: Arc, - warp_sync_config: Option>, - warp_sync_protocol_name: Option, - ) -> Result { - if config.max_blocks_per_request > MAX_BLOCKS_IN_RESPONSE as u32 { - info!( - target: LOG_TARGET, - "clamping maximum blocks per request to {MAX_BLOCKS_IN_RESPONSE}", - ); - config.max_blocks_per_request = MAX_BLOCKS_IN_RESPONSE as u32; - } - - if let SyncMode::Warp = config.mode { - let warp_sync_config = warp_sync_config - .expect("Warp sync configuration must be supplied in warp sync mode."); - let warp_sync = - WarpSync::new(client.clone(), warp_sync_config, warp_sync_protocol_name); - Ok(Self { - config, - client, - warp: Some(warp_sync), - state: None, - chain_sync: None, - peer_best_blocks: Default::default(), - }) - } else { - let chain_sync = ChainSync::new( - chain_sync_mode(config.mode), - client.clone(), - config.max_parallel_downloads, - config.max_blocks_per_request, - config.state_request_protocol_name.clone(), - config.metrics_registry.as_ref(), - std::iter::empty(), - )?; - Ok(Self { - config, - client, - warp: None, - state: None, - chain_sync: Some(chain_sync), - peer_best_blocks: Default::default(), - }) - } - } - - /// Proceed with the next strategy if the active one finished. - pub fn proceed_to_next(&mut self) -> Result<(), ClientError> { - // The strategies are switched as `WarpSync` -> `StateStrategy` -> `ChainSync`. - if let Some(ref mut warp) = self.warp { - match warp.take_result() { - Some(res) => { - info!( - target: LOG_TARGET, - "Warp sync is complete, continuing with state sync." - ); - let state_sync = StateStrategy::new( - self.client.clone(), - res.target_header, - res.target_body, - res.target_justifications, - false, - self.peer_best_blocks - .iter() - .map(|(peer_id, (_, best_number))| (*peer_id, *best_number)), - self.config.state_request_protocol_name.clone(), - ); - - self.warp = None; - self.state = Some(state_sync); - Ok(()) - }, - None => { - error!( - target: LOG_TARGET, - "Warp sync failed. Continuing with full sync." - ); - let chain_sync = match ChainSync::new( - chain_sync_mode(self.config.mode), - self.client.clone(), - self.config.max_parallel_downloads, - self.config.max_blocks_per_request, - self.config.state_request_protocol_name.clone(), - self.config.metrics_registry.as_ref(), - self.peer_best_blocks.iter().map(|(peer_id, (best_hash, best_number))| { - (*peer_id, *best_hash, *best_number) - }), - ) { - Ok(chain_sync) => chain_sync, - Err(e) => { - error!(target: LOG_TARGET, "Failed to start `ChainSync`."); - return Err(e) - }, - }; - - self.warp = None; - self.chain_sync = Some(chain_sync); - Ok(()) - }, - } - } else if let Some(state) = &self.state { - if state.is_succeeded() { - info!(target: LOG_TARGET, "State sync is complete, continuing with block sync."); - } else { - error!(target: LOG_TARGET, "State sync failed. Falling back to full sync."); - } - let chain_sync = match ChainSync::new( - chain_sync_mode(self.config.mode), - self.client.clone(), - self.config.max_parallel_downloads, - self.config.max_blocks_per_request, - self.config.state_request_protocol_name.clone(), - self.config.metrics_registry.as_ref(), - self.peer_best_blocks.iter().map(|(peer_id, (best_hash, best_number))| { - (*peer_id, *best_hash, *best_number) - }), - ) { - Ok(chain_sync) => chain_sync, - Err(e) => { - error!(target: LOG_TARGET, "Failed to start `ChainSync`."); - return Err(e); - }, - }; - self.state = None; - self.chain_sync = Some(chain_sync); - Ok(()) - } else { - unreachable!("Only warp & state strategies can finish; qed") + #[cfg(test)] + pub(crate) fn name(&self) -> &'static str { + match self { + Self::StartRequest { .. } => "StartRequest", + Self::CancelRequest { .. } => "CancelRequest", + Self::DropPeer(_) => "DropPeer", + Self::ImportBlocks { .. } => "ImportBlocks", + Self::ImportJustifications { .. } => "ImportJustifications", + Self::Finished => "Finished", } } } diff --git a/substrate/client/network/sync/src/strategy/chain_sync.rs b/substrate/client/network/sync/src/strategy/chain_sync.rs index 202033e8e00a..18170b77881e 100644 --- a/substrate/client/network/sync/src/strategy/chain_sync.rs +++ b/substrate/client/network/sync/src/strategy/chain_sync.rs @@ -29,24 +29,28 @@ //! order to update it. use crate::{ + block_relay_protocol::{BlockDownloader, BlockResponseError}, blocks::BlockCollection, justification_requests::ExtraRequests, - schema::v1::StateResponse, + schema::v1::{StateRequest, StateResponse}, + service::network::NetworkServiceHandle, strategy::{ disconnected_peers::DisconnectedPeers, state_sync::{ImportResult, StateSync, StateSyncProvider}, - warp::{EncodedProof, WarpSyncPhase, WarpSyncProgress}, + warp::{WarpSyncPhase, WarpSyncProgress}, StrategyKey, SyncingAction, SyncingStrategy, }, - types::{BadPeer, OpaqueStateRequest, OpaqueStateResponse, SyncState, SyncStatus}, + types::{BadPeer, SyncState, SyncStatus}, LOG_TARGET, }; +use futures::{channel::oneshot, FutureExt}; use log::{debug, error, info, trace, warn}; use prometheus_endpoint::{register, Gauge, PrometheusError, Registry, U64}; +use prost::Message; use sc_client_api::{blockchain::BlockGap, BlockBackend, ProofProvider}; use sc_consensus::{BlockImportError, BlockImportStatus, IncomingBlock}; -use sc_network::ProtocolName; +use sc_network::{IfDisconnected, ProtocolName}; use sc_network_common::sync::message::{ BlockAnnounce, BlockAttributes, BlockData, BlockRequest, BlockResponse, Direction, FromBlock, }; @@ -62,6 +66,7 @@ use sp_runtime::{ }; use std::{ + any::Any, collections::{HashMap, HashSet}, ops::Range, sync::Arc, @@ -123,6 +128,9 @@ mod rep { /// Peer response data does not have requested bits. pub const BAD_RESPONSE: Rep = Rep::new(-(1 << 12), "Incomplete response"); + + /// We received a message that failed to decode. + pub const BAD_MESSAGE: Rep = Rep::new(-(1 << 12), "Bad message"); } struct Metrics { @@ -324,9 +332,11 @@ pub struct ChainSync { downloaded_blocks: usize, /// State sync in progress, if any. state_sync: Option>, - /// Enable importing existing blocks. This is used used after the state download to + /// Enable importing existing blocks. This is used after the state download to /// catch up to the latest state while re-importing blocks. import_existing: bool, + /// Block downloader + block_downloader: Arc>, /// Gap download process. gap_sync: Option>, /// Pending actions. @@ -348,11 +358,10 @@ where { fn add_peer(&mut self, peer_id: PeerId, best_hash: B::Hash, best_number: NumberFor) { match self.add_peer_inner(peer_id, best_hash, best_number) { - Ok(Some(request)) => self.actions.push(SyncingAction::SendBlockRequest { - peer_id, - key: StrategyKey::ChainSync, - request, - }), + Ok(Some(request)) => { + let action = self.create_block_request_action(peer_id, request); + self.actions.push(action); + }, Ok(None) => {}, Err(bad_peer) => self.actions.push(SyncingAction::DropPeer(bad_peer)), } @@ -564,82 +573,77 @@ where self.allowed_requests.set_all(); } - fn on_block_response( + fn on_generic_response( &mut self, - peer_id: PeerId, + peer_id: &PeerId, key: StrategyKey, - request: BlockRequest, - blocks: Vec>, + protocol_name: ProtocolName, + response: Box, ) { - if key != StrategyKey::ChainSync { - error!( + if Self::STRATEGY_KEY != key { + warn!( target: LOG_TARGET, - "`on_block_response()` called with unexpected key {key:?} for chain sync", + "Unexpected generic response strategy key {key:?}, protocol {protocol_name}", ); debug_assert!(false); + return; } - let block_response = BlockResponse:: { id: request.id, blocks }; - let blocks_range = || match ( - block_response - .blocks - .first() - .and_then(|b| b.header.as_ref().map(|h| h.number())), - block_response.blocks.last().and_then(|b| b.header.as_ref().map(|h| h.number())), - ) { - (Some(first), Some(last)) if first != last => format!(" ({}..{})", first, last), - (Some(first), Some(_)) => format!(" ({})", first), - _ => Default::default(), - }; - trace!( - target: LOG_TARGET, - "BlockResponse {} from {} with {} blocks {}", - block_response.id, - peer_id, - block_response.blocks.len(), - blocks_range(), - ); + if protocol_name == self.state_request_protocol_name { + let Ok(response) = response.downcast::>() else { + warn!(target: LOG_TARGET, "Failed to downcast state response"); + debug_assert!(false); + return; + }; - let res = if request.fields == BlockAttributes::JUSTIFICATION { - self.on_block_justification(peer_id, block_response) - } else { - self.on_block_data(&peer_id, Some(request), block_response) - }; + if let Err(bad_peer) = self.on_state_data(&peer_id, &response) { + self.actions.push(SyncingAction::DropPeer(bad_peer)); + } + } else if &protocol_name == self.block_downloader.protocol_name() { + let Ok(response) = response + .downcast::<(BlockRequest, Result>, BlockResponseError>)>() + else { + warn!(target: LOG_TARGET, "Failed to downcast block response"); + debug_assert!(false); + return; + }; - if let Err(bad_peer) = res { - self.actions.push(SyncingAction::DropPeer(bad_peer)); - } - } + let (request, response) = *response; + let blocks = match response { + Ok(blocks) => blocks, + Err(BlockResponseError::DecodeFailed(e)) => { + debug!( + target: LOG_TARGET, + "Failed to decode block response from peer {:?}: {:?}.", + peer_id, + e + ); + self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE))); + return; + }, + Err(BlockResponseError::ExtractionFailed(e)) => { + debug!( + target: LOG_TARGET, + "Failed to extract blocks from peer response {:?}: {:?}.", + peer_id, + e + ); + self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE))); + return; + }, + }; - fn on_state_response( - &mut self, - peer_id: PeerId, - key: StrategyKey, - response: OpaqueStateResponse, - ) { - if key != StrategyKey::ChainSync { - error!( + if let Err(bad_peer) = self.on_block_response(peer_id, key, request, blocks) { + self.actions.push(SyncingAction::DropPeer(bad_peer)); + } + } else { + warn!( target: LOG_TARGET, - "`on_state_response()` called with unexpected key {key:?} for chain sync", + "Unexpected generic response protocol {protocol_name}, strategy key \ + {key:?}", ); debug_assert!(false); } - if let Err(bad_peer) = self.on_state_data(&peer_id, response) { - self.actions.push(SyncingAction::DropPeer(bad_peer)); - } - } - - fn on_warp_proof_response( - &mut self, - _peer_id: &PeerId, - _key: StrategyKey, - _response: EncodedProof, - ) { - error!( - target: LOG_TARGET, - "`on_warp_proof_response()` called for chain sync strategy", - ); - debug_assert!(false); } fn on_blocks_processed( @@ -863,30 +867,56 @@ where .count() } - fn actions(&mut self) -> Result>, ClientError> { + fn actions( + &mut self, + network_service: &NetworkServiceHandle, + ) -> Result>, ClientError> { if !self.peers.is_empty() && self.queue_blocks.is_empty() { if let Some((hash, number, skip_proofs)) = self.pending_state_sync_attempt.take() { self.attempt_state_sync(hash, number, skip_proofs); } } - let block_requests = self.block_requests().into_iter().map(|(peer_id, request)| { - SyncingAction::SendBlockRequest { peer_id, key: StrategyKey::ChainSync, request } - }); + let block_requests = self + .block_requests() + .into_iter() + .map(|(peer_id, request)| self.create_block_request_action(peer_id, request)) + .collect::>(); self.actions.extend(block_requests); - let justification_requests = - self.justification_requests().into_iter().map(|(peer_id, request)| { - SyncingAction::SendBlockRequest { peer_id, key: StrategyKey::ChainSync, request } - }); + let justification_requests = self + .justification_requests() + .into_iter() + .map(|(peer_id, request)| self.create_block_request_action(peer_id, request)) + .collect::>(); self.actions.extend(justification_requests); let state_request = self.state_request().into_iter().map(|(peer_id, request)| { - SyncingAction::SendStateRequest { + trace!( + target: LOG_TARGET, + "Created `StrategyRequest` to {peer_id}.", + ); + + let (tx, rx) = oneshot::channel(); + + network_service.start_request( peer_id, - key: StrategyKey::ChainSync, - protocol_name: self.state_request_protocol_name.clone(), - request, + self.state_request_protocol_name.clone(), + request.encode_to_vec(), + tx, + IfDisconnected::ImmediateError, + ); + + SyncingAction::StartRequest { + peer_id, + key: Self::STRATEGY_KEY, + request: async move { + Ok(rx.await?.and_then(|(response, protocol_name)| { + Ok((Box::new(response) as Box, protocol_name)) + })) + } + .boxed(), + remove_obsolete: false, } }); self.actions.extend(state_request); @@ -906,6 +936,9 @@ where + Sync + 'static, { + /// Strategy key used by chain sync. + pub const STRATEGY_KEY: StrategyKey = StrategyKey::new("ChainSync"); + /// Create a new instance. pub fn new( mode: ChainSyncMode, @@ -913,6 +946,7 @@ where max_parallel_downloads: u32, max_blocks_per_request: u32, state_request_protocol_name: ProtocolName, + block_downloader: Arc>, metrics_registry: Option<&Registry>, initial_peers: impl Iterator)>, ) -> Result { @@ -935,6 +969,7 @@ where downloaded_blocks: 0, state_sync: None, import_existing: false, + block_downloader, gap_sync: None, actions: Vec::new(), metrics: metrics_registry.and_then(|r| match Metrics::register(r) { @@ -1075,6 +1110,33 @@ where } } + fn create_block_request_action( + &mut self, + peer_id: PeerId, + request: BlockRequest, + ) -> SyncingAction { + let downloader = self.block_downloader.clone(); + + SyncingAction::StartRequest { + peer_id, + key: Self::STRATEGY_KEY, + request: async move { + Ok(downloader.download_blocks(peer_id, request.clone()).await?.and_then( + |(response, protocol_name)| { + let decoded_response = + downloader.block_response_into_blocks(&request, response); + let result = Box::new((request, decoded_response)) as Box; + Ok((result, protocol_name)) + }, + )) + } + .boxed(), + // Sending block request implies dropping obsolete pending response as we are not + // interested in it anymore. + remove_obsolete: true, + } + } + /// Submit a block response for processing. #[must_use] fn on_block_data( @@ -1248,11 +1310,8 @@ where state: next_state, }; let request = ancestry_request::(next_num); - self.actions.push(SyncingAction::SendBlockRequest { - peer_id: *peer_id, - key: StrategyKey::ChainSync, - request, - }); + let action = self.create_block_request_action(*peer_id, request); + self.actions.push(action); return Ok(()); } else { // Ancestry search is complete. Check if peer is on a stale fork unknown @@ -1334,6 +1393,49 @@ where Ok(()) } + fn on_block_response( + &mut self, + peer_id: &PeerId, + key: StrategyKey, + request: BlockRequest, + blocks: Vec>, + ) -> Result<(), BadPeer> { + if key != Self::STRATEGY_KEY { + error!( + target: LOG_TARGET, + "`on_block_response()` called with unexpected key {key:?} for chain sync", + ); + debug_assert!(false); + } + let block_response = BlockResponse:: { id: request.id, blocks }; + + let blocks_range = || match ( + block_response + .blocks + .first() + .and_then(|b| b.header.as_ref().map(|h| h.number())), + block_response.blocks.last().and_then(|b| b.header.as_ref().map(|h| h.number())), + ) { + (Some(first), Some(last)) if first != last => format!(" ({}..{})", first, last), + (Some(first), Some(_)) => format!(" ({})", first), + _ => Default::default(), + }; + trace!( + target: LOG_TARGET, + "BlockResponse {} from {} with {} blocks {}", + block_response.id, + peer_id, + block_response.blocks.len(), + blocks_range(), + ); + + if request.fields == BlockAttributes::JUSTIFICATION { + self.on_block_justification(*peer_id, block_response) + } else { + self.on_block_data(peer_id, Some(request), block_response) + } + } + /// Submit a justification response for processing. #[must_use] fn on_block_justification( @@ -1548,10 +1650,8 @@ where PeerSyncState::DownloadingGap(_) | PeerSyncState::DownloadingState => { // Cancel a request first, as `add_peer` may generate a new request. - self.actions.push(SyncingAction::CancelRequest { - peer_id, - key: StrategyKey::ChainSync, - }); + self.actions + .push(SyncingAction::CancelRequest { peer_id, key: Self::STRATEGY_KEY }); self.add_peer(peer_id, peer_sync.best_hash, peer_sync.best_number); }, PeerSyncState::DownloadingJustification(_) => { @@ -1831,7 +1931,7 @@ where } /// Get a state request scheduled by sync to be sent out (if any). - fn state_request(&mut self) -> Option<(PeerId, OpaqueStateRequest)> { + fn state_request(&mut self) -> Option<(PeerId, StateRequest)> { if self.allowed_requests.is_empty() { return None; } @@ -1855,7 +1955,7 @@ where let request = sync.next_request(); trace!(target: LOG_TARGET, "New StateRequest for {}: {:?}", id, request); self.allowed_requests.clear(); - return Some((*id, OpaqueStateRequest(Box::new(request)))); + return Some((*id, request)); } } } @@ -1863,19 +1963,18 @@ where } #[must_use] - fn on_state_data( - &mut self, - peer_id: &PeerId, - response: OpaqueStateResponse, - ) -> Result<(), BadPeer> { - let response: Box = response.0.downcast().map_err(|_error| { - error!( - target: LOG_TARGET, - "Failed to downcast opaque state response, this is an implementation bug." - ); + fn on_state_data(&mut self, peer_id: &PeerId, response: &[u8]) -> Result<(), BadPeer> { + let response = match StateResponse::decode(response) { + Ok(response) => response, + Err(error) => { + debug!( + target: LOG_TARGET, + "Failed to decode state response from peer {peer_id:?}: {error:?}.", + ); - BadPeer(*peer_id, rep::BAD_RESPONSE) - })?; + return Err(BadPeer(*peer_id, rep::BAD_RESPONSE)); + }, + }; if let Some(peer) = self.peers.get_mut(peer_id) { if let PeerSyncState::DownloadingState = peer.state { @@ -1891,7 +1990,7 @@ where response.entries.len(), response.proof.len(), ); - sync.import(*response) + sync.import(response) } else { debug!(target: LOG_TARGET, "Ignored obsolete state response from {peer_id}"); return Err(BadPeer(*peer_id, rep::NOT_REQUESTED)); diff --git a/substrate/client/network/sync/src/strategy/chain_sync/test.rs b/substrate/client/network/sync/src/strategy/chain_sync/test.rs index d13f034e2e8d..4a5682722389 100644 --- a/substrate/client/network/sync/src/strategy/chain_sync/test.rs +++ b/substrate/client/network/sync/src/strategy/chain_sync/test.rs @@ -19,16 +19,64 @@ //! Tests of [`ChainSync`]. use super::*; -use futures::executor::block_on; +use crate::{ + block_relay_protocol::BlockResponseError, mock::MockBlockDownloader, + service::network::NetworkServiceProvider, +}; +use futures::{channel::oneshot::Canceled, executor::block_on}; use sc_block_builder::BlockBuilderBuilder; +use sc_network::RequestFailure; use sc_network_common::sync::message::{BlockAnnounce, BlockData, BlockState, FromBlock}; use sp_blockchain::HeaderBackend; +use std::sync::Mutex; use substrate_test_runtime_client::{ runtime::{Block, Hash, Header}, BlockBuilderExt, ClientBlockImportExt, ClientExt, DefaultTestClientBuilderExt, TestClient, TestClientBuilder, TestClientBuilderExt, }; +#[derive(Debug)] +struct ProxyBlockDownloader { + protocol_name: ProtocolName, + sender: std::sync::mpsc::Sender>, + request: Mutex>>, +} + +#[async_trait::async_trait] +impl BlockDownloader for ProxyBlockDownloader { + fn protocol_name(&self) -> &ProtocolName { + &self.protocol_name + } + + async fn download_blocks( + &self, + _who: PeerId, + request: BlockRequest, + ) -> Result, ProtocolName), RequestFailure>, Canceled> { + self.sender.send(request).unwrap(); + Ok(Ok((Vec::new(), self.protocol_name.clone()))) + } + + fn block_response_into_blocks( + &self, + _request: &BlockRequest, + _response: Vec, + ) -> Result>, BlockResponseError> { + Ok(Vec::new()) + } +} + +impl ProxyBlockDownloader { + fn new(protocol_name: ProtocolName) -> Self { + let (sender, receiver) = std::sync::mpsc::channel(); + Self { protocol_name, sender, request: Mutex::new(receiver) } + } + + fn next_request(&self) -> BlockRequest { + self.request.lock().unwrap().recv().unwrap() + } +} + #[test] fn processes_empty_response_on_justification_request_for_unknown_block() { // if we ask for a justification for a given block to a peer that doesn't know that block @@ -44,6 +92,7 @@ fn processes_empty_response_on_justification_request_for_unknown_block() { 1, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -108,6 +157,7 @@ fn restart_doesnt_affect_peers_downloading_finality_data() { 1, 8, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -140,13 +190,15 @@ fn restart_doesnt_affect_peers_downloading_finality_data() { sync.add_peer(peer_id1, Hash::random(), 42); sync.add_peer(peer_id2, Hash::random(), 10); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // we wil send block requests to these peers // for these blocks we don't know about - let actions = sync.actions().unwrap(); + let actions = sync.actions(&network_handle).unwrap(); assert_eq!(actions.len(), 2); assert!(actions.iter().all(|action| match action { - SyncingAction::SendBlockRequest { peer_id, .. } => - peer_id == &peer_id1 || peer_id == &peer_id2, + SyncingAction::StartRequest { peer_id, .. } => peer_id == &peer_id1 || peer_id == &peer_id2, _ => false, })); @@ -176,7 +228,7 @@ fn restart_doesnt_affect_peers_downloading_finality_data() { sync.restart(); // which should make us cancel and send out again block requests to the first two peers - let actions = sync.actions().unwrap(); + let actions = sync.actions(&network_handle).unwrap(); assert_eq!(actions.len(), 4); let mut cancelled_first = HashSet::new(); assert!(actions.iter().all(|action| match action { @@ -184,7 +236,7 @@ fn restart_doesnt_affect_peers_downloading_finality_data() { cancelled_first.insert(peer_id); peer_id == &peer_id1 || peer_id == &peer_id2 }, - SyncingAction::SendBlockRequest { peer_id, .. } => { + SyncingAction::StartRequest { peer_id, .. } => { assert!(cancelled_first.remove(peer_id)); peer_id == &peer_id1 || peer_id == &peer_id2 }, @@ -311,6 +363,7 @@ fn do_ancestor_search_when_common_block_to_best_queued_gap_is_to_big() { 5, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -459,12 +512,16 @@ fn can_sync_huge_fork() { let info = client.info(); + let protocol_name = ProtocolName::Static(""); + let proxy_block_downloader = Arc::new(ProxyBlockDownloader::new(protocol_name.clone())); + let mut sync = ChainSync::new( ChainSyncMode::Full, client.clone(), 5, 64, - ProtocolName::Static(""), + protocol_name, + proxy_block_downloader.clone(), None, std::iter::empty(), ) @@ -494,18 +551,21 @@ fn can_sync_huge_fork() { let block = &fork_blocks[unwrap_from_block_number(request.from.clone()) as usize - 1]; let response = create_block_response(vec![block.clone()]); - sync.on_block_data(&peer_id1, Some(request), response).unwrap(); + sync.on_block_data(&peer_id1, Some(request.clone()), response).unwrap(); - let actions = sync.take_actions().collect::>(); + let mut actions = sync.take_actions().collect::>(); request = if actions.is_empty() { // We found the ancestor break } else { assert_eq!(actions.len(), 1); - match &actions[0] { - SyncingAction::SendBlockRequest { peer_id: _, request, key: _ } => request.clone(), - action @ _ => panic!("Unexpected action: {action:?}"), + match actions.pop().unwrap() { + SyncingAction::StartRequest { request, .. } => { + block_on(request).unwrap().unwrap(); + proxy_block_downloader.next_request() + }, + action => panic!("Unexpected action: {}", action.name()), } }; @@ -600,12 +660,16 @@ fn syncs_fork_without_duplicate_requests() { let info = client.info(); + let protocol_name = ProtocolName::Static(""); + let proxy_block_downloader = Arc::new(ProxyBlockDownloader::new(protocol_name.clone())); + let mut sync = ChainSync::new( ChainSyncMode::Full, client.clone(), 5, 64, - ProtocolName::Static(""), + protocol_name, + proxy_block_downloader.clone(), None, std::iter::empty(), ) @@ -637,16 +701,19 @@ fn syncs_fork_without_duplicate_requests() { sync.on_block_data(&peer_id1, Some(request), response).unwrap(); - let actions = sync.take_actions().collect::>(); + let mut actions = sync.take_actions().collect::>(); request = if actions.is_empty() { // We found the ancestor break } else { assert_eq!(actions.len(), 1); - match &actions[0] { - SyncingAction::SendBlockRequest { peer_id: _, request, key: _ } => request.clone(), - action @ _ => panic!("Unexpected action: {action:?}"), + match actions.pop().unwrap() { + SyncingAction::StartRequest { request, .. } => { + block_on(request).unwrap().unwrap(); + proxy_block_downloader.next_request() + }, + action => panic!("Unexpected action: {}", action.name()), } }; @@ -750,6 +817,7 @@ fn removes_target_fork_on_disconnect() { 1, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -784,6 +852,7 @@ fn can_import_response_with_missing_blocks() { 1, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -824,6 +893,7 @@ fn sync_restart_removes_block_but_not_justification_requests() { 1, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) @@ -898,17 +968,17 @@ fn sync_restart_removes_block_but_not_justification_requests() { SyncingAction::CancelRequest { peer_id, key: _ } => { pending_responses.remove(&peer_id); }, - SyncingAction::SendBlockRequest { peer_id, .. } => { + SyncingAction::StartRequest { peer_id, .. } => { // we drop obsolete response, but don't register a new request, it's checked in // the `assert!` below pending_responses.remove(&peer_id); }, - action @ _ => panic!("Unexpected action: {action:?}"), + action @ _ => panic!("Unexpected action: {}", action.name()), } } assert!(actions.iter().any(|action| { match action { - SyncingAction::SendBlockRequest { peer_id, .. } => peer_id == &peers[0], + SyncingAction::StartRequest { peer_id, .. } => peer_id == &peers[0], _ => false, } })); @@ -975,6 +1045,7 @@ fn request_across_forks() { 5, 64, ProtocolName::Static(""), + Arc::new(MockBlockDownloader::new()), None, std::iter::empty(), ) diff --git a/substrate/client/network/sync/src/strategy/polkadot.rs b/substrate/client/network/sync/src/strategy/polkadot.rs new file mode 100644 index 000000000000..44b05966af06 --- /dev/null +++ b/substrate/client/network/sync/src/strategy/polkadot.rs @@ -0,0 +1,481 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +//! [`PolkadotSyncingStrategy`] is a proxy between [`crate::engine::SyncingEngine`] +//! and specific syncing algorithms. + +use crate::{ + block_relay_protocol::BlockDownloader, + block_request_handler::MAX_BLOCKS_IN_RESPONSE, + service::network::NetworkServiceHandle, + strategy::{ + chain_sync::{ChainSync, ChainSyncMode}, + state::StateStrategy, + warp::{WarpSync, WarpSyncConfig}, + StrategyKey, SyncingAction, SyncingStrategy, + }, + types::SyncStatus, + LOG_TARGET, +}; +use log::{debug, error, info, warn}; +use prometheus_endpoint::Registry; +use sc_client_api::{BlockBackend, ProofProvider}; +use sc_consensus::{BlockImportError, BlockImportStatus}; +use sc_network::ProtocolName; +use sc_network_common::sync::{message::BlockAnnounce, SyncMode}; +use sc_network_types::PeerId; +use sp_blockchain::{Error as ClientError, HeaderBackend, HeaderMetadata}; +use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; +use std::{any::Any, collections::HashMap, sync::Arc}; + +/// Corresponding `ChainSync` mode. +fn chain_sync_mode(sync_mode: SyncMode) -> ChainSyncMode { + match sync_mode { + SyncMode::Full => ChainSyncMode::Full, + SyncMode::LightState { skip_proofs, storage_chain_mode } => + ChainSyncMode::LightState { skip_proofs, storage_chain_mode }, + SyncMode::Warp => ChainSyncMode::Full, + } +} + +/// Syncing configuration containing data for [`PolkadotSyncingStrategy`]. +#[derive(Clone, Debug)] +pub struct PolkadotSyncingStrategyConfig +where + Block: BlockT, +{ + /// Syncing mode. + pub mode: SyncMode, + /// The number of parallel downloads to guard against slow peers. + pub max_parallel_downloads: u32, + /// Maximum number of blocks to request. + pub max_blocks_per_request: u32, + /// Prometheus metrics registry. + pub metrics_registry: Option, + /// Protocol name used to send out state requests + pub state_request_protocol_name: ProtocolName, + /// Block downloader + pub block_downloader: Arc>, +} + +/// Proxy to specific syncing strategies used in Polkadot. +pub struct PolkadotSyncingStrategy { + /// Initial syncing configuration. + config: PolkadotSyncingStrategyConfig, + /// Client used by syncing strategies. + client: Arc, + /// Warp strategy. + warp: Option>, + /// State strategy. + state: Option>, + /// `ChainSync` strategy.` + chain_sync: Option>, + /// Connected peers and their best blocks used to seed a new strategy when switching to it in + /// `PolkadotSyncingStrategy::proceed_to_next`. + peer_best_blocks: HashMap)>, +} + +impl SyncingStrategy for PolkadotSyncingStrategy +where + B: BlockT, + Client: HeaderBackend + + BlockBackend + + HeaderMetadata + + ProofProvider + + Send + + Sync + + 'static, +{ + fn add_peer(&mut self, peer_id: PeerId, best_hash: B::Hash, best_number: NumberFor) { + self.peer_best_blocks.insert(peer_id, (best_hash, best_number)); + + self.warp.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); + self.state.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); + self.chain_sync.as_mut().map(|s| s.add_peer(peer_id, best_hash, best_number)); + } + + fn remove_peer(&mut self, peer_id: &PeerId) { + self.warp.as_mut().map(|s| s.remove_peer(peer_id)); + self.state.as_mut().map(|s| s.remove_peer(peer_id)); + self.chain_sync.as_mut().map(|s| s.remove_peer(peer_id)); + + self.peer_best_blocks.remove(peer_id); + } + + fn on_validated_block_announce( + &mut self, + is_best: bool, + peer_id: PeerId, + announce: &BlockAnnounce, + ) -> Option<(B::Hash, NumberFor)> { + let new_best = if let Some(ref mut warp) = self.warp { + warp.on_validated_block_announce(is_best, peer_id, announce) + } else if let Some(ref mut state) = self.state { + state.on_validated_block_announce(is_best, peer_id, announce) + } else if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.on_validated_block_announce(is_best, peer_id, announce) + } else { + error!(target: LOG_TARGET, "No syncing strategy is active."); + debug_assert!(false); + Some((announce.header.hash(), *announce.header.number())) + }; + + if let Some(new_best) = new_best { + if let Some(best) = self.peer_best_blocks.get_mut(&peer_id) { + *best = new_best; + } else { + debug!( + target: LOG_TARGET, + "Cannot update `peer_best_blocks` as peer {peer_id} is not known to `Strategy` \ + (already disconnected?)", + ); + } + } + + new_best + } + + fn set_sync_fork_request(&mut self, peers: Vec, hash: &B::Hash, number: NumberFor) { + // Fork requests are only handled by `ChainSync`. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.set_sync_fork_request(peers.clone(), hash, number); + } + } + + fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { + // Justifications can only be requested via `ChainSync`. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.request_justification(hash, number); + } + } + + fn clear_justification_requests(&mut self) { + // Justification requests can only be cleared by `ChainSync`. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.clear_justification_requests(); + } + } + + fn on_justification_import(&mut self, hash: B::Hash, number: NumberFor, success: bool) { + // Only `ChainSync` is interested in justification import. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.on_justification_import(hash, number, success); + } + } + + fn on_generic_response( + &mut self, + peer_id: &PeerId, + key: StrategyKey, + protocol_name: ProtocolName, + response: Box, + ) { + match key { + StateStrategy::::STRATEGY_KEY => + if let Some(state) = &mut self.state { + let Ok(response) = response.downcast::>() else { + warn!(target: LOG_TARGET, "Failed to downcast state response"); + debug_assert!(false); + return; + }; + + state.on_state_response(peer_id, *response); + } else if let Some(chain_sync) = &mut self.chain_sync { + chain_sync.on_generic_response(peer_id, key, protocol_name, response); + } else { + error!( + target: LOG_TARGET, + "`on_generic_response()` called with unexpected key {key:?} \ + or corresponding strategy is not active.", + ); + debug_assert!(false); + }, + WarpSync::::STRATEGY_KEY => + if let Some(warp) = &mut self.warp { + warp.on_generic_response(peer_id, protocol_name, response); + } else { + error!( + target: LOG_TARGET, + "`on_generic_response()` called with unexpected key {key:?} \ + or warp strategy is not active", + ); + debug_assert!(false); + }, + ChainSync::::STRATEGY_KEY => + if let Some(chain_sync) = &mut self.chain_sync { + chain_sync.on_generic_response(peer_id, key, protocol_name, response); + } else { + error!( + target: LOG_TARGET, + "`on_generic_response()` called with unexpected key {key:?} \ + or corresponding strategy is not active.", + ); + debug_assert!(false); + }, + key => { + warn!( + target: LOG_TARGET, + "Unexpected generic response strategy key {key:?}, protocol {protocol_name}", + ); + debug_assert!(false); + }, + } + } + + fn on_blocks_processed( + &mut self, + imported: usize, + count: usize, + results: Vec<(Result>, BlockImportError>, B::Hash)>, + ) { + // Only `StateStrategy` and `ChainSync` are interested in block processing notifications. + if let Some(ref mut state) = self.state { + state.on_blocks_processed(imported, count, results); + } else if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.on_blocks_processed(imported, count, results); + } + } + + fn on_block_finalized(&mut self, hash: &B::Hash, number: NumberFor) { + // Only `ChainSync` is interested in block finalization notifications. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.on_block_finalized(hash, number); + } + } + + fn update_chain_info(&mut self, best_hash: &B::Hash, best_number: NumberFor) { + // This is relevant to `ChainSync` only. + if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.update_chain_info(best_hash, best_number); + } + } + + fn is_major_syncing(&self) -> bool { + self.warp.is_some() || + self.state.is_some() || + match self.chain_sync { + Some(ref s) => s.status().state.is_major_syncing(), + None => unreachable!("At least one syncing strategy is active; qed"), + } + } + + fn num_peers(&self) -> usize { + self.peer_best_blocks.len() + } + + fn status(&self) -> SyncStatus { + // This function presumes that strategies are executed serially and must be refactored + // once we have parallel strategies. + if let Some(ref warp) = self.warp { + warp.status() + } else if let Some(ref state) = self.state { + state.status() + } else if let Some(ref chain_sync) = self.chain_sync { + chain_sync.status() + } else { + unreachable!("At least one syncing strategy is always active; qed") + } + } + + fn num_downloaded_blocks(&self) -> usize { + self.chain_sync + .as_ref() + .map_or(0, |chain_sync| chain_sync.num_downloaded_blocks()) + } + + fn num_sync_requests(&self) -> usize { + self.chain_sync.as_ref().map_or(0, |chain_sync| chain_sync.num_sync_requests()) + } + + fn actions( + &mut self, + network_service: &NetworkServiceHandle, + ) -> Result>, ClientError> { + // This function presumes that strategies are executed serially and must be refactored once + // we have parallel strategies. + let actions: Vec<_> = if let Some(ref mut warp) = self.warp { + warp.actions(network_service).map(Into::into).collect() + } else if let Some(ref mut state) = self.state { + state.actions(network_service).map(Into::into).collect() + } else if let Some(ref mut chain_sync) = self.chain_sync { + chain_sync.actions(network_service)? + } else { + unreachable!("At least one syncing strategy is always active; qed") + }; + + if actions.iter().any(SyncingAction::is_finished) { + self.proceed_to_next()?; + } + + Ok(actions) + } +} + +impl PolkadotSyncingStrategy +where + B: BlockT, + Client: HeaderBackend + + BlockBackend + + HeaderMetadata + + ProofProvider + + Send + + Sync + + 'static, +{ + /// Initialize a new syncing strategy. + pub fn new( + mut config: PolkadotSyncingStrategyConfig, + client: Arc, + warp_sync_config: Option>, + warp_sync_protocol_name: Option, + ) -> Result { + if config.max_blocks_per_request > MAX_BLOCKS_IN_RESPONSE as u32 { + info!( + target: LOG_TARGET, + "clamping maximum blocks per request to {MAX_BLOCKS_IN_RESPONSE}", + ); + config.max_blocks_per_request = MAX_BLOCKS_IN_RESPONSE as u32; + } + + if let SyncMode::Warp = config.mode { + let warp_sync_config = warp_sync_config + .expect("Warp sync configuration must be supplied in warp sync mode."); + let warp_sync = WarpSync::new( + client.clone(), + warp_sync_config, + warp_sync_protocol_name, + config.block_downloader.clone(), + ); + Ok(Self { + config, + client, + warp: Some(warp_sync), + state: None, + chain_sync: None, + peer_best_blocks: Default::default(), + }) + } else { + let chain_sync = ChainSync::new( + chain_sync_mode(config.mode), + client.clone(), + config.max_parallel_downloads, + config.max_blocks_per_request, + config.state_request_protocol_name.clone(), + config.block_downloader.clone(), + config.metrics_registry.as_ref(), + std::iter::empty(), + )?; + Ok(Self { + config, + client, + warp: None, + state: None, + chain_sync: Some(chain_sync), + peer_best_blocks: Default::default(), + }) + } + } + + /// Proceed with the next strategy if the active one finished. + pub fn proceed_to_next(&mut self) -> Result<(), ClientError> { + // The strategies are switched as `WarpSync` -> `StateStrategy` -> `ChainSync`. + if let Some(ref mut warp) = self.warp { + match warp.take_result() { + Some(res) => { + info!( + target: LOG_TARGET, + "Warp sync is complete, continuing with state sync." + ); + let state_sync = StateStrategy::new( + self.client.clone(), + res.target_header, + res.target_body, + res.target_justifications, + false, + self.peer_best_blocks + .iter() + .map(|(peer_id, (_, best_number))| (*peer_id, *best_number)), + self.config.state_request_protocol_name.clone(), + ); + + self.warp = None; + self.state = Some(state_sync); + Ok(()) + }, + None => { + error!( + target: LOG_TARGET, + "Warp sync failed. Continuing with full sync." + ); + let chain_sync = match ChainSync::new( + chain_sync_mode(self.config.mode), + self.client.clone(), + self.config.max_parallel_downloads, + self.config.max_blocks_per_request, + self.config.state_request_protocol_name.clone(), + self.config.block_downloader.clone(), + self.config.metrics_registry.as_ref(), + self.peer_best_blocks.iter().map(|(peer_id, (best_hash, best_number))| { + (*peer_id, *best_hash, *best_number) + }), + ) { + Ok(chain_sync) => chain_sync, + Err(e) => { + error!(target: LOG_TARGET, "Failed to start `ChainSync`."); + return Err(e) + }, + }; + + self.warp = None; + self.chain_sync = Some(chain_sync); + Ok(()) + }, + } + } else if let Some(state) = &self.state { + if state.is_succeeded() { + info!(target: LOG_TARGET, "State sync is complete, continuing with block sync."); + } else { + error!(target: LOG_TARGET, "State sync failed. Falling back to full sync."); + } + let chain_sync = match ChainSync::new( + chain_sync_mode(self.config.mode), + self.client.clone(), + self.config.max_parallel_downloads, + self.config.max_blocks_per_request, + self.config.state_request_protocol_name.clone(), + self.config.block_downloader.clone(), + self.config.metrics_registry.as_ref(), + self.peer_best_blocks.iter().map(|(peer_id, (best_hash, best_number))| { + (*peer_id, *best_hash, *best_number) + }), + ) { + Ok(chain_sync) => chain_sync, + Err(e) => { + error!(target: LOG_TARGET, "Failed to start `ChainSync`."); + return Err(e); + }, + }; + + self.state = None; + self.chain_sync = Some(chain_sync); + Ok(()) + } else { + unreachable!("Only warp & state strategies can finish; qed") + } + } +} diff --git a/substrate/client/network/sync/src/strategy/state.rs b/substrate/client/network/sync/src/strategy/state.rs index d69ab3e2d535..93125fe8f66a 100644 --- a/substrate/client/network/sync/src/strategy/state.rs +++ b/substrate/client/network/sync/src/strategy/state.rs @@ -19,18 +19,22 @@ //! State sync strategy. use crate::{ - schema::v1::StateResponse, + schema::v1::{StateRequest, StateResponse}, + service::network::NetworkServiceHandle, strategy::{ disconnected_peers::DisconnectedPeers, state_sync::{ImportResult, StateSync, StateSyncProvider}, + StrategyKey, SyncingAction, }, - types::{BadPeer, OpaqueStateRequest, OpaqueStateResponse, SyncState, SyncStatus}, + types::{BadPeer, SyncState, SyncStatus}, LOG_TARGET, }; +use futures::{channel::oneshot, FutureExt}; use log::{debug, error, trace}; +use prost::Message; use sc_client_api::ProofProvider; use sc_consensus::{BlockImportError, BlockImportStatus, IncomingBlock}; -use sc_network::ProtocolName; +use sc_network::{IfDisconnected, ProtocolName}; use sc_network_common::sync::message::BlockAnnounce; use sc_network_types::PeerId; use sp_consensus::BlockOrigin; @@ -38,7 +42,7 @@ use sp_runtime::{ traits::{Block as BlockT, Header, NumberFor}, Justifications, SaturatedConversion, }; -use std::{collections::HashMap, sync::Arc}; +use std::{any::Any, collections::HashMap, sync::Arc}; mod rep { use sc_network::ReputationChange as Rep; @@ -50,18 +54,6 @@ mod rep { pub const BAD_STATE: Rep = Rep::new(-(1 << 29), "Bad state"); } -/// Action that should be performed on [`StateStrategy`]'s behalf. -pub enum StateStrategyAction { - /// Send state request to peer. - SendStateRequest { peer_id: PeerId, protocol_name: ProtocolName, request: OpaqueStateRequest }, - /// Disconnect and report peer. - DropPeer(BadPeer), - /// Import blocks. - ImportBlocks { origin: BlockOrigin, blocks: Vec> }, - /// State sync has finished. - Finished, -} - enum PeerState { Available, DownloadingState, @@ -83,12 +75,15 @@ pub struct StateStrategy { state_sync: Box>, peers: HashMap>, disconnected_peers: DisconnectedPeers, - actions: Vec>, + actions: Vec>, protocol_name: ProtocolName, succeeded: bool, } impl StateStrategy { + /// Strategy key used by state sync. + pub const STRATEGY_KEY: StrategyKey = StrategyKey::new("State"); + /// Create a new instance. pub fn new( client: Arc, @@ -157,7 +152,7 @@ impl StateStrategy { if let Some(bad_peer) = self.disconnected_peers.on_disconnect_during_request(*peer_id) { - self.actions.push(StateStrategyAction::DropPeer(bad_peer)); + self.actions.push(SyncingAction::DropPeer(bad_peer)); } } } @@ -185,30 +180,32 @@ impl StateStrategy { } /// Process state response. - pub fn on_state_response(&mut self, peer_id: PeerId, response: OpaqueStateResponse) { - if let Err(bad_peer) = self.on_state_response_inner(peer_id, response) { - self.actions.push(StateStrategyAction::DropPeer(bad_peer)); + pub fn on_state_response(&mut self, peer_id: &PeerId, response: Vec) { + if let Err(bad_peer) = self.on_state_response_inner(peer_id, &response) { + self.actions.push(SyncingAction::DropPeer(bad_peer)); } } fn on_state_response_inner( &mut self, - peer_id: PeerId, - response: OpaqueStateResponse, + peer_id: &PeerId, + response: &[u8], ) -> Result<(), BadPeer> { if let Some(peer) = self.peers.get_mut(&peer_id) { peer.state = PeerState::Available; } - let response: Box = response.0.downcast().map_err(|_error| { - error!( - target: LOG_TARGET, - "Failed to downcast opaque state response, this is an implementation bug." - ); - debug_assert!(false); + let response = match StateResponse::decode(response) { + Ok(response) => response, + Err(error) => { + debug!( + target: LOG_TARGET, + "Failed to decode state response from peer {peer_id:?}: {error:?}.", + ); - BadPeer(peer_id, rep::BAD_RESPONSE) - })?; + return Err(BadPeer(*peer_id, rep::BAD_RESPONSE)); + }, + }; debug!( target: LOG_TARGET, @@ -218,7 +215,7 @@ impl StateStrategy { response.proof.len(), ); - match self.state_sync.import(*response) { + match self.state_sync.import(response) { ImportResult::Import(hash, header, state, body, justifications) => { let origin = BlockOrigin::NetworkInitialSync; let block = IncomingBlock { @@ -234,14 +231,13 @@ impl StateStrategy { state: Some(state), }; debug!(target: LOG_TARGET, "State download is complete. Import is queued"); - self.actions - .push(StateStrategyAction::ImportBlocks { origin, blocks: vec![block] }); + self.actions.push(SyncingAction::ImportBlocks { origin, blocks: vec![block] }); Ok(()) }, ImportResult::Continue => Ok(()), ImportResult::BadResponse => { debug!(target: LOG_TARGET, "Bad state data received from {peer_id}"); - Err(BadPeer(peer_id, rep::BAD_STATE)) + Err(BadPeer(*peer_id, rep::BAD_STATE)) }, } } @@ -281,12 +277,12 @@ impl StateStrategy { ); }); self.succeeded |= results.into_iter().any(|result| result.is_ok()); - self.actions.push(StateStrategyAction::Finished); + self.actions.push(SyncingAction::Finished); } } /// Produce state request. - fn state_request(&mut self) -> Option<(PeerId, OpaqueStateRequest)> { + fn state_request(&mut self) -> Option<(PeerId, StateRequest)> { if self.state_sync.is_complete() { return None } @@ -307,7 +303,7 @@ impl StateStrategy { target: LOG_TARGET, "New state request to {peer_id}: {request:?}.", ); - Some((peer_id, OpaqueStateRequest(Box::new(request)))) + Some((peer_id, request)) } fn schedule_next_peer( @@ -354,12 +350,31 @@ impl StateStrategy { /// Get actions that should be performed by the owner on [`WarpSync`]'s behalf #[must_use] - pub fn actions(&mut self) -> impl Iterator> { + pub fn actions( + &mut self, + network_service: &NetworkServiceHandle, + ) -> impl Iterator> { let state_request = self.state_request().into_iter().map(|(peer_id, request)| { - StateStrategyAction::SendStateRequest { + let (tx, rx) = oneshot::channel(); + + network_service.start_request( + peer_id, + self.protocol_name.clone(), + request.encode_to_vec(), + tx, + IfDisconnected::ImmediateError, + ); + + SyncingAction::StartRequest { peer_id, - protocol_name: self.protocol_name.clone(), - request, + key: Self::STRATEGY_KEY, + request: async move { + Ok(rx.await?.and_then(|(response, protocol_name)| { + Ok((Box::new(response) as Box, protocol_name)) + })) + } + .boxed(), + remove_obsolete: false, } }); self.actions.extend(state_request); @@ -379,6 +394,7 @@ mod test { use super::*; use crate::{ schema::v1::{StateRequest, StateResponse}, + service::network::NetworkServiceProvider, strategy::state_sync::{ImportResult, StateSyncProgress, StateSyncProvider}, }; use codec::Decode; @@ -579,8 +595,7 @@ mod test { ProtocolName::Static(""), ); - let (_peer_id, mut opaque_request) = state_strategy.state_request().unwrap(); - let request: &mut StateRequest = opaque_request.0.downcast_mut().unwrap(); + let (_peer_id, request) = state_strategy.state_request().unwrap(); let hash = Hash::decode(&mut &*request.block).unwrap(); assert_eq!(hash, target_block.header().hash()); @@ -631,8 +646,8 @@ mod test { // Manually set the peer's state. state_strategy.peers.get_mut(&peer_id).unwrap().state = PeerState::DownloadingState; - let dummy_response = OpaqueStateResponse(Box::new(StateResponse::default())); - state_strategy.on_state_response(peer_id, dummy_response); + let dummy_response = StateResponse::default().encode_to_vec(); + state_strategy.on_state_response(&peer_id, dummy_response); assert!(state_strategy.peers.get(&peer_id).unwrap().state.is_available()); } @@ -651,10 +666,10 @@ mod test { ); // Manually set the peer's state. state_strategy.peers.get_mut(&peer_id).unwrap().state = PeerState::DownloadingState; - let dummy_response = OpaqueStateResponse(Box::new(StateResponse::default())); + let dummy_response = StateResponse::default().encode_to_vec(); // Receiving response drops the peer. assert!(matches!( - state_strategy.on_state_response_inner(peer_id, dummy_response), + state_strategy.on_state_response_inner(&peer_id, &dummy_response), Err(BadPeer(id, _rep)) if id == peer_id, )); } @@ -674,8 +689,8 @@ mod test { // Manually set the peer's state . state_strategy.peers.get_mut(&peer_id).unwrap().state = PeerState::DownloadingState; - let dummy_response = OpaqueStateResponse(Box::new(StateResponse::default())); - state_strategy.on_state_response(peer_id, dummy_response); + let dummy_response = StateResponse::default().encode_to_vec(); + state_strategy.on_state_response(&peer_id, dummy_response); // No actions generated. assert_eq!(state_strategy.actions.len(), 0) @@ -737,13 +752,13 @@ mod test { state_strategy.peers.get_mut(&peer_id).unwrap().state = PeerState::DownloadingState; // Receive response. - let dummy_response = OpaqueStateResponse(Box::new(StateResponse::default())); - state_strategy.on_state_response(peer_id, dummy_response); + let dummy_response = StateResponse::default().encode_to_vec(); + state_strategy.on_state_response(&peer_id, dummy_response); assert_eq!(state_strategy.actions.len(), 1); assert!(matches!( &state_strategy.actions[0], - StateStrategyAction::ImportBlocks { origin, blocks } + SyncingAction::ImportBlocks { origin, blocks } if *origin == expected_origin && *blocks == expected_blocks, )); } @@ -799,7 +814,7 @@ mod test { // Strategy finishes. assert_eq!(state_strategy.actions.len(), 1); - assert!(matches!(&state_strategy.actions[0], StateStrategyAction::Finished)); + assert!(matches!(&state_strategy.actions[0], SyncingAction::Finished)); } #[test] @@ -826,7 +841,7 @@ mod test { // Strategy finishes. assert_eq!(state_strategy.actions.len(), 1); - assert!(matches!(&state_strategy.actions[0], StateStrategyAction::Finished)); + assert!(matches!(&state_strategy.actions[0], SyncingAction::Finished)); } #[test] @@ -854,12 +869,15 @@ mod test { )], ); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // Strategy finishes. - let actions = state_strategy.actions().collect::>(); + let actions = state_strategy.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - assert!(matches!(&actions[0], StateStrategyAction::Finished)); + assert!(matches!(&actions[0], SyncingAction::Finished)); // No more actions generated. - assert_eq!(state_strategy.actions().count(), 0); + assert_eq!(state_strategy.actions(&network_handle).count(), 0); } } diff --git a/substrate/client/network/sync/src/strategy/warp.rs b/substrate/client/network/sync/src/strategy/warp.rs index 0c71dd3c6aee..673bc1688ecc 100644 --- a/substrate/client/network/sync/src/strategy/warp.rs +++ b/substrate/client/network/sync/src/strategy/warp.rs @@ -21,13 +21,19 @@ pub use sp_consensus_grandpa::{AuthorityList, SetId}; use crate::{ - strategy::{chain_sync::validate_blocks, disconnected_peers::DisconnectedPeers}, + block_relay_protocol::{BlockDownloader, BlockResponseError}, + service::network::NetworkServiceHandle, + strategy::{ + chain_sync::validate_blocks, disconnected_peers::DisconnectedPeers, StrategyKey, + SyncingAction, + }, types::{BadPeer, SyncState, SyncStatus}, LOG_TARGET, }; use codec::{Decode, Encode}; +use futures::{channel::oneshot, FutureExt}; use log::{debug, error, trace, warn}; -use sc_network::ProtocolName; +use sc_network::{IfDisconnected, ProtocolName}; use sc_network_common::sync::message::{ BlockAnnounce, BlockAttributes, BlockData, BlockRequest, Direction, FromBlock, }; @@ -37,7 +43,7 @@ use sp_runtime::{ traits::{Block as BlockT, Header, NumberFor, Zero}, Justifications, SaturatedConversion, }; -use std::{collections::HashMap, fmt, sync::Arc}; +use std::{any::Any, collections::HashMap, fmt, sync::Arc}; /// Number of peers that need to be connected before warp sync is started. const MIN_PEERS_TO_START_WARP_SYNC: usize = 3; @@ -97,6 +103,9 @@ mod rep { /// Reputation change for peers which send us a block which we fail to verify. pub const VERIFICATION_FAIL: Rep = Rep::new(-(1 << 29), "Block verification failed"); + + /// We received a message that failed to decode. + pub const BAD_MESSAGE: Rep = Rep::new(-(1 << 12), "Bad message"); } /// Reported warp sync phase. @@ -186,22 +195,6 @@ struct Peer { state: PeerState, } -/// Action that should be performed on [`WarpSync`]'s behalf. -pub enum WarpSyncAction { - /// Send warp proof request to peer. - SendWarpProofRequest { - peer_id: PeerId, - protocol_name: ProtocolName, - request: WarpProofRequest, - }, - /// Send block request to peer. Always implies dropping a stale block request to the same peer. - SendBlockRequest { peer_id: PeerId, request: BlockRequest }, - /// Disconnect and report peer. - DropPeer(BadPeer), - /// Warp sync has finished. - Finished, -} - pub struct WarpSyncResult { pub target_header: B::Header, pub target_body: Option>, @@ -217,7 +210,8 @@ pub struct WarpSync { peers: HashMap>, disconnected_peers: DisconnectedPeers, protocol_name: Option, - actions: Vec>, + block_downloader: Arc>, + actions: Vec>, result: Option>, } @@ -226,6 +220,9 @@ where B: BlockT, Client: HeaderBackend + 'static, { + /// Strategy key used by warp sync. + pub const STRATEGY_KEY: StrategyKey = StrategyKey::new("Warp"); + /// Create a new instance. When passing a warp sync provider we will be checking for proof and /// authorities. Alternatively we can pass a target block when we want to skip downloading /// proofs, in this case we will continue polling until the target block is known. @@ -233,6 +230,7 @@ where client: Arc, warp_sync_config: WarpSyncConfig, protocol_name: Option, + block_downloader: Arc>, ) -> Self { if client.info().finalized_state.is_some() { error!( @@ -247,7 +245,8 @@ where peers: HashMap::new(), disconnected_peers: DisconnectedPeers::new(), protocol_name, - actions: vec![WarpSyncAction::Finished], + block_downloader, + actions: vec![SyncingAction::Finished], result: None, } } @@ -266,6 +265,7 @@ where peers: HashMap::new(), disconnected_peers: DisconnectedPeers::new(), protocol_name, + block_downloader, actions: Vec::new(), result: None, } @@ -285,7 +285,7 @@ where if let Some(bad_peer) = self.disconnected_peers.on_disconnect_during_request(*peer_id) { - self.actions.push(WarpSyncAction::DropPeer(bad_peer)); + self.actions.push(SyncingAction::DropPeer(bad_peer)); } } } @@ -329,6 +329,58 @@ where trace!(target: LOG_TARGET, "Started warp sync with {} peers.", self.peers.len()); } + pub fn on_generic_response( + &mut self, + peer_id: &PeerId, + protocol_name: ProtocolName, + response: Box, + ) { + if &protocol_name == self.block_downloader.protocol_name() { + let Ok(response) = response + .downcast::<(BlockRequest, Result>, BlockResponseError>)>() + else { + warn!(target: LOG_TARGET, "Failed to downcast block response"); + debug_assert!(false); + return; + }; + + let (request, response) = *response; + let blocks = match response { + Ok(blocks) => blocks, + Err(BlockResponseError::DecodeFailed(e)) => { + debug!( + target: LOG_TARGET, + "Failed to decode block response from peer {:?}: {:?}.", + peer_id, + e + ); + self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE))); + return; + }, + Err(BlockResponseError::ExtractionFailed(e)) => { + debug!( + target: LOG_TARGET, + "Failed to extract blocks from peer response {:?}: {:?}.", + peer_id, + e + ); + self.actions.push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_MESSAGE))); + return; + }, + }; + + self.on_block_response(*peer_id, request, blocks); + } else { + let Ok(response) = response.downcast::>() else { + warn!(target: LOG_TARGET, "Failed to downcast warp sync response"); + debug_assert!(false); + return; + }; + + self.on_warp_proof_response(peer_id, EncodedProof(*response)); + } + } + /// Process warp proof response. pub fn on_warp_proof_response(&mut self, peer_id: &PeerId, response: EncodedProof) { if let Some(peer) = self.peers.get_mut(peer_id) { @@ -340,7 +392,7 @@ where else { debug!(target: LOG_TARGET, "Unexpected warp proof response"); self.actions - .push(WarpSyncAction::DropPeer(BadPeer(*peer_id, rep::UNEXPECTED_RESPONSE))); + .push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::UNEXPECTED_RESPONSE))); return }; @@ -348,7 +400,7 @@ where Err(e) => { debug!(target: LOG_TARGET, "Bad warp proof response: {}", e); self.actions - .push(WarpSyncAction::DropPeer(BadPeer(*peer_id, rep::BAD_WARP_PROOF))) + .push(SyncingAction::DropPeer(BadPeer(*peer_id, rep::BAD_WARP_PROOF))) }, Ok(VerificationResult::Partial(new_set_id, new_authorities, new_last_hash)) => { log::debug!(target: LOG_TARGET, "Verified partial proof, set_id={:?}", new_set_id); @@ -379,7 +431,7 @@ where blocks: Vec>, ) { if let Err(bad_peer) = self.on_block_response_inner(peer_id, request, blocks) { - self.actions.push(WarpSyncAction::DropPeer(bad_peer)); + self.actions.push(SyncingAction::DropPeer(bad_peer)); } } @@ -449,7 +501,7 @@ where target_justifications: block.justifications, }); self.phase = Phase::Complete; - self.actions.push(WarpSyncAction::Finished); + self.actions.push(SyncingAction::Finished); Ok(()) } @@ -606,17 +658,67 @@ where /// Get actions that should be performed by the owner on [`WarpSync`]'s behalf #[must_use] - pub fn actions(&mut self) -> impl Iterator> { + pub fn actions( + &mut self, + network_service: &NetworkServiceHandle, + ) -> impl Iterator> { let warp_proof_request = self.warp_proof_request().into_iter().map(|(peer_id, protocol_name, request)| { - WarpSyncAction::SendWarpProofRequest { peer_id, protocol_name, request } + trace!( + target: LOG_TARGET, + "Created `WarpProofRequest` to {}, request: {:?}.", + peer_id, + request, + ); + + let (tx, rx) = oneshot::channel(); + + network_service.start_request( + peer_id, + protocol_name, + request.encode(), + tx, + IfDisconnected::ImmediateError, + ); + + SyncingAction::StartRequest { + peer_id, + key: Self::STRATEGY_KEY, + request: async move { + Ok(rx.await?.and_then(|(response, protocol_name)| { + Ok((Box::new(response) as Box, protocol_name)) + })) + } + .boxed(), + remove_obsolete: false, + } }); self.actions.extend(warp_proof_request); - let target_block_request = self - .target_block_request() - .into_iter() - .map(|(peer_id, request)| WarpSyncAction::SendBlockRequest { peer_id, request }); + let target_block_request = + self.target_block_request().into_iter().map(|(peer_id, request)| { + let downloader = self.block_downloader.clone(); + + SyncingAction::StartRequest { + peer_id, + key: Self::STRATEGY_KEY, + request: async move { + Ok(downloader.download_blocks(peer_id, request.clone()).await?.and_then( + |(response, protocol_name)| { + let decoded_response = + downloader.block_response_into_blocks(&request, response); + let result = + Box::new((request, decoded_response)) as Box; + Ok((result, protocol_name)) + }, + )) + } + .boxed(), + // Sending block request implies dropping obsolete pending response as we are + // not interested in it anymore. + remove_obsolete: true, + } + }); self.actions.extend(target_block_request); std::mem::take(&mut self.actions).into_iter() @@ -632,6 +734,7 @@ where #[cfg(test)] mod test { use super::*; + use crate::{mock::MockBlockDownloader, service::network::NetworkServiceProvider}; use sc_block_builder::BlockBuilderBuilder; use sp_blockchain::{BlockStatus, Error as BlockchainError, HeaderBackend, Info}; use sp_consensus_grandpa::{AuthorityList, SetId}; @@ -716,12 +819,16 @@ mod test { let client = mock_client_with_state(); let provider = MockWarpSyncProvider::::new(); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); + + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); // Warp sync instantly finishes - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - assert!(matches!(actions[0], WarpSyncAction::Finished)); + assert!(matches!(actions[0], SyncingAction::Finished)); // ... with no result. assert!(warp_sync.take_result().is_none()); @@ -737,12 +844,16 @@ mod test { Default::default(), Default::default(), )); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); + + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); // Warp sync instantly finishes - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - assert!(matches!(actions[0], WarpSyncAction::Finished)); + assert!(matches!(actions[0], SyncingAction::Finished)); // ... with no result. assert!(warp_sync.take_result().is_none()); @@ -753,10 +864,14 @@ mod test { let client = mock_client_without_state(); let provider = MockWarpSyncProvider::::new(); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); + + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); // No actions are emitted. - assert_eq!(warp_sync.actions().count(), 0) + assert_eq!(warp_sync.actions(&network_handle).count(), 0) } #[test] @@ -769,10 +884,14 @@ mod test { Default::default(), Default::default(), )); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); + + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); // No actions are emitted. - assert_eq!(warp_sync.actions().count(), 0) + assert_eq!(warp_sync.actions(&network_handle).count(), 0) } #[test] @@ -784,7 +903,8 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); // Warp sync is not started when there is not enough peers. for _ in 0..(MIN_PEERS_TO_START_WARP_SYNC - 1) { @@ -802,7 +922,8 @@ mod test { let client = mock_client_without_state(); let provider = MockWarpSyncProvider::::new(); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); assert!(warp_sync.schedule_next_peer(PeerState::DownloadingProofs, None).is_none()); } @@ -826,7 +947,8 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); for best_number in 1..11 { warp_sync.add_peer(PeerId::random(), Hash::random(), best_number); @@ -847,7 +969,8 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); for best_number in 1..11 { warp_sync.add_peer(PeerId::random(), Hash::random(), best_number); @@ -867,7 +990,8 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); for best_number in 1..11 { warp_sync.add_peer(PeerId::random(), Hash::random(), best_number); @@ -911,7 +1035,12 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + Arc::new(client), + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -940,7 +1069,12 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + Arc::new(client), + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -971,7 +1105,12 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + Arc::new(client), + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make requests. for best_number in 1..11 { @@ -998,7 +1137,12 @@ mod test { Err(Box::new(std::io::Error::new(ErrorKind::Other, "test-verification-failure"))) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + Arc::new(client), + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1006,11 +1150,13 @@ mod test { } assert!(matches!(warp_sync.phase, Phase::WarpProof { .. })); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // Consume `SendWarpProofRequest` action. - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - let WarpSyncAction::SendWarpProofRequest { peer_id: request_peer_id, .. } = actions[0] - else { + let SyncingAction::StartRequest { peer_id: request_peer_id, .. } = actions[0] else { panic!("Invalid action"); }; @@ -1021,7 +1167,7 @@ mod test { assert_eq!(actions.len(), 1); assert!(matches!( actions[0], - WarpSyncAction::DropPeer(BadPeer(peer_id, _rep)) if peer_id == request_peer_id + SyncingAction::DropPeer(BadPeer(peer_id, _rep)) if peer_id == request_peer_id )); assert!(matches!(warp_sync.phase, Phase::WarpProof { .. })); } @@ -1039,7 +1185,12 @@ mod test { Ok(VerificationResult::Partial(set_id, authorities, Hash::random())) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + Arc::new(client), + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1047,11 +1198,13 @@ mod test { } assert!(matches!(warp_sync.phase, Phase::WarpProof { .. })); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // Consume `SendWarpProofRequest` action. - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - let WarpSyncAction::SendWarpProofRequest { peer_id: request_peer_id, .. } = actions[0] - else { + let SyncingAction::StartRequest { peer_id: request_peer_id, .. } = actions[0] else { panic!("Invalid action"); }; @@ -1083,7 +1236,12 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, Some(ProtocolName::Static(""))); + let mut warp_sync = WarpSync::new( + client, + config, + Some(ProtocolName::Static("")), + Arc::new(MockBlockDownloader::new()), + ); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1091,11 +1249,13 @@ mod test { } assert!(matches!(warp_sync.phase, Phase::WarpProof { .. })); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // Consume `SendWarpProofRequest` action. - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - let WarpSyncAction::SendWarpProofRequest { peer_id: request_peer_id, .. } = actions[0] - else { + let SyncingAction::StartRequest { peer_id: request_peer_id, .. } = actions[0] else { panic!("Invalid action."); }; @@ -1116,7 +1276,8 @@ mod test { .once() .return_const(AuthorityList::default()); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(Arc::new(client), config, None); + let mut warp_sync = + WarpSync::new(Arc::new(client), config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1151,7 +1312,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1183,7 +1345,8 @@ mod test { .block; let target_header = target_block.header().clone(); let config = WarpSyncConfig::WithTarget(target_header); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1223,7 +1386,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1261,7 +1425,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1315,7 +1480,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1392,7 +1558,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1445,7 +1612,8 @@ mod test { Ok(VerificationResult::Complete(set_id, authorities, target_header)) }); let config = WarpSyncConfig::WithProvider(Arc::new(provider)); - let mut warp_sync = WarpSync::new(client, config, None); + let mut warp_sync = + WarpSync::new(client, config, None, Arc::new(MockBlockDownloader::new())); // Make sure we have enough peers to make a request. for best_number in 1..11 { @@ -1473,10 +1641,13 @@ mod test { assert!(warp_sync.on_block_response_inner(peer_id, request, response).is_ok()); + let network_provider = NetworkServiceProvider::new(); + let network_handle = network_provider.handle(); + // Strategy finishes. - let actions = warp_sync.actions().collect::>(); + let actions = warp_sync.actions(&network_handle).collect::>(); assert_eq!(actions.len(), 1); - assert!(matches!(actions[0], WarpSyncAction::Finished)); + assert!(matches!(actions[0], SyncingAction::Finished)); // With correct result. let result = warp_sync.take_result().unwrap(); diff --git a/substrate/client/network/sync/src/types.rs b/substrate/client/network/sync/src/types.rs index c3403fe1e5f7..5745a34378df 100644 --- a/substrate/client/network/sync/src/types.rs +++ b/substrate/client/network/sync/src/types.rs @@ -23,11 +23,10 @@ use sc_network_common::{role::Roles, types::ReputationChange}; use crate::strategy::{state_sync::StateSyncProgress, warp::WarpSyncProgress}; -use sc_network_common::sync::message::BlockRequest; use sc_network_types::PeerId; use sp_runtime::traits::{Block as BlockT, NumberFor}; -use std::{any::Any, fmt, fmt::Formatter, pin::Pin, sync::Arc}; +use std::{fmt, pin::Pin, sync::Arc}; /// The sync status of a peer we are trying to sync with #[derive(Debug)] @@ -107,52 +106,6 @@ impl fmt::Display for BadPeer { impl std::error::Error for BadPeer {} -#[derive(Debug)] -pub enum PeerRequest { - Block(BlockRequest), - State, - WarpProof, -} - -#[derive(Debug)] -pub enum PeerRequestType { - Block, - State, - WarpProof, -} - -impl PeerRequest { - pub fn get_type(&self) -> PeerRequestType { - match self { - PeerRequest::Block(_) => PeerRequestType::Block, - PeerRequest::State => PeerRequestType::State, - PeerRequest::WarpProof => PeerRequestType::WarpProof, - } - } -} - -/// Wrapper for implementation-specific state request. -/// -/// NOTE: Implementation must be able to encode and decode it for network purposes. -pub struct OpaqueStateRequest(pub Box); - -impl fmt::Debug for OpaqueStateRequest { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.debug_struct("OpaqueStateRequest").finish() - } -} - -/// Wrapper for implementation-specific state response. -/// -/// NOTE: Implementation must be able to encode and decode it for network purposes. -pub struct OpaqueStateResponse(pub Box); - -impl fmt::Debug for OpaqueStateResponse { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - f.debug_struct("OpaqueStateResponse").finish() - } -} - /// Provides high-level status of syncing. #[async_trait::async_trait] pub trait SyncStatusProvider: Send + Sync { diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index 06e243342fb2..825481314c67 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -67,11 +67,11 @@ use sc_network_sync::{ service::{network::NetworkServiceProvider, syncing_service::SyncingService}, state_request_handler::StateRequestHandler, strategy::{ + polkadot::{PolkadotSyncingStrategy, PolkadotSyncingStrategyConfig}, warp::{ AuthorityList, EncodedProof, SetId, VerificationResult, WarpSyncConfig, WarpSyncProvider, }, - PolkadotSyncingStrategy, SyncingConfig, }, warp_request_handler, }; @@ -833,8 +833,8 @@ pub trait TestNetFactory: Default + Sized + Send { let fork_id = Some(String::from("test-fork-id")); - let (chain_sync_network_provider, chain_sync_network_handle) = - NetworkServiceProvider::new(); + let chain_sync_network_provider = NetworkServiceProvider::new(); + let chain_sync_network_handle = chain_sync_network_provider.handle(); let mut block_relay_params = BlockRequestHandler::new::>( chain_sync_network_handle.clone(), &protocol_id, @@ -908,12 +908,13 @@ pub trait TestNetFactory: Default + Sized + Send { ::Hash, >>::register_notification_metrics(None); - let syncing_config = SyncingConfig { + let syncing_config = PolkadotSyncingStrategyConfig { mode: network_config.sync_mode, max_parallel_downloads: network_config.max_parallel_downloads, max_blocks_per_request: network_config.max_blocks_per_request, metrics_registry: None, state_request_protocol_name: state_request_protocol_config.name.clone(), + block_downloader: block_relay_params.downloader, }; // Initialize syncing strategy. let syncing_strategy = Box::new( @@ -934,16 +935,14 @@ pub trait TestNetFactory: Default + Sized + Send { metrics, &full_net_config, protocol_id.clone(), - &fork_id, + fork_id.as_deref(), block_announce_validator, syncing_strategy, chain_sync_network_handle, import_queue.service(), - block_relay_params.downloader, peer_store_handle.clone(), ) .unwrap(); - let sync_service_import_queue = Box::new(sync_service.clone()); let sync_service = Arc::new(sync_service.clone()); for config in config.request_response_protocols { @@ -987,8 +986,12 @@ pub trait TestNetFactory: Default + Sized + Send { chain_sync_network_provider.run(service).await; }); - tokio::spawn(async move { - import_queue.run(sync_service_import_queue).await; + tokio::spawn({ + let sync_service = sync_service.clone(); + + async move { + import_queue.run(sync_service.as_ref()).await; + } }); tokio::spawn(async move { diff --git a/substrate/client/network/test/src/service.rs b/substrate/client/network/test/src/service.rs index ad2d1d9ec24d..688b569c3222 100644 --- a/substrate/client/network/test/src/service.rs +++ b/substrate/client/network/test/src/service.rs @@ -32,9 +32,9 @@ use sc_network_light::light_client_requests::handler::LightClientRequestHandler; use sc_network_sync::{ block_request_handler::BlockRequestHandler, engine::SyncingEngine, - service::network::{NetworkServiceHandle, NetworkServiceProvider}, + service::network::NetworkServiceProvider, state_request_handler::StateRequestHandler, - strategy::{PolkadotSyncingStrategy, SyncingConfig}, + strategy::polkadot::{PolkadotSyncingStrategy, PolkadotSyncingStrategyConfig}, }; use sp_blockchain::HeaderBackend; use sp_runtime::traits::{Block as BlockT, Zero}; @@ -78,7 +78,7 @@ struct TestNetworkBuilder { client: Option>, listen_addresses: Vec, set_config: Option, - chain_sync_network: Option<(NetworkServiceProvider, NetworkServiceHandle)>, + chain_sync_network: Option, notification_protocols: Vec, config: Option, } @@ -157,8 +157,9 @@ impl TestNetworkBuilder { let fork_id = Some(String::from("test-fork-id")); let mut full_net_config = FullNetworkConfiguration::new(&network_config, None); - let (chain_sync_network_provider, chain_sync_network_handle) = + let chain_sync_network_provider = self.chain_sync_network.unwrap_or(NetworkServiceProvider::new()); + let chain_sync_network_handle = chain_sync_network_provider.handle(); let mut block_relay_params = BlockRequestHandler::new::< NetworkWorker< @@ -203,12 +204,13 @@ impl TestNetworkBuilder { let peer_store_handle: Arc = Arc::new(peer_store.handle()); tokio::spawn(peer_store.run().boxed()); - let syncing_config = SyncingConfig { + let syncing_config = PolkadotSyncingStrategyConfig { mode: network_config.sync_mode, max_parallel_downloads: network_config.max_parallel_downloads, max_blocks_per_request: network_config.max_blocks_per_request, metrics_registry: None, state_request_protocol_name: state_request_protocol_config.name.clone(), + block_downloader: block_relay_params.downloader, }; // Initialize syncing strategy. let syncing_strategy = Box::new( @@ -222,12 +224,11 @@ impl TestNetworkBuilder { NotificationMetrics::new(None), &full_net_config, protocol_id.clone(), - &None, + None, Box::new(sp_consensus::block_validation::DefaultBlockAnnounceValidator), syncing_strategy, chain_sync_network_handle, import_queue.service(), - block_relay_params.downloader, Arc::clone(&peer_store_handle), ) .unwrap(); diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index f27b7ec6fbad..ce4ce7c08248 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -35,7 +35,7 @@ use sc_client_api::{ BlockBackend, BlockchainEvents, ExecutorProvider, ForkBlocks, StorageProvider, UsageProvider, }; use sc_client_db::{Backend, BlocksPruning, DatabaseSettings, PruningMode}; -use sc_consensus::import_queue::ImportQueue; +use sc_consensus::import_queue::{ImportQueue, ImportQueueService}; use sc_executor::{ sp_wasm_interface::HostFunctions, HeapAllocStrategy, NativeExecutionDispatch, RuntimeVersionOf, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY, @@ -50,15 +50,18 @@ use sc_network::{ }, NetworkBackend, NetworkStateInfo, }; -use sc_network_common::role::Roles; +use sc_network_common::role::{Role, Roles}; use sc_network_light::light_client_requests::handler::LightClientRequestHandler; use sc_network_sync::{ - block_relay_protocol::BlockRelayParams, + block_relay_protocol::{BlockDownloader, BlockRelayParams}, block_request_handler::BlockRequestHandler, engine::SyncingEngine, - service::network::NetworkServiceProvider, + service::network::{NetworkServiceHandle, NetworkServiceProvider}, state_request_handler::StateRequestHandler, - strategy::{PolkadotSyncingStrategy, SyncingConfig, SyncingStrategy}, + strategy::{ + polkadot::{PolkadotSyncingStrategy, PolkadotSyncingStrategyConfig}, + SyncingStrategy, + }, warp_request_handler::RequestHandler as WarpSyncRequestHandler, SyncingService, WarpSyncConfig, }; @@ -780,7 +783,7 @@ where Ok(rpc_api) } -/// Parameters to pass into `build_network`. +/// Parameters to pass into [`build_network`]. pub struct BuildNetworkParams<'a, Block, Net, TxPool, IQ, Client> where Block: BlockT, @@ -802,8 +805,8 @@ where pub block_announce_validator_builder: Option< Box) -> Box + Send> + Send>, >, - /// Syncing strategy to use in syncing engine. - pub syncing_strategy: Box>, + /// Optional warp sync config. + pub warp_sync_config: Option>, /// User specified block relay params. If not specified, the default /// block request handler will be used. pub block_relay: Option>, @@ -847,100 +850,217 @@ where spawn_handle, import_queue, block_announce_validator_builder, - syncing_strategy, + warp_sync_config, block_relay, metrics, } = params; - let protocol_id = config.protocol_id(); - let genesis_hash = client.info().genesis_hash; - let block_announce_validator = if let Some(f) = block_announce_validator_builder { f(client.clone()) } else { Box::new(DefaultBlockAnnounceValidator) }; - let (chain_sync_network_provider, chain_sync_network_handle) = NetworkServiceProvider::new(); - let (mut block_server, block_downloader, block_request_protocol_config) = match block_relay { - Some(params) => (params.server, params.downloader, params.request_response_config), - None => { - // Custom protocol was not specified, use the default block handler. - // Allow both outgoing and incoming requests. - let params = BlockRequestHandler::new::( - chain_sync_network_handle.clone(), - &protocol_id, - config.chain_spec.fork_id(), - client.clone(), - config.network.default_peers_set.in_peers as usize + - config.network.default_peers_set.out_peers as usize, - ); - (params.server, params.downloader, params.request_response_config) + let network_service_provider = NetworkServiceProvider::new(); + let protocol_id = config.protocol_id(); + let fork_id = config.chain_spec.fork_id(); + let metrics_registry = config.prometheus_config.as_ref().map(|config| &config.registry); + + let block_downloader = match block_relay { + Some(params) => { + let BlockRelayParams { mut server, downloader, request_response_config } = params; + + net_config.add_request_response_protocol(request_response_config); + + spawn_handle.spawn("block-request-handler", Some("networking"), async move { + server.run().await; + }); + + downloader }, + None => build_default_block_downloader( + &protocol_id, + fork_id, + &mut net_config, + network_service_provider.handle(), + Arc::clone(&client), + config.network.default_peers_set.in_peers as usize + + config.network.default_peers_set.out_peers as usize, + &spawn_handle, + ), }; - spawn_handle.spawn("block-request-handler", Some("networking"), async move { - block_server.run().await; - }); + + let syncing_strategy = build_polkadot_syncing_strategy( + protocol_id.clone(), + fork_id, + &mut net_config, + warp_sync_config, + block_downloader, + client.clone(), + &spawn_handle, + metrics_registry, + )?; + + let (syncing_engine, sync_service, block_announce_config) = SyncingEngine::new( + Roles::from(&config.role), + Arc::clone(&client), + metrics_registry, + metrics.clone(), + &net_config, + protocol_id.clone(), + fork_id, + block_announce_validator, + syncing_strategy, + network_service_provider.handle(), + import_queue.service(), + net_config.peer_store_handle(), + )?; + + spawn_handle.spawn_blocking("syncing", None, syncing_engine.run()); + + build_network_advanced(BuildNetworkAdvancedParams { + role: config.role, + protocol_id, + fork_id, + ipfs_server: config.network.ipfs_server, + announce_block: config.announce_block, + net_config, + client, + transaction_pool, + spawn_handle, + import_queue, + sync_service, + block_announce_config, + network_service_provider, + metrics_registry, + metrics, + }) +} + +/// Parameters to pass into [`build_network_advanced`]. +pub struct BuildNetworkAdvancedParams<'a, Block, Net, TxPool, IQ, Client> +where + Block: BlockT, + Net: NetworkBackend::Hash>, +{ + /// Role of the local node. + pub role: Role, + /// Protocol name prefix. + pub protocol_id: ProtocolId, + /// Fork ID. + pub fork_id: Option<&'a str>, + /// Enable serving block data over IPFS bitswap. + pub ipfs_server: bool, + /// Announce block automatically after they have been imported. + pub announce_block: bool, + /// Full network configuration. + pub net_config: FullNetworkConfiguration::Hash, Net>, + /// A shared client returned by `new_full_parts`. + pub client: Arc, + /// A shared transaction pool. + pub transaction_pool: Arc, + /// A handle for spawning tasks. + pub spawn_handle: SpawnTaskHandle, + /// An import queue. + pub import_queue: IQ, + /// Syncing service to communicate with syncing engine. + pub sync_service: SyncingService, + /// Block announce config. + pub block_announce_config: Net::NotificationProtocolConfig, + /// Network service provider to drive with network internally. + pub network_service_provider: NetworkServiceProvider, + /// Prometheus metrics registry. + pub metrics_registry: Option<&'a Registry>, + /// Metrics. + pub metrics: NotificationMetrics, +} + +/// Build the network service, the network status sinks and an RPC sender, this is a lower-level +/// version of [`build_network`] for those needing more control. +pub fn build_network_advanced( + params: BuildNetworkAdvancedParams, +) -> Result< + ( + Arc, + TracingUnboundedSender>, + sc_network_transactions::TransactionsHandlerController<::Hash>, + NetworkStarter, + Arc>, + ), + Error, +> +where + Block: BlockT, + Client: ProvideRuntimeApi + + HeaderMetadata + + Chain + + BlockBackend + + BlockIdTo + + ProofProvider + + HeaderBackend + + BlockchainEvents + + 'static, + TxPool: TransactionPool::Hash> + 'static, + IQ: ImportQueue + 'static, + Net: NetworkBackend::Hash>, +{ + let BuildNetworkAdvancedParams { + role, + protocol_id, + fork_id, + ipfs_server, + announce_block, + mut net_config, + client, + transaction_pool, + spawn_handle, + import_queue, + sync_service, + block_announce_config, + network_service_provider, + metrics_registry, + metrics, + } = params; + + let genesis_hash = client.info().genesis_hash; let light_client_request_protocol_config = { // Allow both outgoing and incoming requests. - let (handler, protocol_config) = LightClientRequestHandler::new::( - &protocol_id, - config.chain_spec.fork_id(), - client.clone(), - ); + let (handler, protocol_config) = + LightClientRequestHandler::new::(&protocol_id, fork_id, client.clone()); spawn_handle.spawn("light-client-request-handler", Some("networking"), handler.run()); protocol_config }; // install request handlers to `FullNetworkConfiguration` - net_config.add_request_response_protocol(block_request_protocol_config); net_config.add_request_response_protocol(light_client_request_protocol_config); - let bitswap_config = config.network.ipfs_server.then(|| { + let bitswap_config = ipfs_server.then(|| { let (handler, config) = Net::bitswap_server(client.clone()); spawn_handle.spawn("bitswap-request-handler", Some("networking"), handler); config }); - // create transactions protocol and add it to the list of supported protocols of - let peer_store_handle = net_config.peer_store_handle(); + // Create transactions protocol and add it to the list of supported protocols of let (transactions_handler_proto, transactions_config) = sc_network_transactions::TransactionsHandlerPrototype::new::<_, Block, Net>( protocol_id.clone(), genesis_hash, - config.chain_spec.fork_id(), + fork_id, metrics.clone(), - Arc::clone(&peer_store_handle), + net_config.peer_store_handle(), ); net_config.add_notification_protocol(transactions_config); // Start task for `PeerStore` let peer_store = net_config.take_peer_store(); - let peer_store_handle = peer_store.handle(); spawn_handle.spawn("peer-store", Some("networking"), peer_store.run()); - let (engine, sync_service, block_announce_config) = SyncingEngine::new( - Roles::from(&config.role), - client.clone(), - config.prometheus_config.as_ref().map(|config| config.registry.clone()).as_ref(), - metrics.clone(), - &net_config, - protocol_id.clone(), - &config.chain_spec.fork_id().map(ToOwned::to_owned), - block_announce_validator, - syncing_strategy, - chain_sync_network_handle, - import_queue.service(), - block_downloader, - Arc::clone(&peer_store_handle), - )?; - let sync_service_import_queue = sync_service.clone(); let sync_service = Arc::new(sync_service); let network_params = sc_network::config::Params::::Hash, Net> { - role: config.role, + role, executor: { let spawn_handle = Clone::clone(&spawn_handle); Box::new(move |fut| { @@ -950,8 +1070,8 @@ where network_config: net_config, genesis_hash, protocol_id, - fork_id: config.chain_spec.fork_id().map(ToOwned::to_owned), - metrics_registry: config.prometheus_config.as_ref().map(|config| config.registry.clone()), + fork_id: fork_id.map(ToOwned::to_owned), + metrics_registry: metrics_registry.cloned(), block_announce_config, bitswap_config, notification_metrics: metrics, @@ -965,7 +1085,7 @@ where network.clone(), sync_service.clone(), Arc::new(TransactionPoolAdapter { pool: transaction_pool, client: client.clone() }), - config.prometheus_config.as_ref().map(|config| &config.registry), + metrics_registry, )?; spawn_handle.spawn_blocking( "network-transactions-handler", @@ -976,17 +1096,20 @@ where spawn_handle.spawn_blocking( "chain-sync-network-service-provider", Some("networking"), - chain_sync_network_provider.run(Arc::new(network.clone())), + network_service_provider.run(Arc::new(network.clone())), ); - spawn_handle.spawn("import-queue", None, import_queue.run(Box::new(sync_service_import_queue))); - spawn_handle.spawn_blocking("syncing", None, engine.run()); + spawn_handle.spawn("import-queue", None, { + let sync_service = sync_service.clone(); + + async move { import_queue.run(sync_service.as_ref()).await } + }); let (system_rpc_tx, system_rpc_rx) = tracing_unbounded("mpsc_system_rpc", 10_000); spawn_handle.spawn( "system-rpc-handler", Some("networking"), build_system_rpc_future::<_, _, ::Hash>( - config.role, + role, network_mut.network_service(), sync_service.clone(), client.clone(), @@ -999,7 +1122,7 @@ where network_mut, client, sync_service.clone(), - config.announce_block, + announce_block, ); // TODO: Normally, one is supposed to pass a list of notifications protocols supported by the @@ -1047,12 +1170,154 @@ where )) } +/// Configuration for [`build_default_syncing_engine`]. +pub struct DefaultSyncingEngineConfig<'a, Block, Client, Net> +where + Block: BlockT, + Net: NetworkBackend::Hash>, +{ + /// Role of the local node. + pub role: Role, + /// Protocol name prefix. + pub protocol_id: ProtocolId, + /// Fork ID. + pub fork_id: Option<&'a str>, + /// Full network configuration. + pub net_config: &'a mut FullNetworkConfiguration::Hash, Net>, + /// Validator for incoming block announcements. + pub block_announce_validator: Box + Send>, + /// Handle to communicate with `NetworkService`. + pub network_service_handle: NetworkServiceHandle, + /// Warp sync configuration (when used). + pub warp_sync_config: Option>, + /// A shared client returned by `new_full_parts`. + pub client: Arc, + /// Blocks import queue API. + pub import_queue_service: Box>, + /// Expected max total number of peer connections (in + out). + pub num_peers_hint: usize, + /// A handle for spawning tasks. + pub spawn_handle: &'a SpawnTaskHandle, + /// Prometheus metrics registry. + pub metrics_registry: Option<&'a Registry>, + /// Metrics. + pub metrics: NotificationMetrics, +} + +/// Build default syncing engine using [`build_default_block_downloader`] and +/// [`build_polkadot_syncing_strategy`] internally. +pub fn build_default_syncing_engine( + config: DefaultSyncingEngineConfig, +) -> Result<(SyncingService, Net::NotificationProtocolConfig), Error> +where + Block: BlockT, + Client: HeaderBackend + + BlockBackend + + HeaderMetadata + + ProofProvider + + Send + + Sync + + 'static, + Net: NetworkBackend::Hash>, +{ + let DefaultSyncingEngineConfig { + role, + protocol_id, + fork_id, + net_config, + block_announce_validator, + network_service_handle, + warp_sync_config, + client, + import_queue_service, + num_peers_hint, + spawn_handle, + metrics_registry, + metrics, + } = config; + + let block_downloader = build_default_block_downloader( + &protocol_id, + fork_id, + net_config, + network_service_handle.clone(), + client.clone(), + num_peers_hint, + spawn_handle, + ); + let syncing_strategy = build_polkadot_syncing_strategy( + protocol_id.clone(), + fork_id, + net_config, + warp_sync_config, + block_downloader, + client.clone(), + spawn_handle, + metrics_registry, + )?; + + let (syncing_engine, sync_service, block_announce_config) = SyncingEngine::new( + Roles::from(&role), + client, + metrics_registry, + metrics, + &net_config, + protocol_id, + fork_id, + block_announce_validator, + syncing_strategy, + network_service_handle, + import_queue_service, + net_config.peer_store_handle(), + )?; + + spawn_handle.spawn_blocking("syncing", None, syncing_engine.run()); + + Ok((sync_service, block_announce_config)) +} + +/// Build default block downloader +pub fn build_default_block_downloader( + protocol_id: &ProtocolId, + fork_id: Option<&str>, + net_config: &mut FullNetworkConfiguration::Hash, Net>, + network_service_handle: NetworkServiceHandle, + client: Arc, + num_peers_hint: usize, + spawn_handle: &SpawnTaskHandle, +) -> Arc> +where + Block: BlockT, + Client: HeaderBackend + BlockBackend + Send + Sync + 'static, + Net: NetworkBackend::Hash>, +{ + // Custom protocol was not specified, use the default block handler. + // Allow both outgoing and incoming requests. + let BlockRelayParams { mut server, downloader, request_response_config } = + BlockRequestHandler::new::( + network_service_handle, + &protocol_id, + fork_id, + client.clone(), + num_peers_hint, + ); + + spawn_handle.spawn("block-request-handler", Some("networking"), async move { + server.run().await; + }); + + net_config.add_request_response_protocol(request_response_config); + + downloader +} + /// Build standard polkadot syncing strategy pub fn build_polkadot_syncing_strategy( protocol_id: ProtocolId, fork_id: Option<&str>, net_config: &mut FullNetworkConfiguration::Hash, Net>, warp_sync_config: Option>, + block_downloader: Arc>, client: Arc, spawn_handle: &SpawnTaskHandle, metrics_registry: Option<&Registry>, @@ -1066,7 +1331,6 @@ where + Send + Sync + 'static, - Net: NetworkBackend::Hash>, { if warp_sync_config.is_none() && net_config.network_config.sync_mode.is_warp() { @@ -1117,12 +1381,13 @@ where net_config.add_request_response_protocol(config); } - let syncing_config = SyncingConfig { + let syncing_config = PolkadotSyncingStrategyConfig { mode: net_config.network_config.sync_mode, max_parallel_downloads: net_config.network_config.max_parallel_downloads, max_blocks_per_request: net_config.network_config.max_blocks_per_request, metrics_registry: metrics_registry.cloned(), state_request_protocol_name, + block_downloader, }; Ok(Box::new(PolkadotSyncingStrategy::new( syncing_config, diff --git a/substrate/client/service/src/chain_ops/import_blocks.rs b/substrate/client/service/src/chain_ops/import_blocks.rs index 661fc09a8f19..8e759faa0775 100644 --- a/substrate/client/service/src/chain_ops/import_blocks.rs +++ b/substrate/client/service/src/chain_ops/import_blocks.rs @@ -37,6 +37,10 @@ use sp_runtime::{ use std::{ io::Read, pin::Pin, + sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, + }, task::Poll, time::{Duration, Instant}, }; @@ -50,8 +54,6 @@ const DELAY_TIME: u64 = 200; /// Number of milliseconds that must have passed between two updates. const TIME_BETWEEN_UPDATES: u64 = 3_000; -use std::sync::Arc; - /// Build a chain spec json pub fn build_spec(spec: &dyn ChainSpec, raw: bool) -> error::Result { spec.as_json(raw).map_err(Into::into) @@ -301,29 +303,29 @@ where IQ: ImportQueue + 'static, { struct WaitLink { - imported_blocks: u64, - has_error: bool, + imported_blocks: AtomicU64, + has_error: AtomicBool, } impl WaitLink { fn new() -> WaitLink { - WaitLink { imported_blocks: 0, has_error: false } + WaitLink { imported_blocks: AtomicU64::new(0), has_error: AtomicBool::new(false) } } } impl Link for WaitLink { fn blocks_processed( - &mut self, + &self, imported: usize, _num_expected_blocks: usize, results: Vec<(Result>, BlockImportError>, B::Hash)>, ) { - self.imported_blocks += imported as u64; + self.imported_blocks.fetch_add(imported as u64, Ordering::AcqRel); for result in results { if let (Err(err), hash) = result { warn!("There was an error importing block with hash {:?}: {}", hash, err); - self.has_error = true; + self.has_error.store(true, Ordering::Release); break } } @@ -373,7 +375,9 @@ where let read_block_count = block_iter.read_block_count(); match block_result { Ok(block) => { - if read_block_count - link.imported_blocks >= MAX_PENDING_BLOCKS { + if read_block_count - link.imported_blocks.load(Ordering::Acquire) >= + MAX_PENDING_BLOCKS + { // The queue is full, so do not add this block and simply wait // until the queue has made some progress. let delay = Delay::new(Duration::from_millis(DELAY_TIME)); @@ -399,7 +403,9 @@ where }, ImportState::WaitingForImportQueueToCatchUp { block_iter, mut delay, block } => { let read_block_count = block_iter.read_block_count(); - if read_block_count - link.imported_blocks >= MAX_PENDING_BLOCKS { + if read_block_count - link.imported_blocks.load(Ordering::Acquire) >= + MAX_PENDING_BLOCKS + { // Queue is still full, so wait until there is room to insert our block. match Pin::new(&mut delay).poll(cx) { Poll::Pending => { @@ -433,7 +439,11 @@ where } => { // All the blocks have been added to the queue, which doesn't mean they // have all been properly imported. - if importing_is_done(num_expected_blocks, read_block_count, link.imported_blocks) { + if importing_is_done( + num_expected_blocks, + read_block_count, + link.imported_blocks.load(Ordering::Acquire), + ) { // Importing is done, we can log the result and return. info!( "🎉 Imported {} blocks. Best: #{}", @@ -472,10 +482,10 @@ where let best_number = client.info().best_number; speedometer.notify_user(best_number); - if link.has_error { + if link.has_error.load(Ordering::Acquire) { return Poll::Ready(Err(Error::Other(format!( "Stopping after #{} blocks because of an error", - link.imported_blocks + link.imported_blocks.load(Ordering::Acquire) )))) } diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 3df9020b0418..ee4f4e7622e7 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -59,11 +59,13 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; pub use self::{ builder::{ - build_network, build_polkadot_syncing_strategy, gen_rpc_module, init_telemetry, new_client, - new_db_backend, new_full_client, new_full_parts, new_full_parts_record_import, + build_default_block_downloader, build_default_syncing_engine, build_network, + build_network_advanced, build_polkadot_syncing_strategy, gen_rpc_module, init_telemetry, + new_client, new_db_backend, new_full_client, new_full_parts, new_full_parts_record_import, new_full_parts_with_genesis_builder, new_wasm_executor, - propagate_transaction_notifications, spawn_tasks, BuildNetworkParams, KeystoreContainer, - NetworkStarter, SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient, + propagate_transaction_notifications, spawn_tasks, BuildNetworkAdvancedParams, + BuildNetworkParams, DefaultSyncingEngineConfig, KeystoreContainer, NetworkStarter, + SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient, }, client::{ClientConfig, LocalCallExecutor}, error::Error, diff --git a/templates/minimal/node/src/service.rs b/templates/minimal/node/src/service.rs index f9a9d1e0f3cf..b4e6fc0b728b 100644 --- a/templates/minimal/node/src/service.rs +++ b/templates/minimal/node/src/service.rs @@ -21,9 +21,7 @@ use minimal_template_runtime::{interface::OpaqueBlock as Block, RuntimeApi}; use polkadot_sdk::{ sc_client_api::backend::Backend, sc_executor::WasmExecutor, - sc_service::{ - build_polkadot_syncing_strategy, error::Error as ServiceError, Configuration, TaskManager, - }, + sc_service::{error::Error as ServiceError, Configuration, TaskManager}, sc_telemetry::{Telemetry, TelemetryWorker}, sc_transaction_pool_api::OffchainTransactionPoolFactory, sp_runtime::traits::Block as BlockT, @@ -124,7 +122,7 @@ pub fn new_full::Ha other: mut telemetry, } = new_partial(&config)?; - let mut net_config = sc_network::config::FullNetworkConfiguration::< + let net_config = sc_network::config::FullNetworkConfiguration::< Block, ::Hash, Network, @@ -136,26 +134,16 @@ pub fn new_full::Ha config.prometheus_config.as_ref().map(|cfg| &cfg.registry), ); - let syncing_strategy = build_polkadot_syncing_strategy( - config.protocol_id(), - config.chain_spec.fork_id(), - &mut net_config, - None, - client.clone(), - &task_manager.spawn_handle(), - config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, + net_config, client: client.clone(), transaction_pool: transaction_pool.clone(), spawn_handle: task_manager.spawn_handle(), import_queue, - net_config, block_announce_validator_builder: None, - syncing_strategy, + warp_sync_config: None, block_relay: None, metrics, })?; diff --git a/templates/solochain/node/Cargo.toml b/templates/solochain/node/Cargo.toml index 8a3c7d0ac780..4c0ab31df95e 100644 --- a/templates/solochain/node/Cargo.toml +++ b/templates/solochain/node/Cargo.toml @@ -30,9 +30,9 @@ sc-telemetry = { workspace = true, default-features = true } sc-transaction-pool = { workspace = true, default-features = true } sc-transaction-pool-api = { workspace = true, default-features = true } sc-offchain = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } sc-consensus-aura = { workspace = true, default-features = true } sp-consensus-aura = { workspace = true, default-features = true } -sc-consensus = { workspace = true, default-features = true } sc-consensus-grandpa = { workspace = true, default-features = true } sp-consensus-grandpa = { workspace = true, default-features = true } sp-genesis-builder = { workspace = true, default-features = true } diff --git a/templates/solochain/node/src/service.rs b/templates/solochain/node/src/service.rs index 2524906fd508..d6fcebe239f7 100644 --- a/templates/solochain/node/src/service.rs +++ b/templates/solochain/node/src/service.rs @@ -4,10 +4,7 @@ use futures::FutureExt; use sc_client_api::{Backend, BlockBackend}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_grandpa::SharedVoterState; -use sc_service::{ - build_polkadot_syncing_strategy, error::Error as ServiceError, Configuration, TaskManager, - WarpSyncConfig, -}; +use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncConfig}; use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use solochain_template_runtime::{self, apis::RuntimeApi, opaque::Block}; @@ -172,16 +169,6 @@ pub fn new_full< Vec::default(), )); - let syncing_strategy = build_polkadot_syncing_strategy( - config.protocol_id(), - config.chain_spec.fork_id(), - &mut net_config, - Some(WarpSyncConfig::WithProvider(warp_sync)), - client.clone(), - &task_manager.spawn_handle(), - config.prometheus_config.as_ref().map(|config| &config.registry), - )?; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, @@ -191,7 +178,7 @@ pub fn new_full< spawn_handle: task_manager.spawn_handle(), import_queue, block_announce_validator_builder: None, - syncing_strategy, + warp_sync_config: Some(WarpSyncConfig::WithProvider(warp_sync)), block_relay: None, metrics, })?; From 8c146a7c7133f00567c8b48277db79236dc6d751 Mon Sep 17 00:00:00 2001 From: Ankan <10196091+Ank4n@users.noreply.github.com> Date: Thu, 7 Nov 2024 11:22:06 +0100 Subject: [PATCH 055/166] [pallet-staking] Add page info to `PayoutStarted` event (#5984) fixes https://github.com/paritytech/polkadot-sdk/issues/5966 --------- Co-authored-by: Guillaume Thiolliere --- prdoc/pr_5984.prdoc | 14 ++++++++++++++ substrate/frame/staking/src/pallet/impls.rs | 2 ++ substrate/frame/staking/src/pallet/mod.rs | 9 +++++++-- substrate/frame/staking/src/tests.rs | 6 ++++-- 4 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 prdoc/pr_5984.prdoc diff --git a/prdoc/pr_5984.prdoc b/prdoc/pr_5984.prdoc new file mode 100644 index 000000000000..3b6651bac6b9 --- /dev/null +++ b/prdoc/pr_5984.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add page information to staking::PayoutStarted event + +doc: + - audience: Runtime User + description: | + Adds page index that is claimed, and optional next page that can be claimed. If next is none, then the page is the + last one. + +crates: + - name: pallet-staking + bump: major diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index 649903741140..d3423d82769d 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -349,6 +349,8 @@ impl Pallet { Self::deposit_event(Event::::PayoutStarted { era_index: era, validator_stash: stash.clone(), + page, + next: EraInfo::::get_next_claimable_page(era, &stash, &ledger), }); let mut total_imbalance = PositiveImbalanceOf::::zero(); diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index 28aa4f89b622..5210bef853b2 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -851,8 +851,13 @@ pub mod pallet { StakingElectionFailed, /// An account has stopped participating as either a validator or nominator. Chilled { stash: T::AccountId }, - /// The stakers' rewards are getting paid. - PayoutStarted { era_index: EraIndex, validator_stash: T::AccountId }, + /// A Page of stakers rewards are getting paid. `next` is `None` if all pages are claimed. + PayoutStarted { + era_index: EraIndex, + validator_stash: T::AccountId, + page: Page, + next: Option, + }, /// A validator has set their preferences. ValidatorPrefsSet { stash: T::AccountId, prefs: ValidatorPrefs }, /// Voters size limit reached. diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 639f4096456f..d1dc6c3db659 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -3978,6 +3978,7 @@ fn test_multi_page_payout_stakers_by_page() { assert!(matches!( staking_events_since_last_call().as_slice(), &[ + Event::PayoutStarted { era_index: 1, validator_stash: 11, page: 0, next: Some(1) }, .., Event::Rewarded { stash: 1063, dest: RewardDestination::Stash, amount: 111 }, Event::Rewarded { stash: 1064, dest: RewardDestination::Stash, amount: 111 }, @@ -4001,7 +4002,7 @@ fn test_multi_page_payout_stakers_by_page() { assert!(matches!( events.as_slice(), &[ - Event::PayoutStarted { era_index: 1, validator_stash: 11 }, + Event::PayoutStarted { era_index: 1, validator_stash: 11, page: 1, next: None }, Event::Rewarded { stash: 1065, dest: RewardDestination::Stash, amount: 111 }, Event::Rewarded { stash: 1066, dest: RewardDestination::Stash, amount: 111 }, .. @@ -8011,7 +8012,8 @@ mod ledger_recovery { assert_eq!(asset::staked::(&333), lock_333_before); // OK assert_eq!(Bonded::::get(&333), Some(444)); // OK assert!(Payee::::get(&333).is_some()); // OK - // however, ledger associated with its controller was killed. + + // however, ledger associated with its controller was killed. assert!(Ledger::::get(&444).is_none()); // NOK // side effects on 444 - ledger, bonded, payee, lock should be completely removed. From bb8c7a3bd9b38ad89370d19cd68601598276942c Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Thu, 7 Nov 2024 13:47:22 +0200 Subject: [PATCH 056/166] net/discovery: Do not propagate external addr with different peerIDs (#6380) This PR ensures that external addresses with different PeerIDs are not propagated to the higher layer of the network code. While at it, this ensures that libp2p only adds the `/p2p/peerid` part to the discovered address if it does not contain it already. This is a followup from: - https://github.com/paritytech/polkadot-sdk/pull/6298 cc @paritytech/networking --------- Signed-off-by: Alexandru Vasile Co-authored-by: Dmitry Markin --- prdoc/pr_6380.prdoc | 11 ++++ substrate/client/network/src/discovery.rs | 22 +++++-- .../client/network/src/litep2p/discovery.rs | 58 +++++++++++++------ substrate/client/network/src/litep2p/mod.rs | 1 + 4 files changed, 70 insertions(+), 22 deletions(-) create mode 100644 prdoc/pr_6380.prdoc diff --git a/prdoc/pr_6380.prdoc b/prdoc/pr_6380.prdoc new file mode 100644 index 000000000000..72853bcf230c --- /dev/null +++ b/prdoc/pr_6380.prdoc @@ -0,0 +1,11 @@ +title: Do not propagate external addr with different peerIDs + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + External addresses that belong to a different peerID are no longer + propagated to the higher layers of the networking backends. + +crates: + - name: sc-network + bump: patch diff --git a/substrate/client/network/src/discovery.rs b/substrate/client/network/src/discovery.rs index 49e0797c126c..8080bda9a574 100644 --- a/substrate/client/network/src/discovery.rs +++ b/substrate/client/network/src/discovery.rs @@ -749,16 +749,28 @@ impl NetworkBehaviour for DiscoveryBehaviour { self.mdns.on_swarm_event(FromSwarm::NewListenAddr(e)); }, FromSwarm::ExternalAddrConfirmed(e @ ExternalAddrConfirmed { addr }) => { - let new_addr = addr.clone().with(Protocol::P2p(self.local_peer_id)); + let mut address = addr.clone(); - if Self::can_add_to_dht(addr) { + if let Some(Protocol::P2p(peer_id)) = addr.iter().last() { + if peer_id != self.local_peer_id { + warn!( + target: "sub-libp2p", + "🔍 Discovered external address for a peer that is not us: {addr}", + ); + // Ensure this address is not propagated to kademlia. + return + } + } else { + address.push(Protocol::P2p(self.local_peer_id)); + } + + if Self::can_add_to_dht(&address) { // NOTE: we might re-discover the same address multiple times // in which case we just want to refrain from logging. - if self.known_external_addresses.insert(new_addr.clone()) { + if self.known_external_addresses.insert(address.clone()) { info!( target: "sub-libp2p", - "🔍 Discovered new external address for our node: {}", - new_addr, + "🔍 Discovered new external address for our node: {address}", ); } } diff --git a/substrate/client/network/src/litep2p/discovery.rs b/substrate/client/network/src/litep2p/discovery.rs index 7b2e713dffd2..9043f9420e8d 100644 --- a/substrate/client/network/src/litep2p/discovery.rs +++ b/substrate/client/network/src/litep2p/discovery.rs @@ -162,6 +162,9 @@ pub enum DiscoveryEvent { /// Discovery. pub struct Discovery { + /// Local peer ID. + local_peer_id: litep2p::PeerId, + /// Ping event stream. ping_event_stream: Box + Send + Unpin>, @@ -233,6 +236,7 @@ impl Discovery { /// Enables `/ipfs/ping/1.0.0` and `/ipfs/identify/1.0.0` by default and starts /// the mDNS peer discovery if it was enabled. pub fn new + Clone>( + local_peer_id: litep2p::PeerId, config: &NetworkConfiguration, genesis_hash: Hash, fork_id: Option<&str>, @@ -273,6 +277,7 @@ impl Discovery { ( Self { + local_peer_id, ping_event_stream, identify_event_stream, mdns_event_stream, @@ -591,24 +596,43 @@ impl Stream for Discovery { observed_address, .. })) => { - let (is_new, expired_address) = - this.is_new_external_address(&observed_address, peer); - - if let Some(expired_address) = expired_address { - log::trace!( - target: LOG_TARGET, - "Removing expired external address expired={expired_address} is_new={is_new} observed={observed_address}", - ); - - this.pending_events.push_back(DiscoveryEvent::ExternalAddressExpired { - address: expired_address, - }); - } + let observed_address = + if let Some(Protocol::P2p(peer_id)) = observed_address.iter().last() { + if peer_id != *this.local_peer_id.as_ref() { + log::warn!( + target: LOG_TARGET, + "Discovered external address for a peer that is not us: {observed_address}", + ); + None + } else { + Some(observed_address) + } + } else { + Some(observed_address.with(Protocol::P2p(this.local_peer_id.into()))) + }; + + // Ensure that an external address with a different peer ID does not have + // side effects of evicting other external addresses via `ExternalAddressExpired`. + if let Some(observed_address) = observed_address { + let (is_new, expired_address) = + this.is_new_external_address(&observed_address, peer); + + if let Some(expired_address) = expired_address { + log::trace!( + target: LOG_TARGET, + "Removing expired external address expired={expired_address} is_new={is_new} observed={observed_address}", + ); + + this.pending_events.push_back(DiscoveryEvent::ExternalAddressExpired { + address: expired_address, + }); + } - if is_new { - this.pending_events.push_back(DiscoveryEvent::ExternalAddressDiscovered { - address: observed_address.clone(), - }); + if is_new { + this.pending_events.push_back(DiscoveryEvent::ExternalAddressDiscovered { + address: observed_address.clone(), + }); + } } return Poll::Ready(Some(DiscoveryEvent::Identified { diff --git a/substrate/client/network/src/litep2p/mod.rs b/substrate/client/network/src/litep2p/mod.rs index df4244890f96..87b992423674 100644 --- a/substrate/client/network/src/litep2p/mod.rs +++ b/substrate/client/network/src/litep2p/mod.rs @@ -540,6 +540,7 @@ impl NetworkBackend for Litep2pNetworkBac let listen_addresses = Arc::new(Default::default()); let (discovery, ping_config, identify_config, kademlia_config, maybe_mdns_config) = Discovery::new( + local_peer_id, &network_config, params.genesis_hash, params.fork_id.as_deref(), From 6c8a347a8fe77c6d3dcd951fd585618083cf149e Mon Sep 17 00:00:00 2001 From: Andrei Eres Date: Thu, 7 Nov 2024 12:48:13 +0100 Subject: [PATCH 057/166] PVF: drop backing jobs if it is too late (#5616) Fixes https://github.com/paritytech/polkadot-sdk/issues/5530 This PR introduces the removal of backing jobs that have been back pressured for longer than `allowedAncestryLen`, as these candidates are no longer viable. It is reasonable to expect a result for a backing job execution within `allowedAncestryLen` blocks. Therefore, we set the job TTL as a relay block number and synchronize the validation host by sending activated leaves. --------- Co-authored-by: Andrei Sandu <54316454+sandreim@users.noreply.github.com> Co-authored-by: Branislav Kontur --- Cargo.lock | 2 +- polkadot/node/core/backing/src/lib.rs | 5 +- polkadot/node/core/backing/src/tests/mod.rs | 20 +- .../src/tests/prospective_parachains.rs | 2 +- .../node/core/candidate-validation/src/lib.rs | 106 ++++++- .../core/candidate-validation/src/tests.rs | 54 +++- polkadot/node/core/pvf/Cargo.toml | 1 + polkadot/node/core/pvf/src/error.rs | 5 + polkadot/node/core/pvf/src/execute/queue.rs | 277 ++++++++++++++---- polkadot/node/core/pvf/src/host.rs | 55 +++- polkadot/node/core/pvf/src/priority.rs | 4 +- polkadot/node/core/pvf/tests/it/adder.rs | 5 + polkadot/node/core/pvf/tests/it/main.rs | 47 ++- polkadot/node/core/pvf/tests/it/process.rs | 5 + .../node/overseer/examples/minimal-example.rs | 2 +- polkadot/node/overseer/src/lib.rs | 1 + polkadot/node/overseer/src/tests.rs | 4 +- polkadot/node/subsystem-types/Cargo.toml | 1 - polkadot/node/subsystem-types/src/messages.rs | 21 +- prdoc/pr_5616.prdoc | 25 ++ 20 files changed, 513 insertions(+), 129 deletions(-) create mode 100644 prdoc/pr_5616.prdoc diff --git a/Cargo.lock b/Cargo.lock index 5f81f77991a7..1036e4016746 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14697,6 +14697,7 @@ dependencies = [ "polkadot-node-metrics", "polkadot-node-primitives", "polkadot-node-subsystem", + "polkadot-node-subsystem-test-helpers", "polkadot-parachain-primitives", "polkadot-primitives", "procfs", @@ -14960,7 +14961,6 @@ dependencies = [ "sp-blockchain", "sp-consensus-babe", "sp-runtime 31.0.1", - "strum 0.26.3", "substrate-prometheus-endpoint", "thiserror", ] diff --git a/polkadot/node/core/backing/src/lib.rs b/polkadot/node/core/backing/src/lib.rs index b5362d32ad88..30121418a2fd 100644 --- a/polkadot/node/core/backing/src/lib.rs +++ b/polkadot/node/core/backing/src/lib.rs @@ -632,6 +632,7 @@ async fn request_candidate_validation( ) -> Result { let (tx, rx) = oneshot::channel(); let is_system = candidate_receipt.descriptor.para_id().is_system(); + let relay_parent = candidate_receipt.descriptor.relay_parent(); sender .send_message(CandidateValidationMessage::ValidateFromExhaustive { @@ -641,9 +642,9 @@ async fn request_candidate_validation( pov, executor_params, exec_kind: if is_system { - PvfExecKind::BackingSystemParas + PvfExecKind::BackingSystemParas(relay_parent) } else { - PvfExecKind::Backing + PvfExecKind::Backing(relay_parent) }, response_sender: tx, }) diff --git a/polkadot/node/core/backing/src/tests/mod.rs b/polkadot/node/core/backing/src/tests/mod.rs index dbb974a634fe..97e25c04282c 100644 --- a/polkadot/node/core/backing/src/tests/mod.rs +++ b/polkadot/node/core/backing/src/tests/mod.rs @@ -435,7 +435,7 @@ async fn assert_validate_from_exhaustive( ) if validation_data == *assert_pvd && validation_code == *assert_validation_code && *pov == *assert_pov && candidate_receipt.descriptor == assert_candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_receipt.commitments_hash == assert_candidate.commitments.hash() => { response_sender.send(Ok(ValidationResult::Valid( @@ -652,7 +652,7 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { ) if validation_data == pvd_ab && validation_code == validation_code_ab && *pov == pov_ab && candidate_receipt.descriptor == candidate_a.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_receipt.commitments_hash == candidate_a_commitments_hash => { response_sender.send(Ok( @@ -1288,7 +1288,7 @@ fn backing_works_while_validation_ongoing() { ) if validation_data == pvd_abc && validation_code == validation_code_abc && *pov == pov_abc && candidate_receipt.descriptor == candidate_a.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_a_commitments_hash == candidate_receipt.commitments_hash => { // we never validate the candidate. our local node @@ -1455,7 +1455,7 @@ fn backing_misbehavior_works() { ) if validation_data == pvd_a && validation_code == validation_code_a && *pov == pov_a && candidate_receipt.descriptor == candidate_a.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_a_commitments_hash == candidate_receipt.commitments_hash => { response_sender.send(Ok( @@ -1622,7 +1622,7 @@ fn backing_dont_second_invalid() { ) if validation_data == pvd_a && validation_code == validation_code_a && *pov == pov_block_a && candidate_receipt.descriptor == candidate_a.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_a.commitments.hash() == candidate_receipt.commitments_hash => { response_sender.send(Ok(ValidationResult::Invalid(InvalidCandidate::BadReturn))).unwrap(); @@ -1662,7 +1662,7 @@ fn backing_dont_second_invalid() { ) if validation_data == pvd_b && validation_code == validation_code_b && *pov == pov_block_b && candidate_receipt.descriptor == candidate_b.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_b.commitments.hash() == candidate_receipt.commitments_hash => { response_sender.send(Ok( @@ -1789,7 +1789,7 @@ fn backing_second_after_first_fails_works() { ) if validation_data == pvd_a && validation_code == validation_code_a && *pov == pov_a && candidate_receipt.descriptor == candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate.commitments.hash() == candidate_receipt.commitments_hash => { response_sender.send(Ok(ValidationResult::Invalid(InvalidCandidate::BadReturn))).unwrap(); @@ -1933,7 +1933,7 @@ fn backing_works_after_failed_validation() { ) if validation_data == pvd_a && validation_code == validation_code_a && *pov == pov_a && candidate_receipt.descriptor == candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate.commitments.hash() == candidate_receipt.commitments_hash => { response_sender.send(Err(ValidationFailed("Internal test error".into()))).unwrap(); @@ -2212,7 +2212,7 @@ fn retry_works() { ) if validation_data == pvd_a && validation_code == validation_code_a && *pov == pov_a && candidate_receipt.descriptor == candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate.commitments.hash() == candidate_receipt.commitments_hash ); virtual_overseer @@ -2754,7 +2754,7 @@ fn validator_ignores_statements_from_disabled_validators() { ) if validation_data == pvd && validation_code == expected_validation_code && *pov == expected_pov && candidate_receipt.descriptor == candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate_commitments_hash == candidate_receipt.commitments_hash => { response_sender.send(Ok( diff --git a/polkadot/node/core/backing/src/tests/prospective_parachains.rs b/polkadot/node/core/backing/src/tests/prospective_parachains.rs index caddd2408057..db5409ee4bd5 100644 --- a/polkadot/node/core/backing/src/tests/prospective_parachains.rs +++ b/polkadot/node/core/backing/src/tests/prospective_parachains.rs @@ -276,7 +276,7 @@ async fn assert_validate_seconded_candidate( &validation_code == assert_validation_code && &*pov == assert_pov && candidate_receipt.descriptor == candidate.descriptor && - exec_kind == PvfExecKind::BackingSystemParas && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && candidate.commitments.hash() == candidate_receipt.commitments_hash => { response_sender.send(Ok(ValidationResult::Valid( diff --git a/polkadot/node/core/candidate-validation/src/lib.rs b/polkadot/node/core/candidate-validation/src/lib.rs index 1e732e2f1f03..25614349486e 100644 --- a/polkadot/node/core/candidate-validation/src/lib.rs +++ b/polkadot/node/core/candidate-validation/src/lib.rs @@ -31,13 +31,16 @@ use polkadot_node_primitives::{InvalidCandidate, PoV, ValidationResult}; use polkadot_node_subsystem::{ errors::RuntimeApiError, messages::{ - CandidateValidationMessage, PreCheckOutcome, PvfExecKind, RuntimeApiMessage, - RuntimeApiRequest, ValidationFailed, + CandidateValidationMessage, ChainApiMessage, PreCheckOutcome, PvfExecKind, + RuntimeApiMessage, RuntimeApiRequest, ValidationFailed, }, overseer, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError, SubsystemResult, SubsystemSender, }; -use polkadot_node_subsystem_util::{self as util, runtime::ClaimQueueSnapshot}; +use polkadot_node_subsystem_util::{ + self as util, + runtime::{prospective_parachains_mode, ClaimQueueSnapshot, ProspectiveParachainsMode}, +}; use polkadot_overseer::ActiveLeavesUpdate; use polkadot_parachain_primitives::primitives::ValidationResult as WasmValidationResult; use polkadot_primitives::{ @@ -279,6 +282,7 @@ async fn run( comm = ctx.recv().fuse() => { match comm { Ok(FromOrchestra::Signal(OverseerSignal::ActiveLeaves(update))) => { + update_active_leaves(ctx.sender(), validation_host.clone(), update.clone()).await; maybe_prepare_validation(ctx.sender(), keystore.clone(), validation_host.clone(), update, &mut prepare_state).await; }, Ok(FromOrchestra::Signal(OverseerSignal::BlockFinalized(..))) => {}, @@ -551,6 +555,66 @@ where Some(processed_code_hashes) } +async fn update_active_leaves( + sender: &mut Sender, + mut validation_backend: impl ValidationBackend, + update: ActiveLeavesUpdate, +) where + Sender: SubsystemSender + SubsystemSender, +{ + let ancestors = get_block_ancestors(sender, update.activated.as_ref().map(|x| x.hash)).await; + if let Err(err) = validation_backend.update_active_leaves(update, ancestors).await { + gum::warn!( + target: LOG_TARGET, + ?err, + "cannot update active leaves in validation backend", + ); + }; +} + +async fn get_allowed_ancestry_len(sender: &mut Sender, relay_parent: Hash) -> Option +where + Sender: SubsystemSender + SubsystemSender, +{ + match prospective_parachains_mode(sender, relay_parent).await { + Ok(ProspectiveParachainsMode::Enabled { allowed_ancestry_len, .. }) => + Some(allowed_ancestry_len), + res => { + gum::warn!(target: LOG_TARGET, ?res, "async backing is disabled"); + None + }, + } +} + +async fn get_block_ancestors( + sender: &mut Sender, + maybe_relay_parent: Option, +) -> Vec +where + Sender: SubsystemSender + SubsystemSender, +{ + let Some(relay_parent) = maybe_relay_parent else { return vec![] }; + let Some(allowed_ancestry_len) = get_allowed_ancestry_len(sender, relay_parent).await else { + return vec![] + }; + + let (tx, rx) = oneshot::channel(); + sender + .send_message(ChainApiMessage::Ancestors { + hash: relay_parent, + k: allowed_ancestry_len, + response_channel: tx, + }) + .await; + match rx.await { + Ok(Ok(x)) => x, + res => { + gum::warn!(target: LOG_TARGET, ?res, "cannot request ancestors"); + vec![] + }, + } +} + struct RuntimeRequestFailed; async fn runtime_api_request( @@ -698,7 +762,7 @@ async fn validate_candidate_exhaustive( // We only check the session index for backing. match (exec_kind, candidate_receipt.descriptor.session_index()) { - (PvfExecKind::Backing | PvfExecKind::BackingSystemParas, Some(session_index)) => { + (PvfExecKind::Backing(_) | PvfExecKind::BackingSystemParas(_), Some(session_index)) => { let Some(expected_session_index) = maybe_expected_session_index else { let error = "cannot fetch session index from the runtime"; gum::warn!( @@ -731,7 +795,7 @@ async fn validate_candidate_exhaustive( let result = match exec_kind { // Retry is disabled to reduce the chance of nondeterministic blocks getting backed and // honest backers getting slashed. - PvfExecKind::Backing | PvfExecKind::BackingSystemParas => { + PvfExecKind::Backing(_) | PvfExecKind::BackingSystemParas(_) => { let prep_timeout = pvf_prep_timeout(&executor_params, PvfPrepKind::Prepare); let exec_timeout = pvf_exec_timeout(&executor_params, exec_kind.into()); let pvf = PvfPrepData::from_code( @@ -809,6 +873,15 @@ async fn validate_candidate_exhaustive( ); Err(ValidationFailed(e.to_string())) }, + Err(e @ ValidationError::ExecutionDeadline) => { + gum::warn!( + target: LOG_TARGET, + ?para_id, + ?e, + "Job assigned too late, execution queue probably overloaded", + ); + Err(ValidationFailed(e.to_string())) + }, Ok(res) => if res.head_data.hash() != candidate_receipt.descriptor.para_head() { gum::info!(target: LOG_TARGET, ?para_id, "Invalid candidate (para_head)"); @@ -846,7 +919,7 @@ async fn validate_candidate_exhaustive( // descriptor core index. ( Some(_core_index), - PvfExecKind::Backing | PvfExecKind::BackingSystemParas, + PvfExecKind::Backing(_) | PvfExecKind::BackingSystemParas(_), ) => { let Some(claim_queue) = maybe_claim_queue else { let error = "cannot fetch the claim queue from the runtime"; @@ -994,7 +1067,12 @@ trait ValidationBackend { retry_immediately = true; }, - Ok(_) | Err(ValidationError::Invalid(_) | ValidationError::Preparation(_)) => break, + Ok(_) | + Err( + ValidationError::Invalid(_) | + ValidationError::Preparation(_) | + ValidationError::ExecutionDeadline, + ) => break, } // If we got a possibly transient error, retry once after a brief delay, on the @@ -1035,6 +1113,12 @@ trait ValidationBackend { async fn precheck_pvf(&mut self, pvf: PvfPrepData) -> Result<(), PrepareError>; async fn heads_up(&mut self, active_pvfs: Vec) -> Result<(), String>; + + async fn update_active_leaves( + &mut self, + update: ActiveLeavesUpdate, + ancestors: Vec, + ) -> Result<(), String>; } #[async_trait] @@ -1085,6 +1169,14 @@ impl ValidationBackend for ValidationHost { async fn heads_up(&mut self, active_pvfs: Vec) -> Result<(), String> { self.heads_up(active_pvfs).await } + + async fn update_active_leaves( + &mut self, + update: ActiveLeavesUpdate, + ancestors: Vec, + ) -> Result<(), String> { + self.update_active_leaves(update, ancestors).await + } } /// Does basic checks of a candidate. Provide the encoded PoV-block. Returns `Ok` if basic checks diff --git a/polkadot/node/core/candidate-validation/src/tests.rs b/polkadot/node/core/candidate-validation/src/tests.rs index 391247858ed6..98e34a1cb4c1 100644 --- a/polkadot/node/core/candidate-validation/src/tests.rs +++ b/polkadot/node/core/candidate-validation/src/tests.rs @@ -473,6 +473,14 @@ impl ValidationBackend for MockValidateCandidateBackend { async fn heads_up(&mut self, _active_pvfs: Vec) -> Result<(), String> { unreachable!() } + + async fn update_active_leaves( + &mut self, + _update: ActiveLeavesUpdate, + _ancestors: Vec, + ) -> Result<(), String> { + unreachable!() + } } #[test] @@ -531,7 +539,7 @@ fn session_index_checked_only_in_backing() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )) @@ -670,7 +678,7 @@ fn candidate_validation_ok_is_ok(#[case] v2_descriptor: bool) { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Some(ClaimQueueSnapshot(cq)), )) @@ -748,7 +756,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )) @@ -764,7 +772,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::BackingSystemParas, + PvfExecKind::BackingSystemParas(dummy_hash()), &Default::default(), Default::default(), )) @@ -782,7 +790,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Some(Default::default()), )) @@ -797,7 +805,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::BackingSystemParas, + PvfExecKind::BackingSystemParas(dummy_hash()), &Default::default(), Some(Default::default()), )) @@ -866,7 +874,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Some(ClaimQueueSnapshot(cq.clone())), )) @@ -889,7 +897,7 @@ fn invalid_session_or_core_index() { candidate_receipt.clone(), Arc::new(pov.clone()), ExecutorParams::default(), - PvfExecKind::BackingSystemParas, + PvfExecKind::BackingSystemParas(dummy_hash()), &Default::default(), Some(ClaimQueueSnapshot(cq)), )) @@ -944,7 +952,7 @@ fn candidate_validation_bad_return_is_invalid() { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )) @@ -1102,7 +1110,7 @@ fn candidate_validation_retry_internal_errors() { #[test] fn candidate_validation_dont_retry_internal_errors() { let v = candidate_validation_retry_on_error_helper( - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), vec![ Err(InternalValidationError::HostCommunication("foo".into()).into()), // Throw an AWD error, we should still retry again. @@ -1136,7 +1144,7 @@ fn candidate_validation_retry_panic_errors() { #[test] fn candidate_validation_dont_retry_panic_errors() { let v = candidate_validation_retry_on_error_helper( - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), vec![ Err(ValidationError::PossiblyInvalid(PossiblyInvalidError::JobError("foo".into()))), // Throw an AWD error, we should still retry again. @@ -1233,7 +1241,7 @@ fn candidate_validation_timeout_is_internal_error() { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )); @@ -1282,7 +1290,7 @@ fn candidate_validation_commitment_hash_mismatch_is_invalid() { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )) @@ -1337,7 +1345,7 @@ fn candidate_validation_code_mismatch_is_invalid() { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )) @@ -1397,7 +1405,7 @@ fn compressed_code_works() { candidate_receipt, Arc::new(pov), ExecutorParams::default(), - PvfExecKind::Backing, + PvfExecKind::Backing(dummy_hash()), &Default::default(), Default::default(), )); @@ -1436,6 +1444,14 @@ impl ValidationBackend for MockPreCheckBackend { async fn heads_up(&mut self, _active_pvfs: Vec) -> Result<(), String> { unreachable!() } + + async fn update_active_leaves( + &mut self, + _update: ActiveLeavesUpdate, + _ancestors: Vec, + ) -> Result<(), String> { + unreachable!() + } } #[test] @@ -1592,6 +1608,14 @@ impl ValidationBackend for MockHeadsUp { let _ = self.heads_up_call_count.fetch_add(1, Ordering::SeqCst); Ok(()) } + + async fn update_active_leaves( + &mut self, + _update: ActiveLeavesUpdate, + _ancestors: Vec, + ) -> Result<(), String> { + unreachable!() + } } fn alice_keystore() -> KeystorePtr { diff --git a/polkadot/node/core/pvf/Cargo.toml b/polkadot/node/core/pvf/Cargo.toml index 13fcdc69a99a..a9f97c308f26 100644 --- a/polkadot/node/core/pvf/Cargo.toml +++ b/polkadot/node/core/pvf/Cargo.toml @@ -52,6 +52,7 @@ criterion = { features = [ hex-literal = { workspace = true, default-features = true } polkadot-node-core-pvf-common = { features = ["test-utils"], workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } # For benches and integration tests, depend on ourselves with the test-utils # feature. polkadot-node-core-pvf = { features = ["test-utils"], workspace = true, default-features = true } diff --git a/polkadot/node/core/pvf/src/error.rs b/polkadot/node/core/pvf/src/error.rs index a0634106052d..e68ba595ef5a 100644 --- a/polkadot/node/core/pvf/src/error.rs +++ b/polkadot/node/core/pvf/src/error.rs @@ -39,6 +39,11 @@ pub enum ValidationError { /// Preparation or execution issue caused by an internal condition. Should not vote against. #[error("candidate validation: internal: {0}")] Internal(#[from] InternalValidationError), + /// The execution deadline of allowed_ancestry_len + 1 has been reached. Jobs like backing have + /// a limited time to execute. Once the deadline is reached, the current candidate cannot be + /// backed, regardless of its validity. + #[error("candidate validation: execution deadline has been reached.")] + ExecutionDeadline, } /// A description of an error raised during executing a PVF and can be attributed to the combination diff --git a/polkadot/node/core/pvf/src/execute/queue.rs b/polkadot/node/core/pvf/src/execute/queue.rs index 2ac5116912eb..6d27ab0261d9 100644 --- a/polkadot/node/core/pvf/src/execute/queue.rs +++ b/polkadot/node/core/pvf/src/execute/queue.rs @@ -35,8 +35,8 @@ use polkadot_node_core_pvf_common::{ SecurityStatus, }; use polkadot_node_primitives::PoV; -use polkadot_node_subsystem::messages::PvfExecKind; -use polkadot_primitives::{ExecutorParams, ExecutorParamsHash, PersistedValidationData}; +use polkadot_node_subsystem::{messages::PvfExecKind, ActiveLeavesUpdate}; +use polkadot_primitives::{ExecutorParams, ExecutorParamsHash, Hash, PersistedValidationData}; use slotmap::HopSlotMap; use std::{ collections::{HashMap, VecDeque}, @@ -45,7 +45,7 @@ use std::{ sync::Arc, time::{Duration, Instant}, }; -use strum::IntoEnumIterator; +use strum::{EnumIter, IntoEnumIterator}; /// The amount of time a job for which the queue does not have a compatible worker may wait in the /// queue. After that time passes, the queue will kill the first worker which becomes idle to @@ -58,6 +58,7 @@ slotmap::new_key_type! { struct Worker; } #[derive(Debug)] pub enum ToQueue { + UpdateActiveLeaves { update: ActiveLeavesUpdate, ancestors: Vec }, Enqueue { artifact: ArtifactPathId, pending_execution_request: PendingExecutionRequest }, } @@ -82,6 +83,7 @@ pub struct PendingExecutionRequest { struct ExecuteJob { artifact: ArtifactPathId, exec_timeout: Duration, + exec_kind: PvfExecKind, pvd: Arc, pov: Arc, executor_params: ExecutorParams, @@ -172,6 +174,9 @@ struct Queue { unscheduled: Unscheduled, workers: Workers, mux: Mux, + + /// Active leaves and their ancestors to check the viability of backing jobs. + active_leaves: HashMap>, } impl Queue { @@ -202,6 +207,7 @@ impl Queue { spawn_inflight: 0, capacity: worker_capacity, }, + active_leaves: Default::default(), } } @@ -278,15 +284,74 @@ impl Queue { } let job = queue.remove(job_index).expect("Job is just checked to be in queue; qed"); + let exec_kind = job.exec_kind; if let Some(worker) = worker { assign(self, worker, job); } else { spawn_extra_worker(self, job); } - self.metrics.on_execute_kind(priority); + self.metrics.on_execute_kind(exec_kind); self.unscheduled.mark_scheduled(priority); } + + fn update_active_leaves(&mut self, update: ActiveLeavesUpdate, ancestors: Vec) { + self.prune_deactivated_leaves(&update); + self.insert_active_leaf(update, ancestors); + self.prune_old_jobs(); + } + + fn prune_deactivated_leaves(&mut self, update: &ActiveLeavesUpdate) { + for hash in &update.deactivated { + let _ = self.active_leaves.remove(&hash); + } + + gum::debug!(target: LOG_TARGET, size = ?self.active_leaves.len(), "Active leaves pruned"); + } + + fn insert_active_leaf(&mut self, update: ActiveLeavesUpdate, ancestors: Vec) { + let Some(leaf) = update.activated else { return }; + let _ = self.active_leaves.insert(leaf.hash, ancestors); + } + + fn prune_old_jobs(&mut self) { + for &priority in &[Priority::Backing, Priority::BackingSystemParas] { + let Some(queue) = self.unscheduled.get_mut(priority) else { continue }; + let to_remove: Vec = queue + .iter() + .enumerate() + .filter_map(|(index, job)| { + let relay_parent = match job.exec_kind { + PvfExecKind::Backing(x) | PvfExecKind::BackingSystemParas(x) => x, + _ => return None, + }; + let in_active_fork = self.active_leaves.iter().any(|(hash, ancestors)| { + *hash == relay_parent || ancestors.contains(&relay_parent) + }); + if in_active_fork { + None + } else { + Some(index) + } + }) + .collect(); + + for &index in to_remove.iter().rev() { + if index > queue.len() { + continue + } + + let Some(job) = queue.remove(index) else { continue }; + let _ = job.result_tx.send(Err(ValidationError::ExecutionDeadline)); + gum::warn!( + target: LOG_TARGET, + ?priority, + exec_kind = ?job.exec_kind, + "Job exceeded its deadline and was dropped without execution", + ); + } + } + } } async fn purge_dead(metrics: &Metrics, workers: &mut Workers) { @@ -305,27 +370,40 @@ async fn purge_dead(metrics: &Metrics, workers: &mut Workers) { } fn handle_to_queue(queue: &mut Queue, to_queue: ToQueue) { - let ToQueue::Enqueue { artifact, pending_execution_request } = to_queue; - let PendingExecutionRequest { exec_timeout, pvd, pov, executor_params, result_tx, exec_kind } = - pending_execution_request; - gum::debug!( - target: LOG_TARGET, - validation_code_hash = ?artifact.id.code_hash, - "enqueueing an artifact for execution", - ); - queue.metrics.observe_pov_size(pov.block_data.0.len(), true); - queue.metrics.execute_enqueued(); - let job = ExecuteJob { - artifact, - exec_timeout, - pvd, - pov, - executor_params, - result_tx, - waiting_since: Instant::now(), - }; - queue.unscheduled.add(job, exec_kind); - queue.try_assign_next_job(None); + match to_queue { + ToQueue::UpdateActiveLeaves { update, ancestors } => { + queue.update_active_leaves(update, ancestors); + }, + ToQueue::Enqueue { artifact, pending_execution_request } => { + let PendingExecutionRequest { + exec_timeout, + pvd, + pov, + executor_params, + result_tx, + exec_kind, + } = pending_execution_request; + gum::debug!( + target: LOG_TARGET, + validation_code_hash = ?artifact.id.code_hash, + "enqueueing an artifact for execution", + ); + queue.metrics.observe_pov_size(pov.block_data.0.len(), true); + queue.metrics.execute_enqueued(); + let job = ExecuteJob { + artifact, + exec_timeout, + exec_kind, + pvd, + pov, + executor_params, + result_tx, + waiting_since: Instant::now(), + }; + queue.unscheduled.add(job, exec_kind.into()); + queue.try_assign_next_job(None); + }, + } } async fn handle_mux(queue: &mut Queue, event: QueueEvent) { @@ -648,9 +726,32 @@ pub fn start( (to_queue_tx, from_queue_rx, run) } +/// Priority of execution jobs based on PvfExecKind. +/// +/// The order is important, because we iterate through the values and assume it is going from higher +/// to lowest priority. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, EnumIter)] +enum Priority { + Dispute, + Approval, + BackingSystemParas, + Backing, +} + +impl From for Priority { + fn from(kind: PvfExecKind) -> Self { + match kind { + PvfExecKind::Dispute => Priority::Dispute, + PvfExecKind::Approval => Priority::Approval, + PvfExecKind::BackingSystemParas(_) => Priority::BackingSystemParas, + PvfExecKind::Backing(_) => Priority::Backing, + } + } +} + struct Unscheduled { - unscheduled: HashMap>, - counter: HashMap, + unscheduled: HashMap>, + counter: HashMap, } impl Unscheduled { @@ -677,34 +778,34 @@ impl Unscheduled { /// approvals could not exceed 24%, even if there are no disputes. /// - We cannot fully prioritize backing system parachains over backing other parachains based /// on the distribution of the original 100%. - const PRIORITY_ALLOCATION_THRESHOLDS: &'static [(PvfExecKind, usize)] = &[ - (PvfExecKind::Dispute, 70), - (PvfExecKind::Approval, 80), - (PvfExecKind::BackingSystemParas, 100), - (PvfExecKind::Backing, 100), + const PRIORITY_ALLOCATION_THRESHOLDS: &'static [(Priority, usize)] = &[ + (Priority::Dispute, 70), + (Priority::Approval, 80), + (Priority::BackingSystemParas, 100), + (Priority::Backing, 100), ]; fn new() -> Self { Self { - unscheduled: PvfExecKind::iter().map(|priority| (priority, VecDeque::new())).collect(), - counter: PvfExecKind::iter().map(|priority| (priority, 0)).collect(), + unscheduled: Priority::iter().map(|priority| (priority, VecDeque::new())).collect(), + counter: Priority::iter().map(|priority| (priority, 0)).collect(), } } - fn select_next_priority(&self) -> PvfExecKind { + fn select_next_priority(&self) -> Priority { gum::debug!( target: LOG_TARGET, - unscheduled = ?self.unscheduled.iter().map(|(p, q)| (*p, q.len())).collect::>(), + unscheduled = ?self.unscheduled.iter().map(|(p, q)| (*p, q.len())).collect::>(), counter = ?self.counter, "Selecting next execution priority...", ); - let priority = PvfExecKind::iter() + let priority = Priority::iter() .find(|priority| self.has_pending(priority) && !self.has_reached_threshold(priority)) .unwrap_or_else(|| { - PvfExecKind::iter() + Priority::iter() .find(|priority| self.has_pending(priority)) - .unwrap_or(PvfExecKind::Backing) + .unwrap_or(Priority::Backing) }); gum::debug!( @@ -716,19 +817,19 @@ impl Unscheduled { priority } - fn get_mut(&mut self, priority: PvfExecKind) -> Option<&mut VecDeque> { + fn get_mut(&mut self, priority: Priority) -> Option<&mut VecDeque> { self.unscheduled.get_mut(&priority) } - fn add(&mut self, job: ExecuteJob, priority: PvfExecKind) { + fn add(&mut self, job: ExecuteJob, priority: Priority) { self.unscheduled.entry(priority).or_default().push_back(job); } - fn has_pending(&self, priority: &PvfExecKind) -> bool { + fn has_pending(&self, priority: &Priority) -> bool { !self.unscheduled.get(priority).unwrap_or(&VecDeque::new()).is_empty() } - fn priority_allocation_threshold(priority: &PvfExecKind) -> Option { + fn priority_allocation_threshold(priority: &Priority) -> Option { Self::PRIORITY_ALLOCATION_THRESHOLDS.iter().find_map(|&(p, value)| { if p == *priority { Some(value) @@ -740,7 +841,7 @@ impl Unscheduled { /// Checks if a given priority has reached its allocated threshold /// The thresholds are defined in `PRIORITY_ALLOCATION_THRESHOLDS`. - fn has_reached_threshold(&self, priority: &PvfExecKind) -> bool { + fn has_reached_threshold(&self, priority: &Priority) -> bool { let Some(threshold) = Self::priority_allocation_threshold(priority) else { return false }; let Some(count) = self.counter.get(&priority) else { return false }; // Every time we iterate by lower level priorities @@ -769,22 +870,28 @@ impl Unscheduled { has_reached_threshold } - fn mark_scheduled(&mut self, priority: PvfExecKind) { + fn mark_scheduled(&mut self, priority: Priority) { *self.counter.entry(priority).or_default() += 1; if self.counter.values().sum::() >= Self::SCHEDULING_WINDOW_SIZE { self.reset_counter(); } + gum::debug!( + target: LOG_TARGET, + ?priority, + "Job marked as scheduled", + ); } fn reset_counter(&mut self) { - self.counter = PvfExecKind::iter().map(|kind| (kind, 0)).collect(); + self.counter = Priority::iter().map(|kind| (kind, 0)).collect(); } } #[cfg(test)] mod tests { use polkadot_node_primitives::BlockData; + use polkadot_node_subsystem_test_helpers::mock::new_leaf; use sp_core::H256; use super::*; @@ -803,6 +910,7 @@ mod tests { ExecuteJob { artifact: ArtifactPathId { id: artifact_id(0), path: PathBuf::new() }, exec_timeout: Duration::from_secs(10), + exec_kind: PvfExecKind::Approval, pvd, pov, executor_params: ExecutorParams::default(), @@ -815,11 +923,11 @@ mod tests { fn test_unscheduled_add() { let mut unscheduled = Unscheduled::new(); - PvfExecKind::iter().for_each(|priority| { + Priority::iter().for_each(|priority| { unscheduled.add(create_execution_job(), priority); }); - PvfExecKind::iter().for_each(|priority| { + Priority::iter().for_each(|priority| { let queue = unscheduled.unscheduled.get(&priority).unwrap(); assert_eq!(queue.len(), 1); }); @@ -827,7 +935,7 @@ mod tests { #[test] fn test_unscheduled_priority_distribution() { - use PvfExecKind::*; + use Priority::*; let mut priorities = vec![]; @@ -852,7 +960,7 @@ mod tests { #[test] fn test_unscheduled_priority_distribution_without_backing_system_paras() { - use PvfExecKind::*; + use Priority::*; let mut priorities = vec![]; @@ -876,7 +984,7 @@ mod tests { #[test] fn test_unscheduled_priority_distribution_without_disputes() { - use PvfExecKind::*; + use Priority::*; let mut priorities = vec![]; @@ -900,7 +1008,7 @@ mod tests { #[test] fn test_unscheduled_priority_distribution_without_disputes_and_only_one_backing() { - use PvfExecKind::*; + use Priority::*; let mut priorities = vec![]; @@ -922,7 +1030,7 @@ mod tests { #[test] fn test_unscheduled_does_not_postpone_backing() { - use PvfExecKind::*; + use Priority::*; let mut priorities = vec![]; @@ -940,4 +1048,67 @@ mod tests { assert_eq!(&priorities[..4], &[Approval, Backing, Approval, Approval]); } + + #[tokio::test] + async fn test_prunes_old_jobs_on_active_leaves_update() { + // Set up a queue, but without a real worker, we won't execute any jobs. + let (_, to_queue_rx) = mpsc::channel(1); + let (from_queue_tx, _) = mpsc::unbounded(); + let mut queue = Queue::new( + Metrics::default(), + PathBuf::new(), + PathBuf::new(), + 1, + Duration::from_secs(1), + None, + SecurityStatus::default(), + to_queue_rx, + from_queue_tx, + ); + let old_relay_parent = Hash::random(); + let relevant_relay_parent = Hash::random(); + + assert_eq!(queue.unscheduled.unscheduled.values().map(|x| x.len()).sum::(), 0); + let mut result_rxs = vec![]; + let (result_tx, _result_rx) = oneshot::channel(); + let relevant_job = ExecuteJob { + artifact: ArtifactPathId { id: artifact_id(0), path: PathBuf::new() }, + exec_timeout: Duration::from_secs(1), + exec_kind: PvfExecKind::Backing(relevant_relay_parent), + pvd: Arc::new(PersistedValidationData::default()), + pov: Arc::new(PoV { block_data: BlockData(Vec::new()) }), + executor_params: ExecutorParams::default(), + result_tx, + waiting_since: Instant::now(), + }; + queue.unscheduled.add(relevant_job, Priority::Backing); + for _ in 0..10 { + let (result_tx, result_rx) = oneshot::channel(); + let expired_job = ExecuteJob { + artifact: ArtifactPathId { id: artifact_id(0), path: PathBuf::new() }, + exec_timeout: Duration::from_secs(1), + exec_kind: PvfExecKind::Backing(old_relay_parent), + pvd: Arc::new(PersistedValidationData::default()), + pov: Arc::new(PoV { block_data: BlockData(Vec::new()) }), + executor_params: ExecutorParams::default(), + result_tx, + waiting_since: Instant::now(), + }; + queue.unscheduled.add(expired_job, Priority::Backing); + result_rxs.push(result_rx); + } + assert_eq!(queue.unscheduled.unscheduled.values().map(|x| x.len()).sum::(), 11); + + // Add an active leaf + queue.update_active_leaves( + ActiveLeavesUpdate::start_work(new_leaf(Hash::random(), 1)), + vec![relevant_relay_parent], + ); + + // It prunes all old jobs and drops them with an `ExecutionDeadline` error. + for rx in result_rxs { + assert!(matches!(rx.await, Ok(Err(ValidationError::ExecutionDeadline)))); + } + assert_eq!(queue.unscheduled.unscheduled.values().map(|x| x.len()).sum::(), 1); + } } diff --git a/polkadot/node/core/pvf/src/host.rs b/polkadot/node/core/pvf/src/host.rs index 37cd6fcbf74a..8252904095b3 100644 --- a/polkadot/node/core/pvf/src/host.rs +++ b/polkadot/node/core/pvf/src/host.rs @@ -37,9 +37,11 @@ use polkadot_node_core_pvf_common::{ pvf::PvfPrepData, }; use polkadot_node_primitives::PoV; -use polkadot_node_subsystem::{messages::PvfExecKind, SubsystemError, SubsystemResult}; +use polkadot_node_subsystem::{ + messages::PvfExecKind, ActiveLeavesUpdate, SubsystemError, SubsystemResult, +}; use polkadot_parachain_primitives::primitives::ValidationResult; -use polkadot_primitives::PersistedValidationData; +use polkadot_primitives::{Hash, PersistedValidationData}; use std::{ collections::HashMap, path::PathBuf, @@ -143,12 +145,27 @@ impl ValidationHost { .await .map_err(|_| "the inner loop hung up".to_string()) } + + /// Sends a signal to the validation host requesting to update best block. + /// + /// Returns an error if the request cannot be sent to the validation host, i.e. if it shut down. + pub async fn update_active_leaves( + &mut self, + update: ActiveLeavesUpdate, + ancestors: Vec, + ) -> Result<(), String> { + self.to_host_tx + .send(ToHost::UpdateActiveLeaves { update, ancestors }) + .await + .map_err(|_| "the inner loop hung up".to_string()) + } } enum ToHost { PrecheckPvf { pvf: PvfPrepData, result_tx: PrecheckResultSender }, ExecutePvf(ExecutePvfInputs), HeadsUp { active_pvfs: Vec }, + UpdateActiveLeaves { update: ActiveLeavesUpdate, ancestors: Vec }, } struct ExecutePvfInputs { @@ -488,6 +505,8 @@ async fn handle_to_host( }, ToHost::HeadsUp { active_pvfs } => handle_heads_up(artifacts, prepare_queue, active_pvfs).await?, + ToHost::UpdateActiveLeaves { update, ancestors } => + handle_update_active_leaves(execute_queue, update, ancestors).await?, } Ok(()) @@ -855,6 +874,14 @@ async fn handle_prepare_done( Ok(()) } +async fn handle_update_active_leaves( + execute_queue: &mut mpsc::Sender, + update: ActiveLeavesUpdate, + ancestors: Vec, +) -> Result<(), Fatal> { + send_execute(execute_queue, execute::ToQueue::UpdateActiveLeaves { update, ancestors }).await +} + async fn send_prepare( prepare_queue: &mut mpsc::Sender, to_queue: prepare::ToQueue, @@ -1255,7 +1282,7 @@ pub(crate) mod tests { pvd.clone(), pov1.clone(), Priority::Normal, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1268,7 +1295,7 @@ pub(crate) mod tests { pvd.clone(), pov1, Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1281,7 +1308,7 @@ pub(crate) mod tests { pvd, pov2, Priority::Normal, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1431,7 +1458,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1480,7 +1507,7 @@ pub(crate) mod tests { pvd, pov, Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1591,7 +1618,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1623,7 +1650,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx_2, ) .await @@ -1647,7 +1674,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx_3, ) .await @@ -1706,7 +1733,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await @@ -1738,7 +1765,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx_2, ) .await @@ -1762,7 +1789,7 @@ pub(crate) mod tests { pvd.clone(), pov.clone(), Priority::Critical, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx_3, ) .await @@ -1837,7 +1864,7 @@ pub(crate) mod tests { pvd, pov, Priority::Normal, - PvfExecKind::Backing, + PvfExecKind::Backing(H256::default()), result_tx, ) .await diff --git a/polkadot/node/core/pvf/src/priority.rs b/polkadot/node/core/pvf/src/priority.rs index 7aaeacf36220..5a58fbc8ade3 100644 --- a/polkadot/node/core/pvf/src/priority.rs +++ b/polkadot/node/core/pvf/src/priority.rs @@ -43,8 +43,8 @@ impl From for Priority { match priority { PvfExecKind::Dispute => Priority::Critical, PvfExecKind::Approval => Priority::Critical, - PvfExecKind::BackingSystemParas => Priority::Normal, - PvfExecKind::Backing => Priority::Normal, + PvfExecKind::BackingSystemParas(_) => Priority::Normal, + PvfExecKind::Backing(_) => Priority::Normal, } } } diff --git a/polkadot/node/core/pvf/tests/it/adder.rs b/polkadot/node/core/pvf/tests/it/adder.rs index 1a95a28fe077..924ea7166702 100644 --- a/polkadot/node/core/pvf/tests/it/adder.rs +++ b/polkadot/node/core/pvf/tests/it/adder.rs @@ -46,6 +46,7 @@ async fn execute_good_block_on_parent() { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap(); @@ -82,6 +83,7 @@ async fn execute_good_chain_on_parent() { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap(); @@ -120,6 +122,7 @@ async fn execute_bad_block_on_parent() { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap_err(); @@ -145,6 +148,7 @@ async fn stress_spawn() { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap(); @@ -185,6 +189,7 @@ async fn execute_can_run_serially() { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap(); diff --git a/polkadot/node/core/pvf/tests/it/main.rs b/polkadot/node/core/pvf/tests/it/main.rs index 4cbc6fb04a8e..cfb78fd530d2 100644 --- a/polkadot/node/core/pvf/tests/it/main.rs +++ b/polkadot/node/core/pvf/tests/it/main.rs @@ -28,8 +28,8 @@ use polkadot_node_primitives::{PoV, POV_BOMB_LIMIT, VALIDATION_CODE_BOMB_LIMIT}; use polkadot_node_subsystem::messages::PvfExecKind; use polkadot_parachain_primitives::primitives::{BlockData, ValidationResult}; use polkadot_primitives::{ - ExecutorParam, ExecutorParams, PersistedValidationData, PvfExecKind as RuntimePvfExecKind, - PvfPrepKind, + ExecutorParam, ExecutorParams, Hash, PersistedValidationData, + PvfExecKind as RuntimePvfExecKind, PvfPrepKind, }; use sp_core::H256; @@ -108,6 +108,7 @@ impl TestHost { pvd: PersistedValidationData, pov: PoV, executor_params: ExecutorParams, + relay_parent: Hash, ) -> Result { let (result_tx, result_rx) = futures::channel::oneshot::channel(); @@ -125,7 +126,7 @@ impl TestHost { Arc::new(pvd), Arc::new(pov), polkadot_node_core_pvf::Priority::Normal, - PvfExecKind::Backing, + PvfExecKind::Backing(relay_parent), result_tx, ) .await @@ -171,7 +172,13 @@ async fn execute_job_terminates_on_timeout() { let start = std::time::Instant::now(); let result = host - .validate_candidate(test_parachain_halt::wasm_binary_unwrap(), pvd, pov, Default::default()) + .validate_candidate( + test_parachain_halt::wasm_binary_unwrap(), + pvd, + pov, + Default::default(), + H256::default(), + ) .await; match result { @@ -201,12 +208,14 @@ async fn ensure_parallel_execution() { pvd.clone(), pov.clone(), Default::default(), + H256::default(), ); let execute_pvf_future_2 = host.validate_candidate( test_parachain_halt::wasm_binary_unwrap(), pvd, pov, Default::default(), + H256::default(), ); let start = std::time::Instant::now(); @@ -254,6 +263,7 @@ async fn execute_queue_doesnt_stall_if_workers_died() { pvd.clone(), pov.clone(), Default::default(), + H256::default(), ) })) .await; @@ -303,6 +313,7 @@ async fn execute_queue_doesnt_stall_with_varying_executor_params() { 0 => executor_params_1.clone(), _ => executor_params_2.clone(), }, + H256::default(), ) })) .await; @@ -359,7 +370,13 @@ async fn deleting_prepared_artifact_does_not_dispute() { // Try to validate, artifact should get recreated. let result = host - .validate_candidate(test_parachain_halt::wasm_binary_unwrap(), pvd, pov, Default::default()) + .validate_candidate( + test_parachain_halt::wasm_binary_unwrap(), + pvd, + pov, + Default::default(), + H256::default(), + ) .await; assert_matches!(result, Err(ValidationError::Invalid(InvalidCandidate::HardTimeout))); @@ -410,7 +427,13 @@ async fn corrupted_prepared_artifact_does_not_dispute() { // Try to validate, artifact should get removed because of the corruption. let result = host - .validate_candidate(test_parachain_halt::wasm_binary_unwrap(), pvd, pov, Default::default()) + .validate_candidate( + test_parachain_halt::wasm_binary_unwrap(), + pvd, + pov, + Default::default(), + H256::default(), + ) .await; assert_matches!( @@ -684,7 +707,9 @@ async fn invalid_compressed_code_fails_validation() { let validation_code = sp_maybe_compressed_blob::compress(&raw_code, VALIDATION_CODE_BOMB_LIMIT + 1).unwrap(); - let result = host.validate_candidate(&validation_code, pvd, pov, Default::default()).await; + let result = host + .validate_candidate(&validation_code, pvd, pov, Default::default(), H256::default()) + .await; assert_matches!( result, @@ -708,7 +733,13 @@ async fn invalid_compressed_pov_fails_validation() { let pov = PoV { block_data: BlockData(block_data) }; let result = host - .validate_candidate(test_parachain_halt::wasm_binary_unwrap(), pvd, pov, Default::default()) + .validate_candidate( + test_parachain_halt::wasm_binary_unwrap(), + pvd, + pov, + Default::default(), + H256::default(), + ) .await; assert_matches!( diff --git a/polkadot/node/core/pvf/tests/it/process.rs b/polkadot/node/core/pvf/tests/it/process.rs index b3023c8a45c3..353367b394f3 100644 --- a/polkadot/node/core/pvf/tests/it/process.rs +++ b/polkadot/node/core/pvf/tests/it/process.rs @@ -141,6 +141,7 @@ rusty_fork_test! { pvd, pov, Default::default(), + H256::default(), ) .await .unwrap(); @@ -187,6 +188,7 @@ rusty_fork_test! { pvd, pov, Default::default(), + H256::default(), ), // Send a stop signal to pause the worker. async { @@ -242,6 +244,7 @@ rusty_fork_test! { pvd, pov, Default::default(), + H256::default(), ), // Run a future that kills the job while it's running. async { @@ -301,6 +304,7 @@ rusty_fork_test! { pvd, pov, Default::default(), + H256::default(), ), // Run a future that kills the job while it's running. async { @@ -372,6 +376,7 @@ rusty_fork_test! { pvd, pov, Default::default(), + H256::default(), ), // Run a future that tests the thread count while the worker is running. async { diff --git a/polkadot/node/overseer/examples/minimal-example.rs b/polkadot/node/overseer/examples/minimal-example.rs index e1b2af733b47..f2cf60280b72 100644 --- a/polkadot/node/overseer/examples/minimal-example.rs +++ b/polkadot/node/overseer/examples/minimal-example.rs @@ -83,7 +83,7 @@ impl Subsystem1 { candidate_receipt, pov: PoV { block_data: BlockData(Vec::new()) }.into(), executor_params: Default::default(), - exec_kind: PvfExecKind::Backing, + exec_kind: PvfExecKind::Backing(dummy_hash()), response_sender: tx, }; ctx.send_message(msg).await; diff --git a/polkadot/node/overseer/src/lib.rs b/polkadot/node/overseer/src/lib.rs index 87ef63d8a5d7..3881ddbcc904 100644 --- a/polkadot/node/overseer/src/lib.rs +++ b/polkadot/node/overseer/src/lib.rs @@ -468,6 +468,7 @@ pub async fn forward_events>(client: Arc

, mut hand )] pub struct Overseer { #[subsystem(CandidateValidationMessage, sends: [ + ChainApiMessage, RuntimeApiMessage, ])] candidate_validation: CandidateValidation, diff --git a/polkadot/node/overseer/src/tests.rs b/polkadot/node/overseer/src/tests.rs index c3c47335cd3e..0b9b783ef9b1 100644 --- a/polkadot/node/overseer/src/tests.rs +++ b/polkadot/node/overseer/src/tests.rs @@ -111,7 +111,7 @@ where candidate_receipt, pov: PoV { block_data: BlockData(Vec::new()) }.into(), executor_params: Default::default(), - exec_kind: PvfExecKind::Backing, + exec_kind: PvfExecKind::Backing(dummy_hash()), response_sender: tx, }) .await; @@ -811,7 +811,7 @@ fn test_candidate_validation_msg() -> CandidateValidationMessage { candidate_receipt, pov, executor_params: Default::default(), - exec_kind: PvfExecKind::Backing, + exec_kind: PvfExecKind::Backing(dummy_hash()), response_sender, } } diff --git a/polkadot/node/subsystem-types/Cargo.toml b/polkadot/node/subsystem-types/Cargo.toml index b8bad8f8a295..b5686ec96be1 100644 --- a/polkadot/node/subsystem-types/Cargo.toml +++ b/polkadot/node/subsystem-types/Cargo.toml @@ -32,4 +32,3 @@ prometheus-endpoint = { workspace = true, default-features = true } thiserror = { workspace = true } async-trait = { workspace = true } bitvec = { features = ["alloc"], workspace = true } -strum = { features = ["derive"], workspace = true, default-features = true } diff --git a/polkadot/node/subsystem-types/src/messages.rs b/polkadot/node/subsystem-types/src/messages.rs index ba1ba5755be0..28a3a1ab82ab 100644 --- a/polkadot/node/subsystem-types/src/messages.rs +++ b/polkadot/node/subsystem-types/src/messages.rs @@ -24,7 +24,6 @@ use futures::channel::oneshot; use sc_network::{Multiaddr, ReputationChange}; -use strum::EnumIter; use thiserror::Error; pub use sc_network::IfDisconnected; @@ -189,18 +188,16 @@ pub enum CandidateValidationMessage { /// Extends primitives::PvfExecKind, which is a runtime parameter we don't want to change, /// to separate and prioritize execution jobs by request type. -/// The order is important, because we iterate through the values and assume it is going from higher -/// to lowest priority. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, EnumIter)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PvfExecKind { /// For dispute requests Dispute, /// For approval requests Approval, - /// For backing requests from system parachains. - BackingSystemParas, - /// For backing requests. - Backing, + /// For backing requests from system parachains. With relay parent hash + BackingSystemParas(Hash), + /// For backing requests. With relay parent hash + Backing(Hash), } impl PvfExecKind { @@ -209,8 +206,8 @@ impl PvfExecKind { match *self { Self::Dispute => "dispute", Self::Approval => "approval", - Self::BackingSystemParas => "backing_system_paras", - Self::Backing => "backing", + Self::BackingSystemParas(_) => "backing_system_paras", + Self::Backing(_) => "backing", } } } @@ -220,8 +217,8 @@ impl From for RuntimePvfExecKind { match exec { PvfExecKind::Dispute => RuntimePvfExecKind::Approval, PvfExecKind::Approval => RuntimePvfExecKind::Approval, - PvfExecKind::BackingSystemParas => RuntimePvfExecKind::Backing, - PvfExecKind::Backing => RuntimePvfExecKind::Backing, + PvfExecKind::BackingSystemParas(_) => RuntimePvfExecKind::Backing, + PvfExecKind::Backing(_) => RuntimePvfExecKind::Backing, } } } diff --git a/prdoc/pr_5616.prdoc b/prdoc/pr_5616.prdoc new file mode 100644 index 000000000000..16d81c291c30 --- /dev/null +++ b/prdoc/pr_5616.prdoc @@ -0,0 +1,25 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "PVF: drop backing jobs if it is too late" + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + Introduces the removal of backing jobs that have been back pressured for longer than `allowedAncestryLen`, as these candidates are no longer viable. + +crates: + - name: polkadot-overseer + bump: major + - name: polkadot-node-core-pvf + bump: major + - name: polkadot-node-subsystem-types + bump: major + - name: polkadot-node-core-approval-voting + bump: patch + - name: polkadot-node-core-backing + bump: patch + - name: polkadot-node-core-candidate-validation + bump: patch + - name: polkadot-node-core-dispute-coordinator + bump: patch From 1100c1843ee60f2011400febd9f588463087ad8e Mon Sep 17 00:00:00 2001 From: Egor_P Date: Thu, 7 Nov 2024 12:59:26 +0100 Subject: [PATCH 058/166] [Release|CI/CD] Add node version to deb package version (#6399) This PR has small addition to the db package version. As `cargodeb` takes the version from the `*.toml` file, this PR adds an extra flag to the `cargodeb` command so that the version of the deb package matches the `polkadot` node version. --- .github/scripts/release/build-deb.sh | 3 +-- .github/workflows/release-reusable-rc-buid.yml | 4 +++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/scripts/release/build-deb.sh b/.github/scripts/release/build-deb.sh index 6cb833f98a4e..8dce621bb4de 100755 --- a/.github/scripts/release/build-deb.sh +++ b/.github/scripts/release/build-deb.sh @@ -9,8 +9,7 @@ cargo install --version 2.7.0 cargo-deb --locked -q echo "Using cargo-deb v$(cargo-deb --version)" echo "Building a Debian package for '$PRODUCT' in '$PROFILE' profile" -# we need to start the custom version with a didgit as requires it cargo-deb -cargo deb --profile $PROFILE --no-strip --no-build -p $PRODUCT --deb-version 1-$VERSION +cargo deb --profile $PROFILE --no-strip --no-build -p $PRODUCT --deb-version $VERSION deb=target/debian/$PRODUCT_*_amd64.deb diff --git a/.github/workflows/release-reusable-rc-buid.yml b/.github/workflows/release-reusable-rc-buid.yml index d76f36e95c8d..d925839fb84a 100644 --- a/.github/workflows/release-reusable-rc-buid.yml +++ b/.github/workflows/release-reusable-rc-buid.yml @@ -151,7 +151,9 @@ jobs: - name: Build polkadot deb package shell: bash run: | - . "${GITHUB_WORKSPACE}"/.github/scripts/release/build-deb.sh ${{ inputs.package }} ${{ inputs.release_tag }} + . "${GITHUB_WORKSPACE}"/.github/scripts/common/lib.sh + VERSION=$(get_polkadot_node_version_from_code) + . "${GITHUB_WORKSPACE}"/.github/scripts/release/build-deb.sh ${{ inputs.package }} ${VERSION} - name: Generate artifact attestation uses: actions/attest-build-provenance@1c608d11d69870c2092266b3f9a6f3abbf17002c # v1.4.3 From 566706dd64bd3816e05c7db8bf1917f23cc96b5d Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Thu, 7 Nov 2024 15:01:21 +0100 Subject: [PATCH 059/166] gensis-config: patching default `RuntimeGenesisConfig` fixed (#6382) This PR changes the behavior of `json_patch::merge` function which no longer removes any keys from the base JSON object. fixes: #6306 --------- Co-authored-by: GitHub Action --- prdoc/pr_6382.prdoc | 12 +++++++++ .../bin/utils/chain-spec-builder/src/lib.rs | 16 ++++++------ .../chain-spec/src/genesis_config_builder.rs | 4 +-- substrate/client/chain-spec/src/json_patch.rs | 25 ++++++++++++------- 4 files changed, 37 insertions(+), 20 deletions(-) create mode 100644 prdoc/pr_6382.prdoc diff --git a/prdoc/pr_6382.prdoc b/prdoc/pr_6382.prdoc new file mode 100644 index 000000000000..ac6821c1100a --- /dev/null +++ b/prdoc/pr_6382.prdoc @@ -0,0 +1,12 @@ +title: 'gensis-config: patching default `RuntimeGenesisConfig` fixed' +doc: +- audience: Node Dev + description: |- + This PR fixes issue reported in #6306. + It changes the behavior of `sc_chain_spec::json_patch::merge` function which no longer removes any keys from the base JSON object. + +crates: +- name: staging-chain-spec-builder + bump: major +- name: sc-chain-spec + bump: major diff --git a/substrate/bin/utils/chain-spec-builder/src/lib.rs b/substrate/bin/utils/chain-spec-builder/src/lib.rs index 6f3128ed7eb0..73c2868b3312 100644 --- a/substrate/bin/utils/chain-spec-builder/src/lib.rs +++ b/substrate/bin/utils/chain-spec-builder/src/lib.rs @@ -261,19 +261,19 @@ impl ChainSpecBuilder { .map_err(|e| format!("Conversion to json failed: {e}"))?; // We want to extract only raw genesis ("genesis::raw" key), and apply it as a patch - // for the original json file. However, the file also contains original plain - // genesis ("genesis::runtimeGenesis") so set it to null so the patch will erase it. + // for the original json file. genesis_json.as_object_mut().map(|map| { map.retain(|key, _| key == "genesis"); - map.get_mut("genesis").map(|genesis| { - genesis.as_object_mut().map(|genesis_map| { - genesis_map - .insert("runtimeGenesis".to_string(), serde_json::Value::Null); - }); - }); }); let mut org_chain_spec_json = extract_chain_spec_json(input_chain_spec.as_path())?; + + // The original plain genesis ("genesis::runtimeGenesis") is no longer needed, so + // just remove it: + org_chain_spec_json + .get_mut("genesis") + .and_then(|genesis| genesis.as_object_mut()) + .and_then(|genesis| genesis.remove("runtimeGenesis")); json_patch::merge(&mut org_chain_spec_json, genesis_json); let chain_spec_json = serde_json::to_string_pretty(&org_chain_spec_json) diff --git a/substrate/client/chain-spec/src/genesis_config_builder.rs b/substrate/client/chain-spec/src/genesis_config_builder.rs index 66989495d423..5fe8f9dc053c 100644 --- a/substrate/client/chain-spec/src/genesis_config_builder.rs +++ b/substrate/client/chain-spec/src/genesis_config_builder.rs @@ -142,11 +142,9 @@ where /// The patching process modifies the default `RuntimeGenesisConfig` according to the following /// rules: /// 1. Existing keys in the default configuration will be overridden by the corresponding values - /// in the patch. + /// in the patch (also applies to `null` values). /// 2. If a key exists in the patch but not in the default configuration, it will be added to /// the resulting `RuntimeGenesisConfig`. - /// 3. Keys in the default configuration that have null values in the patch will be removed from - /// the resulting `RuntimeGenesisConfig`. This is helpful for changing enum variant value. /// /// Please note that the patch may contain full `RuntimeGenesisConfig`. pub fn get_storage_for_patch(&self, patch: Value) -> core::result::Result { diff --git a/substrate/client/chain-spec/src/json_patch.rs b/substrate/client/chain-spec/src/json_patch.rs index c3930069a60d..a223792374e0 100644 --- a/substrate/client/chain-spec/src/json_patch.rs +++ b/substrate/client/chain-spec/src/json_patch.rs @@ -22,9 +22,10 @@ use serde_json::Value; /// Recursively merges two JSON objects, `a` and `b`, into a single object. /// -/// If a key exists in both objects, the value from `b` will override the value from `a`. -/// If a key exists in `b` with a `null` value, it will be removed from `a`. +/// If a key exists in both objects, the value from `b` will override the value from `a` (also if +/// value in `b` is `null`). /// If a key exists only in `b` and not in `a`, it will be added to `a`. +/// No keys will be removed from `a`. /// /// # Arguments /// @@ -34,11 +35,7 @@ pub fn merge(a: &mut Value, b: Value) { match (a, b) { (Value::Object(a), Value::Object(b)) => for (k, v) in b { - if v.is_null() { - a.remove(&k); - } else { - merge(a.entry(k).or_insert(Value::Null), v); - } + merge(a.entry(k).or_insert(Value::Null), v); }, (a, b) => *a = b, }; @@ -166,7 +163,7 @@ mod tests { } #[test] - fn test6_patch_removes_keys_if_null() { + fn test6_patch_does_not_remove_keys_if_null() { let mut j1 = json!({ "a": { "name": "xxx", @@ -186,6 +183,16 @@ mod tests { }); merge(&mut j1, j2); - assert_eq!(j1, json!({ "a": {"name":"xxx", "value":456, "enum_variant_2": 32 }})); + assert_eq!( + j1, + json!({ + "a": { + "name":"xxx", + "value":456, + "enum_variant_1": null, + "enum_variant_2": 32 + } + }) + ); } } From 65e79720fa5c06ce81455aaa62fe84ee5cabf9b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20R=2E=20Bald=C3=A9?= Date: Thu, 7 Nov 2024 14:46:29 +0000 Subject: [PATCH 060/166] Add missing events to identity pallet (#6261) # Description E2E tests to Polkadot/Kusama's people chains (in https://github.com/open-web3-stack/polkadot-ecosystem-tests/pull/63) revealed that 2 of the identity pallet's extrinsics did not emit events in case of success: * `pallet_identity::rename_sub`, and * `pallet_identity::set_subs` This PR fixes that. ## Integration Other than 2 extrinsics emiting an event when previously they did not, no other behavior in pallets/extrinsics was modified, so no integration is needed. ## Review Notes N/A --- prdoc/pr_6261.prdoc | 13 +++++++++++++ substrate/frame/identity/src/lib.rs | 14 +++++++++++++- substrate/frame/identity/src/tests.rs | 11 +++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 prdoc/pr_6261.prdoc diff --git a/prdoc/pr_6261.prdoc b/prdoc/pr_6261.prdoc new file mode 100644 index 000000000000..20ee5563bcfd --- /dev/null +++ b/prdoc/pr_6261.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add missing events to identity pallet + +doc: + - audience: Runtime Dev + description: | + Extrinsics from `pallet_identity` that were missing an event emission on success now emit one. + +crates: + - name: pallet-identity + bump: major diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index 11b43f958c4e..6a71e831cca1 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -421,6 +421,10 @@ pub mod pallet { RegistrarAdded { registrar_index: RegistrarIndex }, /// A sub-identity was added to an identity and the deposit paid. SubIdentityAdded { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf }, + /// An account's sub-identities were set (in bulk). + SubIdentitiesSet { main: T::AccountId, number_of_subs: u32, new_deposit: BalanceOf }, + /// A given sub-account's associated name was changed by its super-identity. + SubIdentityRenamed { sub: T::AccountId, main: T::AccountId }, /// A sub-identity was removed from an identity and the deposit freed. SubIdentityRemoved { sub: T::AccountId, main: T::AccountId, deposit: BalanceOf }, /// A sub-identity was cleared, and the given deposit repatriated from the @@ -591,6 +595,12 @@ pub mod pallet { SubsOf::::insert(&sender, (new_deposit, ids)); } + Self::deposit_event(Event::SubIdentitiesSet { + main: sender, + number_of_subs: new_subs as u32, + new_deposit, + }); + Ok(Some( T::WeightInfo::set_subs_old(old_ids.len() as u32) // P: Real number of old accounts removed. // S: New subs added @@ -992,7 +1002,9 @@ pub mod pallet { let sub = T::Lookup::lookup(sub)?; ensure!(IdentityOf::::contains_key(&sender), Error::::NoIdentity); ensure!(SuperOf::::get(&sub).map_or(false, |x| x.0 == sender), Error::::NotOwned); - SuperOf::::insert(&sub, (sender, data)); + SuperOf::::insert(&sub, (&sender, data)); + + Self::deposit_event(Event::SubIdentityRenamed { main: sender, sub }); Ok(()) } diff --git a/substrate/frame/identity/src/tests.rs b/substrate/frame/identity/src/tests.rs index a095085a8188..7bf5b2a72760 100644 --- a/substrate/frame/identity/src/tests.rs +++ b/substrate/frame/identity/src/tests.rs @@ -273,6 +273,10 @@ fn editing_subaccounts_should_work() { // rename first sub account assert_ok!(Identity::rename_sub(RuntimeOrigin::signed(ten.clone()), one.clone(), data(11))); + System::assert_last_event(tests::RuntimeEvent::Identity(Event::SubIdentityRenamed { + main: ten.clone(), + sub: one.clone(), + })); assert_eq!(SuperOf::::get(one.clone()), Some((ten.clone(), data(11)))); assert_eq!(SuperOf::::get(two.clone()), Some((ten.clone(), data(2)))); assert_eq!(Balances::free_balance(ten.clone()), 1000 - id_deposit - 2 * sub_deposit); @@ -546,6 +550,13 @@ fn setting_subaccounts_should_work() { assert_ok!(Identity::set_identity(RuntimeOrigin::signed(ten.clone()), Box::new(ten_info))); assert_eq!(Balances::free_balance(ten.clone()), 1000 - id_deposit); assert_ok!(Identity::set_subs(RuntimeOrigin::signed(ten.clone()), subs.clone())); + + System::assert_last_event(tests::RuntimeEvent::Identity(Event::SubIdentitiesSet { + main: ten.clone(), + number_of_subs: 1, + new_deposit: sub_deposit, + })); + assert_eq!(Balances::free_balance(ten.clone()), 1000 - id_deposit - sub_deposit); assert_eq!( SubsOf::::get(ten.clone()), From 8795ae66fb31cc6765b8d8a993d092d7ce240f33 Mon Sep 17 00:00:00 2001 From: Andrei Eres Date: Thu, 7 Nov 2024 15:50:29 +0100 Subject: [PATCH 061/166] Add networking benchmarks for libp2p (#6077) # Description Implemented benchmarks for Notifications and RequestResponse protocols with libp2p implementation. These benchmarks allow us to monitor regressions and implement fixes before they are observed in real chain. In the future, they can be used for targeted optimizations of litep2p compared to libp2p. Part of https://github.com/paritytech/polkadot-sdk/issues/5220 Next steps: - Add benchmarks for litep2p implementation - Optimize load to get better results - Add benchmarks to CI to catch regressions ## Integration Benchmarks don't affect downstream projects. --------- Co-authored-by: alvicsam Co-authored-by: GitHub Action --- Cargo.lock | 2 + prdoc/pr_6077.prdoc | 9 + substrate/client/network/Cargo.toml | 14 +- .../network/benches/notifications_protocol.rs | 290 ++++++++++++++++++ .../benches/request_response_protocol.rs | 278 +++++++++++++++++ 5 files changed, 592 insertions(+), 1 deletion(-) create mode 100644 prdoc/pr_6077.prdoc create mode 100644 substrate/client/network/benches/notifications_protocol.rs create mode 100644 substrate/client/network/benches/request_response_protocol.rs diff --git a/Cargo.lock b/Cargo.lock index 1036e4016746..1e1c902df0e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19393,6 +19393,7 @@ dependencies = [ "asynchronous-codec", "bytes", "cid 0.9.0", + "criterion", "either", "fnv", "futures", @@ -19414,6 +19415,7 @@ dependencies = [ "rand", "sc-block-builder", "sc-client-api", + "sc-consensus", "sc-network-common", "sc-network-light", "sc-network-sync", diff --git a/prdoc/pr_6077.prdoc b/prdoc/pr_6077.prdoc new file mode 100644 index 000000000000..f222fb27ce07 --- /dev/null +++ b/prdoc/pr_6077.prdoc @@ -0,0 +1,9 @@ +title: Add networking benchmarks for libp2p +doc: +- audience: node_dev + description: |- + Adds benchmarks for Notifications and RequestResponse protocols with libp2p implementation + +crates: +- name: sc-network + validate: false diff --git a/substrate/client/network/Cargo.toml b/substrate/client/network/Cargo.toml index 8ae3de72f796..c8fd28e08109 100644 --- a/substrate/client/network/Cargo.toml +++ b/substrate/client/network/Cargo.toml @@ -70,7 +70,7 @@ mockall = { workspace = true } multistream-select = { workspace = true } rand = { workspace = true, default-features = true } tempfile = { workspace = true } -tokio = { features = ["macros"], workspace = true, default-features = true } +tokio = { features = ["macros", "rt-multi-thread"], workspace = true, default-features = true } tokio-util = { features = ["compat"], workspace = true } tokio-test = { workspace = true } sc-block-builder = { workspace = true, default-features = true } @@ -83,5 +83,17 @@ sp-tracing = { workspace = true, default-features = true } substrate-test-runtime = { workspace = true } substrate-test-runtime-client = { workspace = true } +criterion = { workspace = true, default-features = true, features = ["async_tokio"] } +sc-consensus = { workspace = true, default-features = true } + [features] default = [] + + +[[bench]] +name = "notifications_protocol" +harness = false + +[[bench]] +name = "request_response_protocol" +harness = false diff --git a/substrate/client/network/benches/notifications_protocol.rs b/substrate/client/network/benches/notifications_protocol.rs new file mode 100644 index 000000000000..7d32c9faeba1 --- /dev/null +++ b/substrate/client/network/benches/notifications_protocol.rs @@ -0,0 +1,290 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use criterion::{ + criterion_group, criterion_main, AxisScale, BenchmarkId, Criterion, PlotConfiguration, + Throughput, +}; +use sc_network::{ + config::{ + FullNetworkConfiguration, MultiaddrWithPeerId, NetworkConfiguration, NonDefaultSetConfig, + NonReservedPeerMode, NotificationHandshake, Params, ProtocolId, Role, SetConfig, + }, + service::traits::NotificationEvent, + NetworkWorker, NotificationMetrics, NotificationService, Roles, +}; +use sc_network_common::sync::message::BlockAnnouncesHandshake; +use sc_network_types::build_multiaddr; +use sp_runtime::traits::Zero; +use std::{ + net::{IpAddr, Ipv4Addr, TcpListener}, + str::FromStr, +}; +use substrate_test_runtime_client::runtime; + +const MAX_SIZE: u64 = 2u64.pow(30); +const SAMPLE_SIZE: usize = 50; +const NOTIFICATIONS: usize = 50; +const EXPONENTS: &[(u32, &'static str)] = &[ + (6, "64B"), + (9, "512B"), + (12, "4KB"), + (15, "64KB"), + (18, "256KB"), + (21, "2MB"), + (24, "16MB"), + (27, "128MB"), +]; + +// TODO: It's be better to bind system-provided port when initializing the worker +fn get_listen_address() -> sc_network::Multiaddr { + let ip = Ipv4Addr::from_str("127.0.0.1").unwrap(); + let listener = TcpListener::bind((IpAddr::V4(ip), 0)).unwrap(); // Bind to a random port + let local_addr = listener.local_addr().unwrap(); + let port = local_addr.port(); + + build_multiaddr!(Ip4(ip), Tcp(port)) +} + +pub fn create_network_worker( + listen_addr: sc_network::Multiaddr, +) -> (NetworkWorker, Box) { + let role = Role::Full; + let genesis_hash = runtime::Hash::zero(); + let (block_announce_config, notification_service) = NonDefaultSetConfig::new( + "/block-announces/1".into(), + vec!["/bench-notifications-protocol/block-announces/1".into()], + MAX_SIZE, + Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( + Roles::from(&role), + Zero::zero(), + genesis_hash, + genesis_hash, + ))), + SetConfig { + in_peers: 1, + out_peers: 1, + reserved_nodes: vec![], + non_reserved_mode: NonReservedPeerMode::Accept, + }, + ); + let mut net_conf = NetworkConfiguration::new_local(); + net_conf.listen_addresses = vec![listen_addr]; + let worker = NetworkWorker::::new(Params::< + runtime::Block, + runtime::Hash, + NetworkWorker<_, _>, + > { + block_announce_config, + role, + executor: Box::new(|f| { + tokio::spawn(f); + }), + genesis_hash, + network_config: FullNetworkConfiguration::new(&net_conf, None), + protocol_id: ProtocolId::from("bench-protocol-name"), + fork_id: None, + metrics_registry: None, + bitswap_config: None, + notification_metrics: NotificationMetrics::new(None), + }) + .unwrap(); + + (worker, notification_service) +} + +async fn run_serially(size: usize, limit: usize) { + let listen_address1 = get_listen_address(); + let listen_address2 = get_listen_address(); + let (worker1, mut notification_service1) = create_network_worker(listen_address1); + let (worker2, mut notification_service2) = create_network_worker(listen_address2.clone()); + let peer_id2: sc_network::PeerId = (*worker2.local_peer_id()).into(); + + worker1 + .add_reserved_peer(MultiaddrWithPeerId { multiaddr: listen_address2, peer_id: peer_id2 }) + .unwrap(); + + let network1_run = worker1.run(); + let network2_run = worker2.run(); + let (tx, rx) = async_channel::bounded(10); + + let network1 = tokio::spawn(async move { + tokio::pin!(network1_run); + loop { + tokio::select! { + _ = &mut network1_run => {}, + event = notification_service1.next_event() => { + match event { + Some(NotificationEvent::NotificationStreamOpened { .. }) => { + notification_service1 + .send_async_notification(&peer_id2, vec![0; size]) + .await + .unwrap(); + }, + event => panic!("Unexpected event {:?}", event), + }; + }, + message = rx.recv() => { + match message { + Ok(Some(_)) => { + notification_service1 + .send_async_notification(&peer_id2, vec![0; size]) + .await + .unwrap(); + }, + Ok(None) => break, + Err(err) => panic!("Unexpected error {:?}", err), + + } + } + } + } + }); + let network2 = tokio::spawn(async move { + let mut received_counter = 0; + tokio::pin!(network2_run); + loop { + tokio::select! { + _ = &mut network2_run => {}, + event = notification_service2.next_event() => { + match event { + Some(NotificationEvent::ValidateInboundSubstream { result_tx, .. }) => { + result_tx.send(sc_network::service::traits::ValidationResult::Accept).unwrap(); + }, + Some(NotificationEvent::NotificationStreamOpened { .. }) => {}, + Some(NotificationEvent::NotificationReceived { .. }) => { + received_counter += 1; + if received_counter >= limit { + let _ = tx.send(None).await; + break + } + let _ = tx.send(Some(())).await; + }, + event => panic!("Unexpected event {:?}", event), + }; + }, + } + } + }); + + let _ = tokio::join!(network1, network2); +} + +async fn run_with_backpressure(size: usize, limit: usize) { + let listen_address1 = get_listen_address(); + let listen_address2 = get_listen_address(); + let (worker1, mut notification_service1) = create_network_worker(listen_address1); + let (worker2, mut notification_service2) = create_network_worker(listen_address2.clone()); + let peer_id2: sc_network::PeerId = (*worker2.local_peer_id()).into(); + + worker1 + .add_reserved_peer(MultiaddrWithPeerId { multiaddr: listen_address2, peer_id: peer_id2 }) + .unwrap(); + + let network1_run = worker1.run(); + let network2_run = worker2.run(); + + let network1 = tokio::spawn(async move { + let mut sent_counter = 0; + tokio::pin!(network1_run); + loop { + tokio::select! { + _ = &mut network1_run => {}, + event = notification_service1.next_event() => { + match event { + Some(NotificationEvent::NotificationStreamOpened { .. }) => { + while sent_counter < limit { + sent_counter += 1; + notification_service1 + .send_async_notification(&peer_id2, vec![0; size]) + .await + .unwrap(); + } + }, + Some(NotificationEvent::NotificationStreamClosed { .. }) => { + if sent_counter != limit { panic!("Stream closed unexpectedly") } + break + }, + event => panic!("Unexpected event {:?}", event), + }; + }, + } + } + }); + let network2 = tokio::spawn(async move { + let mut received_counter = 0; + tokio::pin!(network2_run); + loop { + tokio::select! { + _ = &mut network2_run => {}, + event = notification_service2.next_event() => { + match event { + Some(NotificationEvent::ValidateInboundSubstream { result_tx, .. }) => { + result_tx.send(sc_network::service::traits::ValidationResult::Accept).unwrap(); + }, + Some(NotificationEvent::NotificationStreamOpened { .. }) => {}, + Some(NotificationEvent::NotificationStreamClosed { .. }) => { + if received_counter != limit { panic!("Stream closed unexpectedly") } + break + }, + Some(NotificationEvent::NotificationReceived { .. }) => { + received_counter += 1; + if received_counter >= limit { break } + }, + event => panic!("Unexpected event {:?}", event), + }; + }, + } + } + }); + + let _ = tokio::join!(network1, network2); +} + +fn run_benchmark(c: &mut Criterion) { + let rt = tokio::runtime::Runtime::new().unwrap(); + let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic); + let mut group = c.benchmark_group("notifications_benchmark"); + group.plot_config(plot_config); + + for &(exponent, label) in EXPONENTS.iter() { + let size = 2usize.pow(exponent); + group.throughput(Throughput::Bytes(NOTIFICATIONS as u64 * size as u64)); + group.bench_with_input( + BenchmarkId::new("consistently", label), + &(size, NOTIFICATIONS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| run_serially(size, limit)); + }, + ); + group.bench_with_input( + BenchmarkId::new("with_backpressure", label), + &(size, NOTIFICATIONS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| run_with_backpressure(size, limit)); + }, + ); + } +} + +criterion_group! { + name = benches; + config = Criterion::default().sample_size(SAMPLE_SIZE); + targets = run_benchmark +} +criterion_main!(benches); diff --git a/substrate/client/network/benches/request_response_protocol.rs b/substrate/client/network/benches/request_response_protocol.rs new file mode 100644 index 000000000000..09bf829f5a7e --- /dev/null +++ b/substrate/client/network/benches/request_response_protocol.rs @@ -0,0 +1,278 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use criterion::{ + criterion_group, criterion_main, AxisScale, BenchmarkId, Criterion, PlotConfiguration, + Throughput, +}; +use sc_network::{ + config::{ + FullNetworkConfiguration, IncomingRequest, NetworkConfiguration, NonDefaultSetConfig, + NonReservedPeerMode, NotificationHandshake, OutgoingResponse, Params, ProtocolId, Role, + SetConfig, + }, + IfDisconnected, NetworkBackend, NetworkRequest, NetworkWorker, NotificationMetrics, + NotificationService, Roles, +}; +use sc_network_common::sync::message::BlockAnnouncesHandshake; +use sc_network_types::build_multiaddr; +use sp_runtime::traits::Zero; +use std::{ + net::{IpAddr, Ipv4Addr, TcpListener}, + str::FromStr, + time::Duration, +}; +use substrate_test_runtime_client::runtime; + +const MAX_SIZE: u64 = 2u64.pow(30); +const SAMPLE_SIZE: usize = 50; +const REQUESTS: usize = 50; +const EXPONENTS: &[(u32, &'static str)] = &[ + (6, "64B"), + (9, "512B"), + (12, "4KB"), + (15, "64KB"), + (18, "256KB"), + (21, "2MB"), + (24, "16MB"), + (27, "128MB"), +]; + +fn get_listen_address() -> sc_network::Multiaddr { + let ip = Ipv4Addr::from_str("127.0.0.1").unwrap(); + let listener = TcpListener::bind((IpAddr::V4(ip), 0)).unwrap(); // Bind to a random port + let local_addr = listener.local_addr().unwrap(); + let port = local_addr.port(); + + build_multiaddr!(Ip4(ip), Tcp(port)) +} + +pub fn create_network_worker( + listen_addr: sc_network::Multiaddr, +) -> ( + NetworkWorker, + async_channel::Receiver, + Box, +) { + let (tx, rx) = async_channel::bounded(10); + let request_response_config = + NetworkWorker::::request_response_config( + "/request-response/1".into(), + vec![], + MAX_SIZE, + MAX_SIZE, + Duration::from_secs(2), + Some(tx), + ); + let mut net_conf = NetworkConfiguration::new_local(); + net_conf.listen_addresses = vec![listen_addr]; + let mut network_config = FullNetworkConfiguration::new(&net_conf, None); + network_config.add_request_response_protocol(request_response_config); + let (block_announce_config, notification_service) = NonDefaultSetConfig::new( + "/block-announces/1".into(), + vec![], + 1024, + Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( + Roles::from(&Role::Full), + Zero::zero(), + runtime::Hash::zero(), + runtime::Hash::zero(), + ))), + SetConfig { + in_peers: 1, + out_peers: 1, + reserved_nodes: vec![], + non_reserved_mode: NonReservedPeerMode::Accept, + }, + ); + let worker = NetworkWorker::::new(Params::< + runtime::Block, + runtime::Hash, + NetworkWorker<_, _>, + > { + block_announce_config, + role: Role::Full, + executor: Box::new(|f| { + tokio::spawn(f); + }), + genesis_hash: runtime::Hash::zero(), + network_config, + protocol_id: ProtocolId::from("bench-request-response-protocol"), + fork_id: None, + metrics_registry: None, + bitswap_config: None, + notification_metrics: NotificationMetrics::new(None), + }) + .unwrap(); + + (worker, rx, notification_service) +} + +async fn run_serially(size: usize, limit: usize) { + let listen_address1 = get_listen_address(); + let listen_address2 = get_listen_address(); + let (mut worker1, _rx1, _notification_service1) = create_network_worker(listen_address1); + let service1 = worker1.service().clone(); + let (worker2, rx2, _notification_service2) = create_network_worker(listen_address2.clone()); + let peer_id2 = *worker2.local_peer_id(); + + worker1.add_known_address(peer_id2, listen_address2.into()); + + let network1_run = worker1.run(); + let network2_run = worker2.run(); + let (break_tx, break_rx) = async_channel::bounded(10); + let requests = async move { + let mut sent_counter = 0; + while sent_counter < limit { + let _ = service1 + .request( + peer_id2.into(), + "/request-response/1".into(), + vec![0; 2], + None, + IfDisconnected::TryConnect, + ) + .await + .unwrap(); + sent_counter += 1; + } + let _ = break_tx.send(()).await; + }; + + let network1 = tokio::spawn(async move { + tokio::pin!(requests); + tokio::pin!(network1_run); + loop { + tokio::select! { + _ = &mut network1_run => {}, + _ = &mut requests => break, + } + } + }); + let network2 = tokio::spawn(async move { + tokio::pin!(network2_run); + loop { + tokio::select! { + _ = &mut network2_run => {}, + res = rx2.recv() => { + let IncomingRequest { pending_response, .. } = res.unwrap(); + pending_response.send(OutgoingResponse { + result: Ok(vec![0; size]), + reputation_changes: vec![], + sent_feedback: None, + }).unwrap(); + }, + _ = break_rx.recv() => break, + } + } + }); + + let _ = tokio::join!(network1, network2); +} + +// The libp2p request-response implementation does not provide any backpressure feedback. +// So this benchmark is useless until we implement it for litep2p. +#[allow(dead_code)] +async fn run_with_backpressure(size: usize, limit: usize) { + let listen_address1 = get_listen_address(); + let listen_address2 = get_listen_address(); + let (mut worker1, _rx1, _notification_service1) = create_network_worker(listen_address1); + let service1 = worker1.service().clone(); + let (worker2, rx2, _notification_service2) = create_network_worker(listen_address2.clone()); + let peer_id2 = *worker2.local_peer_id(); + + worker1.add_known_address(peer_id2, listen_address2.into()); + + let network1_run = worker1.run(); + let network2_run = worker2.run(); + let (break_tx, break_rx) = async_channel::bounded(10); + let requests = futures::future::join_all((0..limit).into_iter().map(|_| { + let (tx, rx) = futures::channel::oneshot::channel(); + service1.start_request( + peer_id2.into(), + "/request-response/1".into(), + vec![0; 8], + None, + tx, + IfDisconnected::TryConnect, + ); + rx + })); + + let network1 = tokio::spawn(async move { + tokio::pin!(requests); + tokio::pin!(network1_run); + loop { + tokio::select! { + _ = &mut network1_run => {}, + responses = &mut requests => { + for res in responses { + res.unwrap().unwrap(); + } + let _ = break_tx.send(()).await; + break; + }, + } + } + }); + let network2 = tokio::spawn(async move { + tokio::pin!(network2_run); + loop { + tokio::select! { + _ = &mut network2_run => {}, + res = rx2.recv() => { + let IncomingRequest { pending_response, .. } = res.unwrap(); + pending_response.send(OutgoingResponse { + result: Ok(vec![0; size]), + reputation_changes: vec![], + sent_feedback: None, + }).unwrap(); + }, + _ = break_rx.recv() => break, + } + } + }); + + let _ = tokio::join!(network1, network2); +} + +fn run_benchmark(c: &mut Criterion) { + let rt = tokio::runtime::Runtime::new().unwrap(); + let plot_config = PlotConfiguration::default().summary_scale(AxisScale::Logarithmic); + let mut group = c.benchmark_group("request_response_benchmark"); + group.plot_config(plot_config); + + for &(exponent, label) in EXPONENTS.iter() { + let size = 2usize.pow(exponent); + group.throughput(Throughput::Bytes(REQUESTS as u64 * size as u64)); + group.bench_with_input( + BenchmarkId::new("consistently", label), + &(size, REQUESTS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| run_serially(size, limit)); + }, + ); + } +} + +criterion_group! { + name = benches; + config = Criterion::default().sample_size(SAMPLE_SIZE); + targets = run_benchmark +} +criterion_main!(benches); From 2680f20a88a0f553c9da4169531852b40d1f305b Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Thu, 7 Nov 2024 17:00:15 +0200 Subject: [PATCH 062/166] make prospective-parachains debug logs less spammy (#6406) Fixes https://github.com/paritytech/polkadot-sdk/issues/6172 --- .../core/prospective-parachains/src/lib.rs | 47 ++++++++++++------- prdoc/pr_6406.prdoc | 9 ++++ 2 files changed, 39 insertions(+), 17 deletions(-) create mode 100644 prdoc/pr_6406.prdoc diff --git a/polkadot/node/core/prospective-parachains/src/lib.rs b/polkadot/node/core/prospective-parachains/src/lib.rs index 34c1d8823bfc..92aea8509f8c 100644 --- a/polkadot/node/core/prospective-parachains/src/lib.rs +++ b/polkadot/node/core/prospective-parachains/src/lib.rs @@ -524,7 +524,7 @@ async fn handle_introduce_seconded_candidate( }, }; - let mut added = false; + let mut added = Vec::with_capacity(view.per_relay_parent.len()); let mut para_scheduled = false; // We don't iterate only through the active leaves. We also update the deactivated parents in // the implicit view, so that their upcoming children may see these candidates. @@ -536,18 +536,10 @@ async fn handle_introduce_seconded_candidate( match chain.try_adding_seconded_candidate(&candidate_entry) { Ok(()) => { - gum::debug!( - target: LOG_TARGET, - ?para, - ?relay_parent, - ?is_active_leaf, - "Added seconded candidate {:?}", - candidate_hash - ); - added = true; + added.push(*relay_parent); }, Err(FragmentChainError::CandidateAlreadyKnown) => { - gum::debug!( + gum::trace!( target: LOG_TARGET, ?para, ?relay_parent, @@ -555,10 +547,10 @@ async fn handle_introduce_seconded_candidate( "Attempting to introduce an already known candidate: {:?}", candidate_hash ); - added = true; + added.push(*relay_parent); }, Err(err) => { - gum::debug!( + gum::trace!( target: LOG_TARGET, ?para, ?relay_parent, @@ -580,16 +572,24 @@ async fn handle_introduce_seconded_candidate( ); } - if !added { + if added.is_empty() { gum::debug!( target: LOG_TARGET, para = ?para, candidate = ?candidate_hash, "Newly-seconded candidate cannot be kept under any relay parent", ); + } else { + gum::debug!( + target: LOG_TARGET, + ?para, + "Added/Kept seconded candidate {:?} on relay parents: {:?}", + candidate_hash, + added + ); } - let _ = tx.send(added); + let _ = tx.send(!added.is_empty()); } async fn handle_candidate_backed( @@ -779,12 +779,12 @@ fn answer_hypothetical_membership_request( membership.push(*active_leaf); }, Err(err) => { - gum::debug!( + gum::trace!( target: LOG_TARGET, para = ?para_id, leaf = ?active_leaf, candidate = ?candidate.candidate_hash(), - "Candidate is not a hypothetical member: {}", + "Candidate is not a hypothetical member on: {}", err ) }, @@ -792,6 +792,19 @@ fn answer_hypothetical_membership_request( } } + for (candidate, membership) in &response { + if membership.is_empty() { + gum::debug!( + target: LOG_TARGET, + para = ?candidate.candidate_para(), + active_leaves = ?view.active_leaves, + ?required_active_leaf, + candidate = ?candidate.candidate_hash(), + "Candidate is not a hypothetical member on any of the active leaves", + ) + } + } + let _ = tx.send(response); } diff --git a/prdoc/pr_6406.prdoc b/prdoc/pr_6406.prdoc new file mode 100644 index 000000000000..9da4462263b9 --- /dev/null +++ b/prdoc/pr_6406.prdoc @@ -0,0 +1,9 @@ +title: 'make prospective-parachains debug logs less spammy' +doc: +- audience: [Node Dev, Node Operator] + description: | + Demote some of the frequent prospective-parachains debug logs to trace level and prefer printing aggregate debug logs. + +crates: +- name: polkadot-node-core-prospective-parachains + bump: patch From c4e94d35b0cf56477e27ef599415d7bf7f39b0ca Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Thu, 7 Nov 2024 23:43:58 +0800 Subject: [PATCH 063/166] Migrate pallet-elections-phragmen benchmark to v2 and improve doc (#6314) Part of: - #6202. --------- Co-authored-by: Giuseppe Re Co-authored-by: GitHub Action --- prdoc/pr_6314.prdoc | 10 + .../elections-phragmen/src/benchmarking.rs | 381 ++++++++++-------- 2 files changed, 229 insertions(+), 162 deletions(-) create mode 100644 prdoc/pr_6314.prdoc diff --git a/prdoc/pr_6314.prdoc b/prdoc/pr_6314.prdoc new file mode 100644 index 000000000000..2ebbc68158d5 --- /dev/null +++ b/prdoc/pr_6314.prdoc @@ -0,0 +1,10 @@ +title: Migrate pallet-elections-phragmen benchmark to v2 and improve doc +doc: +- audience: Runtime Dev + description: |- + Part of: + + - #6202. +crates: +- name: pallet-elections-phragmen + bump: patch diff --git a/substrate/frame/elections-phragmen/src/benchmarking.rs b/substrate/frame/elections-phragmen/src/benchmarking.rs index 8e762f667b2a..60771fa89ad7 100644 --- a/substrate/frame/elections-phragmen/src/benchmarking.rs +++ b/substrate/frame/elections-phragmen/src/benchmarking.rs @@ -19,47 +19,47 @@ #![cfg(feature = "runtime-benchmarks")] -use super::*; - -use frame_benchmarking::v1::{account, benchmarks, whitelist, BenchmarkError, BenchmarkResult}; +use frame_benchmarking::v2::*; use frame_support::{dispatch::DispatchResultWithPostInfo, traits::OnInitialize}; use frame_system::RawOrigin; -use crate::Pallet as Elections; +#[cfg(test)] +use crate::tests::MEMBERS; +use crate::*; const BALANCE_FACTOR: u32 = 250; -/// grab new account with infinite balance. +// grab new account with infinite balance. fn endowed_account(name: &'static str, index: u32) -> T::AccountId { let account: T::AccountId = account(name, index, 0); // Fund each account with at-least their stake but still a sane amount as to not mess up // the vote calculation. let amount = default_stake::(T::MaxVoters::get()) * BalanceOf::::from(BALANCE_FACTOR); let _ = T::Currency::make_free_balance_be(&account, amount); - // important to increase the total issuance since T::CurrencyToVote will need it to be sane for - // phragmen to work. + // Important to increase the total issuance since `T::CurrencyToVote` will need it to be sane + // for phragmen to work. let _ = T::Currency::issue(amount); account } -/// Account to lookup type of system trait. +// Account to lookup type of system trait. fn as_lookup(account: T::AccountId) -> AccountIdLookupOf { T::Lookup::unlookup(account) } -/// Get a reasonable amount of stake based on the execution trait's configuration +// Get a reasonable amount of stake based on the execution trait's configuration. fn default_stake(num_votes: u32) -> BalanceOf { let min = T::Currency::minimum_balance(); - Elections::::deposit_of(num_votes as usize).max(min) + Pallet::::deposit_of(num_votes as usize).max(min) } -/// Get the current number of candidates. +// Get the current number of candidates. fn candidate_count() -> u32 { Candidates::::decode_len().unwrap_or(0usize) as u32 } -/// Add `c` new candidates. +// Add `c` new candidates. fn submit_candidates( c: u32, prefix: &'static str, @@ -67,7 +67,7 @@ fn submit_candidates( (0..c) .map(|i| { let account = endowed_account::(prefix, i); - Elections::::submit_candidacy( + Pallet::::submit_candidacy( RawOrigin::Signed(account.clone()).into(), candidate_count::(), ) @@ -77,7 +77,7 @@ fn submit_candidates( .collect::>() } -/// Add `c` new candidates with self vote. +// Add `c` new candidates with self vote. fn submit_candidates_with_self_vote( c: u32, prefix: &'static str, @@ -90,17 +90,17 @@ fn submit_candidates_with_self_vote( Ok(candidates) } -/// Submit one voter. +// Submit one voter. fn submit_voter( caller: T::AccountId, votes: Vec, stake: BalanceOf, ) -> DispatchResultWithPostInfo { - Elections::::vote(RawOrigin::Signed(caller).into(), votes, stake) + Pallet::::vote(RawOrigin::Signed(caller).into(), votes, stake) } -/// create `num_voter` voters who randomly vote for at most `votes` of `all_candidates` if -/// available. +// Create `num_voter` voters who randomly vote for at most `votes` of `all_candidates` if +// available. fn distribute_voters( mut all_candidates: Vec, num_voters: u32, @@ -117,12 +117,12 @@ fn distribute_voters( Ok(()) } -/// Fill the seats of members and runners-up up until `m`. Note that this might include either only -/// members, or members and runners-up. +// Fill the seats of members and runners-up up until `m`. Note that this might include either only +// members, or members and runners-up. fn fill_seats_up_to(m: u32) -> Result, &'static str> { let _ = submit_candidates_with_self_vote::(m, "fill_seats_up_to")?; assert_eq!(Candidates::::get().len() as u32, m, "wrong number of candidates."); - Elections::::do_phragmen(); + Pallet::::do_phragmen(); assert_eq!(Candidates::::get().len(), 0, "some candidates remaining."); assert_eq!( Members::::get().len() + RunnersUp::::get().len(), @@ -136,7 +136,7 @@ fn fill_seats_up_to(m: u32) -> Result, &'static str .collect()) } -/// removes all the storage items to reverse any genesis state. +// Removes all the storage items to reverse any genesis state. fn clean() { Members::::kill(); Candidates::::kill(); @@ -145,10 +145,13 @@ fn clean() { Voting::::remove_all(None); } -benchmarks! { +#[benchmarks] +mod benchmarks { + use super::*; + // -- Signed ones - vote_equal { - let v in 1 .. T::MaxVotesPerVoter::get(); + #[benchmark] + fn vote_equal(v: Linear<1, { T::MaxVotesPerVoter::get() }>) -> Result<(), BenchmarkError> { clean::(); // create a bunch of candidates. @@ -157,65 +160,81 @@ benchmarks! { let caller = endowed_account::("caller", 0); let stake = default_stake::(v); - // original votes. + // Original votes. let mut votes = all_candidates; submit_voter::(caller.clone(), votes.clone(), stake)?; - // new votes. + // New votes. votes.rotate_left(1); whitelist!(caller); - }: vote(RawOrigin::Signed(caller), votes, stake) - vote_more { - let v in 2 .. T::MaxVotesPerVoter::get(); + #[extrinsic_call] + vote(RawOrigin::Signed(caller), votes, stake); + + Ok(()) + } + + #[benchmark] + fn vote_more(v: Linear<2, { T::MaxVotesPerVoter::get() }>) -> Result<(), BenchmarkError> { clean::(); - // create a bunch of candidates. + // Create a bunch of candidates. let all_candidates = submit_candidates::(v, "candidates")?; let caller = endowed_account::("caller", 0); // Multiply the stake with 10 since we want to be able to divide it by 10 again. - let stake = default_stake::(v) * BalanceOf::::from(10u32); + let stake = default_stake::(v) * BalanceOf::::from(10_u32); - // original votes. + // Original votes. let mut votes = all_candidates.iter().skip(1).cloned().collect::>(); - submit_voter::(caller.clone(), votes.clone(), stake / BalanceOf::::from(10u32))?; + submit_voter::(caller.clone(), votes.clone(), stake / BalanceOf::::from(10_u32))?; - // new votes. + // New votes. votes = all_candidates; assert!(votes.len() > Voting::::get(caller.clone()).votes.len()); whitelist!(caller); - }: vote(RawOrigin::Signed(caller), votes, stake / BalanceOf::::from(10u32)) - vote_less { - let v in 2 .. T::MaxVotesPerVoter::get(); + #[extrinsic_call] + vote(RawOrigin::Signed(caller), votes, stake / BalanceOf::::from(10_u32)); + + Ok(()) + } + + #[benchmark] + fn vote_less(v: Linear<2, { T::MaxVotesPerVoter::get() }>) -> Result<(), BenchmarkError> { clean::(); - // create a bunch of candidates. + // Create a bunch of candidates. let all_candidates = submit_candidates::(v, "candidates")?; let caller = endowed_account::("caller", 0); let stake = default_stake::(v); - // original votes. + // Original votes. let mut votes = all_candidates; submit_voter::(caller.clone(), votes.clone(), stake)?; - // new votes. + // New votes. votes = votes.into_iter().skip(1).collect::>(); assert!(votes.len() < Voting::::get(caller.clone()).votes.len()); whitelist!(caller); - }: vote(RawOrigin::Signed(caller), votes, stake) - remove_voter { - // we fix the number of voted candidates to max + #[extrinsic_call] + vote(RawOrigin::Signed(caller), votes, stake); + + Ok(()) + } + + #[benchmark] + fn remove_voter() -> Result<(), BenchmarkError> { + // We fix the number of voted candidates to max. let v = T::MaxVotesPerVoter::get(); clean::(); - // create a bunch of candidates. + // Create a bunch of candidates. let all_candidates = submit_candidates::(v, "candidates")?; let caller = endowed_account::("caller", 0); @@ -224,207 +243,245 @@ benchmarks! { submit_voter::(caller.clone(), all_candidates, stake)?; whitelist!(caller); - }: _(RawOrigin::Signed(caller)) - submit_candidacy { - // number of already existing candidates. - let c in 1 .. T::MaxCandidates::get(); - // we fix the number of members to the number of desired members and runners-up. We'll be in - // this state almost always. + #[extrinsic_call] + _(RawOrigin::Signed(caller)); + + Ok(()) + } + + #[benchmark] + fn submit_candidacy( + // Number of already existing candidates. + c: Linear<1, { T::MaxCandidates::get() }>, + ) -> Result<(), BenchmarkError> { + // We fix the number of members to the number of desired members and runners-up. + // We'll be in this state almost always. let m = T::DesiredMembers::get() + T::DesiredRunnersUp::get(); clean::(); - let stake = default_stake::(c); - // create m members and runners combined. + // Create `m` members and runners combined. let _ = fill_seats_up_to::(m)?; - // create previous candidates; + // Create previous candidates. let _ = submit_candidates::(c, "candidates")?; - // we assume worse case that: extrinsic is successful and candidate is not duplicate. + // We assume worse case that: extrinsic is successful and candidate is not duplicate. let candidate_account = endowed_account::("caller", 0); whitelist!(candidate_account); - }: _(RawOrigin::Signed(candidate_account.clone()), candidate_count::()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(candidate_account), candidate_count::()); + + // Reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); + + Ok(()) } - renounce_candidacy_candidate { - // this will check members, runners-up and candidate for removal. Members and runners-up are - // limited by the runtime bound, nonetheless we fill them by `m`. - // number of already existing candidates. - let c in 1 .. T::MaxCandidates::get(); - // we fix the number of members to the number of desired members and runners-up. We'll be in - // this state almost always. + #[benchmark] + fn renounce_candidacy_candidate( + // This will check members, runners-up and candidate for removal. + // Members and runners-up are limited by the runtime bound, nonetheless we fill them by + // `m`. + // Number of already existing candidates. + c: Linear<1, { T::MaxCandidates::get() }>, + ) -> Result<(), BenchmarkError> { + // We fix the number of members to the number of desired members and runners-up. + // We'll be in this state almost always. let m = T::DesiredMembers::get() + T::DesiredRunnersUp::get(); clean::(); - // create m members and runners combined. + // Create `m` members and runners combined. let _ = fill_seats_up_to::(m)?; let all_candidates = submit_candidates::(c, "caller")?; let bailing = all_candidates[0].clone(); // Should be ("caller", 0) let count = candidate_count::(); whitelist!(bailing); - }: renounce_candidacy(RawOrigin::Signed(bailing), Renouncing::Candidate(count)) - verify { + + #[extrinsic_call] + renounce_candidacy(RawOrigin::Signed(bailing), Renouncing::Candidate(count)); + + // Reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); + + Ok(()) } - renounce_candidacy_members { - // removing members and runners will be cheaper than a candidate. - // we fix the number of members to when members and runners-up to the desired. We'll be in - // this state almost always. + #[benchmark] + fn renounce_candidacy_members() -> Result<(), BenchmarkError> { + // Removing members and runners will be cheaper than a candidate. + // We fix the number of members to when members and runners-up to the desired. + // We'll be in this state almost always. let m = T::DesiredMembers::get() + T::DesiredRunnersUp::get(); clean::(); - // create m members and runners combined. + // Create `m` members and runners combined. let members_and_runners_up = fill_seats_up_to::(m)?; let bailing = members_and_runners_up[0].clone(); - assert!(Elections::::is_member(&bailing)); + assert!(Pallet::::is_member(&bailing)); whitelist!(bailing); - }: renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::Member) - verify { + + #[extrinsic_call] + renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::Member); + + // Reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); + + Ok(()) } - renounce_candidacy_runners_up { - // removing members and runners will be cheaper than a candidate. - // we fix the number of members to when members and runners-up to the desired. We'll be in - // this state almost always. + #[benchmark] + fn renounce_candidacy_runners_up() -> Result<(), BenchmarkError> { + // Removing members and runners will be cheaper than a candidate. + // We fix the number of members to when members and runners-up to the desired. + // We'll be in this state almost always. let m = T::DesiredMembers::get() + T::DesiredRunnersUp::get(); clean::(); - // create m members and runners combined. + // Create `m` members and runners combined. let members_and_runners_up = fill_seats_up_to::(m)?; let bailing = members_and_runners_up[T::DesiredMembers::get() as usize + 1].clone(); - assert!(Elections::::is_runner_up(&bailing)); + assert!(Pallet::::is_runner_up(&bailing)); whitelist!(bailing); - }: renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::RunnerUp) - verify { + + #[extrinsic_call] + renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::RunnerUp); + + // Reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); + + Ok(()) } // We use the max block weight for this extrinsic for now. See below. - remove_member_without_replacement {}: { - Err(BenchmarkError::Override( - BenchmarkResult::from_weight(T::BlockWeights::get().max_block) - ))?; + #[benchmark] + fn remove_member_without_replacement() -> Result<(), BenchmarkError> { + #[block] + { + Err(BenchmarkError::Override(BenchmarkResult::from_weight( + T::BlockWeights::get().max_block, + )))?; + } + + Ok(()) } - remove_member_with_replacement { - // easy case. We have a runner up. Nothing will have that much of an impact. m will be - // number of members and runners. There is always at least one runner. + #[benchmark] + fn remove_member_with_replacement() -> Result<(), BenchmarkError> { + // Easy case. + // We have a runner up. + // Nothing will have that much of an impact. + // `m` will be number of members and runners. + // There is always at least one runner. let m = T::DesiredMembers::get() + T::DesiredRunnersUp::get(); clean::(); let _ = fill_seats_up_to::(m)?; - let removing = as_lookup::(Elections::::members_ids()[0].clone()); - }: remove_member(RawOrigin::Root, removing, true, false) - verify { - // must still have enough members. + let removing = as_lookup::(Pallet::::members_ids()[0].clone()); + + #[extrinsic_call] + remove_member(RawOrigin::Root, removing, true, false); + + // Must still have enough members. assert_eq!(Members::::get().len() as u32, T::DesiredMembers::get()); + + // Reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); - clean_defunct_voters { - // total number of voters. - let v in (T::MaxVoters::get() / 2) .. T::MaxVoters::get(); - // those that are defunct and need removal. - let d in 0 .. (T::MaxVoters::get() / 2); + Ok(()) + } - // remove any previous stuff. + #[benchmark] + fn clean_defunct_voters( + // Total number of voters. + v: Linear<{ T::MaxVoters::get() / 2 }, { T::MaxVoters::get() }>, + // Those that are defunct and need removal. + d: Linear<0, { T::MaxVoters::get() / 2 }>, + ) -> Result<(), BenchmarkError> { + // Remove any previous stuff. clean::(); let all_candidates = submit_candidates::(T::MaxCandidates::get(), "candidates")?; distribute_voters::(all_candidates, v, T::MaxVotesPerVoter::get() as usize)?; - // all candidates leave. + // All candidates leave. Candidates::::kill(); - // now everyone is defunct - assert!(Voting::::iter().all(|(_, v)| Elections::::is_defunct_voter(&v.votes))); + // Now everyone is defunct. + assert!(Voting::::iter().all(|(_, v)| Pallet::::is_defunct_voter(&v.votes))); assert_eq!(Voting::::iter().count() as u32, v); - let root = RawOrigin::Root; - }: _(root, v, d) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, v, d); + assert_eq!(Voting::::iter().count() as u32, v - d); + + Ok(()) } - election_phragmen { - // This is just to focus on phragmen in the context of this module. We always select 20 - // members, this is hard-coded in the runtime and cannot be trivially changed at this stage. - // Yet, change the number of voters, candidates and edge per voter to see the impact. Note - // that we give all candidates a self vote to make sure they are all considered. - let c in 1 .. T::MaxCandidates::get(); - let v in 1 .. T::MaxVoters::get(); - let e in (T::MaxVoters::get()) .. T::MaxVoters::get() * T::MaxVotesPerVoter::get(); + #[benchmark] + fn election_phragmen( + // This is just to focus on phragmen in the context of this module. + // We always select 20 members, this is hard-coded in the runtime and cannot be trivially + // changed at this stage. Yet, change the number of voters, candidates and edge per voter + // to see the impact. Note that we give all candidates a self vote to make sure they are + // all considered. + c: Linear<1, { T::MaxCandidates::get() }>, + v: Linear<1, { T::MaxVoters::get() }>, + e: Linear<{ T::MaxVoters::get() }, { T::MaxVoters::get() * T::MaxVotesPerVoter::get() }>, + ) -> Result<(), BenchmarkError> { clean::(); - // so we have a situation with v and e. we want e to basically always be in the range of `e - // -> e * T::MaxVotesPerVoter::get()`, but we cannot express that now with the benchmarks. - // So what we do is: when c is being iterated, v, and e are max and fine. when v is being - // iterated, e is being set to max and this is a problem. In these cases, we cap e to a - // lower value, namely v * T::MaxVotesPerVoter::get(). when e is being iterated, v is at - // max, and again fine. all in all, votes_per_voter can never be more than - // T::MaxVotesPerVoter::get(). Note that this might cause `v` to be an overestimate. + // So we have a situation with `v` and `e`. + // We want `e` to basically always be in the range of + // `e -> e * T::MaxVotesPerVoter::get()`, but we cannot express that now with the + // benchmarks. So what we do is: when `c` is being iterated, `v`, and `e` are max and + // fine. When `v` is being iterated, `e` is being set to max and this is a problem. + // In these cases, we cap `e` to a lower value, namely `v * T::MaxVotesPerVoter::get()`. + // When `e` is being iterated, `v` is at max, and again fine. + // All in all, `votes_per_voter` can never be more than `T::MaxVotesPerVoter::get()`. + // Note that this might cause `v` to be an overestimate. let votes_per_voter = (e / v).min(T::MaxVotesPerVoter::get()); let all_candidates = submit_candidates_with_self_vote::(c, "candidates")?; - let _ = distribute_voters::(all_candidates, v.saturating_sub(c), votes_per_voter as usize)?; - }: { - Elections::::on_initialize(T::TermDuration::get()); - } - verify { + let _ = + distribute_voters::(all_candidates, v.saturating_sub(c), votes_per_voter as usize)?; + + #[block] + { + Pallet::::on_initialize(T::TermDuration::get()); + } + assert_eq!(Members::::get().len() as u32, T::DesiredMembers::get().min(c)); assert_eq!( RunnersUp::::get().len() as u32, T::DesiredRunnersUp::get().min(c.saturating_sub(T::DesiredMembers::get())), ); + // reset members in between benchmark tests. #[cfg(test)] - { - // reset members in between benchmark tests. - use crate::tests::MEMBERS; - MEMBERS.with(|m| *m.borrow_mut() = vec![]); - } + MEMBERS.with(|m| *m.borrow_mut() = vec![]); + + Ok(()) } - impl_benchmark_test_suite!( - Elections, - crate::tests::ExtBuilder::default().desired_members(13).desired_runners_up(7), - crate::tests::Test, + impl_benchmark_test_suite! { + Pallet, + tests::ExtBuilder::default().desired_members(13).desired_runners_up(7), + tests::Test, exec_name = build_and_execute, - ); + } } From 0e09ad448bce27fcd255370cc2827ea5d2cf3892 Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Fri, 8 Nov 2024 00:45:38 +0800 Subject: [PATCH 064/166] Expose more syncing types to enable custom syncing strategy (#6163) This PR exposes additional syncing types to facilitate the development of a custom syncing strategy based on the existing Polkadot syncing strategy. Specifically, my goal is to isolate the state sync and chain sync components, allowing the state to be downloaded from the P2P network without running a full regular Substrate node. I also need to intercept the state responses during the state sync process. The newly exposed types are necessary to implement this custom syncing strategy. --- prdoc/pr_6163.prdoc | 13 +++++++++++++ substrate/client/network/sync/src/lib.rs | 1 + substrate/client/network/sync/src/strategy.rs | 5 +++-- substrate/client/network/sync/src/strategy/state.rs | 11 ++++++----- 4 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 prdoc/pr_6163.prdoc diff --git a/prdoc/pr_6163.prdoc b/prdoc/pr_6163.prdoc new file mode 100644 index 000000000000..c8571f80ed52 --- /dev/null +++ b/prdoc/pr_6163.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Expose more syncing types to enable custom syncing strategy + +doc: + - audience: Node Dev + description: | + Exposes additional syncing types to facilitate the development of a custom syncing strategy. + +crates: + - name: sc-network-sync + bump: patch diff --git a/substrate/client/network/sync/src/lib.rs b/substrate/client/network/sync/src/lib.rs index c458c7a5da49..e503a1cbdb18 100644 --- a/substrate/client/network/sync/src/lib.rs +++ b/substrate/client/network/sync/src/lib.rs @@ -18,6 +18,7 @@ //! Blockchain syncing implementation in Substrate. +pub use schema::v1::*; pub use service::syncing_service::SyncingService; pub use strategy::warp::{WarpSyncConfig, WarpSyncPhase, WarpSyncProgress}; pub use types::{SyncEvent, SyncEventStream, SyncState, SyncStatus, SyncStatusProvider}; diff --git a/substrate/client/network/sync/src/strategy.rs b/substrate/client/network/sync/src/strategy.rs index cdc6de1f8c65..2ac6674231e5 100644 --- a/substrate/client/network/sync/src/strategy.rs +++ b/substrate/client/network/sync/src/strategy.rs @@ -25,7 +25,7 @@ pub mod chain_sync; mod disconnected_peers; pub mod polkadot; -mod state; +pub mod state; pub mod state_sync; pub mod warp; @@ -177,7 +177,8 @@ pub enum SyncingAction { } impl SyncingAction { - fn is_finished(&self) -> bool { + /// Returns `true` if the syncing action has completed. + pub fn is_finished(&self) -> bool { matches!(self, SyncingAction::Finished) } diff --git a/substrate/client/network/sync/src/strategy/state.rs b/substrate/client/network/sync/src/strategy/state.rs index 93125fe8f66a..1abbb96ccd90 100644 --- a/substrate/client/network/sync/src/strategy/state.rs +++ b/substrate/client/network/sync/src/strategy/state.rs @@ -118,10 +118,11 @@ impl StateStrategy { } } - // Create a new instance with a custom state sync provider. - // Used in tests. - #[cfg(test)] - fn new_with_provider( + /// Create a new instance with a custom state sync provider. + /// + /// Note: In most cases, users should use [`StateStrategy::new`]. + /// This method is intended for custom sync strategies and advanced use cases. + pub fn new_with_provider( state_sync_provider: Box>, initial_peers: impl Iterator)>, protocol_name: ProtocolName, @@ -348,7 +349,7 @@ impl StateStrategy { } } - /// Get actions that should be performed by the owner on [`WarpSync`]'s behalf + /// Get actions that should be performed. #[must_use] pub fn actions( &mut self, From 8c8f339004058d268853d6dc5b225927234c6815 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Fri, 8 Nov 2024 13:25:22 +0100 Subject: [PATCH 065/166] runtimes: presets are provided as config patches (#6349) This PR introduces usage of `build_struct_json_patch` macro in all runtimes (also guides) within the code base. It also fixes macro to support _field init shorthand_, and _Struct Update_ syntax which were missing in original implementation. Follow up of #5700 and #5813 --- .../src/genesis_config_presets.rs | 17 +- .../src/genesis_config_presets.rs | 34 +- .../src/genesis_config_presets.rs | 38 +- .../src/genesis_config_presets.rs | 17 +- .../packages/guides/first-runtime/src/lib.rs | 8 +- .../rococo/src/genesis_config_presets.rs | 31 +- .../westend/src/genesis_config_presets.rs | 18 +- prdoc/pr_6349.prdoc | 44 ++ .../support/src/generate_genesis_config.rs | 560 +++++++++++++++--- templates/minimal/runtime/src/lib.rs | 7 +- .../runtime/src/genesis_config_presets.rs | 17 +- .../runtime/src/genesis_config_presets.rs | 9 +- 12 files changed, 572 insertions(+), 228 deletions(-) create mode 100644 prdoc/pr_6349.prdoc diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs index f440b5a2f421..824544e3b687 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/genesis_config_presets.rs @@ -18,6 +18,7 @@ use crate::*; use alloc::{vec, vec::Vec}; use cumulus_primitives_core::ParaId; +use frame_support::build_struct_json_patch; use hex_literal::hex; use parachains_common::{AccountId, AuraId}; use sp_core::crypto::UncheckedInto; @@ -35,15 +36,14 @@ fn asset_hub_westend_genesis( endowment: Balance, id: ParaId, ) -> serde_json::Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts.iter().cloned().map(|k| (k, endowment)).collect(), }, - parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() }, + parachain_info: ParachainInfoConfig { parachain_id: id }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: ASSET_HUB_WESTEND_ED * 16, - ..Default::default() }, session: SessionConfig { keys: invulnerables @@ -56,16 +56,9 @@ fn asset_hub_westend_genesis( ) }) .collect(), - ..Default::default() }, - polkadot_xcm: PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION) }, + }) } /// Encapsulates names of predefined presets. diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs index 20ca88bbc542..98e2450ee832 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/genesis_config_presets.rs @@ -18,6 +18,7 @@ use crate::*; use alloc::{vec, vec::Vec}; use cumulus_primitives_core::ParaId; +use frame_support::build_struct_json_patch; use parachains_common::{AccountId, AuraId}; use sp_genesis_builder::PresetId; use sp_keyring::Sr25519Keyring; @@ -34,7 +35,7 @@ fn bridge_hub_rococo_genesis( asset_hub_para_id: ParaId, opened_bridges: Vec<(Location, InteriorLocation, Option)>, ) -> serde_json::Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -42,11 +43,10 @@ fn bridge_hub_rococo_genesis( .map(|k| (k, 1u128 << 60)) .collect::>(), }, - parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() }, + parachain_info: ParachainInfoConfig { parachain_id: id }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: BRIDGE_HUB_ROCOCO_ED * 16, - ..Default::default() }, session: SessionConfig { keys: invulnerables @@ -59,33 +59,15 @@ fn bridge_hub_rococo_genesis( ) }) .collect(), - ..Default::default() - }, - polkadot_xcm: PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - bridge_westend_grandpa: BridgeWestendGrandpaConfig { - owner: bridges_pallet_owner.clone(), - ..Default::default() }, + polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION) }, + bridge_westend_grandpa: BridgeWestendGrandpaConfig { owner: bridges_pallet_owner.clone() }, bridge_westend_messages: BridgeWestendMessagesConfig { owner: bridges_pallet_owner.clone(), - ..Default::default() - }, - xcm_over_bridge_hub_westend: XcmOverBridgeHubWestendConfig { - opened_bridges, - ..Default::default() }, - ethereum_system: EthereumSystemConfig { - para_id: id, - asset_hub_para_id, - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + xcm_over_bridge_hub_westend: XcmOverBridgeHubWestendConfig { opened_bridges }, + ethereum_system: EthereumSystemConfig { para_id: id, asset_hub_para_id }, + }) } /// Provides the JSON representation of predefined genesis config for given `id`. diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs index 421c36246774..69ba9ca9ece7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/genesis_config_presets.rs @@ -18,6 +18,7 @@ use crate::*; use alloc::{vec, vec::Vec}; use cumulus_primitives_core::ParaId; +use frame_support::build_struct_json_patch; use parachains_common::{AccountId, AuraId}; use sp_genesis_builder::PresetId; use sp_keyring::Sr25519Keyring; @@ -34,7 +35,7 @@ fn bridge_hub_westend_genesis( asset_hub_para_id: ParaId, opened_bridges: Vec<(Location, InteriorLocation, Option)>, ) -> serde_json::Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -42,11 +43,10 @@ fn bridge_hub_westend_genesis( .map(|k| (k, 1u128 << 60)) .collect::>(), }, - parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() }, + parachain_info: ParachainInfoConfig { parachain_id: id }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: BRIDGE_HUB_WESTEND_ED * 16, - ..Default::default() }, session: SessionConfig { keys: invulnerables @@ -59,33 +59,13 @@ fn bridge_hub_westend_genesis( ) }) .collect(), - ..Default::default() }, - polkadot_xcm: PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - bridge_rococo_grandpa: BridgeRococoGrandpaConfig { - owner: bridges_pallet_owner.clone(), - ..Default::default() - }, - bridge_rococo_messages: BridgeRococoMessagesConfig { - owner: bridges_pallet_owner.clone(), - ..Default::default() - }, - xcm_over_bridge_hub_rococo: XcmOverBridgeHubRococoConfig { - opened_bridges, - ..Default::default() - }, - ethereum_system: EthereumSystemConfig { - para_id: id, - asset_hub_para_id, - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION) }, + bridge_rococo_grandpa: BridgeRococoGrandpaConfig { owner: bridges_pallet_owner.clone() }, + bridge_rococo_messages: BridgeRococoMessagesConfig { owner: bridges_pallet_owner.clone() }, + xcm_over_bridge_hub_rococo: XcmOverBridgeHubRococoConfig { opened_bridges }, + ethereum_system: EthereumSystemConfig { para_id: id, asset_hub_para_id }, + }) } /// Provides the JSON representation of predefined genesis config for given `id`. diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs index 77e971ff8ad7..007ff6164a74 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/genesis_config_presets.rs @@ -18,6 +18,7 @@ use crate::*; use alloc::{vec, vec::Vec}; use cumulus_primitives_core::ParaId; +use frame_support::build_struct_json_patch; use parachains_common::{AccountId, AuraId}; use sp_genesis_builder::PresetId; use sp_keyring::Sr25519Keyring; @@ -30,7 +31,7 @@ fn collectives_westend_genesis( endowed_accounts: Vec, id: ParaId, ) -> serde_json::Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -38,11 +39,10 @@ fn collectives_westend_genesis( .map(|k| (k, COLLECTIVES_WESTEND_ED * 4096)) .collect::>(), }, - parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() }, + parachain_info: ParachainInfoConfig { parachain_id: id }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect(), candidacy_bond: COLLECTIVES_WESTEND_ED * 16, - ..Default::default() }, session: SessionConfig { keys: invulnerables @@ -55,16 +55,9 @@ fn collectives_westend_genesis( ) }) .collect(), - ..Default::default() }, - polkadot_xcm: PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION) }, + }) } /// Provides the JSON representation of predefined genesis config for given `id`. diff --git a/docs/sdk/packages/guides/first-runtime/src/lib.rs b/docs/sdk/packages/guides/first-runtime/src/lib.rs index 7c96f5653e52..61ca550c8750 100644 --- a/docs/sdk/packages/guides/first-runtime/src/lib.rs +++ b/docs/sdk/packages/guides/first-runtime/src/lib.rs @@ -130,23 +130,21 @@ pub mod genesis_config_presets { interface::{Balance, MinimumBalance}, BalancesConfig, RuntimeGenesisConfig, SudoConfig, }; + use frame::deps::frame_support::build_struct_json_patch; use serde_json::Value; /// Returns a development genesis config preset. #[docify::export] pub fn development_config_genesis() -> Value { let endowment = >::get().max(1) * 1000; - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: AccountKeyring::iter() .map(|a| (a.to_account_id(), endowment)) .collect::>(), }, sudo: SudoConfig { key: Some(AccountKeyring::Alice.to_account_id()) }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + }) } /// Get the set of the available genesis config presets. diff --git a/polkadot/runtime/rococo/src/genesis_config_presets.rs b/polkadot/runtime/rococo/src/genesis_config_presets.rs index 39c862660894..bdbf6f37d92c 100644 --- a/polkadot/runtime/rococo/src/genesis_config_presets.rs +++ b/polkadot/runtime/rococo/src/genesis_config_presets.rs @@ -23,6 +23,7 @@ use crate::{ #[cfg(not(feature = "std"))] use alloc::format; use alloc::{vec, vec::Vec}; +use frame_support::build_struct_json_patch; use polkadot_primitives::{AccountId, AssignmentId, SchedulerParams, ValidatorId}; use rococo_runtime_constants::currency::UNITS as ROC; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; @@ -163,7 +164,7 @@ fn rococo_testnet_genesis( const ENDOWMENT: u128 = 1_000_000 * ROC; - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts.iter().map(|k| (k.clone(), ENDOWMENT)).collect::>(), }, @@ -185,9 +186,8 @@ fn rococo_testnet_genesis( ) }) .collect::>(), - ..Default::default() }, - babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG, ..Default::default() }, + babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG }, sudo: SudoConfig { key: Some(root_key.clone()) }, configuration: ConfigurationConfig { config: polkadot_runtime_parachains::configuration::HostConfiguration { @@ -198,14 +198,8 @@ fn rococo_testnet_genesis( ..default_parachains_host_configuration() }, }, - registrar: RegistrarConfig { - next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID, - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + registrar: RegistrarConfig { next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID }, + }) } // staging_testnet @@ -427,7 +421,7 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { const ENDOWMENT: u128 = 1_000_000 * ROC; const STASH: u128 = 100 * ROC; - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -440,19 +434,12 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { .into_iter() .map(|x| (x.0.clone(), x.0, rococo_session_keys(x.2, x.3, x.4, x.5, x.6, x.7))) .collect::>(), - ..Default::default() }, - babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG, ..Default::default() }, + babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG }, sudo: SudoConfig { key: Some(endowed_accounts[0].clone()) }, configuration: ConfigurationConfig { config: default_parachains_host_configuration() }, - registrar: RegistrarConfig { - next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID, - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + registrar: RegistrarConfig { next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID }, + }) } //development diff --git a/polkadot/runtime/westend/src/genesis_config_presets.rs b/polkadot/runtime/westend/src/genesis_config_presets.rs index b074d54fb582..b8f7710089e0 100644 --- a/polkadot/runtime/westend/src/genesis_config_presets.rs +++ b/polkadot/runtime/westend/src/genesis_config_presets.rs @@ -222,7 +222,7 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { // // SECRET_SEED="slow awkward present example safe bundle science ocean cradle word tennis earn" // subkey inspect -n polkadot "$SECRET_SEED" - let endowed_accounts = vec![ + let endowed_accounts: Vec = vec![ // 15S75FkhCWEowEGfxWwVfrW3LQuy8w8PNhVmrzfsVhCMjUh1 hex!["c416837e232d9603e83162ef4bda08e61580eeefe60fe92fc044aa508559ae42"].into(), ]; @@ -338,7 +338,7 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { const ENDOWMENT: u128 = 1_000_000 * WND; const STASH: u128 = 100 * WND; - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -364,7 +364,6 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { ) }) .collect::>(), - ..Default::default() }, staking: StakingConfig { validator_count: 50, @@ -376,19 +375,12 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect::>(), force_era: Forcing::ForceNone, slash_reward_fraction: Perbill::from_percent(10), - ..Default::default() }, - babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG, ..Default::default() }, + babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG }, sudo: SudoConfig { key: Some(endowed_accounts[0].clone()) }, configuration: ConfigurationConfig { config: default_parachains_host_configuration() }, - registrar: RegistrarConfig { - next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID, - ..Default::default() - }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + registrar: RegistrarConfig { next_free_para_id: polkadot_primitives::LOWEST_PUBLIC_ID }, + }) } //development diff --git a/prdoc/pr_6349.prdoc b/prdoc/pr_6349.prdoc new file mode 100644 index 000000000000..40f02712c99a --- /dev/null +++ b/prdoc/pr_6349.prdoc @@ -0,0 +1,44 @@ +title: "runtimes: presets are provided as config patches" + +doc: + - audience: Runtime Dev + description: | + This PR introduces usage of build_struct_json_patch macro in all + runtimes (also guides) within the code base. It also fixes macro to support + field init shorthand, and Struct Update syntax which were missing in original + implementation. + +crates: + - name: frame-support + bump: major + + - name: westend-runtime + bump: patch + + - name: rococo-runtime + bump: patch + + - name: asset-hub-westend-runtime + bump: patch + + - name: bridge-hub-rococo-runtime + bump: patch + + - name: bridge-hub-westend-runtime + bump: patch + + - name: collectives-westend-runtime + bump: patch + + - name: minimal-template-runtime + bump: patch + + - name: solochain-template-runtime + bump: patch + + - name: parachain-template-runtime + bump: patch + + - name: polkadot-sdk-docs-first-runtime + bump: patch + diff --git a/substrate/frame/support/src/generate_genesis_config.rs b/substrate/frame/support/src/generate_genesis_config.rs index fc21e76c7427..283840d70c7c 100644 --- a/substrate/frame/support/src/generate_genesis_config.rs +++ b/substrate/frame/support/src/generate_genesis_config.rs @@ -23,41 +23,44 @@ use alloc::{borrow::Cow, format, string::String}; /// Represents the initialization method of a field within a struct. /// -/// This enum provides information about how it was initialized and the field name (as a `String`). +/// This enum provides information about how it was initialized. /// /// Intended to be used in `build_struct_json_patch` macro. #[derive(Debug)] -pub enum InitializedField<'a> { +pub enum InitilizationType { /// The field was partially initialized (e.g., specific fields within the struct were set /// manually). - Partial(Cow<'a, str>), - /// The field was fully initialized (e.g., using `new()` or `default()` like methods). - Full(Cow<'a, str>), + Partial, + /// The field was fully initialized (e.g., using `new()` or `default()` like methods + Full, } +/// This struct provides information about how the struct field was initialized and the field name +/// (as a `&str`). +/// +/// Intended to be used in `build_struct_json_patch` macro. +#[derive(Debug)] +pub struct InitializedField<'a>(InitilizationType, Cow<'a, str>); + impl<'a> InitializedField<'a> { /// Returns a name of the field. pub fn get_name(&'a self) -> &'a str { - match self { - Self::Partial(s) | Self::Full(s) => s, - } + &self.1 } /// Injects a prefix to the field name. pub fn add_prefix(&mut self, prefix: &str) { - match self { - Self::Partial(s) | Self::Full(s) => *s = format!("{prefix}.{s}").into(), - }; + self.1 = format!("{prefix}.{}", self.1).into() } /// Creates new partial field instiance. pub fn partial(s: &'a str) -> Self { - Self::Partial(s.into()) + Self(InitilizationType::Partial, s.into()) } /// Creates new full field instiance. pub fn full(s: &'a str) -> Self { - Self::Full(s.into()) + Self(InitilizationType::Full, s.into()) } } @@ -73,9 +76,15 @@ impl PartialEq for InitializedField<'_> { .map(|c| c.to_ascii_uppercase()) .eq(camel_chars.map(|c| c.to_ascii_uppercase())) } - match self { - InitializedField::Partial(field_name) | InitializedField::Full(field_name) => - field_name == other || compare_keys(field_name.chars(), other.chars()), + *self.1 == *other || compare_keys(self.1.chars(), other.chars()) + } +} + +impl<'a> From<(InitilizationType, &'a str)> for InitializedField<'a> { + fn from(value: (InitilizationType, &'a str)) -> Self { + match value.0 { + InitilizationType::Full => InitializedField::full(value.1), + InitilizationType::Partial => InitializedField::partial(value.1), } } } @@ -104,8 +113,8 @@ pub fn retain_initialized_fields( let current_key = if current_root.is_empty() { key.clone() } else { format!("{current_root}.{key}") }; match keys_to_retain.iter().find(|key| **key == current_key) { - Some(InitializedField::Full(_)) => true, - Some(InitializedField::Partial(_)) => { + Some(InitializedField(InitilizationType::Full, _)) => true, + Some(InitializedField(InitilizationType::Partial, _)) => { retain_initialized_fields(value, keys_to_retain, current_key.clone()); true }, @@ -208,89 +217,154 @@ pub fn retain_initialized_fields( #[macro_export] macro_rules! build_struct_json_patch { ( - $($struct_type:ident)::+ { $($tail:tt)* } + $($struct_type:ident)::+ { $($body:tt)* } ) => { { - let mut keys = $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); + let mut __keys = $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); #[allow(clippy::needless_update)] - let struct_instance = $crate::build_struct_json_patch!($($struct_type)::+, keys @ { $($tail)* }); - let mut json_value = - $crate::__private::serde_json::to_value(struct_instance).expect("serialization to json should work. qed"); - $crate::generate_genesis_config::retain_initialized_fields(&mut json_value, &keys, Default::default()); - json_value + let __struct_instance = $crate::build_struct_json_patch!($($struct_type)::+, __keys @ { $($body)* }).0; + let mut __json_value = + $crate::__private::serde_json::to_value(__struct_instance).expect("serialization to json should work. qed"); + $crate::generate_genesis_config::retain_initialized_fields(&mut __json_value, &__keys, Default::default()); + __json_value } }; - ($($struct_type:ident)::+, $all_keys:ident @ { $($tail:tt)* }) => { - $($struct_type)::+ { - ..$crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*) + ($($struct_type:ident)::+, $all_keys:ident @ { $($body:tt)* }) => { + { + let __value = $crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($body)*); + ( + $($struct_type)::+ { ..__value.0 }, + __value.1 + ) } }; - ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $($type:ident)::+ { $keyi:ident : $value:tt } ) => { - $($struct_type)::+ { - $key: { - $all_keys.push($crate::generate_genesis_config::InitializedField::partial(stringify!($key))); - $all_keys.push( - $crate::generate_genesis_config::InitializedField::full(concat!(stringify!($key), ".", stringify!($keyi))) - ); - $($type)::+ { - $keyi:$value, - ..Default::default() - } + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $($type:ident)::+ { $($body:tt)* } ) => { + ( + $($struct_type)::+ { + $key: { + let mut __inner_keys = + $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); + let __value = $crate::build_struct_json_patch!($($type)::+, __inner_keys @ { $($body)* }); + for i in __inner_keys.iter_mut() { + i.add_prefix(stringify!($key)); + }; + $all_keys.push((__value.1,stringify!($key)).into()); + $all_keys.extend(__inner_keys); + __value.0 + }, + ..Default::default() }, - ..Default::default() + $crate::generate_genesis_config::InitilizationType::Partial + ) + }; + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $($type:ident)::+ { $($body:tt)* }, $($tail:tt)*) => { + { + let mut __initialization_type; + ( + $($struct_type)::+ { + $key : { + let mut __inner_keys = + $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); + let __value = $crate::build_struct_json_patch!($($type)::+, __inner_keys @ { $($body)* }); + $all_keys.push((__value.1,stringify!($key)).into()); + + for i in __inner_keys.iter_mut() { + i.add_prefix(stringify!($key)); + }; + $all_keys.extend(__inner_keys); + __value.0 + }, + .. { + let (__value, __tmp) = + $crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*); + __initialization_type = __tmp; + __value + } + }, + __initialization_type + ) } }; - ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $($type:ident)::+ { $($body:tt)* } ) => { - $($struct_type)::+ { - $key: { - $all_keys.push($crate::generate_genesis_config::InitializedField::partial(stringify!($key))); - let mut inner_keys = $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); - let value = $crate::build_struct_json_patch!($($type)::+, inner_keys @ { $($body)* }); - for i in inner_keys.iter_mut() { - i.add_prefix(stringify!($key)); - }; - $all_keys.extend(inner_keys); - value - }, - ..Default::default() + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $value:expr, $($tail:tt)* ) => { + { + let mut __initialization_type; + ( + $($struct_type)::+ { + $key: { + $all_keys.push($crate::generate_genesis_config::InitializedField::full( + stringify!($key)) + ); + $value + }, + .. { + let (__value, __tmp) = + $crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*); + __initialization_type = __tmp; + __value + } + }, + __initialization_type + ) } }; - ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $($type:ident)::+ { $($body:tt)* }, $($tail:tt)* ) => { - $($struct_type)::+ { - $key : { - $all_keys.push($crate::generate_genesis_config::InitializedField::partial(stringify!($key))); - let mut inner_keys = $crate::__private::Vec::<$crate::generate_genesis_config::InitializedField>::default(); - let value = $crate::build_struct_json_patch!($($type)::+, inner_keys @ { $($body)* }); - for i in inner_keys.iter_mut() { - i.add_prefix(stringify!($key)); - }; - $all_keys.extend(inner_keys); - value + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $value:expr ) => { + ( + $($struct_type)::+ { + $key: { + $all_keys.push($crate::generate_genesis_config::InitializedField::full(stringify!($key))); + $value + }, + ..Default::default() }, - .. $crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*) + $crate::generate_genesis_config::InitilizationType::Partial + ) + }; + // field init shorthand + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident, $($tail:tt)* ) => { + { + let __update = $crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*); + ( + $($struct_type)::+ { + $key: { + $all_keys.push($crate::generate_genesis_config::InitializedField::full( + stringify!($key)) + ); + $key + }, + ..__update.0 + }, + __update.1 + ) } }; - ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $value:expr, $($tail:tt)* ) => { - $($struct_type)::+ { - $key: { - $all_keys.push($crate::generate_genesis_config::InitializedField::full(stringify!($key))); - $value + ($($struct_type:ident)::+, $all_keys:ident @ $key:ident ) => { + ( + $($struct_type)::+ { + $key: { + $all_keys.push($crate::generate_genesis_config::InitializedField::full(stringify!($key))); + $key + }, + ..Default::default() }, - ..$crate::build_struct_json_patch!($($struct_type)::+, $all_keys @ $($tail)*) - } + $crate::generate_genesis_config::InitilizationType::Partial + ) }; - ($($struct_type:ident)::+, $all_keys:ident @ $key:ident: $value:expr ) => { - $($struct_type)::+ { - $key: { - $all_keys.push($crate::generate_genesis_config::InitializedField::full(stringify!($key))); - $value + // update struct + ($($struct_type:ident)::+, $all_keys:ident @ ..$update:expr ) => { + ( + $($struct_type)::+ { + ..$update }, - ..Default::default() - } + $crate::generate_genesis_config::InitilizationType::Full + ) }; - ($($struct_type:ident)::+, $all_keys:ident @ $(,)?) => { - $($struct_type)::+ { ..Default::default() } + ( + $($struct_type)::+ { + ..Default::default() + }, + $crate::generate_genesis_config::InitilizationType::Partial + ) }; } @@ -401,11 +475,8 @@ mod test { macro_rules! test { ($($struct:ident)::+ { $($v:tt)* }, { $($j:tt)* } ) => {{ - println!("--"); let expected = serde_json::json!({ $($j)* }); - println!("json: {}", serde_json::to_string_pretty(&expected).unwrap()); let value = build_struct_json_patch!($($struct)::+ { $($v)* }); - println!("gc: {}", serde_json::to_string_pretty(&value).unwrap()); assert_eq!(value, expected); }}; } @@ -415,6 +486,7 @@ mod test { let t = 5; const C: u32 = 5; test!(TestStruct { b: 5 }, { "b": 5 }); + test!(TestStruct { b: 5, }, { "b": 5 }); #[allow(unused_braces)] { test!(TestStruct { b: { 4 + 34 } } , { "b": 38 }); @@ -705,6 +777,324 @@ mod test { ); } + #[test] + fn test_generate_config_macro_field_init_shorthand() { + { + let x = 5; + test!(TestStruct { s: S { x } }, { "s": { "x": 5 } }); + } + { + let s = nested_mod::InsideMod { a: 34, b: 8 }; + test!( + TestStruct { + t: nested_mod::InsideMod { a: 32 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + s, + a: 32, + } + }, + { + "t" : { "a": 32 }, + "u" : { "a": 32, "s": { "a": 34, "b": 8} } + } + ); + } + { + let s = nested_mod::InsideMod { a: 34, b: 8 }; + test!( + TestStruct { + t: nested_mod::InsideMod { a: 32 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + a: 32, + s, + } + }, + { + "t" : { "a": 32 }, + "u" : { "a": 32, "s": { "a": 34, "b": 8} } + } + ); + } + } + + #[test] + fn test_generate_config_macro_struct_update() { + { + let s = S { x: 5 }; + test!(TestStruct { s: S { ..s } }, { "s": { "x": 5 } }); + } + { + mod nested { + use super::*; + pub fn function() -> S { + S { x: 5 } + } + } + test!(TestStruct { s: S { ..nested::function() } }, { "s": { "x": 5 } }); + } + { + let s = nested_mod::InsideMod { a: 34, b: 8 }; + let s1 = nested_mod::InsideMod { a: 34, b: 8 }; + test!( + TestStruct { + t: nested_mod::InsideMod { ..s1 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + s, + a: 32, + } + }, + { + "t" : { "a": 34, "b": 8 }, + "u" : { "a": 32, "s": { "a": 34, "b": 8} } + } + ); + } + { + let i3 = nested_mod::nested_mod2::nested_mod3::InsideMod3 { + a: 1, + b: 2, + s: nested_mod::InsideMod { a: 55, b: 88 }, + }; + test!( + TestStruct { + t: nested_mod::InsideMod { a: 32 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + a: 32, + ..i3 + } + }, + { + "t" : { "a": 32 }, + "u" : { "a": 32, "b": 2, "s": { "a": 55, "b": 88} } + } + ); + } + { + let s = nested_mod::InsideMod { a: 34, b: 8 }; + test!( + TestStruct { + t: nested_mod::InsideMod { a: 32 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + a: 32, + s: nested_mod::InsideMod { + b: 66, + ..s + } + } + }, + { + "t" : { "a": 32 }, + "u" : { "a": 32, "s": { "a": 34, "b": 66} } + } + ); + } + { + let s = nested_mod::InsideMod { a: 34, b: 8 }; + test!( + TestStruct { + t: nested_mod::InsideMod { a: 32 }, + u: nested_mod::nested_mod2::nested_mod3::InsideMod3 { + s: nested_mod::InsideMod { + b: 66, + ..s + }, + a: 32 + } + }, + { + "t" : { "a": 32 }, + "u" : { "a": 32, "s": { "a": 34, "b": 66} } + } + ); + } + } + + #[test] + fn test_generate_config_macro_with_execution_order() { + #[derive(Debug, Default, serde::Serialize, serde::Deserialize, PartialEq)] + struct X { + x: Vec, + x2: Vec, + y2: Y, + } + #[derive(Debug, Default, serde::Serialize, serde::Deserialize, PartialEq)] + struct Y { + y: Vec, + } + #[derive(Debug, Default, serde::Serialize, serde::Deserialize, PartialEq)] + struct Z { + a: u32, + x: X, + y: Y, + } + { + let v = vec![1, 2, 3]; + test!(Z { a: 0, x: X { x: v }, }, { + "a": 0, "x": { "x": [1,2,3] } + }); + } + { + let v = vec![1, 2, 3]; + test!(Z { a: 3, x: X { x: v.clone() }, y: Y { y: v } }, { + "a": 3, "x": { "x": [1,2,3] }, "y": { "y": [1,2,3] } + }); + } + { + let v = vec![1, 2, 3]; + test!(Z { a: 3, x: X { y2: Y { y: v.clone() }, x: v.clone() }, y: Y { y: v } }, { + "a": 3, "x": { "x": [1,2,3], "y2":{ "y":[1,2,3] } }, "y": { "y": [1,2,3] } + }); + } + { + let v = vec![1, 2, 3]; + test!(Z { a: 3, y: Y { y: v.clone() }, x: X { y2: Y { y: v.clone() }, x: v }, }, { + "a": 3, "x": { "x": [1,2,3], "y2":{ "y":[1,2,3] } }, "y": { "y": [1,2,3] } + }); + } + { + let v = vec![1, 2, 3]; + test!( + Z { + y: Y { + y: v.clone() + }, + x: X { + y2: Y { + y: v.clone() + }, + x: v.clone(), + x2: v.clone() + }, + }, + { + "x": { + "x": [1,2,3], + "x2": [1,2,3], + "y2": { + "y":[1,2,3] + } + }, + "y": { + "y": [1,2,3] + } + }); + } + { + let v = vec![1, 2, 3]; + test!( + Z { + y: Y { + y: v.clone() + }, + x: X { + y2: Y { + y: v.clone() + }, + x: v + }, + }, + { + "x": { + "x": [1,2,3], + "y2": { + "y":[1,2,3] + } + }, + "y": { + "y": [1,2,3] + } + }); + } + { + let mut v = vec![0, 1, 2]; + let f = |vec: &mut Vec| -> Vec { + vec.iter_mut().for_each(|x| *x += 1); + vec.clone() + }; + let z = Z { + a: 0, + y: Y { y: f(&mut v) }, + x: X { y2: Y { y: f(&mut v) }, x: f(&mut v), x2: vec![] }, + }; + let z_expected = Z { + a: 0, + y: Y { y: vec![1, 2, 3] }, + x: X { y2: Y { y: vec![2, 3, 4] }, x: vec![3, 4, 5], x2: vec![] }, + }; + assert_eq!(z, z_expected); + v = vec![0, 1, 2]; + println!("{z:?}"); + test!( + Z { + y: Y { + y: f(&mut v) + }, + x: X { + y2: Y { + y: f(&mut v) + }, + x: f(&mut v) + }, + }, + { + "y": { + "y": [1,2,3] + }, + "x": { + "y2": { + "y":[2,3,4] + }, + "x": [3,4,5], + }, + }); + } + { + let mut v = vec![0, 1, 2]; + let f = |vec: &mut Vec| -> Vec { + vec.iter_mut().for_each(|x| *x += 1); + vec.clone() + }; + let z = Z { + a: 0, + y: Y { y: f(&mut v) }, + x: X { y2: Y { y: f(&mut v) }, x: f(&mut v), x2: f(&mut v) }, + }; + let z_expected = Z { + a: 0, + y: Y { y: vec![1, 2, 3] }, + x: X { y2: Y { y: vec![2, 3, 4] }, x: vec![3, 4, 5], x2: vec![4, 5, 6] }, + }; + assert_eq!(z, z_expected); + v = vec![0, 1, 2]; + println!("{z:?}"); + test!( + Z { + y: Y { + y: f(&mut v) + }, + x: X { + y2: Y { + y: f(&mut v) + }, + x: f(&mut v), + x2: f(&mut v) + }, + }, + { + "y": { + "y": [1,2,3] + }, + "x": { + "y2": { + "y":[2,3,4] + }, + "x": [3,4,5], + "x2": [4,5,6], + }, + }); + } + } + #[test] fn test_generate_config_macro_with_nested_mods() { test!( @@ -797,7 +1187,6 @@ mod retain_keys_test { ( $s:literal ) => { let field = InitializedField::full($s); let cc = inflector::cases::camelcase::to_camel_case($s); - println!("field: {:?}, cc: {}", field, cc); assert_eq!(field,cc); } ; ( &[ $f:literal $(, $r:literal)* ]) => { @@ -808,7 +1197,6 @@ mod retain_keys_test { .map(|s| inflector::cases::camelcase::to_camel_case(s)) .collect::>() .join("."); - println!("field: {:?}, cc: {}", field, cc); assert_eq!(field,cc); } ; ); diff --git a/templates/minimal/runtime/src/lib.rs b/templates/minimal/runtime/src/lib.rs index ecdba739c50e..7b8449f2abe4 100644 --- a/templates/minimal/runtime/src/lib.rs +++ b/templates/minimal/runtime/src/lib.rs @@ -51,17 +51,14 @@ pub mod genesis_config_presets { /// Returns a development genesis config preset. pub fn development_config_genesis() -> Value { let endowment = >::get().max(1) * 1000; - let config = RuntimeGenesisConfig { + frame_support::build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: AccountKeyring::iter() .map(|a| (a.to_account_id(), endowment)) .collect::>(), }, sudo: SudoConfig { key: Some(AccountKeyring::Alice.to_account_id()) }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + }) } /// Get the set of the available genesis config presets. diff --git a/templates/parachain/runtime/src/genesis_config_presets.rs b/templates/parachain/runtime/src/genesis_config_presets.rs index 77ae85c0b174..aa1ff7895eb8 100644 --- a/templates/parachain/runtime/src/genesis_config_presets.rs +++ b/templates/parachain/runtime/src/genesis_config_presets.rs @@ -8,6 +8,7 @@ use alloc::{vec, vec::Vec}; use polkadot_sdk::{staging_xcm as xcm, *}; use cumulus_primitives_core::ParaId; +use frame_support::build_struct_json_patch; use parachains_common::AuraId; use serde_json::Value; use sp_genesis_builder::PresetId; @@ -31,7 +32,7 @@ fn testnet_genesis( root: AccountId, id: ParaId, ) -> Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -39,11 +40,10 @@ fn testnet_genesis( .map(|k| (k, 1u128 << 60)) .collect::>(), }, - parachain_info: ParachainInfoConfig { parachain_id: id, ..Default::default() }, + parachain_info: ParachainInfoConfig { parachain_id: id }, collator_selection: CollatorSelectionConfig { invulnerables: invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), candidacy_bond: EXISTENTIAL_DEPOSIT * 16, - ..Default::default() }, session: SessionConfig { keys: invulnerables @@ -56,17 +56,10 @@ fn testnet_genesis( ) }) .collect::>(), - ..Default::default() - }, - polkadot_xcm: PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() }, + polkadot_xcm: PolkadotXcmConfig { safe_xcm_version: Some(SAFE_XCM_VERSION) }, sudo: SudoConfig { key: Some(root) }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + }) } fn local_testnet_genesis() -> Value { diff --git a/templates/solochain/runtime/src/genesis_config_presets.rs b/templates/solochain/runtime/src/genesis_config_presets.rs index 7c444456a600..049f4593451b 100644 --- a/templates/solochain/runtime/src/genesis_config_presets.rs +++ b/templates/solochain/runtime/src/genesis_config_presets.rs @@ -17,6 +17,7 @@ use crate::{AccountId, BalancesConfig, RuntimeGenesisConfig, SudoConfig}; use alloc::{vec, vec::Vec}; +use frame_support::build_struct_json_patch; use serde_json::Value; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_consensus_grandpa::AuthorityId as GrandpaId; @@ -29,7 +30,7 @@ fn testnet_genesis( endowed_accounts: Vec, root: AccountId, ) -> Value { - let config = RuntimeGenesisConfig { + build_struct_json_patch!(RuntimeGenesisConfig { balances: BalancesConfig { balances: endowed_accounts .iter() @@ -42,13 +43,9 @@ fn testnet_genesis( }, grandpa: pallet_grandpa::GenesisConfig { authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect::>(), - ..Default::default() }, sudo: SudoConfig { key: Some(root) }, - ..Default::default() - }; - - serde_json::to_value(config).expect("Could not build genesis config.") + }) } /// Return the development genesis config. From edf79aa972bcf2e043e18065a9bb860ecdbd1a6e Mon Sep 17 00:00:00 2001 From: Joseph Zhao <65984904+programskillforverification@users.noreply.github.com> Date: Fri, 8 Nov 2024 23:39:19 +0800 Subject: [PATCH 066/166] Migrate pallet-transaction-storage and pallet-indices to benchmark v2 (#6290) Part of: #6202 --------- Co-authored-by: Giuseppe Re Co-authored-by: GitHub Action --- prdoc/pr_6290.prdoc | 11 +++ substrate/frame/indices/src/benchmarking.rs | 70 ++++++++++++------- .../transaction-storage/src/benchmarking.rs | 51 +++++++++----- 3 files changed, 88 insertions(+), 44 deletions(-) create mode 100644 prdoc/pr_6290.prdoc diff --git a/prdoc/pr_6290.prdoc b/prdoc/pr_6290.prdoc new file mode 100644 index 000000000000..a05d0cd15acf --- /dev/null +++ b/prdoc/pr_6290.prdoc @@ -0,0 +1,11 @@ +title: Migrate pallet-transaction-storage and pallet-indices to benchmark v2 +doc: +- audience: Runtime Dev + description: |- + Part of: + #6202 +crates: +- name: pallet-indices + bump: patch +- name: pallet-transaction-storage + bump: patch diff --git a/substrate/frame/indices/src/benchmarking.rs b/substrate/frame/indices/src/benchmarking.rs index bd173815cb34..28f5e3bf5cf0 100644 --- a/substrate/frame/indices/src/benchmarking.rs +++ b/substrate/frame/indices/src/benchmarking.rs @@ -19,26 +19,31 @@ #![cfg(feature = "runtime-benchmarks")] -use super::*; -use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; +use crate::*; +use frame_benchmarking::v2::*; use frame_system::RawOrigin; use sp_runtime::traits::Bounded; -use crate::Pallet as Indices; - const SEED: u32 = 0; -benchmarks! { - claim { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn claim() { let account_index = T::AccountIndex::from(SEED); let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); - }: _(RawOrigin::Signed(caller.clone()), account_index) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), account_index); + assert_eq!(Accounts::::get(account_index).unwrap().0, caller); } - transfer { + #[benchmark] + fn transfer() -> Result<(), BenchmarkError> { let account_index = T::AccountIndex::from(SEED); // Setup accounts let caller: T::AccountId = whitelisted_caller(); @@ -47,25 +52,33 @@ benchmarks! { let recipient_lookup = T::Lookup::unlookup(recipient.clone()); T::Currency::make_free_balance_be(&recipient, BalanceOf::::max_value()); // Claim the index - Indices::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; - }: _(RawOrigin::Signed(caller.clone()), recipient_lookup, account_index) - verify { + Pallet::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), recipient_lookup, account_index); + assert_eq!(Accounts::::get(account_index).unwrap().0, recipient); + Ok(()) } - free { + #[benchmark] + fn free() -> Result<(), BenchmarkError> { let account_index = T::AccountIndex::from(SEED); // Setup accounts let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); // Claim the index - Indices::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; - }: _(RawOrigin::Signed(caller.clone()), account_index) - verify { + Pallet::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), account_index); + assert_eq!(Accounts::::get(account_index), None); + Ok(()) } - force_transfer { + #[benchmark] + fn force_transfer() -> Result<(), BenchmarkError> { let account_index = T::AccountIndex::from(SEED); // Setup accounts let original: T::AccountId = account("original", 0, SEED); @@ -74,25 +87,32 @@ benchmarks! { let recipient_lookup = T::Lookup::unlookup(recipient.clone()); T::Currency::make_free_balance_be(&recipient, BalanceOf::::max_value()); // Claim the index - Indices::::claim(RawOrigin::Signed(original).into(), account_index)?; - }: _(RawOrigin::Root, recipient_lookup, account_index, false) - verify { + Pallet::::claim(RawOrigin::Signed(original).into(), account_index)?; + + #[extrinsic_call] + _(RawOrigin::Root, recipient_lookup, account_index, false); + assert_eq!(Accounts::::get(account_index).unwrap().0, recipient); + Ok(()) } - freeze { + #[benchmark] + fn freeze() -> Result<(), BenchmarkError> { let account_index = T::AccountIndex::from(SEED); // Setup accounts let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); // Claim the index - Indices::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; - }: _(RawOrigin::Signed(caller.clone()), account_index) - verify { + Pallet::::claim(RawOrigin::Signed(caller.clone()).into(), account_index)?; + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), account_index); + assert_eq!(Accounts::::get(account_index).unwrap().2, true); + Ok(()) } // TODO in another PR: lookup and unlookup trait weights (not critical) - impl_benchmark_test_suite!(Indices, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite!(Pallet, mock::new_test_ext(), mock::Test); } diff --git a/substrate/frame/transaction-storage/src/benchmarking.rs b/substrate/frame/transaction-storage/src/benchmarking.rs index f360e9847a1e..0b5b0dc99405 100644 --- a/substrate/frame/transaction-storage/src/benchmarking.rs +++ b/substrate/frame/transaction-storage/src/benchmarking.rs @@ -19,16 +19,14 @@ #![cfg(feature = "runtime-benchmarks")] -use super::*; +use crate::*; use alloc::{vec, vec::Vec}; -use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_support::traits::{Get, OnFinalize, OnInitialize}; use frame_system::{pallet_prelude::BlockNumberFor, EventRecord, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, CheckedDiv, One, Zero}; use sp_transaction_storage_proof::TransactionStorageProof; -use crate::Pallet as TransactionStorage; - // Proof generated from max size storage: // ``` // let mut transactions = Vec::new(); @@ -122,39 +120,50 @@ pub fn run_to_block(n: frame_system::pallet_prelude::BlockNumberFor) { let caller: T::AccountId = whitelisted_caller(); let initial_balance = BalanceOf::::max_value().checked_div(&2u32.into()).unwrap(); T::Currency::set_balance(&caller, initial_balance); - }: _(RawOrigin::Signed(caller.clone()), vec![0u8; l as usize]) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), vec![0u8; l as usize]); + assert!(!BlockTransactions::::get().is_empty()); assert_last_event::(Event::Stored { index: 0 }.into()); } - renew { + #[benchmark] + fn renew() -> Result<(), BenchmarkError> { let caller: T::AccountId = whitelisted_caller(); let initial_balance = BalanceOf::::max_value().checked_div(&2u32.into()).unwrap(); T::Currency::set_balance(&caller, initial_balance); - TransactionStorage::::store( + Pallet::::store( RawOrigin::Signed(caller.clone()).into(), vec![0u8; T::MaxTransactionSize::get() as usize], )?; run_to_block::(1u32.into()); - }: _(RawOrigin::Signed(caller.clone()), BlockNumberFor::::zero(), 0) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), BlockNumberFor::::zero(), 0); + assert_last_event::(Event::Renewed { index: 0 }.into()); + + Ok(()) } - check_proof_max { + #[benchmark] + fn check_proof_max() -> Result<(), BenchmarkError> { run_to_block::(1u32.into()); let caller: T::AccountId = whitelisted_caller(); let initial_balance = BalanceOf::::max_value().checked_div(&2u32.into()).unwrap(); T::Currency::set_balance(&caller, initial_balance); - for _ in 0 .. T::MaxBlockTransactions::get() { - TransactionStorage::::store( + for _ in 0..T::MaxBlockTransactions::get() { + Pallet::::store( RawOrigin::Signed(caller.clone()).into(), vec![0u8; T::MaxTransactionSize::get() as usize], )?; @@ -162,10 +171,14 @@ benchmarks! { run_to_block::(StoragePeriod::::get() + BlockNumberFor::::one()); let encoded_proof = proof(); let proof = TransactionStorageProof::decode(&mut &*encoded_proof).unwrap(); - }: check_proof(RawOrigin::None, proof) - verify { + + #[extrinsic_call] + check_proof(RawOrigin::None, proof); + assert_last_event::(Event::ProofChecked.into()); + + Ok(()) } - impl_benchmark_test_suite!(TransactionStorage, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite!(Pallet, mock::new_test_ext(), mock::Test); } From 05ad5475dec748a8a30685bc29a7caba6e63c7ab Mon Sep 17 00:00:00 2001 From: Alin Dima Date: Mon, 11 Nov 2024 11:31:10 +0200 Subject: [PATCH 067/166] fix prospective-parachains best backable chain reversion bug (#6417) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kudos to @EclesioMeloJunior for noticing it Also added a regression test for it. The existing unit test was exercising only the case where the full chain is reverted --------- Co-authored-by: GitHub Action Co-authored-by: Bastian Köcher --- .../src/fragment_chain/mod.rs | 2 +- .../src/fragment_chain/tests.rs | 63 ++++++++++++++++++- prdoc/pr_6417.prdoc | 9 +++ 3 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 prdoc/pr_6417.prdoc diff --git a/polkadot/node/core/prospective-parachains/src/fragment_chain/mod.rs b/polkadot/node/core/prospective-parachains/src/fragment_chain/mod.rs index 265d1498ee96..ded0a3ab73b2 100644 --- a/polkadot/node/core/prospective-parachains/src/fragment_chain/mod.rs +++ b/polkadot/node/core/prospective-parachains/src/fragment_chain/mod.rs @@ -630,7 +630,7 @@ impl BackedChain { ) -> impl Iterator + 'a { let mut found_index = None; for index in 0..self.chain.len() { - let node = &self.chain[0]; + let node = &self.chain[index]; if found_index.is_some() { self.by_parent_head.remove(&node.parent_head_data_hash); diff --git a/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs b/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs index 2f8a5525570c..624dd74132c1 100644 --- a/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs +++ b/polkadot/node/core/prospective-parachains/src/fragment_chain/tests.rs @@ -1165,8 +1165,9 @@ fn test_populate_and_check_potential() { Err(Error::CandidateAlreadyKnown) ); - // Simulate a best chain reorg by backing a2. + // Simulate some best chain reorgs. { + // Back A2. The reversion should happen right at the root. let mut chain = chain.clone(); chain.candidate_backed(&candidate_a2_hash); assert_eq!(chain.best_chain_vec(), vec![candidate_a2_hash, candidate_b2_hash]); @@ -1185,6 +1186,66 @@ fn test_populate_and_check_potential() { chain.can_add_candidate_as_potential(&candidate_a_entry), Err(Error::ForkChoiceRule(_)) ); + + // Simulate a more complex chain reorg. + // A2 points to B2, which is backed. + // A2 has underneath a subtree A2 -> B2 -> C3 and A2 -> B2 -> C4. B2 and C3 are backed. C4 + // is kept because it has a lower candidate hash than C3. Backing C4 will cause a chain + // reorg. + + // Candidate C3. + let (pvd_c3, candidate_c3) = make_committed_candidate( + para_id, + relay_parent_y_info.hash, + relay_parent_y_info.number, + vec![0xb4].into(), + vec![0xc2].into(), + relay_parent_y_info.number, + ); + let candidate_c3_hash = candidate_c3.hash(); + let candidate_c3_entry = + CandidateEntry::new(candidate_c3_hash, candidate_c3, pvd_c3, CandidateState::Seconded) + .unwrap(); + + // Candidate C4. + let (pvd_c4, candidate_c4) = make_committed_candidate( + para_id, + relay_parent_y_info.hash, + relay_parent_y_info.number, + vec![0xb4].into(), + vec![0xc3].into(), + relay_parent_y_info.number, + ); + let candidate_c4_hash = candidate_c4.hash(); + // C4 should have a lower candidate hash than C3. + assert_eq!(fork_selection_rule(&candidate_c4_hash, &candidate_c3_hash), Ordering::Less); + let candidate_c4_entry = + CandidateEntry::new(candidate_c4_hash, candidate_c4, pvd_c4, CandidateState::Seconded) + .unwrap(); + + let mut storage = storage.clone(); + storage.add_candidate_entry(candidate_c3_entry).unwrap(); + storage.add_candidate_entry(candidate_c4_entry).unwrap(); + let mut chain = populate_chain_from_previous_storage(&scope, &storage); + chain.candidate_backed(&candidate_a2_hash); + chain.candidate_backed(&candidate_c3_hash); + + assert_eq!( + chain.best_chain_vec(), + vec![candidate_a2_hash, candidate_b2_hash, candidate_c3_hash] + ); + + // Backing C4 will cause a reorg. + chain.candidate_backed(&candidate_c4_hash); + assert_eq!( + chain.best_chain_vec(), + vec![candidate_a2_hash, candidate_b2_hash, candidate_c4_hash] + ); + + assert_eq!( + chain.unconnected().map(|c| c.candidate_hash).collect::>(), + [candidate_f_hash].into_iter().collect() + ); } // Candidate F has an invalid hrmp watermark. however, it was not checked beforehand as we don't diff --git a/prdoc/pr_6417.prdoc b/prdoc/pr_6417.prdoc new file mode 100644 index 000000000000..dfbc8c0d311b --- /dev/null +++ b/prdoc/pr_6417.prdoc @@ -0,0 +1,9 @@ +title: fix prospective-parachains best backable chain reversion bug +doc: + - audience: Node Dev + description: | + Fixes a bug in the prospective-parachains subsystem that prevented proper best backable chain reorg. + +crates: +- name: polkadot-node-core-prospective-parachains + bump: patch From b601d57aa07b344338f9526073b718923a9223bb Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Mon, 11 Nov 2024 11:50:29 +0200 Subject: [PATCH 068/166] Remove network starter that is no longer needed (#6400) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description This seems to be an old artifact of the long closed https://github.com/paritytech/substrate/issues/6827 that I noticed when working on related code earlier. ## Integration `NetworkStarter` was removed, simply remove its usage: ```diff -let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = +let (network, system_rpc_tx, tx_handler_controller, sync_service) = build_network(BuildNetworkParams { ... -start_network.start_network(); ``` ## Review Notes Changes are trivial, the only reason for this to not be accepted is if it is desired to not start network automatically for whatever reason, in which case the description of network starter needs to change. # Checklist * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. * [ ] My PR follows the [labeling requirements]( https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process ) of this project (at minimum one label for `T` required) * External contributors: ask maintainers to put the right label on your PR. --------- Co-authored-by: GitHub Action Co-authored-by: Bastian Köcher --- .../relay-chain-minimal-node/src/lib.rs | 4 +- .../relay-chain-minimal-node/src/network.rs | 26 ++------ cumulus/client/service/src/lib.rs | 3 +- .../polkadot-omni-node/lib/src/common/spec.rs | 4 +- .../lib/src/nodes/manual_seal.rs | 3 +- cumulus/test/service/src/lib.rs | 4 +- polkadot/node/service/src/lib.rs | 4 +- prdoc/pr_6400.prdoc | 41 +++++++++++++ substrate/bin/node/cli/src/service.rs | 3 +- substrate/client/service/src/builder.rs | 59 +------------------ substrate/client/service/src/lib.rs | 4 +- templates/minimal/node/src/service.rs | 3 +- templates/parachain/node/src/service.rs | 4 +- templates/solochain/node/src/service.rs | 3 +- 14 files changed, 60 insertions(+), 105 deletions(-) create mode 100644 prdoc/pr_6400.prdoc diff --git a/cumulus/client/relay-chain-minimal-node/src/lib.rs b/cumulus/client/relay-chain-minimal-node/src/lib.rs index a3d858ea40c9..f70a73a5d5ce 100644 --- a/cumulus/client/relay-chain-minimal-node/src/lib.rs +++ b/cumulus/client/relay-chain-minimal-node/src/lib.rs @@ -224,7 +224,7 @@ async fn new_minimal_relay_chain( + let (network, sync_service) = build_collator_network::( &config, net_config, task_manager.spawn_handle(), @@ -262,8 +262,6 @@ async fn new_minimal_relay_chain>( genesis_hash: Hash, best_header: Header, notification_metrics: NotificationMetrics, -) -> Result< - (Arc, NetworkStarter, Arc), - Error, -> { +) -> Result<(Arc, Arc), Error> { let protocol_id = config.protocol_id(); let (block_announce_config, _notification_service) = get_block_announce_proto_config::( protocol_id.clone(), @@ -85,8 +82,6 @@ pub(crate) fn build_collator_network>( let network_worker = Network::new(network_params)?; let network_service = network_worker.network_service(); - let (network_start_tx, network_start_rx) = futures::channel::oneshot::channel(); - // The network worker is responsible for gathering all network messages and processing // them. This is quite a heavy task, and at the time of the writing of this comment it // frequently happens that this future takes several seconds or in some situations @@ -94,22 +89,9 @@ pub(crate) fn build_collator_network>( // issue, and ideally we would like to fix the network future to take as little time as // possible, but we also take the extra harm-prevention measure to execute the networking // future using `spawn_blocking`. - spawn_handle.spawn_blocking("network-worker", Some("networking"), async move { - if network_start_rx.await.is_err() { - tracing::warn!( - "The NetworkStart returned as part of `build_network` has been silently dropped" - ); - // This `return` might seem unnecessary, but we don't want to make it look like - // everything is working as normal even though the user is clearly misusing the API. - return - } - - network_worker.run().await; - }); - - let network_starter = NetworkStarter::new(network_start_tx); + spawn_handle.spawn_blocking("network-worker", Some("networking"), network_worker.run()); - Ok((network_service, network_starter, Arc::new(SyncOracle {}))) + Ok((network_service, Arc::new(SyncOracle {}))) } fn adjust_network_config_light_in_peers(config: &mut NetworkConfiguration) { diff --git a/cumulus/client/service/src/lib.rs b/cumulus/client/service/src/lib.rs index ae83f2ade3f6..912109c2ad32 100644 --- a/cumulus/client/service/src/lib.rs +++ b/cumulus/client/service/src/lib.rs @@ -40,7 +40,7 @@ use sc_consensus::{ use sc_network::{config::SyncMode, service::traits::NetworkService, NetworkBackend}; use sc_network_sync::SyncingService; use sc_network_transactions::TransactionsHandlerController; -use sc_service::{Configuration, NetworkStarter, SpawnTaskHandle, TaskManager, WarpSyncConfig}; +use sc_service::{Configuration, SpawnTaskHandle, TaskManager, WarpSyncConfig}; use sc_telemetry::{log, TelemetryWorkerHandle}; use sc_utils::mpsc::TracingUnboundedSender; use sp_api::ProvideRuntimeApi; @@ -439,7 +439,6 @@ pub async fn build_network<'a, Block, Client, RCInterface, IQ, Network>( Arc, TracingUnboundedSender>, TransactionsHandlerController, - NetworkStarter, Arc>, )> where diff --git a/cumulus/polkadot-omni-node/lib/src/common/spec.rs b/cumulus/polkadot-omni-node/lib/src/common/spec.rs index 8397cb778dcf..259f89049c92 100644 --- a/cumulus/polkadot-omni-node/lib/src/common/spec.rs +++ b/cumulus/polkadot-omni-node/lib/src/common/spec.rs @@ -239,7 +239,7 @@ pub(crate) trait NodeSpec: BaseNodeSpec { prometheus_registry.clone(), ); - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = build_network(BuildNetworkParams { parachain_config: ¶chain_config, net_config, @@ -346,8 +346,6 @@ pub(crate) trait NodeSpec: BaseNodeSpec { )?; } - start_network.start_network(); - Ok(task_manager) } .instrument(sc_tracing::tracing::info_span!( diff --git a/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs b/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs index b7fc3489da25..7e36ce735af3 100644 --- a/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs +++ b/cumulus/polkadot-omni-node/lib/src/nodes/manual_seal.rs @@ -93,7 +93,7 @@ impl ManualSealNode { config.prometheus_config.as_ref().map(|cfg| &cfg.registry), ); - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, client: client.clone(), @@ -219,7 +219,6 @@ impl ManualSealNode { telemetry: telemetry.as_mut(), })?; - start_network.start_network(); Ok(task_manager) } } diff --git a/cumulus/test/service/src/lib.rs b/cumulus/test/service/src/lib.rs index fe3cbfbbb498..9234442d399c 100644 --- a/cumulus/test/service/src/lib.rs +++ b/cumulus/test/service/src/lib.rs @@ -367,7 +367,7 @@ where prometheus_registry.clone(), ); - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = build_network(BuildNetworkParams { parachain_config: ¶chain_config, net_config, @@ -542,8 +542,6 @@ where } } - start_network.start_network(); - Ok((task_manager, client, network, rpc_handlers, transaction_pool, backend)) } diff --git a/polkadot/node/service/src/lib.rs b/polkadot/node/service/src/lib.rs index d2424474302a..227bc5253994 100644 --- a/polkadot/node/service/src/lib.rs +++ b/polkadot/node/service/src/lib.rs @@ -1003,7 +1003,7 @@ pub fn new_full< }) }; - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, net_config, @@ -1383,8 +1383,6 @@ pub fn new_full< ); } - network_starter.start_network(); - Ok(NewFull { task_manager, client, diff --git a/prdoc/pr_6400.prdoc b/prdoc/pr_6400.prdoc new file mode 100644 index 000000000000..a29ad49b4e51 --- /dev/null +++ b/prdoc/pr_6400.prdoc @@ -0,0 +1,41 @@ +title: Remove network starter that is no longer needed +doc: +- audience: Node Dev + description: |- + # Description + + This seems to be an old artifact of the long closed https://github.com/paritytech/substrate/issues/6827 that I noticed when working on related code earlier. + + ## Integration + + `NetworkStarter` was removed, simply remove its usage: + ```diff + -let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + +let (network, system_rpc_tx, tx_handler_controller, sync_service) = + build_network(BuildNetworkParams { + ... + -start_network.start_network(); + ``` + + ## Review Notes + + Changes are trivial, the only reason for this to not be accepted is if it is desired to not start network automatically for whatever reason, in which case the description of network starter needs to change. + + # Checklist + + * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. + * [ ] My PR follows the [labeling requirements]( + https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process + ) of this project (at minimum one label for `T` required) + * External contributors: ask maintainers to put the right label on your PR. +crates: +- name: cumulus-relay-chain-minimal-node + bump: major +- name: cumulus-client-service + bump: major +- name: polkadot-omni-node-lib + bump: major +- name: polkadot-service + bump: major +- name: sc-service + bump: major diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index 008cac4ef8a8..5cde85ae5790 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -513,7 +513,7 @@ pub fn new_full_base::Hash>>( Vec::default(), )); - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, net_config, @@ -801,7 +801,6 @@ pub fn new_full_base::Hash>>( ); } - network_starter.start_network(); Ok(NewFullBase { task_manager, client, diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index ce4ce7c08248..68ac94539df8 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -25,7 +25,7 @@ use crate::{ start_rpc_servers, BuildGenesisBlock, GenesisBlockBuilder, RpcHandlers, SpawnTaskHandle, TaskManager, TransactionPoolAdapter, }; -use futures::{channel::oneshot, future::ready, FutureExt, StreamExt}; +use futures::{future::ready, FutureExt, StreamExt}; use jsonrpsee::RpcModule; use log::info; use prometheus_endpoint::Registry; @@ -822,7 +822,6 @@ pub fn build_network( Arc, TracingUnboundedSender>, sc_network_transactions::TransactionsHandlerController<::Hash>, - NetworkStarter, Arc>, ), Error, @@ -984,7 +983,6 @@ pub fn build_network_advanced( Arc, TracingUnboundedSender>, sc_network_transactions::TransactionsHandlerController<::Hash>, - NetworkStarter, Arc>, ), Error, @@ -1125,22 +1123,6 @@ where announce_block, ); - // TODO: Normally, one is supposed to pass a list of notifications protocols supported by the - // node through the `NetworkConfiguration` struct. But because this function doesn't know in - // advance which components, such as GrandPa or Polkadot, will be plugged on top of the - // service, it is unfortunately not possible to do so without some deep refactoring. To - // bypass this problem, the `NetworkService` provides a `register_notifications_protocol` - // method that can be called even after the network has been initialized. However, we want to - // avoid the situation where `register_notifications_protocol` is called *after* the network - // actually connects to other peers. For this reason, we delay the process of the network - // future until the user calls `NetworkStarter::start_network`. - // - // This entire hack should eventually be removed in favour of passing the list of protocols - // through the configuration. - // - // See also https://github.com/paritytech/substrate/issues/6827 - let (network_start_tx, network_start_rx) = oneshot::channel(); - // The network worker is responsible for gathering all network messages and processing // them. This is quite a heavy task, and at the time of the writing of this comment it // frequently happens that this future takes several seconds or in some situations @@ -1148,26 +1130,9 @@ where // issue, and ideally we would like to fix the network future to take as little time as // possible, but we also take the extra harm-prevention measure to execute the networking // future using `spawn_blocking`. - spawn_handle.spawn_blocking("network-worker", Some("networking"), async move { - if network_start_rx.await.is_err() { - log::warn!( - "The NetworkStart returned as part of `build_network` has been silently dropped" - ); - // This `return` might seem unnecessary, but we don't want to make it look like - // everything is working as normal even though the user is clearly misusing the API. - return - } - - future.await - }); + spawn_handle.spawn_blocking("network-worker", Some("networking"), future); - Ok(( - network, - system_rpc_tx, - tx_handler_controller, - NetworkStarter(network_start_tx), - sync_service.clone(), - )) + Ok((network, system_rpc_tx, tx_handler_controller, sync_service.clone())) } /// Configuration for [`build_default_syncing_engine`]. @@ -1396,21 +1361,3 @@ where warp_sync_protocol_name, )?)) } - -/// Object used to start the network. -#[must_use] -pub struct NetworkStarter(oneshot::Sender<()>); - -impl NetworkStarter { - /// Create a new NetworkStarter - pub fn new(sender: oneshot::Sender<()>) -> Self { - NetworkStarter(sender) - } - - /// Start the network. Call this after all sub-components have been initialized. - /// - /// > **Note**: If you don't call this function, the networking will not work. - pub fn start_network(self) { - let _ = self.0.send(()); - } -} diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index ee4f4e7622e7..5cfd80cef910 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -64,8 +64,8 @@ pub use self::{ new_client, new_db_backend, new_full_client, new_full_parts, new_full_parts_record_import, new_full_parts_with_genesis_builder, new_wasm_executor, propagate_transaction_notifications, spawn_tasks, BuildNetworkAdvancedParams, - BuildNetworkParams, DefaultSyncingEngineConfig, KeystoreContainer, NetworkStarter, - SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient, + BuildNetworkParams, DefaultSyncingEngineConfig, KeystoreContainer, SpawnTasksParams, + TFullBackend, TFullCallExecutor, TFullClient, }, client::{ClientConfig, LocalCallExecutor}, error::Error, diff --git a/templates/minimal/node/src/service.rs b/templates/minimal/node/src/service.rs index b4e6fc0b728b..5988dbf3ce6e 100644 --- a/templates/minimal/node/src/service.rs +++ b/templates/minimal/node/src/service.rs @@ -134,7 +134,7 @@ pub fn new_full::Ha config.prometheus_config.as_ref().map(|cfg| &cfg.registry), ); - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, net_config, @@ -264,6 +264,5 @@ pub fn new_full::Ha _ => {}, } - network_starter.start_network(); Ok(task_manager) } diff --git a/templates/parachain/node/src/service.rs b/templates/parachain/node/src/service.rs index 57ffcb9049d8..8c526317283e 100644 --- a/templates/parachain/node/src/service.rs +++ b/templates/parachain/node/src/service.rs @@ -270,7 +270,7 @@ pub async fn start_parachain_node( // NOTE: because we use Aura here explicitly, we can use `CollatorSybilResistance::Resistant` // when starting the network. - let (network, system_rpc_tx, tx_handler_controller, start_network, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = build_network(BuildNetworkParams { parachain_config: ¶chain_config, net_config, @@ -406,7 +406,5 @@ pub async fn start_parachain_node( )?; } - start_network.start_network(); - Ok((task_manager, client)) } diff --git a/templates/solochain/node/src/service.rs b/templates/solochain/node/src/service.rs index d6fcebe239f7..79d97fbab8df 100644 --- a/templates/solochain/node/src/service.rs +++ b/templates/solochain/node/src/service.rs @@ -169,7 +169,7 @@ pub fn new_full< Vec::default(), )); - let (network, system_rpc_tx, tx_handler_controller, network_starter, sync_service) = + let (network, system_rpc_tx, tx_handler_controller, sync_service) = sc_service::build_network(sc_service::BuildNetworkParams { config: &config, net_config, @@ -329,6 +329,5 @@ pub fn new_full< ); } - network_starter.start_network(); Ok(task_manager) } From ace62f120fbc9ec617d6bab0a5180f0be4441537 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Mon, 11 Nov 2024 14:00:08 +0100 Subject: [PATCH 069/166] `fatxpool`: size limits implemented (#6262) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR adds size-limits to the fork-aware transaction pool. **Review Notes** - Existing [`TrackedMap`](https://github.com/paritytech/polkadot-sdk/blob/58fd5ae4ce883f42c360e3ad4a5df7d2258b42fe/substrate/client/transaction-pool/src/graph/tracked_map.rs#L33-L41) is used in internal mempool to track the size of extrinsics: https://github.com/paritytech/polkadot-sdk/blob/58fd5ae4ce883f42c360e3ad4a5df7d2258b42fe/substrate/client/transaction-pool/src/graph/tracked_map.rs#L33-L41 - In this PR, I also removed the logic that kept transactions in the `tx_mem_pool` if they were immediately dropped by the views. Initially, I implemented this as an improvement: if there was available space in the _mempool_ and all views dropped the transaction upon submission, the transaction would still be retained in the _mempool_. However, upon further consideration, I decided to remove this functionality to reduce unnecessary complexity. Now, when all views drop a transaction during submission, it is automatically rejected, with the `submit/submit_and_watch` call returning `ImmediatelyDropped`. Closes: #5476 --------- Co-authored-by: Sebastian Kunert Co-authored-by: Bastian Köcher --- prdoc/pr_6262.prdoc | 10 + .../src/fork_aware_txpool/dropped_watcher.rs | 121 +---- .../fork_aware_txpool/fork_aware_txpool.rs | 78 +-- .../src/fork_aware_txpool/tx_mem_pool.rs | 153 ++++-- .../src/fork_aware_txpool/view_store.rs | 19 +- .../client/transaction-pool/src/graph/mod.rs | 2 +- .../transaction-pool/src/graph/tracked_map.rs | 28 +- .../transaction-pool/tests/fatp_common/mod.rs | 4 +- .../transaction-pool/tests/fatp_limits.rs | 464 ++++++++++++++---- 9 files changed, 556 insertions(+), 323 deletions(-) create mode 100644 prdoc/pr_6262.prdoc diff --git a/prdoc/pr_6262.prdoc b/prdoc/pr_6262.prdoc new file mode 100644 index 000000000000..8ad99bc6ad28 --- /dev/null +++ b/prdoc/pr_6262.prdoc @@ -0,0 +1,10 @@ +title: "Size limits implemented for fork aware transaction pool" + +doc: + - audience: Node Dev + description: | + Size limits are now obeyed in fork aware transaction pool + +crates: + - name: sc-transaction-pool + bump: minor diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs index 2dd5836c570f..ecae21395c91 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/dropped_watcher.rs @@ -68,15 +68,7 @@ where AddView(BlockHash, ViewStream), /// Removes an existing view's stream associated with a specific block hash. RemoveView(BlockHash), - /// Adds initial views for given extrinsics hashes. - /// - /// This message should be sent when the external submission of a transaction occures. It - /// provides the list of initial views for given extrinsics hashes. - /// The dropped notification is not sent if it comes from the initial views. It allows to keep - /// transaction in the mempool, even if all the views are full at the time of submitting - /// transaction to the pool. - AddInitialViews(Vec>, BlockHash), - /// Removes all initial views for given extrinsic hashes. + /// Removes internal states for given extrinsic hashes. /// /// Intended to ba called on finalization. RemoveFinalizedTxs(Vec>), @@ -90,7 +82,6 @@ where match self { Command::AddView(..) => write!(f, "AddView"), Command::RemoveView(..) => write!(f, "RemoveView"), - Command::AddInitialViews(..) => write!(f, "AddInitialViews"), Command::RemoveFinalizedTxs(..) => write!(f, "RemoveFinalizedTxs"), } } @@ -118,13 +109,6 @@ where /// /// Once transaction is dropped, dropping view is removed from the set. transaction_states: HashMap, HashSet>>, - - /// The list of initial view for every extrinsic. - /// - /// Dropped notifications from initial views will be silenced. This allows to accept the - /// transaction into the mempool, even if all the views are full at the time of submitting new - /// transaction. - initial_views: HashMap, HashSet>>, } impl MultiViewDropWatcherContext @@ -164,15 +148,7 @@ where .iter() .all(|h| !self.stream_map.contains_key(h)) { - return self - .initial_views - .get(&tx_hash) - .map(|list| !list.contains(&block_hash)) - .unwrap_or(true) - .then(|| { - debug!("[{:?}] dropped_watcher: removing tx", tx_hash); - tx_hash - }) + return Some(tx_hash) } } else { debug!("[{:?}] dropped_watcher: removing (non-tracked) tx", tx_hash); @@ -201,7 +177,6 @@ where stream_map: StreamMap::new(), command_receiver, transaction_states: Default::default(), - initial_views: Default::default(), }; let stream_map = futures::stream::unfold(ctx, |mut ctx| async move { @@ -217,17 +192,13 @@ where Command::RemoveView(key) => { trace!(target: LOG_TARGET,"dropped_watcher: Command::RemoveView {key:?} views:{:?}",ctx.stream_map.keys().collect::>()); ctx.stream_map.remove(&key); - }, - Command::AddInitialViews(xts,block_hash) => { - log_xt_trace!(target: LOG_TARGET, xts.clone(), "[{:?}] dropped_watcher: xt initial view added {block_hash:?}"); - xts.into_iter().for_each(|xt| { - ctx.initial_views.entry(xt).or_default().insert(block_hash); + ctx.transaction_states.iter_mut().for_each(|(_,state)| { + state.remove(&key); }); }, Command::RemoveFinalizedTxs(xts) => { log_xt_trace!(target: LOG_TARGET, xts.clone(), "[{:?}] dropped_watcher: finalized xt removed"); xts.iter().for_each(|xt| { - ctx.initial_views.remove(xt); ctx.transaction_states.remove(xt); }); @@ -291,34 +262,13 @@ where }); } - /// Adds the initial view for the given transactions hashes. - /// - /// This message should be called when the external submission of a transaction occures. It - /// provides the list of initial views for given extrinsics hashes. - /// - /// The dropped notification is not sent if it comes from the initial views. It allows to keep - /// transaction in the mempool, even if all the views are full at the time of submitting - /// transaction to the pool. - pub fn add_initial_views( - &self, - xts: impl IntoIterator> + Clone, - block_hash: BlockHash, - ) { - let _ = self - .controller - .unbounded_send(Command::AddInitialViews(xts.into_iter().collect(), block_hash)) - .map_err(|e| { - trace!(target: LOG_TARGET, "dropped_watcher: add_initial_views_ send message failed: {e}"); - }); - } - - /// Removes all initial views for finalized transactions. + /// Removes status info for finalized transactions. pub fn remove_finalized_txs(&self, xts: impl IntoIterator> + Clone) { let _ = self .controller .unbounded_send(Command::RemoveFinalizedTxs(xts.into_iter().collect())) .map_err(|e| { - trace!(target: LOG_TARGET, "dropped_watcher: remove_initial_views send message failed: {e}"); + trace!(target: LOG_TARGET, "dropped_watcher: remove_finalized_txs send message failed: {e}"); }); } } @@ -471,63 +421,4 @@ mod dropped_watcher_tests { let handle = tokio::spawn(async move { output_stream.take(1).collect::>().await }); assert_eq!(handle.await.unwrap(), vec![tx_hash]); } - - #[tokio::test] - async fn test06() { - sp_tracing::try_init_simple(); - let (watcher, mut output_stream) = MultiViewDroppedWatcher::new(); - assert!(output_stream.next().now_or_never().is_none()); - - let block_hash0 = H256::repeat_byte(0x01); - let block_hash1 = H256::repeat_byte(0x02); - let tx_hash = H256::repeat_byte(0x0b); - - let view_stream0 = futures::stream::iter(vec![ - (tx_hash, TransactionStatus::Future), - (tx_hash, TransactionStatus::InBlock((block_hash1, 0))), - ]) - .boxed(); - watcher.add_view(block_hash0, view_stream0); - assert!(output_stream.next().now_or_never().is_none()); - - let view_stream1 = futures::stream::iter(vec![ - (tx_hash, TransactionStatus::Ready), - (tx_hash, TransactionStatus::Dropped), - ]) - .boxed(); - - watcher.add_view(block_hash1, view_stream1); - watcher.add_initial_views(vec![tx_hash], block_hash1); - assert!(output_stream.next().now_or_never().is_none()); - } - - #[tokio::test] - async fn test07() { - sp_tracing::try_init_simple(); - let (watcher, mut output_stream) = MultiViewDroppedWatcher::new(); - assert!(output_stream.next().now_or_never().is_none()); - - let block_hash0 = H256::repeat_byte(0x01); - let block_hash1 = H256::repeat_byte(0x02); - let tx_hash = H256::repeat_byte(0x0b); - - let view_stream0 = futures::stream::iter(vec![ - (tx_hash, TransactionStatus::Future), - (tx_hash, TransactionStatus::InBlock((block_hash1, 0))), - ]) - .boxed(); - watcher.add_view(block_hash0, view_stream0); - watcher.add_initial_views(vec![tx_hash], block_hash0); - assert!(output_stream.next().now_or_never().is_none()); - - let view_stream1 = futures::stream::iter(vec![ - (tx_hash, TransactionStatus::Ready), - (tx_hash, TransactionStatus::Dropped), - ]) - .boxed(); - watcher.add_view(block_hash1, view_stream1); - - let handle = tokio::spawn(async move { output_stream.take(1).collect::>().await }); - assert_eq!(handle.await.unwrap(), vec![tx_hash]); - } } diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs index 7e72b44adf38..a342d35b2844 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs @@ -45,7 +45,6 @@ use futures::{ use parking_lot::Mutex; use prometheus_endpoint::Registry as PrometheusRegistry; use sc_transaction_pool_api::{ - error::{Error, IntoPoolError}, ChainEvent, ImportNotificationStream, MaintainedTransactionPool, PoolFuture, PoolStatus, TransactionFor, TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, }; @@ -193,6 +192,7 @@ where listener.clone(), Default::default(), mempool_max_transactions_count, + ready_limits.total_bytes + future_limits.total_bytes, )); let (dropped_stream_controller, dropped_stream) = @@ -283,6 +283,7 @@ where listener.clone(), metrics.clone(), TXMEMPOOL_TRANSACTION_LIMIT_MULTIPLIER * (options.ready.count + options.future.count), + options.ready.total_bytes + options.future.total_bytes, )); let (dropped_stream_controller, dropped_stream) = @@ -599,48 +600,36 @@ where log::debug!(target: LOG_TARGET, "fatp::submit_at count:{} views:{}", xts.len(), self.active_views_count()); log_xt_trace!(target: LOG_TARGET, xts.iter().map(|xt| self.tx_hash(xt)), "[{:?}] fatp::submit_at"); let xts = xts.into_iter().map(Arc::from).collect::>(); - let mempool_result = self.mempool.extend_unwatched(source, &xts); + let mempool_results = self.mempool.extend_unwatched(source, &xts); if view_store.is_empty() { - return future::ready(Ok(mempool_result)).boxed() + return future::ready(Ok(mempool_results)).boxed() } - let (hashes, to_be_submitted): (Vec>, Vec>) = - mempool_result - .iter() - .zip(xts) - .filter_map(|(result, xt)| result.as_ref().ok().map(|xt_hash| (xt_hash, xt))) - .unzip(); + let to_be_submitted = mempool_results + .iter() + .zip(xts) + .filter_map(|(result, xt)| result.as_ref().ok().map(|_| xt)) + .collect::>(); self.metrics .report(|metrics| metrics.submitted_transactions.inc_by(to_be_submitted.len() as _)); let mempool = self.mempool.clone(); async move { - let results_map = view_store.submit(source, to_be_submitted.into_iter(), hashes).await; + let results_map = view_store.submit(source, to_be_submitted.into_iter()).await; let mut submission_results = reduce_multiview_result(results_map).into_iter(); - Ok(mempool_result + Ok(mempool_results .into_iter() .map(|result| { result.and_then(|xt_hash| { - let result = submission_results + submission_results .next() - .expect("The number of Ok results in mempool is exactly the same as the size of to-views-submission result. qed."); - result.or_else(|error| { - let error = error.into_pool_error(); - match error { - Ok( - // The transaction is still in mempool it may get included into the view for the next block. - Error::ImmediatelyDropped - ) => Ok(xt_hash), - Ok(e) => { - mempool.remove(xt_hash); - Err(e.into()) - }, - Err(e) => Err(e), - } - }) + .expect("The number of Ok results in mempool is exactly the same as the size of to-views-submission result. qed.") + .inspect_err(|_| + mempool.remove(xt_hash) + ) }) }) .collect::>()) @@ -692,26 +681,10 @@ where let view_store = self.view_store.clone(); let mempool = self.mempool.clone(); async move { - let result = view_store.submit_and_watch(at, source, xt).await; - let result = result.or_else(|(e, maybe_watcher)| { - let error = e.into_pool_error(); - match (error, maybe_watcher) { - ( - Ok( - // The transaction is still in mempool it may get included into the - // view for the next block. - Error::ImmediatelyDropped, - ), - Some(watcher), - ) => Ok(watcher), - (Ok(e), _) => { - mempool.remove(xt_hash); - Err(e.into()) - }, - (Err(e), _) => Err(e), - } - }); - result + view_store + .submit_and_watch(at, source, xt) + .await + .inspect_err(|_| mempool.remove(xt_hash)) } .boxed() } @@ -1056,7 +1029,7 @@ where future::join_all(results).await } - /// Updates the given view with the transaction from the internal mempol. + /// Updates the given view with the transactions from the internal mempol. /// /// All transactions from the mempool (excluding those which are either already imported or /// already included in blocks since recently finalized block) are submitted to the @@ -1139,12 +1112,9 @@ where // out the invalid event, and remove transaction. if self.view_store.is_empty() { for result in watched_results { - match result { - Err(tx_hash) => { - self.view_store.listener.invalidate_transactions(&[tx_hash]); - self.mempool.remove(tx_hash); - }, - Ok(_) => {}, + if let Err(tx_hash) = result { + self.view_store.listener.invalidate_transactions(&[tx_hash]); + self.mempool.remove(tx_hash); } } } diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs index 989c7e8ef356..86c07008c3f3 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/tx_mem_pool.rs @@ -30,12 +30,11 @@ use super::{metrics::MetricsLink as PrometheusMetrics, multi_view_listener::Mult use crate::{ common::log_xt::log_xt_trace, graph, - graph::{ExtrinsicFor, ExtrinsicHash}, + graph::{tracked_map::Size, ExtrinsicFor, ExtrinsicHash}, LOG_TARGET, }; use futures::FutureExt; use itertools::Itertools; -use parking_lot::RwLock; use sc_transaction_pool_api::TransactionSource; use sp_blockchain::HashAndNumber; use sp_runtime::{ @@ -43,7 +42,7 @@ use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidityError}, }; use std::{ - collections::{hash_map::Entry, HashMap}, + collections::HashMap, sync::{atomic, atomic::AtomicU64, Arc}, time::Instant, }; @@ -72,6 +71,8 @@ where watched: bool, /// Extrinsic actual body. tx: ExtrinsicFor, + /// Size of the extrinsics actual body. + bytes: usize, /// Transaction source. source: TransactionSource, /// When the transaction was revalidated, used to periodically revalidate the mem pool buffer. @@ -99,13 +100,13 @@ where } /// Creates a new instance of wrapper for unwatched transaction. - fn new_unwatched(source: TransactionSource, tx: ExtrinsicFor) -> Self { - Self { watched: false, tx, source, validated_at: AtomicU64::new(0) } + fn new_unwatched(source: TransactionSource, tx: ExtrinsicFor, bytes: usize) -> Self { + Self { watched: false, tx, source, validated_at: AtomicU64::new(0), bytes } } /// Creates a new instance of wrapper for watched transaction. - fn new_watched(source: TransactionSource, tx: ExtrinsicFor) -> Self { - Self { watched: true, tx, source, validated_at: AtomicU64::new(0) } + fn new_watched(source: TransactionSource, tx: ExtrinsicFor, bytes: usize) -> Self { + Self { watched: true, tx, source, validated_at: AtomicU64::new(0), bytes } } /// Provides a clone of actual transaction body. @@ -121,10 +122,18 @@ where } } +impl Size for Arc> +where + Block: BlockT, + ChainApi: graph::ChainApi + 'static, +{ + fn size(&self) -> usize { + self.bytes + } +} + type InternalTxMemPoolMap = - HashMap, Arc>>; -type InternalTxMemPoolMapEntry<'a, ChainApi, Block> = - Entry<'a, ExtrinsicHash, Arc>>; + graph::tracked_map::TrackedMap, Arc>>; /// An intermediary transactions buffer. /// @@ -153,13 +162,16 @@ where /// /// The key is the hash of the transaction, and the value is a wrapper /// structure, which contains the mempool specific details of the transaction. - transactions: RwLock>, + transactions: InternalTxMemPoolMap, /// Prometheus's metrics endpoint. metrics: PrometheusMetrics, /// Indicates the maximum number of transactions that can be maintained in the memory pool. max_transactions_count: usize, + + /// Maximal size of encodings of all transactions in the memory pool. + max_transactions_total_bytes: usize, } impl TxMemPool @@ -175,19 +187,32 @@ where listener: Arc>, metrics: PrometheusMetrics, max_transactions_count: usize, + max_transactions_total_bytes: usize, ) -> Self { - Self { api, listener, transactions: Default::default(), metrics, max_transactions_count } + Self { + api, + listener, + transactions: Default::default(), + metrics, + max_transactions_count, + max_transactions_total_bytes, + } } /// Creates a new `TxMemPool` instance for testing purposes. #[allow(dead_code)] - fn new_test(api: Arc, max_transactions_count: usize) -> Self { + fn new_test( + api: Arc, + max_transactions_count: usize, + max_transactions_total_bytes: usize, + ) -> Self { Self { api, listener: Arc::from(MultiViewListener::new()), transactions: Default::default(), metrics: Default::default(), max_transactions_count, + max_transactions_total_bytes, } } @@ -200,28 +225,42 @@ where } /// Returns a tuple with the count of unwatched and watched transactions in the memory pool. - pub(super) fn unwatched_and_watched_count(&self) -> (usize, usize) { + pub fn unwatched_and_watched_count(&self) -> (usize, usize) { let transactions = self.transactions.read(); let watched_count = transactions.values().filter(|t| t.is_watched()).count(); (transactions.len() - watched_count, watched_count) } + /// Returns the number of bytes used by all extrinsics in the the pool. + #[cfg(test)] + pub fn bytes(&self) -> usize { + return self.transactions.bytes() + } + + /// Returns true if provided values would exceed defined limits. + fn is_limit_exceeded(&self, length: usize, current_total_bytes: usize) -> bool { + length > self.max_transactions_count || + current_total_bytes > self.max_transactions_total_bytes + } + /// Attempts to insert a transaction into the memory pool, ensuring it does not /// exceed the maximum allowed transaction count. fn try_insert( &self, - current_len: usize, - entry: InternalTxMemPoolMapEntry<'_, ChainApi, Block>, hash: ExtrinsicHash, tx: TxInMemPool, ) -> Result, ChainApi::Error> { - //todo: obey size limits [#5476] - let result = match (current_len < self.max_transactions_count, entry) { - (true, Entry::Vacant(v)) => { - v.insert(Arc::from(tx)); + let bytes = self.transactions.bytes(); + let mut transactions = self.transactions.write(); + let result = match ( + !self.is_limit_exceeded(transactions.len() + 1, bytes + tx.bytes), + transactions.contains_key(&hash), + ) { + (true, false) => { + transactions.insert(hash, Arc::from(tx)); Ok(hash) }, - (_, Entry::Occupied(_)) => + (_, true) => Err(sc_transaction_pool_api::error::Error::AlreadyImported(Box::new(hash)).into()), (false, _) => Err(sc_transaction_pool_api::error::Error::ImmediatelyDropped.into()), }; @@ -239,17 +278,11 @@ where source: TransactionSource, xts: &[ExtrinsicFor], ) -> Vec, ChainApi::Error>> { - let mut transactions = self.transactions.write(); let result = xts .iter() .map(|xt| { - let hash = self.api.hash_and_length(&xt).0; - self.try_insert( - transactions.len(), - transactions.entry(hash), - hash, - TxInMemPool::new_unwatched(source, xt.clone()), - ) + let (hash, length) = self.api.hash_and_length(&xt); + self.try_insert(hash, TxInMemPool::new_unwatched(source, xt.clone(), length)) }) .collect::>(); result @@ -262,14 +295,8 @@ where source: TransactionSource, xt: ExtrinsicFor, ) -> Result, ChainApi::Error> { - let mut transactions = self.transactions.write(); - let hash = self.api.hash_and_length(&xt).0; - self.try_insert( - transactions.len(), - transactions.entry(hash), - hash, - TxInMemPool::new_watched(source, xt.clone()), - ) + let (hash, length) = self.api.hash_and_length(&xt); + self.try_insert(hash, TxInMemPool::new_watched(source, xt.clone(), length)) } /// Removes transactions from the memory pool which are specified by the given list of hashes @@ -324,12 +351,11 @@ where let start = Instant::now(); let (count, input) = { - let transactions = self.transactions.read(); + let transactions = self.transactions.clone_map(); ( transactions.len(), transactions - .clone() .into_iter() .filter(|xt| { let finalized_block_number = finalized_block.number.into().as_u64(); @@ -417,8 +443,8 @@ where #[cfg(test)] mod tx_mem_pool_tests { use super::*; - use crate::common::tests::TestApi; - use substrate_test_runtime::{AccountId, Extrinsic, Transfer, H256}; + use crate::{common::tests::TestApi, graph::ChainApi}; + use substrate_test_runtime::{AccountId, Extrinsic, ExtrinsicBuilder, Transfer, H256}; use substrate_test_runtime_client::AccountKeyring::*; fn uxt(nonce: u64) -> Extrinsic { crate::common::tests::uxt(Transfer { @@ -433,7 +459,7 @@ mod tx_mem_pool_tests { fn extend_unwatched_obeys_limit() { let max = 10; let api = Arc::from(TestApi::default()); - let mempool = TxMemPool::new_test(api, max); + let mempool = TxMemPool::new_test(api, max, usize::MAX); let xts = (0..max + 1).map(|x| Arc::from(uxt(x as _))).collect::>(); @@ -450,7 +476,7 @@ mod tx_mem_pool_tests { sp_tracing::try_init_simple(); let max = 10; let api = Arc::from(TestApi::default()); - let mempool = TxMemPool::new_test(api, max); + let mempool = TxMemPool::new_test(api, max, usize::MAX); let mut xts = (0..max - 1).map(|x| Arc::from(uxt(x as _))).collect::>(); xts.push(xts.iter().last().unwrap().clone()); @@ -467,7 +493,7 @@ mod tx_mem_pool_tests { fn push_obeys_limit() { let max = 10; let api = Arc::from(TestApi::default()); - let mempool = TxMemPool::new_test(api, max); + let mempool = TxMemPool::new_test(api, max, usize::MAX); let xts = (0..max).map(|x| Arc::from(uxt(x as _))).collect::>(); @@ -492,7 +518,7 @@ mod tx_mem_pool_tests { fn push_detects_already_imported() { let max = 10; let api = Arc::from(TestApi::default()); - let mempool = TxMemPool::new_test(api, 2 * max); + let mempool = TxMemPool::new_test(api, 2 * max, usize::MAX); let xts = (0..max).map(|x| Arc::from(uxt(x as _))).collect::>(); let xt0 = xts.iter().last().unwrap().clone(); @@ -517,7 +543,7 @@ mod tx_mem_pool_tests { fn count_works() { let max = 100; let api = Arc::from(TestApi::default()); - let mempool = TxMemPool::new_test(api, max); + let mempool = TxMemPool::new_test(api, max, usize::MAX); let xts0 = (0..10).map(|x| Arc::from(uxt(x as _))).collect::>(); @@ -532,4 +558,39 @@ mod tx_mem_pool_tests { assert!(results.iter().all(Result::is_ok)); assert_eq!(mempool.unwatched_and_watched_count(), (10, 5)); } + + fn large_uxt(x: usize) -> Extrinsic { + ExtrinsicBuilder::new_include_data(vec![x as u8; 1024]).build() + } + + #[test] + fn push_obeys_size_limit() { + sp_tracing::try_init_simple(); + let max = 10; + let api = Arc::from(TestApi::default()); + //size of large extrinsic is: 1129 + let mempool = TxMemPool::new_test(api.clone(), usize::MAX, max * 1129); + + let xts = (0..max).map(|x| Arc::from(large_uxt(x))).collect::>(); + + let total_xts_bytes = xts.iter().fold(0, |r, x| r + api.hash_and_length(&x).1); + + let results = mempool.extend_unwatched(TransactionSource::External, &xts); + assert!(results.iter().all(Result::is_ok)); + assert_eq!(mempool.bytes(), total_xts_bytes); + + let xt = Arc::from(large_uxt(98)); + let result = mempool.push_watched(TransactionSource::External, xt); + assert!(matches!( + result.unwrap_err(), + sc_transaction_pool_api::error::Error::ImmediatelyDropped + )); + + let xt = Arc::from(large_uxt(99)); + let mut result = mempool.extend_unwatched(TransactionSource::External, &[xt]); + assert!(matches!( + result.pop().unwrap().unwrap_err(), + sc_transaction_pool_api::error::Error::ImmediatelyDropped + )); + } } diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/view_store.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/view_store.rs index 413fca223242..f23dcedd5bfd 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/view_store.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/view_store.rs @@ -91,7 +91,6 @@ where &self, source: TransactionSource, xts: impl IntoIterator> + Clone, - xts_hashes: impl IntoIterator> + Clone, ) -> HashMap, ChainApi::Error>>> { let submit_futures = { let active_views = self.active_views.read(); @@ -100,9 +99,7 @@ where .map(|(_, view)| { let view = view.clone(); let xts = xts.clone(); - self.dropped_stream_controller - .add_initial_views(xts_hashes.clone(), view.at.hash); - async move { (view.at.hash, view.submit_many(source, xts.clone()).await) } + async move { (view.at.hash, view.submit_many(source, xts).await) } }) .collect::>() }; @@ -127,11 +124,7 @@ where let result = active_views .iter() - .map(|view| { - self.dropped_stream_controller - .add_initial_views(std::iter::once(tx_hash), view.at.hash); - view.submit_local(xt.clone()) - }) + .map(|view| view.submit_local(xt.clone())) .find_or_first(Result::is_ok); if let Some(Err(err)) = result { @@ -154,10 +147,10 @@ where _at: Block::Hash, source: TransactionSource, xt: ExtrinsicFor, - ) -> Result, (ChainApi::Error, Option>)> { + ) -> Result, ChainApi::Error> { let tx_hash = self.api.hash_and_length(&xt).0; let Some(external_watcher) = self.listener.create_external_watcher_for_tx(tx_hash) else { - return Err((PoolError::AlreadyImported(Box::new(tx_hash)).into(), None)) + return Err(PoolError::AlreadyImported(Box::new(tx_hash)).into()) }; let submit_and_watch_futures = { let active_views = self.active_views.read(); @@ -166,8 +159,6 @@ where .map(|(_, view)| { let view = view.clone(); let xt = xt.clone(); - self.dropped_stream_controller - .add_initial_views(std::iter::once(tx_hash), view.at.hash); async move { match view.submit_and_watch(source, xt).await { Ok(watcher) => { @@ -191,7 +182,7 @@ where if let Some(Err(err)) = maybe_error { log::trace!(target: LOG_TARGET, "[{:?}] submit_and_watch: err: {}", tx_hash, err); - return Err((err, Some(external_watcher))); + return Err(err); }; Ok(external_watcher) diff --git a/substrate/client/transaction-pool/src/graph/mod.rs b/substrate/client/transaction-pool/src/graph/mod.rs index c1225d7356d9..d93898b1b22a 100644 --- a/substrate/client/transaction-pool/src/graph/mod.rs +++ b/substrate/client/transaction-pool/src/graph/mod.rs @@ -31,7 +31,7 @@ mod listener; mod pool; mod ready; mod rotator; -mod tracked_map; +pub(crate) mod tracked_map; mod validated_pool; pub mod base_pool; diff --git a/substrate/client/transaction-pool/src/graph/tracked_map.rs b/substrate/client/transaction-pool/src/graph/tracked_map.rs index 9e92dffc9f96..6c3bbbf34b55 100644 --- a/substrate/client/transaction-pool/src/graph/tracked_map.rs +++ b/substrate/client/transaction-pool/src/graph/tracked_map.rs @@ -18,7 +18,7 @@ use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use std::{ - collections::HashMap, + collections::{hash_map::Iter, HashMap}, sync::{ atomic::{AtomicIsize, Ordering as AtomicOrdering}, Arc, @@ -101,20 +101,30 @@ impl<'a, K, V> TrackedMapReadAccess<'a, K, V> where K: Eq + std::hash::Hash, { - /// Returns true if map contains key. + /// Returns true if the map contains given key. pub fn contains_key(&self, key: &K) -> bool { self.inner_guard.contains_key(key) } - /// Returns reference to the contained value by key, if exists. + /// Returns the reference to the contained value by key, if exists. pub fn get(&self, key: &K) -> Option<&V> { self.inner_guard.get(key) } - /// Returns iterator over all values. + /// Returns an iterator over all values. pub fn values(&self) -> std::collections::hash_map::Values { self.inner_guard.values() } + + /// Returns the number of elements in the map. + pub fn len(&self) -> usize { + self.inner_guard.len() + } + + /// Returns an iterator over all key-value pairs. + pub fn iter(&self) -> Iter<'_, K, V> { + self.inner_guard.iter() + } } pub struct TrackedMapWriteAccess<'a, K, V> { @@ -149,10 +159,20 @@ where val } + /// Returns `true` if the inner map contains a value for the specified key. + pub fn contains_key(&self, key: &K) -> bool { + self.inner_guard.contains_key(key) + } + /// Returns mutable reference to the contained value by key, if exists. pub fn get_mut(&mut self, key: &K) -> Option<&mut V> { self.inner_guard.get_mut(key) } + + /// Returns the number of elements in the map. + pub fn len(&mut self) -> usize { + self.inner_guard.len() + } } #[cfg(test)] diff --git a/substrate/client/transaction-pool/tests/fatp_common/mod.rs b/substrate/client/transaction-pool/tests/fatp_common/mod.rs index 63af729b8b73..15f2b7f79c14 100644 --- a/substrate/client/transaction-pool/tests/fatp_common/mod.rs +++ b/substrate/client/transaction-pool/tests/fatp_common/mod.rs @@ -186,9 +186,9 @@ macro_rules! assert_pool_status { #[macro_export] macro_rules! assert_ready_iterator { - ($hash:expr, $pool:expr, [$( $xt:expr ),+]) => {{ + ($hash:expr, $pool:expr, [$( $xt:expr ),*]) => {{ let ready_iterator = $pool.ready_at($hash).now_or_never().unwrap(); - let expected = vec![ $($pool.api().hash_and_length(&$xt).0),+]; + let expected = vec![ $($pool.api().hash_and_length(&$xt).0),*]; let output: Vec<_> = ready_iterator.collect(); log::debug!(target:LOG_TARGET, "expected: {:#?}", expected); log::debug!(target:LOG_TARGET, "output: {:#?}", output); diff --git a/substrate/client/transaction-pool/tests/fatp_limits.rs b/substrate/client/transaction-pool/tests/fatp_limits.rs index 6fd5f93ed070..03792fd89dfa 100644 --- a/substrate/client/transaction-pool/tests/fatp_limits.rs +++ b/substrate/client/transaction-pool/tests/fatp_limits.rs @@ -19,6 +19,7 @@ //! Tests of limits for fork-aware transaction pool. pub mod fatp_common; + use fatp_common::{ finalized_block_event, invalid_hash, new_best_block_event, TestPoolBuilder, LOG_TARGET, SOURCE, }; @@ -27,6 +28,7 @@ use sc_transaction_pool::ChainApi; use sc_transaction_pool_api::{ error::Error as TxPoolError, MaintainedTransactionPool, TransactionPool, TransactionStatus, }; +use std::thread::sleep; use substrate_test_runtime_client::AccountKeyring::*; use substrate_test_runtime_transaction_pool::uxt; @@ -92,25 +94,103 @@ fn fatp_limits_ready_count_works() { //charlie was not included into view: assert_pool_status!(header01.hash(), &pool, 2, 0); assert_ready_iterator!(header01.hash(), pool, [xt1, xt2]); + //todo: can we do better? We don't have API to check if event was processed internally. + let mut counter = 0; + while pool.mempool_len().0 == 3 { + sleep(std::time::Duration::from_millis(1)); + counter = counter + 1; + if counter > 20 { + assert!(false, "timeout"); + } + } + assert_eq!(pool.mempool_len().0, 2); //branch with alice transactions: let header02b = api.push_block(2, vec![xt1.clone(), xt2.clone()], true); let event = new_best_block_event(&pool, Some(header01.hash()), header02b.hash()); block_on(pool.maintain(event)); - assert_eq!(pool.mempool_len().0, 3); - //charlie was resubmitted from mmepool into the view: - assert_pool_status!(header02b.hash(), &pool, 1, 0); - assert_ready_iterator!(header02b.hash(), pool, [xt0]); + assert_eq!(pool.mempool_len().0, 2); + assert_pool_status!(header02b.hash(), &pool, 0, 0); + assert_ready_iterator!(header02b.hash(), pool, []); //branch with alice/charlie transactions shall also work: let header02a = api.push_block(2, vec![xt0.clone(), xt1.clone()], true); + api.set_nonce(header02a.hash(), Alice.into(), 201); let event = new_best_block_event(&pool, Some(header02b.hash()), header02a.hash()); block_on(pool.maintain(event)); - assert_eq!(pool.mempool_len().0, 3); - assert_pool_status!(header02a.hash(), &pool, 1, 0); + assert_eq!(pool.mempool_len().0, 2); + // assert_pool_status!(header02a.hash(), &pool, 1, 0); assert_ready_iterator!(header02a.hash(), pool, [xt2]); } +#[test] +fn fatp_limits_ready_count_works_for_submit_at() { + sp_tracing::try_init_simple(); + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder.with_mempool_count_limit(3).with_ready_count(2).build(); + api.set_nonce(api.genesis_hash(), Bob.into(), 200); + api.set_nonce(api.genesis_hash(), Charlie.into(), 500); + + let header01 = api.push_block(1, vec![], true); + + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = uxt(Charlie, 500); + let xt1 = uxt(Alice, 200); + let xt2 = uxt(Alice, 201); + + let results = block_on(pool.submit_at( + header01.hash(), + SOURCE, + vec![xt0.clone(), xt1.clone(), xt2.clone()], + )) + .unwrap(); + + assert!(matches!(results[0].as_ref().unwrap_err().0, TxPoolError::ImmediatelyDropped)); + assert!(results[1].as_ref().is_ok()); + assert!(results[2].as_ref().is_ok()); + assert_eq!(pool.mempool_len().0, 2); + //charlie was not included into view: + assert_pool_status!(header01.hash(), &pool, 2, 0); + assert_ready_iterator!(header01.hash(), pool, [xt1, xt2]); +} + +#[test] +fn fatp_limits_ready_count_works_for_submit_and_watch() { + sp_tracing::try_init_simple(); + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder.with_mempool_count_limit(3).with_ready_count(2).build(); + api.set_nonce(api.genesis_hash(), Bob.into(), 300); + api.set_nonce(api.genesis_hash(), Charlie.into(), 500); + + let header01 = api.push_block(1, vec![], true); + + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = uxt(Charlie, 500); + let xt1 = uxt(Alice, 200); + let xt2 = uxt(Bob, 300); + api.set_priority(&xt0, 2); + api.set_priority(&xt1, 2); + api.set_priority(&xt2, 1); + + let result0 = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())); + let result1 = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())); + let result2 = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).map(|_| ()); + + assert!(matches!(result2.unwrap_err().0, TxPoolError::ImmediatelyDropped)); + assert!(result0.is_ok()); + assert!(result1.is_ok()); + assert_eq!(pool.mempool_len().1, 2); + //charlie was not included into view: + assert_pool_status!(header01.hash(), &pool, 2, 0); + assert_ready_iterator!(header01.hash(), pool, [xt0, xt1]); +} + #[test] fn fatp_limits_future_count_works() { sp_tracing::try_init_simple(); @@ -131,29 +211,33 @@ fn fatp_limits_future_count_works() { let xt2 = uxt(Alice, 201); let xt3 = uxt(Alice, 202); - let submissions = vec![ - pool.submit_one(header01.hash(), SOURCE, xt1.clone()), - pool.submit_one(header01.hash(), SOURCE, xt2.clone()), - pool.submit_one(header01.hash(), SOURCE, xt3.clone()), - ]; + block_on(pool.submit_one(header01.hash(), SOURCE, xt1.clone())).unwrap(); + block_on(pool.submit_one(header01.hash(), SOURCE, xt2.clone())).unwrap(); + block_on(pool.submit_one(header01.hash(), SOURCE, xt3.clone())).unwrap(); - let results = block_on(futures::future::join_all(submissions)); - assert!(results.iter().all(Result::is_ok)); //charlie was not included into view due to limits: assert_pool_status!(header01.hash(), &pool, 0, 2); + //todo: can we do better? We don't have API to check if event was processed internally. + let mut counter = 0; + while pool.mempool_len().0 != 2 { + sleep(std::time::Duration::from_millis(1)); + counter = counter + 1; + if counter > 20 { + assert!(false, "timeout"); + } + } let header02 = api.push_block(2, vec![xt0], true); api.set_nonce(header02.hash(), Alice.into(), 201); //redundant let event = new_best_block_event(&pool, Some(header01.hash()), header02.hash()); block_on(pool.maintain(event)); - //charlie was resubmitted from mmepool into the view: - assert_pool_status!(header02.hash(), &pool, 2, 1); - assert_eq!(pool.mempool_len().0, 3); + assert_pool_status!(header02.hash(), &pool, 2, 0); + assert_eq!(pool.mempool_len().0, 2); } #[test] -fn fatp_limits_watcher_mempool_prevents_dropping() { +fn fatp_limits_watcher_mempool_doesnt_prevent_dropping() { sp_tracing::try_init_simple(); let builder = TestPoolBuilder::new(); @@ -169,23 +253,15 @@ fn fatp_limits_watcher_mempool_prevents_dropping() { let xt1 = uxt(Bob, 300); let xt2 = uxt(Alice, 200); - let submissions = vec![ - pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone()), - ]; - let mut submissions = block_on(futures::future::join_all(submissions)); - let xt2_watcher = submissions.remove(2).unwrap(); - let xt1_watcher = submissions.remove(1).unwrap(); - let xt0_watcher = submissions.remove(0).unwrap(); + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); assert_pool_status!(header01.hash(), &pool, 2, 0); - let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(1).collect::>(); - + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); log::debug!("xt0_status: {:#?}", xt0_status); - - assert_eq!(xt0_status, vec![TransactionStatus::Ready]); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(1).collect::>(); assert_eq!(xt1_status, vec![TransactionStatus::Ready]); @@ -214,28 +290,23 @@ fn fatp_limits_watcher_non_intial_view_drops_transaction() { let xt1 = uxt(Charlie, 400); let xt2 = uxt(Bob, 300); - let submissions = vec![ - pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone()), - ]; - let mut submissions = block_on(futures::future::join_all(submissions)); - let xt2_watcher = submissions.remove(2).unwrap(); - let xt1_watcher = submissions.remove(1).unwrap(); - let xt0_watcher = submissions.remove(0).unwrap(); + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); + + // make sure tx0 is actually dropped before checking iterator + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); assert_ready_iterator!(header01.hash(), pool, [xt1, xt2]); let header02 = api.push_block_with_parent(header01.hash(), vec![], true); block_on(pool.maintain(finalized_block_event(&pool, api.genesis_hash(), header02.hash()))); assert_pool_status!(header02.hash(), &pool, 2, 0); - assert_ready_iterator!(header02.hash(), pool, [xt2, xt0]); - - let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(1).collect::>(); - assert_eq!(xt0_status, vec![TransactionStatus::Ready]); + assert_ready_iterator!(header02.hash(), pool, [xt1, xt2]); - let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(2).collect::>(); - assert_eq!(xt1_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(1).collect::>(); + assert_eq!(xt1_status, vec![TransactionStatus::Ready]); let xt2_status = futures::executor::block_on_stream(xt2_watcher).take(1).collect::>(); assert_eq!(xt2_status, vec![TransactionStatus::Ready]); @@ -259,32 +330,19 @@ fn fatp_limits_watcher_finalized_transaction_frees_ready_space() { let xt1 = uxt(Charlie, 400); let xt2 = uxt(Bob, 300); - let submissions = vec![ - pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone()), - ]; - let mut submissions = block_on(futures::future::join_all(submissions)); - let xt2_watcher = submissions.remove(2).unwrap(); - let xt1_watcher = submissions.remove(1).unwrap(); - let xt0_watcher = submissions.remove(0).unwrap(); + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); assert_ready_iterator!(header01.hash(), pool, [xt1, xt2]); + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + let header02 = api.push_block_with_parent(header01.hash(), vec![xt0.clone()], true); block_on(pool.maintain(finalized_block_event(&pool, api.genesis_hash(), header02.hash()))); assert_pool_status!(header02.hash(), &pool, 2, 0); assert_ready_iterator!(header02.hash(), pool, [xt1, xt2]); - let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(3).collect::>(); - assert_eq!( - xt0_status, - vec![ - TransactionStatus::Ready, - TransactionStatus::InBlock((header02.hash(), 0)), - TransactionStatus::Finalized((header02.hash(), 0)) - ] - ); - let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(1).collect::>(); assert_eq!(xt1_status, vec![TransactionStatus::Ready]); @@ -311,43 +369,275 @@ fn fatp_limits_watcher_view_can_drop_transcation() { let xt2 = uxt(Bob, 300); let xt3 = uxt(Alice, 200); - let submissions = vec![ - pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone()), - pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone()), - ]; - let mut submissions = block_on(futures::future::join_all(submissions)); - let xt2_watcher = submissions.remove(2).unwrap(); - let xt1_watcher = submissions.remove(1).unwrap(); - let xt0_watcher = submissions.remove(0).unwrap(); + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); + + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped,]); assert_ready_iterator!(header01.hash(), pool, [xt1, xt2]); - let header02 = api.push_block_with_parent(header01.hash(), vec![xt0.clone()], true); + let header02 = api.push_block_with_parent(header01.hash(), vec![], true); block_on(pool.maintain(finalized_block_event(&pool, api.genesis_hash(), header02.hash()))); - let submission = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt3.clone())); - let xt3_watcher = submission.unwrap(); + let xt3_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt3.clone())).unwrap(); + + let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(2).collect::>(); + assert_eq!(xt1_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); assert_pool_status!(header02.hash(), pool, 2, 0); assert_ready_iterator!(header02.hash(), pool, [xt2, xt3]); - let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(3).collect::>(); - assert_eq!( - xt0_status, - vec![ - TransactionStatus::Ready, - TransactionStatus::InBlock((header02.hash(), 0)), - TransactionStatus::Finalized((header02.hash(), 0)) - ] + let xt2_status = futures::executor::block_on_stream(xt2_watcher).take(1).collect::>(); + assert_eq!(xt2_status, vec![TransactionStatus::Ready]); + + let xt3_status = futures::executor::block_on_stream(xt3_watcher).take(1).collect::>(); + assert_eq!(xt3_status, vec![TransactionStatus::Ready]); +} + +#[test] +fn fatp_limits_watcher_empty_and_full_view_immediately_drops() { + sp_tracing::try_init_simple(); + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder.with_mempool_count_limit(4).with_ready_count(2).build(); + api.set_nonce(api.genesis_hash(), Bob.into(), 300); + api.set_nonce(api.genesis_hash(), Charlie.into(), 400); + api.set_nonce(api.genesis_hash(), Dave.into(), 500); + api.set_nonce(api.genesis_hash(), Eve.into(), 600); + api.set_nonce(api.genesis_hash(), Ferdie.into(), 700); + + let header01 = api.push_block(1, vec![], true); + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = uxt(Alice, 200); + let xt1 = uxt(Bob, 300); + let xt2 = uxt(Charlie, 400); + + let xt3 = uxt(Dave, 500); + let xt4 = uxt(Eve, 600); + let xt5 = uxt(Ferdie, 700); + + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); + + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + + assert_pool_status!(header01.hash(), &pool, 2, 0); + assert_eq!(pool.mempool_len().1, 2); + + let header02e = api.push_block_with_parent( + header01.hash(), + vec![xt0.clone(), xt1.clone(), xt2.clone()], + true, ); + api.set_nonce(header02e.hash(), Alice.into(), 201); + api.set_nonce(header02e.hash(), Bob.into(), 301); + api.set_nonce(header02e.hash(), Charlie.into(), 401); + block_on(pool.maintain(new_best_block_event(&pool, Some(header01.hash()), header02e.hash()))); + + assert_pool_status!(header02e.hash(), &pool, 0, 0); + + let header02f = api.push_block_with_parent(header01.hash(), vec![], true); + block_on(pool.maintain(new_best_block_event(&pool, Some(header01.hash()), header02f.hash()))); + assert_pool_status!(header02f.hash(), &pool, 2, 0); + assert_ready_iterator!(header02f.hash(), pool, [xt1, xt2]); + + let xt3_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt3.clone())).unwrap(); + let xt4_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt4.clone())).unwrap(); + let result5 = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt5.clone())).map(|_| ()); + + //xt5 hits internal mempool limit + assert!(matches!(result5.unwrap_err().0, TxPoolError::ImmediatelyDropped)); + + assert_pool_status!(header02e.hash(), &pool, 2, 0); + assert_ready_iterator!(header02e.hash(), pool, [xt3, xt4]); + assert_eq!(pool.mempool_len().1, 4); let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(2).collect::>(); - assert_eq!(xt1_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + assert_eq!( + xt1_status, + vec![TransactionStatus::Ready, TransactionStatus::InBlock((header02e.hash(), 1))] + ); - let xt2_status = futures::executor::block_on_stream(xt2_watcher).take(1).collect::>(); - assert_eq!(xt2_status, vec![TransactionStatus::Ready]); + let xt2_status = futures::executor::block_on_stream(xt2_watcher).take(2).collect::>(); + assert_eq!( + xt2_status, + vec![TransactionStatus::Ready, TransactionStatus::InBlock((header02e.hash(), 2))] + ); let xt3_status = futures::executor::block_on_stream(xt3_watcher).take(1).collect::>(); assert_eq!(xt3_status, vec![TransactionStatus::Ready]); + let xt4_status = futures::executor::block_on_stream(xt4_watcher).take(1).collect::>(); + assert_eq!(xt4_status, vec![TransactionStatus::Ready]); +} + +#[test] +fn fatp_limits_watcher_empty_and_full_view_drops_with_event() { + // it is almost copy of fatp_limits_watcher_empty_and_full_view_immediately_drops, but the + // mempool_count limit is set to 5 (vs 4). + sp_tracing::try_init_simple(); + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder.with_mempool_count_limit(5).with_ready_count(2).build(); + api.set_nonce(api.genesis_hash(), Bob.into(), 300); + api.set_nonce(api.genesis_hash(), Charlie.into(), 400); + api.set_nonce(api.genesis_hash(), Dave.into(), 500); + api.set_nonce(api.genesis_hash(), Eve.into(), 600); + api.set_nonce(api.genesis_hash(), Ferdie.into(), 700); + + let header01 = api.push_block(1, vec![], true); + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = uxt(Alice, 200); + let xt1 = uxt(Bob, 300); + let xt2 = uxt(Charlie, 400); + + let xt3 = uxt(Dave, 500); + let xt4 = uxt(Eve, 600); + let xt5 = uxt(Ferdie, 700); + + let xt0_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt0.clone())).unwrap(); + let xt1_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt1.clone())).unwrap(); + let xt2_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt2.clone())).unwrap(); + + let xt0_status = futures::executor::block_on_stream(xt0_watcher).take(2).collect::>(); + assert_eq!(xt0_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + + assert_pool_status!(header01.hash(), &pool, 2, 0); + assert_eq!(pool.mempool_len().1, 2); + + let header02e = api.push_block_with_parent( + header01.hash(), + vec![xt0.clone(), xt1.clone(), xt2.clone()], + true, + ); + api.set_nonce(header02e.hash(), Alice.into(), 201); + api.set_nonce(header02e.hash(), Bob.into(), 301); + api.set_nonce(header02e.hash(), Charlie.into(), 401); + block_on(pool.maintain(new_best_block_event(&pool, Some(header01.hash()), header02e.hash()))); + + assert_pool_status!(header02e.hash(), &pool, 0, 0); + + let header02f = api.push_block_with_parent(header01.hash(), vec![], true); + block_on(pool.maintain(new_best_block_event(&pool, Some(header01.hash()), header02f.hash()))); + assert_pool_status!(header02f.hash(), &pool, 2, 0); + assert_ready_iterator!(header02f.hash(), pool, [xt1, xt2]); + + let xt3_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt3.clone())).unwrap(); + let xt4_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt4.clone())).unwrap(); + let xt5_watcher = block_on(pool.submit_and_watch(invalid_hash(), SOURCE, xt5.clone())).unwrap(); + + assert_pool_status!(header02e.hash(), &pool, 2, 0); + assert_ready_iterator!(header02e.hash(), pool, [xt4, xt5]); + + let xt3_status = futures::executor::block_on_stream(xt3_watcher).take(2).collect::>(); + assert_eq!(xt3_status, vec![TransactionStatus::Ready, TransactionStatus::Dropped]); + + //xt5 got dropped + assert_eq!(pool.mempool_len().1, 4); + + let xt1_status = futures::executor::block_on_stream(xt1_watcher).take(2).collect::>(); + assert_eq!( + xt1_status, + vec![TransactionStatus::Ready, TransactionStatus::InBlock((header02e.hash(), 1))] + ); + + let xt2_status = futures::executor::block_on_stream(xt2_watcher).take(2).collect::>(); + assert_eq!( + xt2_status, + vec![TransactionStatus::Ready, TransactionStatus::InBlock((header02e.hash(), 2))] + ); + + let xt4_status = futures::executor::block_on_stream(xt4_watcher).take(1).collect::>(); + assert_eq!(xt4_status, vec![TransactionStatus::Ready]); + + let xt5_status = futures::executor::block_on_stream(xt5_watcher).take(1).collect::>(); + assert_eq!(xt5_status, vec![TransactionStatus::Ready]); +} + +fn large_uxt(x: usize) -> substrate_test_runtime::Extrinsic { + substrate_test_runtime::ExtrinsicBuilder::new_include_data(vec![x as u8; 1024]).build() +} + +#[test] +fn fatp_limits_ready_size_works() { + sp_tracing::try_init_simple(); + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder.with_ready_bytes_size(3390).with_future_bytes_size(0).build(); + + let header01 = api.push_block(1, vec![], true); + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = large_uxt(0); + let xt1 = large_uxt(1); + let xt2 = large_uxt(2); + + let submissions = vec![ + pool.submit_one(header01.hash(), SOURCE, xt0.clone()), + pool.submit_one(header01.hash(), SOURCE, xt1.clone()), + pool.submit_one(header01.hash(), SOURCE, xt2.clone()), + ]; + + let results = block_on(futures::future::join_all(submissions)); + assert!(results.iter().all(Result::is_ok)); + //charlie was not included into view: + assert_pool_status!(header01.hash(), &pool, 3, 0); + assert_ready_iterator!(header01.hash(), pool, [xt0, xt1, xt2]); + + let xt3 = large_uxt(3); + let result3 = block_on(pool.submit_one(header01.hash(), SOURCE, xt3.clone())); + assert!(matches!(result3.as_ref().unwrap_err().0, TxPoolError::ImmediatelyDropped)); +} + +#[test] +fn fatp_limits_future_size_works() { + sp_tracing::try_init_simple(); + const UXT_SIZE: usize = 137; + + let builder = TestPoolBuilder::new(); + let (pool, api, _) = builder + .with_ready_bytes_size(UXT_SIZE) + .with_future_bytes_size(3 * UXT_SIZE) + .build(); + api.set_nonce(api.genesis_hash(), Bob.into(), 200); + api.set_nonce(api.genesis_hash(), Charlie.into(), 500); + + let header01 = api.push_block(1, vec![], true); + + let event = new_best_block_event(&pool, None, header01.hash()); + block_on(pool.maintain(event)); + + let xt0 = uxt(Bob, 201); + let xt1 = uxt(Charlie, 501); + let xt2 = uxt(Alice, 201); + let xt3 = uxt(Alice, 202); + assert_eq!(api.hash_and_length(&xt0).1, UXT_SIZE); + assert_eq!(api.hash_and_length(&xt1).1, UXT_SIZE); + assert_eq!(api.hash_and_length(&xt2).1, UXT_SIZE); + assert_eq!(api.hash_and_length(&xt3).1, UXT_SIZE); + + let _ = block_on(pool.submit_one(header01.hash(), SOURCE, xt0.clone())).unwrap(); + let _ = block_on(pool.submit_one(header01.hash(), SOURCE, xt1.clone())).unwrap(); + let _ = block_on(pool.submit_one(header01.hash(), SOURCE, xt2.clone())).unwrap(); + let _ = block_on(pool.submit_one(header01.hash(), SOURCE, xt3.clone())).unwrap(); + + //todo: can we do better? We don't have API to check if event was processed internally. + let mut counter = 0; + while pool.mempool_len().0 == 4 { + sleep(std::time::Duration::from_millis(1)); + counter = counter + 1; + if counter > 20 { + assert!(false, "timeout"); + } + } + assert_pool_status!(header01.hash(), &pool, 0, 3); + assert_eq!(pool.mempool_len().0, 3); } From a5de3b1442691e05b2002e6e9843933703fcc208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Mon, 11 Nov 2024 17:00:54 +0100 Subject: [PATCH 070/166] pallet-membership: Do not verify the `MembershipChanged` in bechmarks (#6439) There is no need to verify in the `pallet-membership` benchmark that the `MemembershipChanged` implementation works as the pallet thinks it should work. If you for example set it to `()`, `get_prime()` will always return `None`. TLDR: Remove the checks of `MembershipChanged` in the benchmarks to support any kind of implementation. --------- Co-authored-by: GitHub Action Co-authored-by: Adrian Catangiu --- prdoc/pr_6439.prdoc | 10 ++++++++++ substrate/frame/membership/src/benchmarking.rs | 5 ++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 prdoc/pr_6439.prdoc diff --git a/prdoc/pr_6439.prdoc b/prdoc/pr_6439.prdoc new file mode 100644 index 000000000000..fb3b62523576 --- /dev/null +++ b/prdoc/pr_6439.prdoc @@ -0,0 +1,10 @@ +title: 'pallet-membership: Do not verify the `MembershipChanged` in bechmarks' +doc: +- audience: Runtime Dev + description: |- + There is no need to verify in the `pallet-membership` benchmark that the `MemembershipChanged` implementation works as the pallet thinks it should work. If you for example set it to `()`, `get_prime()` will always return `None`. + + TLDR: Remove the checks of `MembershipChanged` in the benchmarks to support any kind of implementation. +crates: +- name: pallet-membership + bump: patch diff --git a/substrate/frame/membership/src/benchmarking.rs b/substrate/frame/membership/src/benchmarking.rs index 515be7eb5386..d752abaae866 100644 --- a/substrate/frame/membership/src/benchmarking.rs +++ b/substrate/frame/membership/src/benchmarking.rs @@ -99,7 +99,7 @@ benchmarks_instance_pallet! { assert!(!Members::::get().contains(&remove)); assert!(Members::::get().contains(&add)); // prime is rejigged - assert!(Prime::::get().is_some() && T::MembershipChanged::get_prime().is_some()); + assert!(Prime::::get().is_some()); #[cfg(test)] crate::mock::clean(); } @@ -119,7 +119,7 @@ benchmarks_instance_pallet! { new_members.sort(); assert_eq!(Members::::get(), new_members); // prime is rejigged - assert!(Prime::::get().is_some() && T::MembershipChanged::get_prime().is_some()); + assert!(Prime::::get().is_some()); #[cfg(test)] crate::mock::clean(); } @@ -157,7 +157,6 @@ benchmarks_instance_pallet! { )); } verify { assert!(Prime::::get().is_some()); - assert!(::get_prime().is_some()); #[cfg(test)] crate::mock::clean(); } From dd9514f7fd0467c067dd06eeaa57f02df2d1fc5b Mon Sep 17 00:00:00 2001 From: jpserrat <35823283+jpserrat@users.noreply.github.com> Date: Mon, 11 Nov 2024 13:54:37 -0300 Subject: [PATCH 071/166] add FeeManager to pallet xcm (#5363) Closes #2082 change send xcm to use `xcm::executor::FeeManager` to determine if the sender should be charged. I had to change the `FeeManager` of the penpal config to ensure the same test behaviour as before. For the other tests, I'm using the `FeeManager` from the `xcm::executor::FeeManager` as this one is used to check if the fee can be waived on the charge fees method. --------- Co-authored-by: Adrian Catangiu Co-authored-by: GitHub Action --- .../assets/asset-hub-rococo/src/xcm_config.rs | 2 ++ .../assets/asset-hub-westend/src/xcm_config.rs | 2 ++ .../bridge-hub-rococo/src/xcm_config.rs | 2 ++ .../bridge-hub-westend/src/xcm_config.rs | 2 ++ .../contracts-rococo/src/xcm_config.rs | 2 ++ .../coretime/coretime-rococo/src/xcm_config.rs | 2 ++ .../coretime/coretime-westend/src/xcm_config.rs | 2 ++ .../runtimes/testing/penpal/src/xcm_config.rs | 6 ++++-- polkadot/xcm/pallet-xcm/src/lib.rs | 17 +++++++++-------- polkadot/xcm/xcm-executor/src/lib.rs | 10 ++++++++++ prdoc/pr_5363.prdoc | 14 ++++++++++++++ 11 files changed, 51 insertions(+), 10 deletions(-) create mode 100644 prdoc/pr_5363.prdoc diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 66743fa3a07e..08b2f520c4b9 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -66,6 +66,7 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const TokenLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -315,6 +316,7 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index 88ccd42dff7f..b4e938f1f8b5 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -63,6 +63,7 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const WestendLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -336,6 +337,7 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, FellowshipEntities, diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index d36075444f7b..b37945317f6c 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -57,6 +57,7 @@ use xcm_executor::{ }; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const TokenLocation: Location = Location::parent(); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); pub RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); @@ -164,6 +165,7 @@ pub type Barrier = TrailingSetTopicAsId< /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index e692568932fe..befb63ef9709 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -56,6 +56,7 @@ use xcm_executor::{ }; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const WestendLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -161,6 +162,7 @@ pub type Barrier = TrailingSetTopicAsId< /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index 0151837aa351..532ad4ff4ce0 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -51,6 +51,7 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const RelayLocation: Location = Location::parent(); pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -166,6 +167,7 @@ pub type Barrier = TrailingSetTopicAsId< /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs index 37bf1e681447..33ad172962a1 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs @@ -52,6 +52,7 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const RocRelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(ROCOCO_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -177,6 +178,7 @@ parameter_types! { /// Locations that will not be charged fees in the executor, neither for execution nor delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs index 5616c585a13c..9f38975efae6 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs @@ -52,6 +52,7 @@ use xcm_builder::{ use xcm_executor::XcmExecutor; parameter_types! { + pub const RootLocation: Location = Location::here(); pub const TokenRelayLocation: Location = Location::parent(); pub const RelayNetwork: Option = Some(NetworkId::ByGenesis(WESTEND_GENESIS_HASH)); pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); @@ -185,6 +186,7 @@ parameter_types! { /// Locations that will not be charged fees in the executor, neither for execution nor delivery. /// We only waive fees for system functions, which these locations represent. pub type WaivedLocations = ( + Equals, RelayOrOtherSystemParachains, Equals, ); diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index 375c3d509f48..10481d5d2ebc 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -34,7 +34,7 @@ use core::marker::PhantomData; use frame_support::{ parameter_types, traits::{ - tokens::imbalance::ResolveAssetTo, ConstU32, Contains, ContainsPair, Everything, + tokens::imbalance::ResolveAssetTo, ConstU32, Contains, ContainsPair, Equals, Everything, EverythingBut, Get, Nothing, PalletInfoAccess, }, weights::Weight, @@ -210,6 +210,7 @@ pub type XcmOriginToTransactDispatchOrigin = ( ); parameter_types! { + pub const RootLocation: Location = Location::here(); // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024); pub const MaxInstructions: u32 = 100; @@ -336,6 +337,7 @@ pub type TrustedReserves = ( pub type TrustedTeleporters = (AssetFromChain,); +pub type WaivedLocations = Equals; /// `AssetId`/`Balance` converter for `TrustBackedAssets`. pub type TrustBackedAssetsConvertedConcreteId = assets_common::TrustBackedAssetsConvertedConcreteId; @@ -399,7 +401,7 @@ impl xcm_executor::Config for XcmConfig { type AssetLocker = (); type AssetExchanger = PoolAssetsExchanger; type FeeManager = XcmFeeManagerFromComponents< - (), + WaivedLocations, SendXcmFeeToAccount, >; type MessageExporter = (); diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 4a97546b38d1..5e0512c6a9fd 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -75,6 +75,7 @@ use xcm_runtime_apis::{ #[cfg(any(feature = "try-runtime", test))] use sp_runtime::TryRuntimeError; +use xcm_executor::traits::{FeeManager, FeeReason}; pub trait WeightInfo { fn send() -> Weight; @@ -240,7 +241,7 @@ pub mod pallet { type XcmExecuteFilter: Contains<(Location, Xcm<::RuntimeCall>)>; /// Something to execute an XCM message. - type XcmExecutor: ExecuteXcm<::RuntimeCall> + XcmAssetTransfers; + type XcmExecutor: ExecuteXcm<::RuntimeCall> + XcmAssetTransfers + FeeManager; /// Our XCM filter which messages to be teleported using the dedicated extrinsic must pass. type XcmTeleportFilter: Contains<(Location, Vec)>; @@ -2468,17 +2469,17 @@ impl Pallet { mut message: Xcm<()>, ) -> Result { let interior = interior.into(); + let local_origin = interior.clone().into(); let dest = dest.into(); - let maybe_fee_payer = if interior != Junctions::Here { + let is_waived = + ::is_waived(Some(&local_origin), FeeReason::ChargeFees); + if interior != Junctions::Here { message.0.insert(0, DescendOrigin(interior.clone())); - Some(interior.into()) - } else { - None - }; + } tracing::debug!(target: "xcm::send_xcm", "{:?}, {:?}", dest.clone(), message.clone()); let (ticket, price) = validate_send::(dest, message)?; - if let Some(fee_payer) = maybe_fee_payer { - Self::charge_fees(fee_payer, price).map_err(|e| { + if !is_waived { + Self::charge_fees(local_origin, price).map_err(|e| { tracing::error!( target: "xcm::pallet_xcm::send_xcm", ?e, diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs index a823dc6fec78..e33f94389b21 100644 --- a/polkadot/xcm/xcm-executor/src/lib.rs +++ b/polkadot/xcm/xcm-executor/src/lib.rs @@ -304,6 +304,16 @@ impl XcmAssetTransfers for XcmExecutor { type AssetTransactor = Config::AssetTransactor; } +impl FeeManager for XcmExecutor { + fn is_waived(origin: Option<&Location>, r: FeeReason) -> bool { + Config::FeeManager::is_waived(origin, r) + } + + fn handle_fee(fee: Assets, context: Option<&XcmContext>, r: FeeReason) { + Config::FeeManager::handle_fee(fee, context, r) + } +} + #[derive(Debug)] pub struct ExecutorError { pub index: u32, diff --git a/prdoc/pr_5363.prdoc b/prdoc/pr_5363.prdoc new file mode 100644 index 000000000000..c3ecfffb9e52 --- /dev/null +++ b/prdoc/pr_5363.prdoc @@ -0,0 +1,14 @@ +title: "[pallet-xcm] waive transport fees based on XcmConfig" + +doc: + - audience: Runtime Dev + description: | + pallet-xcm::send() no longer implicitly waives transport fees for the local root location, + but instead relies on xcm_executor::Config::FeeManager to determine whether certain locations have free transport. + + 🚨 Warning: 🚨 If your chain relies on free transport for local root, please make + sure to add Location::here() to the waived-fee locations in your configured xcm_executor::Config::FeeManager. + +crates: + - name: pallet-xcm + bump: major \ No newline at end of file From 1b0cbe99ab8537fa188952a203bdb73b0e5fdd3f Mon Sep 17 00:00:00 2001 From: davidk-pt Date: Mon, 11 Nov 2024 19:23:49 +0200 Subject: [PATCH 072/166] Use relay chain block number in the broker pallet instead of block number (#5656) Based on https://github.com/paritytech/polkadot-sdk/pull/3331 Related to https://github.com/paritytech/polkadot-sdk/issues/3268 Implements migrations with customizable block number to relay height number translation function. Adds block to relay height migration code for rococo and westend. --------- Co-authored-by: DavidK Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- .../coretime/coretime-rococo/src/lib.rs | 22 +- .../coretime/coretime-westend/src/lib.rs | 22 +- prdoc/pr_5656.prdoc | 18 ++ substrate/frame/broker/src/benchmarking.rs | 10 +- .../frame/broker/src/dispatchable_impls.rs | 10 +- substrate/frame/broker/src/lib.rs | 11 +- substrate/frame/broker/src/migration.rs | 252 ++++++++++++++++++ substrate/frame/broker/src/tick_impls.rs | 4 +- substrate/frame/broker/src/types.rs | 24 +- substrate/frame/broker/src/utility_impls.rs | 3 +- 10 files changed, 345 insertions(+), 31 deletions(-) create mode 100644 prdoc/pr_5656.prdoc diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index a4ff48bfc0a0..31700c2e25ff 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -68,7 +68,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; pub use sp_runtime::BuildStorage; use sp_runtime::{ generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT}, + traits::{BlakeTwo256, Block as BlockT, BlockNumberProvider}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, RuntimeDebug, }; @@ -124,6 +124,7 @@ pub type Migrations = ( pallet_broker::migration::MigrateV0ToV1, pallet_broker::migration::MigrateV1ToV2, pallet_broker::migration::MigrateV2ToV3, + pallet_broker::migration::MigrateV3ToV4, // permanent pallet_xcm::migration::MigrateToLatestXcmVersion, ); @@ -591,6 +592,25 @@ impl pallet_sudo::Config for Runtime { type WeightInfo = pallet_sudo::weights::SubstrateWeight; } +pub struct BrokerMigrationV4BlockConversion; + +impl pallet_broker::migration::v4::BlockToRelayHeightConversion + for BrokerMigrationV4BlockConversion +{ + fn convert_block_number_to_relay_height(input_block_number: u32) -> u32 { + let relay_height = pallet_broker::RCBlockNumberProviderOf::< + ::Coretime, + >::current_block_number(); + let parachain_block_number = frame_system::Pallet::::block_number(); + let offset = relay_height - parachain_block_number * 2; + offset + input_block_number * 2 + } + + fn convert_block_length_to_relay_length(input_block_length: u32) -> u32 { + input_block_length * 2 + } +} + // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index edede5aeb46b..1f0f54884fa8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -68,7 +68,7 @@ use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; pub use sp_runtime::BuildStorage; use sp_runtime::{ generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT}, + traits::{BlakeTwo256, Block as BlockT, BlockNumberProvider}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, RuntimeDebug, }; @@ -124,6 +124,7 @@ pub type Migrations = ( pallet_broker::migration::MigrateV0ToV1, pallet_broker::migration::MigrateV1ToV2, pallet_broker::migration::MigrateV2ToV3, + pallet_broker::migration::MigrateV3ToV4, // permanent pallet_xcm::migration::MigrateToLatestXcmVersion, ); @@ -586,6 +587,25 @@ impl pallet_utility::Config for Runtime { type WeightInfo = weights::pallet_utility::WeightInfo; } +pub struct BrokerMigrationV4BlockConversion; + +impl pallet_broker::migration::v4::BlockToRelayHeightConversion + for BrokerMigrationV4BlockConversion +{ + fn convert_block_number_to_relay_height(input_block_number: u32) -> u32 { + let relay_height = pallet_broker::RCBlockNumberProviderOf::< + ::Coretime, + >::current_block_number(); + let parachain_block_number = frame_system::Pallet::::block_number(); + let offset = relay_height - parachain_block_number * 2; + offset + input_block_number * 2 + } + + fn convert_block_length_to_relay_length(input_block_length: u32) -> u32 { + input_block_length * 2 + } +} + // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime diff --git a/prdoc/pr_5656.prdoc b/prdoc/pr_5656.prdoc new file mode 100644 index 000000000000..b20546bf7a5e --- /dev/null +++ b/prdoc/pr_5656.prdoc @@ -0,0 +1,18 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Use Relay Blocknumber in Pallet Broker + +doc: + - audience: Runtime Dev + description: | + Changing `sale_start`, `interlude_length` and `leading_length` in `pallet_broker` to use relay chain block numbers instead of parachain block numbers. + Relay chain block numbers are almost deterministic and more future proof. + +crates: + - name: pallet-broker + bump: major + - name: coretime-rococo-runtime + bump: major + - name: coretime-westend-runtime + bump: major \ No newline at end of file diff --git a/substrate/frame/broker/src/benchmarking.rs b/substrate/frame/broker/src/benchmarking.rs index 595bf564f7e1..9ef9b1254435 100644 --- a/substrate/frame/broker/src/benchmarking.rs +++ b/substrate/frame/broker/src/benchmarking.rs @@ -217,9 +217,11 @@ mod benches { _(origin as T::RuntimeOrigin, initial_price, extra_cores.try_into().unwrap()); assert!(SaleInfo::::get().is_some()); + let sale_start = RCBlockNumberProviderOf::::current_block_number() + + config.interlude_length; assert_last_event::( Event::SaleInitialized { - sale_start: 2u32.into(), + sale_start, leadin_length: 1u32.into(), start_price: 1_000_000_000u32.into(), end_price: 10_000_000u32.into(), @@ -787,7 +789,7 @@ mod benches { let core_count = n.try_into().unwrap(); let config = new_config_record::(); - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); let end_price = 10_000_000u32.into(); let commit_timeslice = Broker::::latest_timeslice_ready_to_commit(&config); let sale = SaleInfoRecordOf:: { @@ -844,9 +846,11 @@ mod benches { } assert!(SaleInfo::::get().is_some()); + let sale_start = RCBlockNumberProviderOf::::current_block_number() + + config.interlude_length; assert_last_event::( Event::SaleInitialized { - sale_start: 2u32.into(), + sale_start, leadin_length: 1u32.into(), start_price: 1_000_000_000u32.into(), end_price: 10_000_000u32.into(), diff --git a/substrate/frame/broker/src/dispatchable_impls.rs b/substrate/frame/broker/src/dispatchable_impls.rs index 5fbd957d7908..733d96625da0 100644 --- a/substrate/frame/broker/src/dispatchable_impls.rs +++ b/substrate/frame/broker/src/dispatchable_impls.rs @@ -21,7 +21,7 @@ use frame_support::{ traits::{fungible::Mutate, tokens::Preservation::Expendable, DefensiveResult}, }; use sp_arithmetic::traits::{CheckedDiv, Saturating, Zero}; -use sp_runtime::traits::Convert; +use sp_runtime::traits::{BlockNumberProvider, Convert}; use CompletionStatus::{Complete, Partial}; impl Pallet { @@ -91,7 +91,7 @@ impl Pallet { last_committed_timeslice: commit_timeslice.saturating_sub(1), last_timeslice: Self::current_timeslice(), }; - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); // Imaginary old sale for bootstrapping the first actual sale: let old_sale = SaleInfoRecord { sale_start: now, @@ -119,7 +119,7 @@ impl Pallet { let mut sale = SaleInfo::::get().ok_or(Error::::NoSales)?; Self::ensure_cores_for_sale(&status, &sale)?; - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); ensure!(now > sale.sale_start, Error::::TooEarly); let price = Self::sale_price(&sale, now); ensure!(price_limit >= price, Error::::Overpriced); @@ -171,7 +171,7 @@ impl Pallet { let begin = sale.region_end; let price_cap = record.price + config.renewal_bump * record.price; - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); let price = Self::sale_price(&sale, now).min(price_cap); log::debug!( "Renew with: sale price: {:?}, price cap: {:?}, old price: {:?}", @@ -569,7 +569,7 @@ impl Pallet { Self::ensure_cores_for_sale(&status, &sale)?; - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); Ok(Self::sale_price(&sale, now)) } } diff --git a/substrate/frame/broker/src/lib.rs b/substrate/frame/broker/src/lib.rs index 10745544fadf..ed16b98d26cc 100644 --- a/substrate/frame/broker/src/lib.rs +++ b/substrate/frame/broker/src/lib.rs @@ -67,7 +67,7 @@ pub mod pallet { use frame_system::pallet_prelude::*; use sp_runtime::traits::{Convert, ConvertBack, MaybeConvert}; - const STORAGE_VERSION: StorageVersion = StorageVersion::new(3); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(4); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -305,10 +305,11 @@ pub mod pallet { }, /// A new sale has been initialized. SaleInitialized { - /// The local block number at which the sale will/did start. - sale_start: BlockNumberFor, - /// The length in blocks of the Leadin Period (where the price is decreasing). - leadin_length: BlockNumberFor, + /// The relay block number at which the sale will/did start. + sale_start: RelayBlockNumberOf, + /// The length in relay chain blocks of the Leadin Period (where the price is + /// decreasing). + leadin_length: RelayBlockNumberOf, /// The price of Bulk Coretime at the beginning of the Leadin Period. start_price: BalanceOf, /// The price of Bulk Coretime after the Leadin Period. diff --git a/substrate/frame/broker/src/migration.rs b/substrate/frame/broker/src/migration.rs index c2a243d6f0e8..f19b1e19bdd1 100644 --- a/substrate/frame/broker/src/migration.rs +++ b/substrate/frame/broker/src/migration.rs @@ -130,7 +130,13 @@ mod v2 { mod v3 { use super::*; + use codec::MaxEncodedLen; + use frame_support::{ + pallet_prelude::{OptionQuery, RuntimeDebug, TypeInfo}, + storage_alias, + }; use frame_system::Pallet as System; + use sp_arithmetic::Perbill; pub struct MigrateToV3Impl(PhantomData); @@ -156,6 +162,244 @@ mod v3 { Ok(()) } } + + #[storage_alias] + pub type Configuration = StorageValue, ConfigRecordOf, OptionQuery>; + pub type ConfigRecordOf = + ConfigRecord, RelayBlockNumberOf>; + + // types added here for v4 migration + #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] + pub struct ConfigRecord { + /// The number of Relay-chain blocks in advance which scheduling should be fixed and the + /// `Coretime::assign` API used to inform the Relay-chain. + pub advance_notice: RelayBlockNumber, + /// The length in blocks of the Interlude Period for forthcoming sales. + pub interlude_length: BlockNumber, + /// The length in blocks of the Leadin Period for forthcoming sales. + pub leadin_length: BlockNumber, + /// The length in timeslices of Regions which are up for sale in forthcoming sales. + pub region_length: Timeslice, + /// The proportion of cores available for sale which should be sold in order for the price + /// to remain the same in the next sale. + pub ideal_bulk_proportion: Perbill, + /// An artificial limit to the number of cores which are allowed to be sold. If `Some` then + /// no more cores will be sold than this. + pub limit_cores_offered: Option, + /// The amount by which the renewal price increases each sale period. + pub renewal_bump: Perbill, + /// The duration by which rewards for contributions to the InstaPool must be collected. + pub contribution_timeout: Timeslice, + } + + #[storage_alias] + pub type SaleInfo = StorageValue, SaleInfoRecordOf, OptionQuery>; + pub type SaleInfoRecordOf = + SaleInfoRecord, frame_system::pallet_prelude::BlockNumberFor>; + + /// The status of a Bulk Coretime Sale. + #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] + pub struct SaleInfoRecord { + /// The relay block number at which the sale will/did start. + pub sale_start: BlockNumber, + /// The length in relay chain blocks of the Leadin Period (where the price is decreasing). + pub leadin_length: BlockNumber, + /// The price of Bulk Coretime after the Leadin Period. + pub price: Balance, + /// The first timeslice of the Regions which are being sold in this sale. + pub region_begin: Timeslice, + /// The timeslice on which the Regions which are being sold in the sale terminate. (i.e. + /// One after the last timeslice which the Regions control.) + pub region_end: Timeslice, + /// The number of cores we want to sell, ideally. Selling this amount would result in no + /// change to the price for the next sale. + pub ideal_cores_sold: CoreIndex, + /// Number of cores which are/have been offered for sale. + pub cores_offered: CoreIndex, + /// The index of the first core which is for sale. Core of Regions which are sold have + /// incrementing indices from this. + pub first_core: CoreIndex, + /// The latest price at which Bulk Coretime was purchased until surpassing the ideal number + /// of cores were sold. + pub sellout_price: Option, + /// Number of cores which have been sold; never more than cores_offered. + pub cores_sold: CoreIndex, + } +} + +pub mod v4 { + use super::*; + + type BlockNumberFor = frame_system::pallet_prelude::BlockNumberFor; + + pub trait BlockToRelayHeightConversion { + /// Converts absolute value of parachain block number to relay chain block number + fn convert_block_number_to_relay_height( + block_number: BlockNumberFor, + ) -> RelayBlockNumberOf; + + /// Converts parachain block length into equivalent relay chain block length + fn convert_block_length_to_relay_length( + block_number: BlockNumberFor, + ) -> RelayBlockNumberOf; + } + + pub struct MigrateToV4Impl(PhantomData, PhantomData); + impl> UncheckedOnRuntimeUpgrade + for MigrateToV4Impl + { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + let (interlude_length, configuration_leadin_length) = + if let Some(config_record) = v3::Configuration::::get() { + (config_record.interlude_length, config_record.leadin_length) + } else { + ((0 as u32).into(), (0 as u32).into()) + }; + + let updated_interlude_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length(interlude_length); + let updated_leadin_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length(configuration_leadin_length); + log::info!(target: LOG_TARGET, "Configuration Pre-Migration: Interlude Length {:?}->{:?} Leadin Length {:?}->{:?}", interlude_length, updated_interlude_length, configuration_leadin_length, updated_leadin_length); + + let (sale_start, sale_info_leadin_length) = + if let Some(sale_info_record) = v3::SaleInfo::::get() { + (sale_info_record.sale_start, sale_info_record.leadin_length) + } else { + ((0 as u32).into(), (0 as u32).into()) + }; + + let updated_sale_start: RelayBlockNumberOf = + BlockConversion::convert_block_number_to_relay_height(sale_start); + let updated_sale_info_leadin_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length(sale_info_leadin_length); + log::info!(target: LOG_TARGET, "SaleInfo Pre-Migration: Sale Start {:?}->{:?} Interlude Length {:?}->{:?}", sale_start, updated_sale_start, sale_info_leadin_length, updated_sale_info_leadin_length); + + Ok((interlude_length, configuration_leadin_length, sale_start, sale_info_leadin_length) + .encode()) + } + + fn on_runtime_upgrade() -> frame_support::weights::Weight { + let mut weight = T::DbWeight::get().reads(1); + + if let Some(config_record) = v3::Configuration::::take() { + log::info!(target: LOG_TARGET, "migrating Configuration record"); + + let updated_interlude_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length( + config_record.interlude_length, + ); + let updated_leadin_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length( + config_record.leadin_length, + ); + + let updated_config_record = ConfigRecord { + interlude_length: updated_interlude_length, + leadin_length: updated_leadin_length, + advance_notice: config_record.advance_notice, + region_length: config_record.region_length, + ideal_bulk_proportion: config_record.ideal_bulk_proportion, + limit_cores_offered: config_record.limit_cores_offered, + renewal_bump: config_record.renewal_bump, + contribution_timeout: config_record.contribution_timeout, + }; + Configuration::::put(updated_config_record); + } + weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1)); + + if let Some(sale_info) = v3::SaleInfo::::take() { + log::info!(target: LOG_TARGET, "migrating SaleInfo record"); + + let updated_sale_start: RelayBlockNumberOf = + BlockConversion::convert_block_number_to_relay_height(sale_info.sale_start); + let updated_leadin_length: RelayBlockNumberOf = + BlockConversion::convert_block_length_to_relay_length(sale_info.leadin_length); + + let updated_sale_info = SaleInfoRecord { + sale_start: updated_sale_start, + leadin_length: updated_leadin_length, + end_price: sale_info.price, + region_begin: sale_info.region_begin, + region_end: sale_info.region_end, + ideal_cores_sold: sale_info.ideal_cores_sold, + cores_offered: sale_info.cores_offered, + first_core: sale_info.first_core, + sellout_price: sale_info.sellout_price, + cores_sold: sale_info.cores_sold, + }; + SaleInfo::::put(updated_sale_info); + } + + weight.saturating_add(T::DbWeight::get().reads_writes(1, 2)) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + let ( + old_interlude_length, + old_configuration_leadin_length, + old_sale_start, + old_sale_info_leadin_length, + ): (BlockNumberFor, BlockNumberFor, BlockNumberFor, BlockNumberFor) = + Decode::decode(&mut &state[..]).expect("pre_upgrade provides a valid state; qed"); + + if let Some(config_record) = Configuration::::get() { + ensure!( + Self::verify_updated_block_length( + old_configuration_leadin_length, + config_record.leadin_length + ), + "must migrate configuration leadin_length" + ); + + ensure!( + Self::verify_updated_block_length( + old_interlude_length, + config_record.interlude_length + ), + "must migrate configuration interlude_length" + ); + } + + if let Some(sale_info) = SaleInfo::::get() { + ensure!( + Self::verify_updated_block_time(old_sale_start, sale_info.sale_start), + "must migrate sale info sale_start" + ); + + ensure!( + Self::verify_updated_block_length( + old_sale_info_leadin_length, + sale_info.leadin_length + ), + "must migrate sale info leadin_length" + ); + } + + Ok(()) + } + } + + #[cfg(feature = "try-runtime")] + impl> + MigrateToV4Impl + { + fn verify_updated_block_time( + old_value: BlockNumberFor, + new_value: RelayBlockNumberOf, + ) -> bool { + BlockConversion::convert_block_number_to_relay_height(old_value) == new_value + } + + fn verify_updated_block_length( + old_value: BlockNumberFor, + new_value: RelayBlockNumberOf, + ) -> bool { + BlockConversion::convert_block_length_to_relay_length(old_value) == new_value + } + } } /// Migrate the pallet storage from `0` to `1`. @@ -182,3 +426,11 @@ pub type MigrateV2ToV3 = frame_support::migrations::VersionedMigration< Pallet, ::DbWeight, >; + +pub type MigrateV3ToV4 = frame_support::migrations::VersionedMigration< + 3, + 4, + v4::MigrateToV4Impl, + Pallet, + ::DbWeight, +>; diff --git a/substrate/frame/broker/src/tick_impls.rs b/substrate/frame/broker/src/tick_impls.rs index 8dbd5df57166..e0b4932f11e2 100644 --- a/substrate/frame/broker/src/tick_impls.rs +++ b/substrate/frame/broker/src/tick_impls.rs @@ -19,7 +19,7 @@ use super::*; use alloc::{vec, vec::Vec}; use frame_support::{pallet_prelude::*, traits::defensive_prelude::*, weights::WeightMeter}; use sp_arithmetic::traits::{One, SaturatedConversion, Saturating, Zero}; -use sp_runtime::traits::{ConvertBack, MaybeConvert}; +use sp_runtime::traits::{BlockNumberProvider, ConvertBack, MaybeConvert}; use CompletionStatus::Complete; impl Pallet { @@ -158,7 +158,7 @@ impl Pallet { config: &ConfigRecordOf, status: &StatusRecord, ) -> Option<()> { - let now = frame_system::Pallet::::block_number(); + let now = RCBlockNumberProviderOf::::current_block_number(); let pool_item = ScheduleItem { assignment: CoreAssignment::Pool, mask: CoreMask::complete() }; diff --git a/substrate/frame/broker/src/types.rs b/substrate/frame/broker/src/types.rs index 10e6756bc90e..f970b310a3cb 100644 --- a/substrate/frame/broker/src/types.rs +++ b/substrate/frame/broker/src/types.rs @@ -21,7 +21,7 @@ use crate::{ }; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::traits::fungible::Inspect; -use frame_system::{pallet_prelude::BlockNumberFor, Config as SConfig}; +use frame_system::Config as SConfig; use scale_info::TypeInfo; use sp_arithmetic::Perbill; use sp_core::{ConstU32, RuntimeDebug}; @@ -208,11 +208,11 @@ pub struct PoolIoRecord { /// The status of a Bulk Coretime Sale. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct SaleInfoRecord { - /// The local block number at which the sale will/did start. - pub sale_start: BlockNumber, +pub struct SaleInfoRecord { + /// The relay block number at which the sale will/did start. + pub sale_start: RelayBlockNumber, /// The length in blocks of the Leadin Period (where the price is decreasing). - pub leadin_length: BlockNumber, + pub leadin_length: RelayBlockNumber, /// The price of Bulk Coretime after the Leadin Period. pub end_price: Balance, /// The first timeslice of the Regions which are being sold in this sale. @@ -235,7 +235,7 @@ pub struct SaleInfoRecord { /// Number of cores which have been sold; never more than cores_offered. pub cores_sold: CoreIndex, } -pub type SaleInfoRecordOf = SaleInfoRecord, BlockNumberFor>; +pub type SaleInfoRecordOf = SaleInfoRecord, RelayBlockNumberOf>; /// Record for Polkadot Core reservations (generally tasked with the maintenance of System /// Chains). @@ -272,14 +272,14 @@ pub type OnDemandRevenueRecordOf = /// Configuration of this pallet. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub struct ConfigRecord { +pub struct ConfigRecord { /// The number of Relay-chain blocks in advance which scheduling should be fixed and the /// `Coretime::assign` API used to inform the Relay-chain. pub advance_notice: RelayBlockNumber, /// The length in blocks of the Interlude Period for forthcoming sales. - pub interlude_length: BlockNumber, + pub interlude_length: RelayBlockNumber, /// The length in blocks of the Leadin Period for forthcoming sales. - pub leadin_length: BlockNumber, + pub leadin_length: RelayBlockNumber, /// The length in timeslices of Regions which are up for sale in forthcoming sales. pub region_length: Timeslice, /// The proportion of cores available for sale which should be sold. @@ -296,11 +296,11 @@ pub struct ConfigRecord { /// The duration by which rewards for contributions to the InstaPool must be collected. pub contribution_timeout: Timeslice, } -pub type ConfigRecordOf = ConfigRecord, RelayBlockNumberOf>; +pub type ConfigRecordOf = ConfigRecord>; -impl ConfigRecord +impl ConfigRecord where - BlockNumber: sp_arithmetic::traits::Zero, + RelayBlockNumber: sp_arithmetic::traits::Zero, { /// Check the config for basic validity constraints. pub(crate) fn validate(&self) -> Result<(), ()> { diff --git a/substrate/frame/broker/src/utility_impls.rs b/substrate/frame/broker/src/utility_impls.rs index e937e0cbbec5..73f05d1e5ef4 100644 --- a/substrate/frame/broker/src/utility_impls.rs +++ b/substrate/frame/broker/src/utility_impls.rs @@ -24,7 +24,6 @@ use frame_support::{ OnUnbalanced, }, }; -use frame_system::pallet_prelude::BlockNumberFor; use sp_arithmetic::{ traits::{SaturatedConversion, Saturating}, FixedPointNumber, FixedU64, @@ -60,7 +59,7 @@ impl Pallet { T::PalletId::get().into_account_truncating() } - pub fn sale_price(sale: &SaleInfoRecordOf, now: BlockNumberFor) -> BalanceOf { + pub fn sale_price(sale: &SaleInfoRecordOf, now: RelayBlockNumberOf) -> BalanceOf { let num = now.saturating_sub(sale.sale_start).min(sale.leadin_length).saturated_into(); let through = FixedU64::from_rational(num, sale.leadin_length.saturated_into()); T::PriceAdapter::leadin_factor_at(through).saturating_mul_int(sale.end_price) From aff3a0796176ff3c0ee1b89c2f1d811a858f17a8 Mon Sep 17 00:00:00 2001 From: clangenb <37865735+clangenb@users.noreply.github.com> Date: Mon, 11 Nov 2024 23:38:59 +0100 Subject: [PATCH 073/166] migrate pallet-nft-fractionalization to benchmarking v2 syntax (#6301) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Migrates pallet-nft-fractionalization to benchmarking v2 syntax. Part of: * #6202 --------- Co-authored-by: Giuseppe Re Co-authored-by: GitHub Action Co-authored-by: Bastian Köcher --- prdoc/pr_6301.prdoc | 11 +++ .../nft-fractionalization/src/benchmarking.rs | 70 ++++++++++++------- 2 files changed, 57 insertions(+), 24 deletions(-) create mode 100644 prdoc/pr_6301.prdoc diff --git a/prdoc/pr_6301.prdoc b/prdoc/pr_6301.prdoc new file mode 100644 index 000000000000..d4c05c17c8fb --- /dev/null +++ b/prdoc/pr_6301.prdoc @@ -0,0 +1,11 @@ +title: migrate pallet-nft-fractionalization to benchmarking v2 syntax +doc: +- audience: Runtime Dev + description: |- + Migrates pallet-nft-fractionalization to benchmarking v2 syntax. + + Part of: + * #6202 +crates: +- name: pallet-nft-fractionalization + bump: patch diff --git a/substrate/frame/nft-fractionalization/src/benchmarking.rs b/substrate/frame/nft-fractionalization/src/benchmarking.rs index 811b5fe1b317..433019280f20 100644 --- a/substrate/frame/nft-fractionalization/src/benchmarking.rs +++ b/substrate/frame/nft-fractionalization/src/benchmarking.rs @@ -20,7 +20,7 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; -use frame_benchmarking::{benchmarks, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_support::{ assert_ok, traits::{ @@ -77,20 +77,37 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { assert_eq!(event, &system_event); } -benchmarks! { - where_clause { - where - T::Nfts: Create, frame_system::pallet_prelude::BlockNumberFor::, T::NftCollectionId>> - + Mutate, - } - - fractionalize { +#[benchmarks( + where + T::Nfts: + Create< + T::AccountId, + CollectionConfig, + frame_system::pallet_prelude::BlockNumberFor::, + T::NftCollectionId> + > + + Mutate, +)] +mod benchmarks { + use super::*; + + #[benchmark] + fn fractionalize() { let asset = T::BenchmarkHelper::asset(0); let collection = T::BenchmarkHelper::collection(0); let nft = T::BenchmarkHelper::nft(0); let (caller, caller_lookup) = mint_nft::(nft); - }: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset.clone(), caller_lookup, 1000u32.into()) - verify { + + #[extrinsic_call] + _( + SystemOrigin::Signed(caller.clone()), + collection, + nft, + asset.clone(), + caller_lookup, + 1000u32.into(), + ); + assert_last_event::( Event::NftFractionalized { nft_collection: collection, @@ -98,34 +115,39 @@ benchmarks! { fractions: 1000u32.into(), asset, beneficiary: caller, - }.into() + } + .into(), ); } - unify { + #[benchmark] + fn unify() { let asset = T::BenchmarkHelper::asset(0); let collection = T::BenchmarkHelper::collection(0); let nft = T::BenchmarkHelper::nft(0); let (caller, caller_lookup) = mint_nft::(nft); - NftFractionalization::::fractionalize( + + assert_ok!(NftFractionalization::::fractionalize( SystemOrigin::Signed(caller.clone()).into(), collection, nft, asset.clone(), caller_lookup.clone(), 1000u32.into(), - )?; - }: _(SystemOrigin::Signed(caller.clone()), collection, nft, asset.clone(), caller_lookup) - verify { + )); + + #[extrinsic_call] + _(SystemOrigin::Signed(caller.clone()), collection, nft, asset.clone(), caller_lookup); + assert_last_event::( - Event::NftUnified { - nft_collection: collection, - nft, - asset, - beneficiary: caller, - }.into() + Event::NftUnified { nft_collection: collection, nft, asset, beneficiary: caller } + .into(), ); } - impl_benchmark_test_suite!(NftFractionalization, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite!( + NftFractionalization, + crate::mock::new_test_ext(), + crate::mock::Test + ); } From 9f8656baadd6b4ed52012a0ac415748c3e4f0891 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Tue, 12 Nov 2024 09:27:31 +0100 Subject: [PATCH 074/166] [pallet-revive] adjust fee dry-run calculation (#6393) - Fix bare_eth_transact so that it estimate more precisely the transaction fee - Add some context to the build.rs to make it easier to troubleshoot errors - Add TransactionBuilder for the RPC tests. - Improve error message, proxy rpc error from the node and handle reverted error message - Add logs in ReceiptInfo --------- Co-authored-by: GitHub Action --- Cargo.lock | 12537 +++++++++++----- Cargo.toml | 8 +- .../assets/asset-hub-westend/src/lib.rs | 2 +- prdoc/pr_6393.prdoc | 16 + substrate/bin/node/cli/src/chain_spec.rs | 2 +- substrate/frame/revive/fixtures/build.rs | 15 +- .../revive/fixtures/contracts/rpc_demo.rs | 8 +- substrate/frame/revive/rpc/Cargo.toml | 9 +- substrate/frame/revive/rpc/examples/README.md | 34 +- substrate/frame/revive/rpc/examples/bun.lockb | Bin 0 -> 10962 bytes .../revive/rpc/examples/js/.prettierrc.json | 6 + .../rpc/examples/js/contracts/Event.sol | 13 + .../rpc/examples/js/contracts/Revert.sol | 11 + .../revive/rpc/examples/js/evm-contracts.json | 56 + .../frame/revive/rpc/examples/js/index.html | 2 +- .../revive/rpc/examples/js/package-lock.json | 443 + .../frame/revive/rpc/examples/js/package.json | 3 +- .../revive/rpc/examples/js/pvm-contracts.json | 56 + .../rpc/examples/js/src/build-contracts.ts | 56 + .../frame/revive/rpc/examples/js/src/event.ts | 15 + .../frame/revive/rpc/examples/js/src/lib.ts | 85 + .../frame/revive/rpc/examples/js/src/main.ts | 141 - .../revive/rpc/examples/js/src/revert.ts | 10 + .../revive/rpc/examples/js/src/script.ts | 49 - .../revive/rpc/examples/js/src/solc.d.ts | 83 + .../frame/revive/rpc/examples/js/src/web.ts | 129 + .../frame/revive/rpc/examples/package.json | 1 + .../frame/revive/rpc/examples/rust/deploy.rs | 20 +- .../revive/rpc/examples/rust/transfer.rs | 19 +- .../frame/revive/rpc/revive_chain.metadata | Bin 655430 -> 656635 bytes substrate/frame/revive/rpc/src/client.rs | 154 +- substrate/frame/revive/rpc/src/example.rs | 168 +- substrate/frame/revive/rpc/src/lib.rs | 19 +- .../frame/revive/rpc/src/subxt_client.rs | 8 +- substrate/frame/revive/rpc/src/tests.rs | 113 +- substrate/frame/revive/src/evm/api/account.rs | 2 +- .../frame/revive/src/evm/api/rpc_types.rs | 8 + substrate/frame/revive/src/evm/runtime.rs | 46 +- substrate/frame/revive/src/lib.rs | 227 +- substrate/frame/revive/src/primitives.rs | 4 +- 40 files changed, 9996 insertions(+), 4582 deletions(-) create mode 100644 prdoc/pr_6393.prdoc create mode 100755 substrate/frame/revive/rpc/examples/bun.lockb create mode 100644 substrate/frame/revive/rpc/examples/js/.prettierrc.json create mode 100644 substrate/frame/revive/rpc/examples/js/contracts/Event.sol create mode 100644 substrate/frame/revive/rpc/examples/js/contracts/Revert.sol create mode 100644 substrate/frame/revive/rpc/examples/js/evm-contracts.json create mode 100644 substrate/frame/revive/rpc/examples/js/package-lock.json create mode 100644 substrate/frame/revive/rpc/examples/js/pvm-contracts.json create mode 100644 substrate/frame/revive/rpc/examples/js/src/build-contracts.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/event.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/lib.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/src/main.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/revert.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/src/script.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/solc.d.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/web.ts create mode 100644 substrate/frame/revive/rpc/examples/package.json diff --git a/Cargo.lock b/Cargo.lock index 1e1c902df0e1..fdaaf2f3b45f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -135,7 +135,7 @@ dependencies = [ "bytes", "cfg-if", "const-hex", - "derive_more", + "derive_more 0.99.17", "hex-literal", "itoa", "proptest", @@ -806,15 +806,15 @@ version = "0.0.0" dependencies = [ "asset-hub-rococo-runtime", "bp-bridge-hub-rococo", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "rococo-emulated-chain", "sp-core 28.0.0", - "sp-keyring", - "staging-xcm", - "testnet-parachains-constants", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", + "testnet-parachains-constants 1.0.0", ] [[package]] @@ -822,112 +822,112 @@ name = "asset-hub-rococo-integration-tests" version = "1.0.0" dependencies = [ "assert_matches", - "asset-test-utils", - "cumulus-pallet-parachain-system", + "asset-test-utils 7.0.0", + "cumulus-pallet-parachain-system 0.7.0", "emulated-integration-tests-common", - "frame-support", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-treasury", - "pallet-utility", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-runtime-common", - "rococo-runtime-constants", + "frame-support 28.0.0", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-treasury 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "rococo-system-emulated-network", "sp-core 28.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "xcm-runtime-apis", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "asset-hub-rococo-runtime" version = "0.11.0" dependencies = [ - "asset-test-utils", - "assets-common", + "asset-test-utils 7.0.0", + "assets-common 0.7.0", "bp-asset-hub-rococo", "bp-asset-hub-westend", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-asset-conversion", - "pallet-asset-conversion-ops", - "pallet-asset-conversion-tx-payment", - "pallet-assets", - "pallet-assets-freezer", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-nft-fractionalization", - "pallet-nfts", - "pallet-nfts-runtime-api", - "pallet-proxy", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-uniques", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub-router", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-asset-conversion 10.0.0", + "pallet-asset-conversion-ops 0.1.0", + "pallet-asset-conversion-tx-payment 10.0.0", + "pallet-assets 29.1.0", + "pallet-assets-freezer 0.1.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-nft-fractionalization 10.0.0", + "pallet-nfts 22.0.0", + "pallet-nfts-runtime-api 14.0.0", + "pallet-proxy 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-uniques 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "pallet-xcm-bridge-hub-router 0.5.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "primitive-types 0.13.1", - "rococo-runtime-constants", + "rococo-runtime-constants 7.0.0", "scale-info", "serde_json", - "snowbridge-router-primitives", + "snowbridge-router-primitives 0.9.0", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-keyring", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", "sp-weights 27.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -936,14 +936,14 @@ version = "0.0.0" dependencies = [ "asset-hub-westend-runtime", "bp-bridge-hub-westend", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "sp-keyring", - "staging-xcm", - "testnet-parachains-constants", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", + "testnet-parachains-constants 1.0.0", "westend-emulated-chain", ] @@ -952,169 +952,223 @@ name = "asset-hub-westend-integration-tests" version = "1.0.0" dependencies = [ "assert_matches", - "asset-test-utils", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", + "asset-test-utils 7.0.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", "emulated-integration-tests-common", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "pallet-asset-conversion", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-transaction-payment", - "pallet-treasury", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-runtime-common", - "sp-core 28.0.0", - "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-asset-conversion 10.0.0", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-treasury 27.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-runtime-common 7.0.0", + "sp-core 28.0.0", + "sp-runtime 31.0.1", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "westend-system-emulated-network", - "xcm-runtime-apis", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "asset-hub-westend-runtime" version = "0.15.0" dependencies = [ - "asset-test-utils", - "assets-common", + "asset-test-utils 7.0.0", + "assets-common 0.7.0", "bp-asset-hub-rococo", "bp-asset-hub-westend", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-asset-conversion", - "pallet-asset-conversion-ops", - "pallet-asset-conversion-tx-payment", - "pallet-assets", - "pallet-assets-freezer", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-nft-fractionalization", - "pallet-nfts", - "pallet-nfts-runtime-api", - "pallet-proxy", - "pallet-revive", - "pallet-session", - "pallet-state-trie-migration", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-uniques", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub-router", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-asset-conversion 10.0.0", + "pallet-asset-conversion-ops 0.1.0", + "pallet-asset-conversion-tx-payment 10.0.0", + "pallet-assets 29.1.0", + "pallet-assets-freezer 0.1.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-nft-fractionalization 10.0.0", + "pallet-nfts 22.0.0", + "pallet-nfts-runtime-api 14.0.0", + "pallet-proxy 28.0.0", + "pallet-revive 0.1.0", + "pallet-session 28.0.0", + "pallet-state-trie-migration 29.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-uniques 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "pallet-xcm-bridge-hub-router 0.5.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "primitive-types 0.13.1", "scale-info", "serde_json", - "snowbridge-router-primitives", + "snowbridge-router-primitives 0.9.0", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-keyring", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-std 14.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "westend-runtime-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "asset-test-utils" version = "7.0.0" dependencies = [ - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "frame-support", - "frame-system", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex-literal", - "pallet-assets", - "pallet-balances", - "pallet-collator-selection", - "pallet-session", - "pallet-timestamp", - "pallet-xcm", - "pallet-xcm-bridge-hub-router", - "parachains-common", - "parachains-runtimes-test-utils", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-bridge-hub-router 0.5.0", + "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "sp-io 30.0.0", "sp-runtime 31.0.1", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", +] + +[[package]] +name = "asset-test-utils" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0324df9ce91a9840632e865dd3272bd20162023856f1b189b7ae58afa5c6b61" +dependencies = [ + "cumulus-pallet-parachain-system 0.17.1", + "cumulus-pallet-xcmp-queue 0.17.0", + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-assets 40.0.0", + "pallet-balances 39.0.0", + "pallet-collator-selection 19.0.0", + "pallet-session 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-xcm 17.0.0", + "pallet-xcm-bridge-hub-router 0.15.1", + "parachains-common 18.0.0", + "parachains-runtimes-test-utils 17.0.0", + "parity-scale-codec", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-parachain-info 0.17.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "substrate-wasm-builder 24.0.1", ] [[package]] name = "assets-common" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", "impl-trait-for-tuples", "log", - "pallet-asset-conversion", - "pallet-assets", - "pallet-xcm", - "parachains-common", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", +] + +[[package]] +name = "assets-common" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4556e56f9206b129c3f96249cd907b76e8d7ad5265fe368c228c708789a451a3" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-asset-conversion 20.0.0", + "pallet-assets 40.0.0", + "pallet-xcm 17.0.0", + "parachains-common 18.0.0", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "substrate-wasm-builder 24.0.1", ] [[package]] @@ -1145,7 +1199,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f2776ead772134d55b62dd45e59a79e21612d85d0af729b8b7d3967d601a62a" dependencies = [ "concurrent-queue", - "event-listener 5.2.0", + "event-listener 5.3.1", "event-listener-strategy", "futures-core", "pin-project-lite", @@ -1257,7 +1311,7 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ - "event-listener 5.2.0", + "event-listener 5.3.1", "event-listener-strategy", "pin-project-lite", ] @@ -1316,7 +1370,7 @@ dependencies = [ "async-task", "blocking", "cfg-if", - "event-listener 5.2.0", + "event-listener 5.3.1", "futures-lite 2.3.0", "rustix 0.38.25", "tracing", @@ -1397,9 +1451,9 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.82" +version = "0.1.83" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" +checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -1569,15 +1623,6 @@ dependencies = [ "serde", ] -[[package]] -name = "beef" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1" -dependencies = [ - "serde", -] - [[package]] name = "binary-merkle-tree" version = "13.0.0" @@ -1591,6 +1636,16 @@ dependencies = [ "sp-tracing 16.0.0", ] +[[package]] +name = "binary-merkle-tree" +version = "15.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "336bf780dd7526a9a4bc1521720b25c1994dc132cccd59553431923fa4d1a693" +dependencies = [ + "hash-db", + "log", +] + [[package]] name = "bincode" version = "1.3.3" @@ -1639,11 +1694,11 @@ dependencies = [ [[package]] name = "bip39" -version = "2.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93f2635620bf0b9d4576eb7bb9a38a55df78bd1205d26fa994b25911a69f212f" +checksum = "33415e24172c1b7d6066f6d999545375ab8e1d95421d6784bdfff9496f292387" dependencies = [ - "bitcoin_hashes 0.11.0", + "bitcoin_hashes 0.13.0", "serde", "unicode-normalization", ] @@ -1670,10 +1725,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9425c3bf7089c983facbae04de54513cce73b41c7f9ff8c845b54e7bc64ebbfb" [[package]] -name = "bitcoin_hashes" -version = "0.11.0" +name = "bitcoin-io" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90064b8dee6815a6470d60bad07bbbaee885c0e12d04177138fa3291a01b7bc4" +checksum = "0b47c4ab7a93edb0c7198c5535ed9b52b63095f4e9b45279c6736cec4b856baf" [[package]] name = "bitcoin_hashes" @@ -1682,7 +1737,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1930a4dabfebb8d7d9992db18ebe3ae2876f0a305fab206fd168df931ede293b" dependencies = [ "bitcoin-internals", - "hex-conservative", + "hex-conservative 0.1.1", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16" +dependencies = [ + "bitcoin-io", + "hex-conservative 0.2.1", ] [[package]] @@ -1864,8 +1929,8 @@ dependencies = [ name = "bp-asset-hub-rococo" version = "0.4.0" dependencies = [ - "bp-xcm-bridge-hub-router", - "frame-support", + "bp-xcm-bridge-hub-router 0.6.0", + "frame-support 28.0.0", "parity-scale-codec", "scale-info", ] @@ -1874,8 +1939,8 @@ dependencies = [ name = "bp-asset-hub-westend" version = "0.3.0" dependencies = [ - "bp-xcm-bridge-hub-router", - "frame-support", + "bp-xcm-bridge-hub-router 0.6.0", + "frame-support 28.0.0", "parity-scale-codec", "scale-info", ] @@ -1884,15 +1949,15 @@ dependencies = [ name = "bp-beefy" version = "0.1.0" dependencies = [ - "binary-merkle-tree", - "bp-runtime", - "frame-support", - "pallet-beefy-mmr", - "pallet-mmr", + "binary-merkle-tree 13.0.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", + "pallet-beefy-mmr 28.0.0", + "pallet-mmr 27.0.0", "parity-scale-codec", "scale-info", "serde", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", ] @@ -1901,12 +1966,12 @@ dependencies = [ name = "bp-bridge-hub-cumulus" version = "0.7.0" dependencies = [ - "bp-messages", - "bp-polkadot-core", - "bp-runtime", - "frame-support", - "frame-system", - "polkadot-primitives", + "bp-messages 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "polkadot-primitives 7.0.0", "sp-api 26.0.0", "sp-std 14.0.0", ] @@ -1916,9 +1981,9 @@ name = "bp-bridge-hub-kusama" version = "0.6.0" dependencies = [ "bp-bridge-hub-cumulus", - "bp-messages", - "bp-runtime", - "frame-support", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", @@ -1929,9 +1994,9 @@ name = "bp-bridge-hub-polkadot" version = "0.6.0" dependencies = [ "bp-bridge-hub-cumulus", - "bp-messages", - "bp-runtime", - "frame-support", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", @@ -1942,10 +2007,10 @@ name = "bp-bridge-hub-rococo" version = "0.7.0" dependencies = [ "bp-bridge-hub-cumulus", - "bp-messages", - "bp-runtime", - "bp-xcm-bridge-hub", - "frame-support", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "frame-support 28.0.0", "parity-scale-codec", "sp-api 26.0.0", "sp-runtime 31.0.1", @@ -1957,10 +2022,10 @@ name = "bp-bridge-hub-westend" version = "0.3.0" dependencies = [ "bp-bridge-hub-cumulus", - "bp-messages", - "bp-runtime", - "bp-xcm-bridge-hub", - "frame-support", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "frame-support 28.0.0", "parity-scale-codec", "sp-api 26.0.0", "sp-runtime 31.0.1", @@ -1971,29 +2036,47 @@ dependencies = [ name = "bp-header-chain" version = "0.7.0" dependencies = [ - "bp-runtime", - "bp-test-utils", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", "finality-grandpa", - "frame-support", + "frame-support 28.0.0", "hex", "hex-literal", "parity-scale-codec", "scale-info", "serde", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", ] +[[package]] +name = "bp-header-chain" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "890df97cea17ee61ff982466bb9e90cb6b1462adb45380999019388d05e4b92d" +dependencies = [ + "bp-runtime 0.18.0", + "finality-grandpa", + "frame-support 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-consensus-grandpa 21.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-kusama" version = "0.5.0" dependencies = [ - "bp-header-chain", - "bp-polkadot-core", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-std 14.0.0", ] @@ -2002,9 +2085,9 @@ dependencies = [ name = "bp-messages" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "hex", "hex-literal", "parity-scale-codec", @@ -2015,14 +2098,31 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "bp-messages" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7efabf94339950b914ba87249497f1a0e35a73849934d164fecae4b275928cf6" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-parachains" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-polkadot-core", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", @@ -2031,28 +2131,60 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "bp-parachains" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9011e5c12c15caf3c4129a98f4f4916ea9165db8daf6ed85867c3106075f40df" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-polkadot-core 0.18.0", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-polkadot" version = "0.5.0" dependencies = [ - "bp-header-chain", - "bp-polkadot-core", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-std 14.0.0", ] +[[package]] +name = "bp-polkadot" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa6277dd4333917ecfbcc35e9332a9f11682e0a506e76b617c336224660fce33" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-polkadot-core 0.18.0", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "sp-api 34.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-polkadot-bulletin" version = "0.4.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-polkadot-core", - "bp-runtime", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", @@ -2064,10 +2196,10 @@ dependencies = [ name = "bp-polkadot-core" version = "0.7.0" dependencies = [ - "bp-messages", - "bp-runtime", - "frame-support", - "frame-system", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex", "parity-scale-codec", "scale-info", @@ -2077,33 +2209,71 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "bp-polkadot-core" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "345cf472bac11ef79d403e4846a666b7d22a13cd16d9c85b62cd6b5e16c4a042" +dependencies = [ + "bp-messages 0.18.0", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "parity-util-mem", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-relayers" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-runtime", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex", "hex-literal", - "pallet-utility", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "sp-runtime 31.0.1", "sp-std 14.0.0", ] +[[package]] +name = "bp-relayers" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9465ad727e466d67d64244a1aa7bb19933a297913fdde34b8e9bda0a341bdeb" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-parachains 0.18.0", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-utility 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "bp-rococo" version = "0.6.0" dependencies = [ - "bp-header-chain", - "bp-polkadot-core", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-std 14.0.0", ] @@ -2112,8 +2282,8 @@ dependencies = [ name = "bp-runtime" version = "0.7.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "hash-db", "hex-literal", "impl-trait-for-tuples", @@ -2128,36 +2298,81 @@ dependencies = [ "sp-state-machine 0.35.0", "sp-std 14.0.0", "sp-trie 29.0.0", - "trie-db 0.29.1", + "trie-db", +] + +[[package]] +name = "bp-runtime" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "746d9464f912b278f8a5e2400f10541f95da7fc6c7d688a2788b9a46296146ee" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "hash-db", + "impl-trait-for-tuples", + "log", + "num-traits", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-state-machine 0.43.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-trie 37.0.0", + "trie-db", ] [[package]] name = "bp-test-utils" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-parachains", - "bp-polkadot-core", - "bp-runtime", + "bp-header-chain 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", "ed25519-dalek", "finality-grandpa", "parity-scale-codec", "sp-application-crypto 30.0.0", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", "sp-trie 29.0.0", ] +[[package]] +name = "bp-test-utils" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e659078b54c0b6bd79896738212a305842ad37168976363233516754337826" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-parachains 0.18.0", + "bp-polkadot-core 0.18.0", + "bp-runtime 0.18.0", + "ed25519-dalek", + "finality-grandpa", + "parity-scale-codec", + "sp-application-crypto 38.0.0", + "sp-consensus-grandpa 21.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-trie 37.0.0", +] + [[package]] name = "bp-westend" version = "0.3.0" dependencies = [ - "bp-header-chain", - "bp-polkadot-core", - "bp-runtime", - "frame-support", + "bp-header-chain 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "sp-api 26.0.0", "sp-std 14.0.0", ] @@ -2166,16 +2381,34 @@ dependencies = [ name = "bp-xcm-bridge-hub" version = "0.2.0" dependencies = [ - "bp-messages", - "bp-runtime", - "frame-support", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "frame-support 28.0.0", "parity-scale-codec", "scale-info", "serde", "sp-core 28.0.0", "sp-io 30.0.0", "sp-std 14.0.0", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "bp-xcm-bridge-hub" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6909117ca87cb93703742939d5f0c4c93e9646d9cda22262e9709d68c929999b" +dependencies = [ + "bp-messages 0.18.0", + "bp-runtime 0.18.0", + "frame-support 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", ] [[package]] @@ -2186,72 +2419,103 @@ dependencies = [ "scale-info", "sp-core 28.0.0", "sp-runtime 31.0.1", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "bp-xcm-bridge-hub-router" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9284820ca704f5c065563cad77d2e3d069a23cc9cb3a29db9c0de8dd3b173a87" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", ] [[package]] name = "bridge-hub-common" version = "0.1.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", - "pallet-message-queue", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "pallet-message-queue 31.0.0", "parity-scale-codec", "scale-info", - "snowbridge-core", + "snowbridge-core 0.2.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "bridge-hub-common" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b53c53d627e2da38f8910807944bf3121e154b5c0ac9e122995af9dfb13ed" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "pallet-message-queue 41.0.1", + "parity-scale-codec", + "scale-info", + "snowbridge-core 0.10.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", ] [[package]] name = "bridge-hub-rococo-emulated-chain" version = "0.0.0" dependencies = [ - "bp-messages", - "bridge-hub-common", + "bp-messages 0.7.0", + "bridge-hub-common 0.1.0", "bridge-hub-rococo-runtime", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "sp-keyring", - "staging-xcm", - "testnet-parachains-constants", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "bridge-hub-rococo-integration-tests" version = "1.0.0" dependencies = [ - "cumulus-pallet-xcmp-queue", + "cumulus-pallet-xcmp-queue 0.7.0", "emulated-integration-tests-common", - "frame-support", + "frame-support 28.0.0", "hex-literal", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", - "pallet-bridge-messages", - "pallet-message-queue", - "pallet-xcm", - "pallet-xcm-bridge-hub", - "parachains-common", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-bridge-messages 0.7.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", "parity-scale-codec", "rococo-system-emulated-network", "rococo-westend-system-emulated-network", "scale-info", - "snowbridge-core", - "snowbridge-pallet-inbound-queue-fixtures", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", - "snowbridge-router-primitives", + "snowbridge-core 0.2.0", + "snowbridge-pallet-inbound-queue-fixtures 0.10.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", + "snowbridge-router-primitives 0.9.0", "sp-core 28.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -2263,154 +2527,198 @@ dependencies = [ "bp-bridge-hub-polkadot", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", - "bp-header-chain", - "bp-messages", - "bp-parachains", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", "bp-polkadot-bulletin", - "bp-polkadot-core", - "bp-relayers", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", "bp-rococo", - "bp-runtime", + "bp-runtime 0.7.0", "bp-westend", - "bridge-hub-common", - "bridge-hub-test-utils", - "bridge-runtime-common", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "bridge-hub-common 0.1.0", + "bridge-hub-test-utils 0.7.0", + "bridge-runtime-common 0.7.0", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-bridge-relayers", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", - "rococo-runtime-constants", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-bridge-relayers 0.7.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "scale-info", "serde", "serde_json", - "snowbridge-beacon-primitives", - "snowbridge-core", - "snowbridge-outbound-queue-runtime-api", - "snowbridge-pallet-ethereum-client", - "snowbridge-pallet-inbound-queue", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", - "snowbridge-router-primitives", - "snowbridge-runtime-common", - "snowbridge-runtime-test-common", - "snowbridge-system-runtime-api", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", + "snowbridge-outbound-queue-runtime-api 0.2.0", + "snowbridge-pallet-ethereum-client 0.2.0", + "snowbridge-pallet-inbound-queue 0.2.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", + "snowbridge-router-primitives 0.9.0", + "snowbridge-runtime-common 0.2.0", + "snowbridge-runtime-test-common 0.2.0", + "snowbridge-system-runtime-api 0.2.0", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-std 14.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "bridge-hub-test-utils" version = "0.7.0" dependencies = [ - "asset-test-utils", - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot-core", - "bp-relayers", - "bp-runtime", - "bp-test-utils", - "bp-xcm-bridge-hub", - "bridge-runtime-common", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "frame-support", - "frame-system", + "asset-test-utils 7.0.0", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "bridge-runtime-common 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-bridge-relayers", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-bridge-hub", - "parachains-common", - "parachains-runtimes-test-utils", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-bridge-relayers 0.7.0", + "pallet-timestamp 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "bridge-hub-test-utils" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de0b3aa5fd8481a06ca16e47fd3d2d9c6abe76b27d922ec8980a853f242173b3" +dependencies = [ + "asset-test-utils 18.0.0", + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-parachains 0.18.0", + "bp-polkadot-core 0.18.0", + "bp-relayers 0.18.0", + "bp-runtime 0.18.0", + "bp-test-utils 0.18.0", + "bp-xcm-bridge-hub 0.4.0", + "bridge-runtime-common 0.18.0", + "cumulus-pallet-parachain-system 0.17.1", + "cumulus-pallet-xcmp-queue 0.17.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-balances 39.0.0", + "pallet-bridge-grandpa 0.18.0", + "pallet-bridge-messages 0.18.0", + "pallet-bridge-parachains 0.18.0", + "pallet-bridge-relayers 0.18.0", + "pallet-timestamp 37.0.0", + "pallet-utility 38.0.0", + "pallet-xcm 17.0.0", + "pallet-xcm-bridge-hub 0.13.0", + "parachains-common 18.0.0", + "parachains-runtimes-test-utils 17.0.0", + "parity-scale-codec", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-keyring 39.0.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "bridge-hub-westend-emulated-chain" version = "0.0.0" dependencies = [ - "bp-messages", - "bridge-hub-common", + "bp-messages 0.7.0", + "bridge-hub-common 0.1.0", "bridge-hub-westend-runtime", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "sp-keyring", - "staging-xcm", - "testnet-parachains-constants", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", + "testnet-parachains-constants 1.0.0", ] [[package]] @@ -2419,34 +2727,34 @@ version = "1.0.0" dependencies = [ "asset-hub-westend-runtime", "bridge-hub-westend-runtime", - "cumulus-pallet-xcmp-queue", + "cumulus-pallet-xcmp-queue 0.7.0", "emulated-integration-tests-common", - "frame-support", + "frame-support 28.0.0", "hex-literal", "log", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", - "pallet-bridge-messages", - "pallet-message-queue", - "pallet-xcm", - "pallet-xcm-bridge-hub", - "parachains-common", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-bridge-messages 0.7.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", "parity-scale-codec", "rococo-westend-system-emulated-network", "scale-info", - "snowbridge-core", - "snowbridge-pallet-inbound-queue", - "snowbridge-pallet-inbound-queue-fixtures", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", - "snowbridge-router-primitives", + "snowbridge-core 0.2.0", + "snowbridge-pallet-inbound-queue 0.2.0", + "snowbridge-pallet-inbound-queue-fixtures 0.10.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", + "snowbridge-router-primitives 0.9.0", "sp-core 28.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -2457,119 +2765,119 @@ dependencies = [ "bp-asset-hub-westend", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot-core", - "bp-relayers", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", "bp-rococo", - "bp-runtime", + "bp-runtime 0.7.0", "bp-westend", - "bridge-hub-common", - "bridge-hub-test-utils", - "bridge-runtime-common", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "bridge-hub-common 0.1.0", + "bridge-hub-test-utils 0.7.0", + "bridge-runtime-common 0.7.0", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-bridge-relayers", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-bridge-relayers 0.7.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "serde", "serde_json", - "snowbridge-beacon-primitives", - "snowbridge-core", - "snowbridge-outbound-queue-runtime-api", - "snowbridge-pallet-ethereum-client", - "snowbridge-pallet-inbound-queue", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", - "snowbridge-router-primitives", - "snowbridge-runtime-common", - "snowbridge-runtime-test-common", - "snowbridge-system-runtime-api", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", + "snowbridge-outbound-queue-runtime-api 0.2.0", + "snowbridge-pallet-ethereum-client 0.2.0", + "snowbridge-pallet-inbound-queue 0.2.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", + "snowbridge-router-primitives 0.9.0", + "snowbridge-runtime-common 0.2.0", + "snowbridge-runtime-test-common 0.2.0", + "snowbridge-system-runtime-api 0.2.0", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-std 14.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "westend-runtime-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "bridge-runtime-common" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot-core", - "bp-relayers", - "bp-runtime", - "bp-test-utils", - "bp-xcm-bridge-hub", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-bridge-relayers", - "pallet-transaction-payment", - "pallet-utility", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-bridge-relayers 0.7.0", + "pallet-transaction-payment 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -2578,11 +2886,43 @@ dependencies = [ "sp-std 14.0.0", "sp-trie 29.0.0", "sp-weights 27.0.0", - "staging-xcm", + "staging-xcm 7.0.0", "static_assertions", "tuplex", ] +[[package]] +name = "bridge-runtime-common" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c639aa22de6e904156a3e8b0e6b9e6af790cb27a1299688cc07997e1ffe5b648" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-parachains 0.18.0", + "bp-polkadot-core 0.18.0", + "bp-relayers 0.18.0", + "bp-runtime 0.18.0", + "bp-xcm-bridge-hub 0.4.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-bridge-grandpa 0.18.0", + "pallet-bridge-messages 0.18.0", + "pallet-bridge-parachains 0.18.0", + "pallet-bridge-relayers 0.18.0", + "pallet-transaction-payment 38.0.0", + "pallet-utility 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-trie 37.0.0", + "staging-xcm 14.2.0", + "tuplex", +] + [[package]] name = "bs58" version = "0.5.1" @@ -2780,12 +3120,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - [[package]] name = "chacha" version = "0.3.0" @@ -2825,25 +3159,25 @@ name = "chain-spec-guide-runtime" version = "0.0.0" dependencies = [ "docify", - "frame-support", - "pallet-balances", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "parity-scale-codec", - "polkadot-sdk-frame", + "frame-support 28.0.0", + "pallet-balances 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "parity-scale-codec", + "polkadot-sdk-frame 0.1.0", "sc-chain-spec", "scale-info", "serde", "serde_json", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-keyring", + "sp-genesis-builder 0.8.0", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "staging-chain-spec-builder", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -3131,12 +3465,12 @@ name = "collectives-westend-emulated-chain" version = "0.0.0" dependencies = [ "collectives-westend-runtime", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "testnet-parachains-constants", + "testnet-parachains-constants 1.0.0", ] [[package]] @@ -3144,26 +3478,26 @@ name = "collectives-westend-integration-tests" version = "1.0.0" dependencies = [ "assert_matches", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", "emulated-integration-tests-common", - "frame-support", - "pallet-asset-rate", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-treasury", - "pallet-utility", - "pallet-whitelist", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-runtime-common", - "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "testnet-parachains-constants", - "westend-runtime-constants", + "frame-support 28.0.0", + "pallet-asset-rate 7.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-treasury 27.0.0", + "pallet-utility 28.0.0", + "pallet-whitelist 27.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-runtime-common 7.0.0", + "sp-runtime 31.0.1", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", "westend-system-emulated-network", ] @@ -3171,79 +3505,79 @@ dependencies = [ name = "collectives-westend-runtime" version = "3.0.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-alliance", - "pallet-asset-rate", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-collective", - "pallet-collective-content", - "pallet-core-fellowship", - "pallet-message-queue", - "pallet-multisig", - "pallet-preimage", - "pallet-proxy", - "pallet-ranked-collective", - "pallet-referenda", - "pallet-salary", - "pallet-scheduler", - "pallet-session", - "pallet-state-trie-migration", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury", - "pallet-utility", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-alliance 27.0.0", + "pallet-asset-rate 7.0.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-collective 28.0.0", + "pallet-collective-content 0.6.0", + "pallet-core-fellowship 12.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-preimage 28.0.0", + "pallet-proxy 28.0.0", + "pallet-ranked-collective 28.0.0", + "pallet-referenda 28.0.0", + "pallet-salary 13.0.0", + "pallet-scheduler 29.0.0", + "pallet-session 28.0.0", + "pallet-state-trie-migration 29.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-treasury 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "serde_json", "sp-api 26.0.0", "sp-arithmetic 23.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-std 14.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "westend-runtime-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -3378,9 +3712,9 @@ dependencies = [ [[package]] name = "concurrent-queue" -version = "2.2.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" dependencies = [ "crossbeam-utils", ] @@ -3477,64 +3811,64 @@ checksum = "f272d0c4cf831b4fa80ee529c7707f76585986e910e1fbce1d7921970bc1a241" name = "contracts-rococo-runtime" version = "0.8.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-contracts", - "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", - "pallet-multisig", - "pallet-session", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", - "rococo-runtime-constants", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-contracts 27.0.0", + "pallet-insecure-randomness-collective-flip 16.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-session 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "scale-info", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -3588,99 +3922,99 @@ name = "coretime-rococo-emulated-chain" version = "0.1.0" dependencies = [ "coretime-rococo-runtime", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "testnet-parachains-constants", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "coretime-rococo-integration-tests" version = "0.0.0" dependencies = [ - "cumulus-pallet-parachain-system", + "cumulus-pallet-parachain-system 0.7.0", "emulated-integration-tests-common", - "frame-support", - "pallet-balances", - "pallet-broker", - "pallet-identity", - "pallet-message-queue", - "polkadot-runtime-common", - "polkadot-runtime-parachains", - "rococo-runtime-constants", + "frame-support 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", + "rococo-runtime-constants 7.0.0", "rococo-system-emulated-network", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", ] [[package]] name = "coretime-rococo-runtime" version = "0.1.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-broker", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-proxy", - "pallet-session", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", - "rococo-runtime-constants", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-proxy 28.0.0", + "pallet-session 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "scale-info", "serde", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -3688,31 +4022,31 @@ name = "coretime-westend-emulated-chain" version = "0.1.0" dependencies = [ "coretime-westend-runtime", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "sp-core 28.0.0", - "testnet-parachains-constants", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "coretime-westend-integration-tests" version = "0.0.0" dependencies = [ - "cumulus-pallet-parachain-system", + "cumulus-pallet-parachain-system 0.7.0", "emulated-integration-tests-common", - "frame-support", - "pallet-balances", - "pallet-broker", - "pallet-identity", - "pallet-message-queue", - "polkadot-runtime-common", - "polkadot-runtime-parachains", - "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "westend-runtime-constants", + "frame-support 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", + "sp-runtime 31.0.1", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "westend-runtime-constants 7.0.0", "westend-system-emulated-network", ] @@ -3720,66 +4054,66 @@ dependencies = [ name = "coretime-westend-runtime" version = "0.1.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-broker", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-multisig", - "pallet-proxy", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-multisig 28.0.0", + "pallet-proxy 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "serde", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "westend-runtime-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -3990,22 +4324,18 @@ dependencies = [ [[package]] name = "crossbeam-queue" -version = "0.3.8" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1cfb3ea8a53f37c40dea2c7bedcbd88bdfae54f5e2175d6ecaff1c988353add" +checksum = "df0346b5d5e76ac2fe4e327c5fd1118d6be7c51dfb18f9b7922923f287471e35" dependencies = [ - "cfg-if", "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.16" +version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294" -dependencies = [ - "cfg-if", -] +checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" [[package]] name = "crunchy" @@ -4056,6 +4386,21 @@ dependencies = [ "subtle 2.5.0", ] +[[package]] +name = "crypto_secretbox" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1" +dependencies = [ + "aead", + "cipher 0.4.4", + "generic-array 0.14.7", + "poly1305", + "salsa20", + "subtle 2.5.0", + "zeroize", +] + [[package]] name = "ctr" version = "0.9.2" @@ -4088,9 +4433,9 @@ dependencies = [ "async-trait", "cumulus-client-consensus-common", "cumulus-client-network", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-test-client", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "cumulus-test-runtime", "futures", "parity-scale-codec", @@ -4099,7 +4444,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sp-api 26.0.0", "sp-consensus", @@ -4120,8 +4465,8 @@ dependencies = [ "cumulus-client-consensus-common", "cumulus-client-consensus-proposer", "cumulus-client-parachain-inherent", - "cumulus-primitives-aura", - "cumulus-primitives-core", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "futures", "parity-scale-codec", @@ -4130,7 +4475,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sc-consensus", "sc-consensus-aura", @@ -4141,16 +4486,16 @@ dependencies = [ "schnellru", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "substrate-prometheus-endpoint", "tokio", "tracing", @@ -4162,26 +4507,26 @@ version = "0.7.0" dependencies = [ "async-trait", "cumulus-client-pov-recovery", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "cumulus-test-client", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "dyn-clone", "futures", "futures-timer", "log", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sc-consensus", "sc-consensus-babe", "schnellru", "sp-blockchain", "sp-consensus", - "sp-consensus-slots", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", @@ -4195,9 +4540,9 @@ version = "0.7.0" dependencies = [ "anyhow", "async-trait", - "cumulus-primitives-parachain-inherent", + "cumulus-primitives-parachain-inherent 0.7.0", "sp-consensus", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "thiserror", @@ -4209,17 +4554,17 @@ version = "0.7.0" dependencies = [ "async-trait", "cumulus-client-consensus-common", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "futures", "parking_lot 0.12.3", "sc-consensus", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "substrate-prometheus-endpoint", "tracing", @@ -4230,7 +4575,7 @@ name = "cumulus-client-network" version = "0.7.0" dependencies = [ "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-test-service", @@ -4240,8 +4585,8 @@ dependencies = [ "parking_lot 0.12.3", "polkadot-node-primitives", "polkadot-node-subsystem", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-test-client", "portpicker", "rstest", @@ -4251,7 +4596,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", @@ -4267,15 +4612,15 @@ name = "cumulus-client-parachain-inherent" version = "0.1.0" dependencies = [ "async-trait", - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", "cumulus-relay-chain-interface", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "parity-scale-codec", "sc-client-api", "sp-api 26.0.0", "sp-crypto-hashing 0.1.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-storage 19.0.0", @@ -4289,7 +4634,7 @@ version = "0.7.0" dependencies = [ "assert_matches", "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "cumulus-test-client", "cumulus-test-service", @@ -4299,7 +4644,7 @@ dependencies = [ "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "portpicker", "rand", "rstest", @@ -4328,13 +4673,13 @@ dependencies = [ "cumulus-client-consensus-common", "cumulus-client-network", "cumulus-client-pov-recovery", - "cumulus-primitives-core", - "cumulus-primitives-proof-size-hostfunction", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", "futures", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sc-consensus", "sc-network", @@ -4352,33 +4697,51 @@ dependencies = [ "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", ] [[package]] name = "cumulus-pallet-aura-ext" version = "0.7.0" dependencies = [ - "cumulus-pallet-parachain-system", - "frame-support", - "frame-system", - "pallet-aura", - "pallet-timestamp", + "cumulus-pallet-parachain-system 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-aura 27.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-runtime 31.0.1", ] +[[package]] +name = "cumulus-pallet-aura-ext" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cbe2735fc7cf2b6521eab00cb1a1ab025abc1575cc36887b36dc8c5cb1c9434" +dependencies = [ + "cumulus-pallet-parachain-system 0.17.1", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-aura 37.0.0", + "pallet-timestamp 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-consensus-aura 0.40.0", + "sp-runtime 39.0.2", +] + [[package]] name = "cumulus-pallet-dmp-queue" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "frame-benchmarking", - "frame-support", - "frame-system", + "cumulus-primitives-core 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -4386,7 +4749,25 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "cumulus-pallet-dmp-queue" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97263a8e758d201ebe81db7cea7b278b4fb869c11442f77acef70138ac1a252f" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", ] [[package]] @@ -4395,51 +4776,100 @@ version = "0.7.0" dependencies = [ "assert_matches", "bytes", - "cumulus-pallet-parachain-system-proc-macro", - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", + "cumulus-pallet-parachain-system-proc-macro 0.6.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", "cumulus-test-client", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "cumulus-test-runtime", "environmental", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "futures", "hex-literal", "impl-trait-for-tuples", "log", - "pallet-message-queue", + "pallet-message-queue 31.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", - "polkadot-runtime-parachains", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", "rand", "sc-client-api", "scale-info", - "sp-consensus-slots", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", "sp-externalities 0.25.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", - "staging-xcm", - "staging-xcm-builder", - "trie-db 0.29.1", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "trie-db", "trie-standardmap", ] +[[package]] +name = "cumulus-pallet-parachain-system" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "546403ee1185f4051a74cc9c9d76e82c63cac3fb68e1bf29f61efb5604c96488" +dependencies = [ + "bytes", + "cumulus-pallet-parachain-system-proc-macro 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cumulus-primitives-core 0.16.0", + "cumulus-primitives-parachain-inherent 0.16.0", + "cumulus-primitives-proof-size-hostfunction 0.10.0", + "environmental", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-message-queue 41.0.1", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "polkadot-runtime-common 17.0.0", + "polkadot-runtime-parachains 17.0.1", + "scale-info", + "sp-core 34.0.0", + "sp-externalities 0.29.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-state-machine 0.43.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-trie 37.0.0", + "sp-version 37.0.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "trie-db", +] + +[[package]] +name = "cumulus-pallet-parachain-system-proc-macro" +version = "0.6.0" +dependencies = [ + "proc-macro-crate 3.1.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "cumulus-pallet-parachain-system-proc-macro" version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "befbaf3a1ce23ac8476481484fef5f4d500cbd15b4dad6380ce1d28134b0c1f7" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", @@ -4451,40 +4881,86 @@ dependencies = [ name = "cumulus-pallet-session-benchmarking" version = "9.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-session", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-session 28.0.0", "parity-scale-codec", "sp-runtime 31.0.1", ] [[package]] -name = "cumulus-pallet-solo-to-para" -version = "0.7.0" +name = "cumulus-pallet-session-benchmarking" +version = "19.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18168570689417abfb514ac8812fca7e6429764d01942750e395d7d8ce0716ef" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "sp-runtime 39.0.2", +] + +[[package]] +name = "cumulus-pallet-solo-to-para" +version = "0.7.0" dependencies = [ - "cumulus-pallet-parachain-system", - "frame-support", - "frame-system", - "pallet-sudo", + "cumulus-pallet-parachain-system 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-sudo 28.0.0", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "scale-info", "sp-runtime 31.0.1", ] +[[package]] +name = "cumulus-pallet-solo-to-para" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42c74548c8cab75da6f2479a953f044b582cfce98479862344a24df7bbd215" +dependencies = [ + "cumulus-pallet-parachain-system 0.17.1", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-sudo 38.0.0", + "parity-scale-codec", + "polkadot-primitives 16.0.0", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "cumulus-pallet-xcm" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", - "frame-system", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-io 30.0.0", "sp-runtime 31.0.1", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "cumulus-pallet-xcm" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49231f6cd8274438b078305dc8ce44c54c0d3f4a28e902589bcbaa53d954608" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", ] [[package]] @@ -4492,39 +4968,81 @@ name = "cumulus-pallet-xcmp-queue" version = "0.7.0" dependencies = [ "bounded-collections", - "bp-xcm-bridge-hub-router", - "cumulus-pallet-parachain-system", - "cumulus-primitives-core", - "frame-benchmarking", - "frame-support", - "frame-system", + "bp-xcm-bridge-hub-router 0.6.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-primitives-core 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-message-queue", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", "parity-scale-codec", - "polkadot-runtime-common", - "polkadot-runtime-parachains", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "cumulus-pallet-xcmp-queue" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f788bdac9474795ea13ba791b55798fb664b2e3da8c3a7385b480c9af4e6539" +dependencies = [ + "bounded-collections", + "bp-xcm-bridge-hub-router 0.14.1", + "cumulus-primitives-core 0.16.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-message-queue 41.0.1", + "parity-scale-codec", + "polkadot-runtime-common 17.0.0", + "polkadot-runtime-parachains 17.0.1", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "cumulus-ping" version = "0.7.0" dependencies = [ - "cumulus-pallet-xcm", - "cumulus-primitives-core", - "frame-support", - "frame-system", + "cumulus-pallet-xcm 0.7.0", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-runtime 31.0.1", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "cumulus-ping" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f47128f797359951723e2d106a80e592d007bb7446c299958cdbafb1489ddbf0" +dependencies = [ + "cumulus-pallet-xcm 0.17.0", + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", ] [[package]] @@ -4535,8 +5053,8 @@ dependencies = [ "clap 4.5.13", "parity-scale-codec", "polkadot-node-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "sc-executor 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", @@ -4550,7 +5068,21 @@ name = "cumulus-primitives-aura" version = "0.7.0" dependencies = [ "sp-api 26.0.0", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", +] + +[[package]] +name = "cumulus-primitives-aura" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11e7825bcf3cc6c962a5b9b9f47e02dc381109e521d0bc00cad785c65da18471" +dependencies = [ + "parity-scale-codec", + "polkadot-core-primitives 15.0.0", + "polkadot-primitives 15.0.0", + "sp-api 34.0.0", + "sp-consensus-aura 0.40.0", + "sp-runtime 39.0.2", ] [[package]] @@ -4558,14 +5090,31 @@ name = "cumulus-primitives-core" version = "0.7.0" dependencies = [ "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "scale-info", "sp-api 26.0.0", "sp-runtime 31.0.1", "sp-trie 29.0.0", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "cumulus-primitives-core" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c6b5221a4a3097f2ebef66c84c1e6d7a0b8ec7e63f2bd5ae04c1e6d3fc7514e" +dependencies = [ + "parity-scale-codec", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "scale-info", + "sp-api 34.0.0", + "sp-runtime 39.0.2", + "sp-trie 37.0.0", + "staging-xcm 14.2.0", ] [[package]] @@ -4573,14 +5122,29 @@ name = "cumulus-primitives-parachain-inherent" version = "0.7.0" dependencies = [ "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-trie 29.0.0", ] +[[package]] +name = "cumulus-primitives-parachain-inherent" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "842a694901e04a62d88995418dec35c22f7dba2b34d32d2b8de37d6b92f973ff" +dependencies = [ + "async-trait", + "cumulus-primitives-core 0.16.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-trie 37.0.0", +] + [[package]] name = "cumulus-primitives-proof-size-hostfunction" version = "0.2.0" @@ -4593,17 +5157,28 @@ dependencies = [ "sp-trie 29.0.0", ] +[[package]] +name = "cumulus-primitives-proof-size-hostfunction" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "421f03af054aac7c89e87a49e47964886e53a8d7395990eab27b6f201d42524f" +dependencies = [ + "sp-externalities 0.29.0", + "sp-runtime-interface 28.0.0", + "sp-trie 37.0.0", +] + [[package]] name = "cumulus-primitives-storage-weight-reclaim" version = "1.0.0" dependencies = [ - "cumulus-primitives-core", - "cumulus-primitives-proof-size-hostfunction", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", "cumulus-test-runtime", "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -4612,29 +5187,75 @@ dependencies = [ "sp-trie 29.0.0", ] +[[package]] +name = "cumulus-primitives-storage-weight-reclaim" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fc49dfec0ba3438afad73787736cc0dba88d15b5855881f12a4d8b812a72927" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "cumulus-primitives-proof-size-hostfunction 0.10.0", + "docify", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "cumulus-primitives-timestamp" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "sp-inherents", - "sp-timestamp", + "cumulus-primitives-core 0.7.0", + "sp-inherents 26.0.0", + "sp-timestamp 26.0.0", +] + +[[package]] +name = "cumulus-primitives-timestamp" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cffb8f010f39ac36b31d38994b8f9d9256d9b5e495d96b4ec59d3e30852d53" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "sp-inherents 34.0.0", + "sp-timestamp 34.0.0", ] [[package]] name = "cumulus-primitives-utility" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", "log", - "pallet-asset-conversion", + "pallet-asset-conversion 10.0.0", "parity-scale-codec", - "polkadot-runtime-common", + "polkadot-runtime-common 7.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "cumulus-primitives-utility" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bdcf4d46dd93f1e6d5dd6d379133566a44042ba6476d04bdcbdb4981c622ae4" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "log", + "pallet-asset-conversion 20.0.0", + "parity-scale-codec", + "polkadot-runtime-common 17.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] @@ -4642,13 +5263,13 @@ name = "cumulus-relay-chain-inprocess-interface" version = "0.7.0" dependencies = [ "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "cumulus-test-service", "futures", "futures-timer", "polkadot-cli", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-service", "polkadot-test-client", "prioritized-metered-channel", @@ -4660,7 +5281,7 @@ dependencies = [ "sp-api 26.0.0", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", ] @@ -4670,9 +5291,9 @@ name = "cumulus-relay-chain-interface" version = "0.7.0" dependencies = [ "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "futures", - "jsonrpsee-core 0.24.3", + "jsonrpsee-core", "parity-scale-codec", "polkadot-overseer", "sc-client-api", @@ -4689,16 +5310,16 @@ version = "0.7.0" dependencies = [ "array-bytes", "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "cumulus-relay-chain-rpc-interface", "futures", - "polkadot-core-primitives", + "polkadot-core-primitives 7.0.0", "polkadot-network-bridge", "polkadot-node-network-protocol", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-service", "sc-authority-discovery", "sc-client-api", @@ -4710,7 +5331,7 @@ dependencies = [ "sp-api 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-runtime 31.0.1", "substrate-prometheus-endpoint", "tokio", @@ -4722,12 +5343,12 @@ name = "cumulus-relay-chain-rpc-interface" version = "0.7.0" dependencies = [ "async-trait", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "either", "futures", "futures-timer", - "jsonrpsee 0.24.3", + "jsonrpsee", "parity-scale-codec", "pin-project", "polkadot-overseer", @@ -4743,8 +5364,8 @@ dependencies = [ "smoldot 0.11.0", "smoldot-light 0.9.0", "sp-api 26.0.0", - "sp-authority-discovery", - "sp-consensus-babe", + "sp-authority-discovery 26.0.0", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", @@ -4762,19 +5383,19 @@ dependencies = [ name = "cumulus-test-client" version = "0.1.0" dependencies = [ - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-test-relay-sproof-builder", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-test-relay-sproof-builder 0.7.0", "cumulus-test-runtime", "cumulus-test-service", - "frame-system", - "pallet-balances", - "pallet-transaction-payment", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "sc-block-builder", "sc-consensus", "sc-consensus-aura", @@ -4784,14 +5405,14 @@ dependencies = [ "sp-api 26.0.0", "sp-application-crypto 30.0.0", "sp-blockchain", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "substrate-test-client", ] @@ -4799,55 +5420,69 @@ dependencies = [ name = "cumulus-test-relay-sproof-builder" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-trie 29.0.0", ] +[[package]] +name = "cumulus-test-relay-sproof-builder" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e570e41c3f05a8143ebff967bbb0c7dcaaa6f0bebd8639b9418b8005b13eda03" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "parity-scale-codec", + "polkadot-primitives 16.0.0", + "sp-runtime 39.0.2", + "sp-state-machine 0.43.0", + "sp-trie 37.0.0", +] + [[package]] name = "cumulus-test-runtime" version = "0.1.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-glutton", - "pallet-message-queue", - "pallet-session", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-glutton 14.0.0", + "pallet-message-queue 31.0.0", + "pallet-session 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "scale-info", "serde_json", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-transaction-pool", + "sp-session 27.0.0", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "substrate-wasm-builder", + "staging-parachain-info 0.7.0", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -4866,27 +5501,27 @@ dependencies = [ "cumulus-client-parachain-inherent", "cumulus-client-pov-recovery", "cumulus-client-service", - "cumulus-pallet-parachain-system", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", "cumulus-test-client", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "cumulus-test-runtime", - "frame-system", - "frame-system-rpc-runtime-api", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", "futures", - "jsonrpsee 0.24.3", - "pallet-timestamp", - "pallet-transaction-payment", - "parachains-common", + "jsonrpsee", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "polkadot-cli", "polkadot-node-subsystem", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-service", "polkadot-test-service", "portpicker", @@ -4912,17 +5547,17 @@ dependencies = [ "serde_json", "sp-api 26.0.0", "sp-arithmetic 23.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", + "sp-genesis-builder 0.8.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "substrate-test-client", "substrate-test-utils", @@ -5060,38 +5695,14 @@ dependencies = [ "syn 2.0.87", ] -[[package]] -name = "darling" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" -dependencies = [ - "darling_core 0.14.4", - "darling_macro 0.14.4", -] - [[package]] name = "darling" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ - "darling_core 0.20.10", - "darling_macro 0.20.10", -] - -[[package]] -name = "darling_core" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2 1.0.86", - "quote 1.0.37", - "strsim 0.10.0", - "syn 1.0.109", + "darling_core", + "darling_macro", ] [[package]] @@ -5108,24 +5719,13 @@ dependencies = [ "syn 2.0.87", ] -[[package]] -name = "darling_macro" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" -dependencies = [ - "darling_core 0.14.4", - "quote 1.0.37", - "syn 1.0.109", -] - [[package]] name = "darling_macro" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ - "darling_core 0.20.10", + "darling_core", "quote 1.0.37", "syn 2.0.87", ] @@ -5282,6 +5882,27 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "derive_more" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", + "unicode-xid 0.2.4", +] + [[package]] name = "diff" version = "0.1.13" @@ -5600,34 +6221,34 @@ dependencies = [ name = "emulated-integration-tests-common" version = "3.0.0" dependencies = [ - "asset-test-utils", - "bp-messages", - "bp-xcm-bridge-hub", - "bridge-runtime-common", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "frame-support", - "pallet-assets", - "pallet-balances", - "pallet-bridge-messages", - "pallet-message-queue", - "pallet-xcm", - "pallet-xcm-bridge-hub", - "parachains-common", + "asset-test-utils 7.0.0", + "bp-messages 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "bridge-runtime-common 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-bridge-messages 0.7.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "parachains-common 7.0.0", "parity-scale-codec", "paste", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "sc-consensus-grandpa", - "sp-authority-discovery", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-authority-discovery 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", - "staging-xcm", + "staging-xcm 7.0.0", "xcm-emulator", ] @@ -5765,9 +6386,9 @@ version = "0.1.0" dependencies = [ "async-std", "async-trait", - "bp-header-chain", + "bp-header-chain 0.7.0", "finality-relay", - "frame-support", + "frame-support 28.0.0", "futures", "log", "num-traits", @@ -5790,7 +6411,7 @@ dependencies = [ "honggfuzz", "polkadot-erasure-coding", "polkadot-node-primitives", - "polkadot-primitives", + "polkadot-primitives 7.0.0", ] [[package]] @@ -5814,13 +6435,55 @@ dependencies = [ "libc", ] +[[package]] +name = "ethabi" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7413c5f74cc903ea37386a8965a936cbeb334bd270862fdece542c1b2dcbc898" +dependencies = [ + "ethereum-types 0.14.1", + "hex", + "once_cell", + "regex", + "serde", + "serde_json", + "sha3 0.10.8", + "thiserror", + "uint 0.9.5", +] + [[package]] name = "ethabi-decode" -version = "1.1.0" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d398648d65820a727d6a81e58b962f874473396a047e4c30bafe3240953417" +dependencies = [ + "ethereum-types 0.14.1", + "tiny-keccak", +] + +[[package]] +name = "ethabi-decode" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52029c4087f9f01108f851d0d02df9c21feb5660a19713466724b7f95bd2d773" +dependencies = [ + "ethereum-types 0.15.1", + "tiny-keccak", +] + +[[package]] +name = "ethbloom" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9af52ec57c5147716872863c2567c886e7d62f539465b94352dbc0108fe5293" +checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" dependencies = [ - "ethereum-types", + "crunchy", + "fixed-hash", + "impl-codec 0.6.0", + "impl-rlp 0.3.0", + "impl-serde 0.4.0", + "scale-info", "tiny-keccak", ] @@ -5833,22 +6496,38 @@ dependencies = [ "crunchy", "fixed-hash", "impl-codec 0.7.0", - "impl-rlp", + "impl-rlp 0.4.0", "impl-serde 0.5.0", "scale-info", "tiny-keccak", ] +[[package]] +name = "ethereum-types" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" +dependencies = [ + "ethbloom 0.13.0", + "fixed-hash", + "impl-codec 0.6.0", + "impl-rlp 0.3.0", + "impl-serde 0.4.0", + "primitive-types 0.12.2", + "scale-info", + "uint 0.9.5", +] + [[package]] name = "ethereum-types" version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ab15ed80916029f878e0267c3a9f92b67df55e79af370bf66199059ae2b4ee3" dependencies = [ - "ethbloom", + "ethbloom 0.14.1", "fixed-hash", "impl-codec 0.7.0", - "impl-rlp", + "impl-rlp 0.4.0", "impl-serde 0.5.0", "primitive-types 0.13.1", "scale-info", @@ -5863,19 +6542,9 @@ checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" [[package]] name = "event-listener" -version = "4.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b215c49b2b248c855fb73579eb1f4f26c38ffdc12973e20e07b91d78d5646e" -dependencies = [ - "concurrent-queue", - "pin-project-lite", -] - -[[package]] -name = "event-listener" -version = "5.2.0" +version = "5.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" +checksum = "6032be9bd27023a771701cc49f9f053c751055f71efb2e0ae5c15809093675ba" dependencies = [ "concurrent-queue", "parking", @@ -5888,7 +6557,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ - "event-listener 5.2.0", + "event-listener 5.3.1", "pin-project-lite", ] @@ -6110,7 +6779,7 @@ dependencies = [ "async-std", "async-trait", "backoff", - "bp-header-chain", + "bp-header-chain 0.7.0", "futures", "log", "num-traits", @@ -6245,9 +6914,9 @@ name = "frame-benchmarking" version = "28.0.0" dependencies = [ "array-bytes", - "frame-support", - "frame-support-procedural", - "frame-system", + "frame-support 28.0.0", + "frame-support-procedural 23.0.0", + "frame-system 28.0.0", "linregress", "log", "parity-scale-codec", @@ -6266,6 +6935,31 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "frame-benchmarking" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01bdd47c2d541b38bd892da647d1e972c9d85b4ecd7094ad64f7600175da54d" +dependencies = [ + "frame-support 38.0.0", + "frame-support-procedural 30.0.4", + "frame-system 38.0.0", + "linregress", + "log", + "parity-scale-codec", + "paste", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-runtime-interface 28.0.0", + "sp-storage 21.0.0", + "static_assertions", +] + [[package]] name = "frame-benchmarking-cli" version = "32.0.0" @@ -6276,11 +6970,11 @@ dependencies = [ "clap 4.5.13", "comfy-table", "cumulus-client-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", + "cumulus-primitives-proof-size-hostfunction 0.2.0", "cumulus-test-runtime", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "gethostname", "handlebars", "hex", @@ -6288,8 +6982,8 @@ dependencies = [ "linked-hash-map", "log", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "rand", "rand_pcg", "sc-block-builder", @@ -6304,21 +6998,21 @@ dependencies = [ "serde", "serde_json", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", "sp-database", "sp-externalities 0.25.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-storage 19.0.0", - "sp-timestamp", - "sp-transaction-pool", + "sp-timestamp 26.0.0", + "sp-transaction-pool 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", "sp-wasm-interface 20.0.0", @@ -6334,21 +7028,50 @@ dependencies = [ name = "frame-benchmarking-pallet-pov" version = "18.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-io 30.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "frame-benchmarking-pallet-pov" +version = "28.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ffde6f573a63eeb1ccb7d2667c5741a11ce93bc30f33712e5326b9d8a811c29" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + +[[package]] +name = "frame-decode" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02d3379df61ff3dd871e2dde7d1bcdc0263e613c21c7579b149fd4f0ad9b1dc2" +dependencies = [ + "frame-metadata 17.0.0", + "parity-scale-codec", + "scale-decode 0.14.0", + "scale-info", + "scale-type-resolver", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "frame-election-provider-solution-type" version = "13.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", "parity-scale-codec", "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", @@ -6360,36 +7083,65 @@ dependencies = [ ] [[package]] -name = "frame-election-provider-support" -version = "28.0.0" +name = "frame-election-provider-solution-type" +version = "14.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8156f209055d352994ecd49e19658c6b469d7c6de923bd79868957d0dcfb6f71" dependencies = [ - "frame-election-provider-solution-type", - "frame-support", - "frame-system", + "proc-macro-crate 3.1.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + +[[package]] +name = "frame-election-provider-support" +version = "28.0.0" +dependencies = [ + "frame-election-provider-solution-type 13.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "rand", "scale-info", "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "frame-election-provider-support" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c36f5116192c63d39f1b4556fa30ac7db5a6a52575fa241b045f7dfa82ecc2be" +dependencies = [ + "frame-election-provider-solution-type 14.0.1", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-npos-elections 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "frame-election-solution-type-fuzzer" version = "2.0.0-alpha.5" dependencies = [ "clap 4.5.13", - "frame-election-provider-solution-type", - "frame-election-provider-support", - "frame-support", + "frame-election-provider-solution-type 13.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", "honggfuzz", "parity-scale-codec", "rand", "scale-info", "sp-arithmetic 23.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", ] @@ -6399,16 +7151,16 @@ version = "28.0.0" dependencies = [ "aquamarine", "array-bytes", - "frame-support", - "frame-system", - "frame-try-runtime", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-try-runtime 0.34.0", "log", - "pallet-balances", - "pallet-transaction-payment", + "pallet-balances 28.0.0", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", @@ -6416,14 +7168,22 @@ dependencies = [ ] [[package]] -name = "frame-metadata" -version = "15.1.0" +name = "frame-executive" +version = "38.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "878babb0b136e731cc77ec2fd883ff02745ff21e6fb662729953d44923df009c" +checksum = "c365bf3879de25bbee28e9584096955a02fbe8d7e7624e10675800317f1cee5b" dependencies = [ - "cfg-if", + "aquamarine", + "frame-support 38.0.0", + "frame-system 38.0.0", + "frame-try-runtime 0.44.0", + "log", "parity-scale-codec", "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", ] [[package]] @@ -6438,6 +7198,18 @@ dependencies = [ "serde", ] +[[package]] +name = "frame-metadata" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "701bac17e9b55e0f95067c428ebcb46496587f08e8cf4ccc0fe5903bea10dbb8" +dependencies = [ + "cfg-if", + "parity-scale-codec", + "scale-info", + "serde", +] + [[package]] name = "frame-metadata-hash-extension" version = "0.1.0" @@ -6446,8 +7218,8 @@ dependencies = [ "const-hex", "docify", "frame-metadata 16.0.0", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "merkleized-metadata", "parity-scale-codec", @@ -6455,9 +7227,25 @@ dependencies = [ "sp-api 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "substrate-test-runtime-client", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", +] + +[[package]] +name = "frame-metadata-hash-extension" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ac71dbd97039c49fdd69f416a4dd5d8da3652fdcafc3738b45772ad79eb4ec" +dependencies = [ + "array-bytes", + "docify", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", ] [[package]] @@ -6466,15 +7254,15 @@ version = "0.1.0" dependencies = [ "assert_cmd", "clap 4.5.13", - "cumulus-primitives-proof-size-hostfunction", + "cumulus-primitives-proof-size-hostfunction 0.2.0", "cumulus-test-runtime", "frame-benchmarking-cli", "log", "sc-chain-spec", "sc-cli", - "sp-genesis-builder", + "sp-genesis-builder 0.8.0", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", "sp-tracing 16.0.0", "tempfile", "tracing-subscriber 0.3.18", @@ -6486,7 +7274,7 @@ version = "0.35.0" dependencies = [ "futures", "indicatif", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "serde", @@ -6510,13 +7298,13 @@ dependencies = [ "aquamarine", "array-bytes", "assert_matches", - "binary-merkle-tree", + "binary-merkle-tree 13.0.0", "bitflags 1.3.2", "docify", "environmental", "frame-metadata 16.0.0", - "frame-support-procedural", - "frame-system", + "frame-support-procedural 23.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "k256", "log", @@ -6534,15 +7322,15 @@ dependencies = [ "sp-crypto-hashing 0.1.0", "sp-crypto-hashing-proc-macro 0.1.0", "sp-debug-derive 14.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-metadata-ir 0.6.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-state-machine 0.35.0", "sp-std 14.0.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "sp-trie 29.0.0", "sp-weights 27.0.0", @@ -6550,6 +7338,48 @@ dependencies = [ "tt-call", ] +[[package]] +name = "frame-support" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e44af69fa61bc5005ffe0339e198957e77f0f255704a9bee720da18a733e3dc" +dependencies = [ + "aquamarine", + "array-bytes", + "bitflags 1.3.2", + "docify", + "environmental", + "frame-metadata 16.0.0", + "frame-support-procedural 30.0.4", + "impl-trait-for-tuples", + "k256", + "log", + "macro_magic", + "parity-scale-codec", + "paste", + "scale-info", + "serde", + "serde_json", + "smallvec", + "sp-api 34.0.0", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-crypto-hashing-proc-macro 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-genesis-builder 0.15.1", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-metadata-ir 0.7.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", + "sp-state-machine 0.43.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-tracing 17.0.1", + "sp-weights 31.0.0", + "static_assertions", + "tt-call", +] + [[package]] name = "frame-support-procedural" version = "23.0.0" @@ -6559,9 +7389,9 @@ dependencies = [ "derive-syn-parse", "docify", "expander", - "frame-support", - "frame-support-procedural-tools", - "frame-system", + "frame-support 28.0.0", + "frame-support-procedural-tools 10.0.0", + "frame-system 28.0.0", "itertools 0.11.0", "macro_magic", "parity-scale-codec", @@ -6580,11 +7410,44 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "frame-support-procedural" +version = "30.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e8f9b6bc1517a6fcbf0b2377e5c8c6d39f5bb7862b191a59a9992081d63972d" +dependencies = [ + "Inflector", + "cfg-expr", + "derive-syn-parse", + "expander", + "frame-support-procedural-tools 13.0.0", + "itertools 0.11.0", + "macro_magic", + "proc-macro-warning 1.0.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 2.0.87", +] + [[package]] name = "frame-support-procedural-tools" version = "10.0.0" dependencies = [ - "frame-support-procedural-tools-derive", + "frame-support-procedural-tools-derive 11.0.0", + "proc-macro-crate 3.1.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + +[[package]] +name = "frame-support-procedural-tools" +version = "13.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bead15a320be1764cdd50458c4cfacb23e0cee65f64f500f8e34136a94c7eeca" +dependencies = [ + "frame-support-procedural-tools-derive 12.0.0", "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", @@ -6600,16 +7463,27 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "frame-support-procedural-tools-derive" +version = "12.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed971c6435503a099bdac99fe4c5bea08981709e5b5a0a8535a1856f48561191" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "frame-support-test" version = "3.0.0" dependencies = [ - "frame-benchmarking", - "frame-executive", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", "frame-metadata 16.0.0", - "frame-support", + "frame-support 28.0.0", "frame-support-test-pallet", - "frame-system", + "frame-system 28.0.0", "parity-scale-codec", "pretty_assertions", "rustversion", @@ -6631,8 +7505,8 @@ dependencies = [ name = "frame-support-test-compile-pass" version = "4.0.0-dev" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -6644,8 +7518,8 @@ dependencies = [ name = "frame-support-test-pallet" version = "4.0.0-dev" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "serde", @@ -6657,7 +7531,7 @@ name = "frame-support-test-stg-frame-crate" version = "0.1.0" dependencies = [ "parity-scale-codec", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", ] @@ -6668,7 +7542,7 @@ dependencies = [ "cfg-if", "criterion", "docify", - "frame-support", + "frame-support 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -6683,13 +7557,34 @@ dependencies = [ "substrate-test-runtime-client", ] +[[package]] +name = "frame-system" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c7fa02f8c305496d2ae52edaecdb9d165f11afa965e05686d7d7dd1ce93611" +dependencies = [ + "cfg-if", + "docify", + "frame-support 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-version 37.0.0", + "sp-weights 31.0.0", +] + [[package]] name = "frame-system-benchmarking" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -6699,6 +7594,21 @@ dependencies = [ "sp-version 29.0.0", ] +[[package]] +name = "frame-system-benchmarking" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9693b2a736beb076e673520e1e8dee4fc128b8d35b020ef3e8a4b1b5ad63d9f2" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "frame-system-rpc-runtime-api" version = "26.0.0" @@ -6708,16 +7618,39 @@ dependencies = [ "sp-api 26.0.0", ] +[[package]] +name = "frame-system-rpc-runtime-api" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "475c4f8604ba7e4f05cd2c881ba71105093e638b9591ec71a8db14a64b3b4ec3" +dependencies = [ + "docify", + "parity-scale-codec", + "sp-api 34.0.0", +] + [[package]] name = "frame-try-runtime" version = "0.34.0" dependencies = [ - "frame-support", + "frame-support 28.0.0", "parity-scale-codec", "sp-api 26.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "frame-try-runtime" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83c811a5a1f5429c7fb5ebbf6cf9502d8f9b673fd395c12cf46c44a30a7daf0e" +dependencies = [ + "frame-support 38.0.0", + "parity-scale-codec", + "sp-api 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "fs-err" version = "2.9.0" @@ -6918,12 +7851,12 @@ name = "generate-bags" version = "28.0.0" dependencies = [ "chrono", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "num-format", - "pallet-staking", - "sp-staking", + "pallet-staking 28.0.0", + "sp-staking 26.0.0", ] [[package]] @@ -7080,45 +8013,45 @@ dependencies = [ name = "glutton-westend-runtime" version = "3.0.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcm", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-timestamp", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", - "pallet-aura", - "pallet-glutton", - "pallet-message-queue", - "pallet-sudo", - "pallet-timestamp", - "parachains-common", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-timestamp 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", + "pallet-aura 27.0.0", + "pallet-glutton 14.0.0", + "pallet-message-queue 31.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", ] [[package]] @@ -7309,6 +8242,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30ed443af458ccb6d81c1e7e661545f94d3176752fb1df2f543b902a1e0f51e2" +[[package]] +name = "hex-conservative" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd" +dependencies = [ + "arrayvec 0.7.4", +] + [[package]] name = "hex-literal" version = "0.4.1" @@ -7785,6 +8727,15 @@ dependencies = [ "uint 0.10.0", ] +[[package]] +name = "impl-rlp" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" +dependencies = [ + "rlp 0.5.2", +] + [[package]] name = "impl-rlp" version = "0.4.0" @@ -8047,6 +8998,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.9" @@ -8101,9 +9061,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" dependencies = [ "wasm-bindgen", ] @@ -8151,76 +9111,34 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfdb12a2381ea5b2e68c3469ec604a007b367778cdb14d09612c8069ebd616ad" -dependencies = [ - "jsonrpsee-client-transport 0.22.5", - "jsonrpsee-core 0.22.5", - "jsonrpsee-http-client 0.22.5", - "jsonrpsee-types 0.22.5", -] - -[[package]] -name = "jsonrpsee" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b089779ad7f80768693755a031cc14a7766aba707cbe886674e3f79e9b7e47" -dependencies = [ - "jsonrpsee-core 0.23.2", - "jsonrpsee-types 0.23.2", - "jsonrpsee-ws-client 0.23.2", -] - -[[package]] -name = "jsonrpsee" -version = "0.24.3" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ec465b607a36dc5dd45d48b7689bc83f679f66a3ac6b6b21cc787a11e0f8685" +checksum = "c5c71d8c1a731cc4227c2f698d377e7848ca12c8a48866fc5e6951c43a4db843" dependencies = [ - "jsonrpsee-client-transport 0.24.3", - "jsonrpsee-core 0.24.3", - "jsonrpsee-http-client 0.24.3", + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-http-client", "jsonrpsee-proc-macros", "jsonrpsee-server", - "jsonrpsee-types 0.24.3", + "jsonrpsee-types", "jsonrpsee-wasm-client", - "jsonrpsee-ws-client 0.24.3", - "tokio", - "tracing", -] - -[[package]] -name = "jsonrpsee-client-transport" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4978087a58c3ab02efc5b07c5e5e2803024536106fd5506f558db172c889b3aa" -dependencies = [ - "futures-util", - "http 0.2.9", - "jsonrpsee-core 0.22.5", - "pin-project", - "rustls-native-certs 0.7.0", - "rustls-pki-types", - "soketto 0.7.1", - "thiserror", + "jsonrpsee-ws-client", "tokio", - "tokio-rustls 0.25.0", - "tokio-util", "tracing", - "url", ] [[package]] name = "jsonrpsee-client-transport" -version = "0.23.2" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08163edd8bcc466c33d79e10f695cdc98c00d1e6ddfb95cec41b6b0279dd5432" +checksum = "548125b159ba1314104f5bb5f38519e03a41862786aa3925cf349aae9cdd546e" dependencies = [ "base64 0.22.1", + "futures-channel", "futures-util", + "gloo-net", "http 1.1.0", - "jsonrpsee-core 0.23.2", + "jsonrpsee-core", "pin-project", "rustls 0.23.14", "rustls-pki-types", @@ -8235,152 +9153,62 @@ dependencies = [ ] [[package]] -name = "jsonrpsee-client-transport" -version = "0.24.3" +name = "jsonrpsee-core" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f0977f9c15694371b8024c35ab58ca043dbbf4b51ccb03db8858a021241df1" +checksum = "f2882f6f8acb9fdaec7cefc4fd607119a9bd709831df7d7672a1d3b644628280" dependencies = [ - "base64 0.22.1", - "futures-channel", + "async-trait", + "bytes", + "futures-timer", "futures-util", - "gloo-net", "http 1.1.0", - "jsonrpsee-core 0.24.3", + "http-body 1.0.0", + "http-body-util", + "jsonrpsee-types", + "parking_lot 0.12.3", "pin-project", - "rustls 0.23.14", - "rustls-pki-types", - "rustls-platform-verifier", - "soketto 0.8.0", + "rand", + "rustc-hash 2.0.0", + "serde", + "serde_json", "thiserror", "tokio", - "tokio-rustls 0.26.0", - "tokio-util", + "tokio-stream", "tracing", - "url", + "wasm-bindgen-futures", ] [[package]] -name = "jsonrpsee-core" -version = "0.22.5" +name = "jsonrpsee-http-client" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b257e1ec385e07b0255dde0b933f948b5c8b8c28d42afda9587c3a967b896d" +checksum = "b3638bc4617f96675973253b3a45006933bde93c2fd8a6170b33c777cc389e5b" dependencies = [ - "anyhow", "async-trait", - "beef", - "futures-timer", - "futures-util", - "hyper 0.14.29", - "jsonrpsee-types 0.22.5", - "pin-project", - "rustc-hash 1.1.0", + "base64 0.22.1", + "http-body 1.0.0", + "hyper 1.3.1", + "hyper-rustls 0.27.3", + "hyper-util", + "jsonrpsee-core", + "jsonrpsee-types", + "rustls 0.23.14", + "rustls-platform-verifier", "serde", "serde_json", "thiserror", "tokio", - "tokio-stream", + "tower", "tracing", -] - -[[package]] -name = "jsonrpsee-core" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79712302e737d23ca0daa178e752c9334846b08321d439fd89af9a384f8c830b" -dependencies = [ - "anyhow", - "async-trait", - "beef", - "futures-timer", - "futures-util", - "jsonrpsee-types 0.23.2", - "pin-project", - "rustc-hash 1.1.0", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "tracing", -] - -[[package]] -name = "jsonrpsee-core" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e942c55635fbf5dc421938b8558a8141c7e773720640f4f1dbe1f4164ca4e221" -dependencies = [ - "async-trait", - "bytes", - "futures-timer", - "futures-util", - "http 1.1.0", - "http-body 1.0.0", - "http-body-util", - "jsonrpsee-types 0.24.3", - "parking_lot 0.12.3", - "pin-project", - "rand", - "rustc-hash 2.0.0", - "serde", - "serde_json", - "thiserror", - "tokio", - "tokio-stream", - "tracing", - "wasm-bindgen-futures", -] - -[[package]] -name = "jsonrpsee-http-client" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ccf93fc4a0bfe05d851d37d7c32b7f370fe94336b52a2f0efc5f1981895c2e5" -dependencies = [ - "async-trait", - "hyper 0.14.29", - "hyper-rustls 0.24.2", - "jsonrpsee-core 0.22.5", - "jsonrpsee-types 0.22.5", - "serde", - "serde_json", - "thiserror", - "tokio", - "tower", - "tracing", - "url", -] - -[[package]] -name = "jsonrpsee-http-client" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33774602df12b68a2310b38a535733c477ca4a498751739f89fe8dbbb62ec4c" -dependencies = [ - "async-trait", - "base64 0.22.1", - "http-body 1.0.0", - "hyper 1.3.1", - "hyper-rustls 0.27.3", - "hyper-util", - "jsonrpsee-core 0.24.3", - "jsonrpsee-types 0.24.3", - "rustls 0.23.14", - "rustls-platform-verifier", - "serde", - "serde_json", - "thiserror", - "tokio", - "tower", - "tracing", - "url", + "url", ] [[package]] name = "jsonrpsee-proc-macros" -version = "0.24.3" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b07a2daf52077ab1b197aea69a5c990c060143835bf04c77070e98903791715" +checksum = "c06c01ae0007548e73412c08e2285ffe5d723195bf268bce67b1b77c3bb2a14d" dependencies = [ "heck 0.5.0", "proc-macro-crate 3.1.0", @@ -8391,9 +9219,9 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.24.3" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038fb697a709bec7134e9ccbdbecfea0e2d15183f7140254afef7c5610a3f488" +checksum = "82ad8ddc14be1d4290cd68046e7d1d37acd408efed6d3ca08aefcc3ad6da069c" dependencies = [ "futures-util", "http 1.1.0", @@ -8401,8 +9229,8 @@ dependencies = [ "http-body-util", "hyper 1.3.1", "hyper-util", - "jsonrpsee-core 0.24.3", - "jsonrpsee-types 0.24.3", + "jsonrpsee-core", + "jsonrpsee-types", "pin-project", "route-recognizer", "serde", @@ -8418,35 +9246,9 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150d6168405890a7a3231a3c74843f58b8959471f6df76078db2619ddee1d07d" -dependencies = [ - "anyhow", - "beef", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "jsonrpsee-types" -version = "0.23.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c465fbe385238e861fdc4d1c85e04ada6c1fd246161d26385c1b311724d2af" -dependencies = [ - "beef", - "http 1.1.0", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "jsonrpsee-types" -version = "0.24.3" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b67d6e008164f027afbc2e7bb79662650158d26df200040282d2aa1cbb093b" +checksum = "a178c60086f24cc35bb82f57c651d0d25d99c4742b4d335de04e97fa1f08a8a1" dependencies = [ "http 1.1.0", "serde", @@ -8456,38 +9258,25 @@ dependencies = [ [[package]] name = "jsonrpsee-wasm-client" -version = "0.24.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0470d0ae043ffcb0cd323797a631e637fb4b55fe3eaa6002934819458bba62a7" -dependencies = [ - "jsonrpsee-client-transport 0.24.3", - "jsonrpsee-core 0.24.3", - "jsonrpsee-types 0.24.3", -] - -[[package]] -name = "jsonrpsee-ws-client" -version = "0.23.2" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c28759775f5cb2f1ea9667672d3fe2b0e701d1f4b7b67954e60afe7fd058b5e" +checksum = "1a01cd500915d24ab28ca17527e23901ef1be6d659a2322451e1045532516c25" dependencies = [ - "http 1.1.0", - "jsonrpsee-client-transport 0.23.2", - "jsonrpsee-core 0.23.2", - "jsonrpsee-types 0.23.2", - "url", + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-types", ] [[package]] name = "jsonrpsee-ws-client" -version = "0.24.3" +version = "0.24.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "992bf67d1132f88edf4a4f8cff474cf01abb2be203004a2b8e11c2b20795b99e" +checksum = "0fe322e0896d0955a3ebdd5bf813571c53fea29edd713bc315b76620b327e86d" dependencies = [ "http 1.1.0", - "jsonrpsee-client-transport 0.24.3", - "jsonrpsee-core 0.24.3", - "jsonrpsee-types 0.24.3", + "jsonrpsee-client-transport", + "jsonrpsee-core", + "jsonrpsee-types", "url", ] @@ -8530,11 +9319,11 @@ dependencies = [ [[package]] name = "keccak-hash" -version = "0.10.0" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b286e6b663fb926e1eeb68528e69cb70ed46c6d65871a21b2215ae8154c6d3c" +checksum = "3e1b8590eb6148af2ea2d75f38e7d29f5ca970d5a4df456b3ef19b8b415d0264" dependencies = [ - "primitive-types 0.12.2", + "primitive-types 0.13.1", "tiny-keccak", ] @@ -8564,13 +9353,13 @@ dependencies = [ "pallet-example-mbm", "pallet-example-tasks", "parity-scale-codec", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "primitive-types 0.13.1", "scale-info", "serde_json", "sp-debug-derive 14.0.0", "static_assertions", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -8610,7 +9399,7 @@ dependencies = [ "rand", "rustls 0.21.7", "rustls-pemfile 1.0.3", - "secrecy", + "secrecy 0.8.0", "serde", "serde_json", "serde_yaml", @@ -9477,6 +10266,15 @@ dependencies = [ "value-bag", ] +[[package]] +name = "lru" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6e8aaa3f231bb4bd57b84b2d5dc3ae7f350265df8aa96492e0bc394a1571909" +dependencies = [ + "hashbrown 0.12.3", +] + [[package]] name = "lru" version = "0.11.0" @@ -9716,7 +10514,7 @@ dependencies = [ "blake3", "frame-metadata 16.0.0", "parity-scale-codec", - "scale-decode", + "scale-decode 0.13.1", "scale-info", ] @@ -9738,7 +10536,7 @@ version = "0.1.0" dependencies = [ "async-std", "async-trait", - "bp-messages", + "bp-messages 0.7.0", "finality-relay", "futures", "hex", @@ -9770,9 +10568,9 @@ dependencies = [ "docify", "futures", "futures-timer", - "jsonrpsee 0.24.3", + "jsonrpsee", "minimal-template-runtime", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "serde_json", ] @@ -9782,7 +10580,7 @@ version = "0.0.0" dependencies = [ "pallet-minimal-template", "parity-scale-codec", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "scale-info", "serde_json", ] @@ -9847,9 +10645,9 @@ dependencies = [ "sp-api 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", - "sp-mmr-primitives", + "sp-mmr-primitives 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", "substrate-test-runtime-client", @@ -9860,14 +10658,14 @@ dependencies = [ name = "mmr-rpc" version = "28.0.0" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "parity-scale-codec", "serde", "serde_json", "sp-api 26.0.0", "sp-blockchain", "sp-core 28.0.0", - "sp-mmr-primitives", + "sp-mmr-primitives 26.0.0", "sp-runtime 31.0.1", ] @@ -10263,7 +11061,7 @@ checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ "bitflags 2.6.0", "cfg-if", - "cfg_aliases 0.1.1", + "cfg_aliases", "libc", ] @@ -10285,7 +11083,7 @@ version = "0.9.0-dev" dependencies = [ "array-bytes", "clap 4.5.13", - "derive_more", + "derive_more 0.99.17", "fs_extra", "futures", "hash-db", @@ -10305,10 +11103,10 @@ dependencies = [ "serde_json", "sp-consensus", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "sp-trie 29.0.0", "tempfile", @@ -10326,7 +11124,7 @@ dependencies = [ name = "node-rpc" version = "3.0.0-dev" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "mmr-rpc", "node-primitives", "pallet-transaction-payment-rpc", @@ -10344,14 +11142,14 @@ dependencies = [ "sc-transaction-pool-api", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", "substrate-frame-rpc-system", "substrate-state-trie-migration-rpc", ] @@ -10383,19 +11181,19 @@ dependencies = [ name = "node-testing" version = "3.0.0-dev" dependencies = [ - "frame-metadata-hash-extension", - "frame-system", + "frame-metadata-hash-extension 0.1.0", + "frame-system 28.0.0", "fs_extra", "futures", "kitchensink-runtime", "log", "node-primitives", - "pallet-asset-conversion", - "pallet-asset-conversion-tx-payment", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-revive", - "pallet-skip-feeless-payment", + "pallet-asset-conversion 10.0.0", + "pallet-asset-conversion-tx-payment 10.0.0", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-revive 0.1.0", + "pallet-skip-feeless-payment 3.0.0", "parity-scale-codec", "sc-block-builder", "sc-client-api", @@ -10404,16 +11202,16 @@ dependencies = [ "sc-executor 0.32.0", "sc-service", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "staging-node-cli", "substrate-test-client", "tempfile", @@ -10574,9 +11372,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", "libm", @@ -10804,13 +11602,13 @@ name = "pallet-alliance" version = "27.0.0" dependencies = [ "array-bytes", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-collective", - "pallet-identity", + "pallet-balances 28.0.0", + "pallet-collective 28.0.0", + "pallet-identity 29.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10819,16 +11617,36 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-alliance" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59378a648a0aa279a4b10650366c3389cd0a1239b1876f74bfecd268eecb086b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-collective 38.0.0", + "pallet-identity 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-asset-conversion" version = "10.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-assets", - "pallet-balances", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", "parity-scale-codec", "primitive-types 0.13.1", "scale-info", @@ -10839,17 +11657,36 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-asset-conversion" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f0078659ae95efe6a1bf138ab5250bc41ab98f22ff3651d0208684f08ae797" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-asset-conversion-ops" version = "0.1.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", "parity-scale-codec", "primitive-types 0.13.1", "scale-info", @@ -10859,17 +11696,36 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-asset-conversion-ops" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3edbeda834bcd6660f311d4eead3dabdf6d385b7308ac75b0fae941a960e6c3a" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-asset-conversion 20.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-asset-conversion-tx-payment" version = "10.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", - "pallet-transaction-payment", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10878,14 +11734,29 @@ dependencies = [ "sp-storage 19.0.0", ] +[[package]] +name = "pallet-asset-conversion-tx-payment" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ab66c4c22ac0f20e620a954ce7ba050118d6d8011e2d02df599309502064e98" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-asset-conversion 20.0.0", + "pallet-transaction-payment 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-asset-rate" version = "7.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10893,17 +11764,32 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-asset-rate" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71b2149aa741bc39466bbcc92d9d0ab6e9adcf39d2790443a735ad573b3191e7" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-asset-tx-payment" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-assets", - "pallet-authorship", - "pallet-balances", - "pallet-transaction-payment", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-assets 29.1.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "scale-info", "serde", @@ -10914,16 +11800,34 @@ dependencies = [ "sp-storage 19.0.0", ] +[[package]] +name = "pallet-asset-tx-payment" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406a486466d15acc48c99420191f96f1af018f3381fde829c467aba489030f18" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-transaction-payment 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-assets" version = "29.1.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10931,16 +11835,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-assets" +version = "40.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f45f4eb6027fc34c4650e0ed6a7e57ed3335cc364be74b4531f714237676bcee" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-assets-freezer" version = "0.1.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-assets", - "pallet-balances", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10948,13 +11869,29 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-assets-freezer" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "127adc2250b89416b940850ce2175dab10a9297b503b1fcb05dc555bd9bd3207" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-assets 40.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-atomic-swap" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", - "pallet-balances", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -10962,45 +11899,93 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-atomic-swap" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15906a685adeabe6027e49c814a34066222dd6136187a8a79c213d0d739b6634" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-aura" version = "27.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-aura" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b31da6e794d655d1f9c4da6557a57399538d75905a7862a2ed3f7e5fb711d7e4" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-timestamp 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-consensus-aura 0.40.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-authority-discovery" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", - "pallet-session", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-session 28.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-authority-discovery" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb0208f0538d58dcb78ce1ff5e6e8641c5f37b23b20b05587e51da30ab13541" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-authority-discovery 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-authorship" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", @@ -11009,31 +11994,69 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-authorship" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625d47577cabbe1318ccec5d612e2379002d1b6af1ab6edcef3243c66ec246df" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-babe" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-authorship", - "pallet-balances", - "pallet-offences", - "pallet-session", - "pallet-staking", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-offences 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-babe" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ee096c0def13832475b340d00121025e0225de29604d44bc6dfcaa294c995b4" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "pallet-session 38.0.0", + "pallet-timestamp 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-consensus-babe 0.40.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", ] [[package]] @@ -11042,12 +12065,12 @@ version = "27.0.0" dependencies = [ "aquamarine", "docify", - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11057,12 +12080,34 @@ dependencies = [ ] [[package]] -name = "pallet-bags-list-fuzzer" -version = "4.0.0-dev" +name = "pallet-bags-list" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fd23a6f94ba9c1e57c8a7f8a41327d132903a79c55c0c83f36cbae19946cf10" +dependencies = [ + "aquamarine", + "docify", + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", +] + +[[package]] +name = "pallet-bags-list-fuzzer" +version = "4.0.0-dev" dependencies = [ - "frame-election-provider-support", + "frame-election-provider-support 28.0.0", "honggfuzz", - "pallet-bags-list", + "pallet-bags-list 27.0.0", "rand", ] @@ -11070,13 +12115,13 @@ dependencies = [ name = "pallet-bags-list-remote-tests" version = "4.0.0-dev" dependencies = [ - "frame-election-provider-support", + "frame-election-provider-support 28.0.0", "frame-remote-externalities", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-bags-list", - "pallet-staking", + "pallet-bags-list 27.0.0", + "pallet-staking 28.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", @@ -11089,11 +12134,11 @@ name = "pallet-balances" version = "28.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-transaction-payment", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "paste", "scale-info", @@ -11102,68 +12147,130 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-balances" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c6945b078919acb14d126490e4b0973a688568b30142476ca69c6df2bed27ad" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-beefy" version = "28.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-authorship", - "pallet-balances", - "pallet-offences", - "pallet-session", - "pallet-staking", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-offences 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "serde", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-state-machine 0.35.0", ] +[[package]] +name = "pallet-beefy" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "014d177a3aba19ac144fc6b2b5eb94930b9874734b91fd014902b6706288bb5f" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-consensus-beefy 22.1.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-beefy-mmr" version = "28.0.0" dependencies = [ "array-bytes", - "binary-merkle-tree", - "frame-benchmarking", - "frame-support", - "frame-system", + "binary-merkle-tree 13.0.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-beefy", - "pallet-mmr", - "pallet-session", + "pallet-beefy 28.0.0", + "pallet-mmr 27.0.0", + "pallet-session 28.0.0", "parity-scale-codec", "scale-info", "serde", "sp-api 26.0.0", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-state-machine 0.35.0", ] +[[package]] +name = "pallet-beefy-mmr" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c64f536e7f04cf3a0a17fdf20870ddb3d63a7690419c40f75cfd2f72b6e6d22" +dependencies = [ + "array-bytes", + "binary-merkle-tree 15.0.1", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-beefy 39.0.0", + "pallet-mmr 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-consensus-beefy 22.1.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-state-machine 0.43.0", +] + [[package]] name = "pallet-bounties" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-treasury", + "pallet-balances 28.0.0", + "pallet-treasury 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11171,24 +12278,42 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-bounties" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1163f9cd8bbc47ec0c6900a3ca67689d8d7b40bedfa6aa22b1b3c6027b1090e" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-treasury 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-bridge-beefy" version = "0.1.0" dependencies = [ "bp-beefy", - "bp-runtime", - "bp-test-utils", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", "ckb-merkle-mountain-range", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-beefy-mmr", - "pallet-mmr", + "pallet-beefy-mmr 28.0.0", + "pallet-mmr 27.0.0", "parity-scale-codec", "rand", "scale-info", "serde", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", @@ -11199,36 +12324,56 @@ dependencies = [ name = "pallet-bridge-grandpa" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-runtime", - "bp-test-utils", - "frame-benchmarking", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", ] +[[package]] +name = "pallet-bridge-grandpa" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d825fbed9fb68bc5d344311653dc0f69caeabe647365abf79a539310b2245f6" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-runtime 0.18.0", + "bp-test-utils 0.18.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-consensus-grandpa 21.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "pallet-bridge-messages" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-runtime", - "bp-test-utils", - "frame-benchmarking", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-bridge-grandpa", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11238,20 +12383,40 @@ dependencies = [ "sp-trie 29.0.0", ] +[[package]] +name = "pallet-bridge-messages" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1decdc9fb885e46eb17f850aa14f8cf39e17f31574aa6a5fa1a9e603cc526a2" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-runtime 0.18.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-trie 37.0.0", +] + [[package]] name = "pallet-bridge-parachains" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-parachains", - "bp-polkadot-core", - "bp-runtime", - "bp-test-utils", - "frame-benchmarking", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-bridge-grandpa", + "pallet-bridge-grandpa 0.7.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11260,27 +12425,48 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "pallet-bridge-parachains" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41450a8d214f20eaff57aeca8e647b20c0df7d66871ee2262609b90824bd4cca" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-parachains 0.18.0", + "bp-polkadot-core 0.18.0", + "bp-runtime 0.18.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-bridge-grandpa 0.18.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "pallet-bridge-relayers" version = "0.7.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot-core", - "bp-relayers", - "bp-runtime", - "bp-test-utils", - "frame-benchmarking", - "frame-support", - "frame-system", - "log", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-transaction-payment", - "pallet-utility", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "log", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-transaction-payment 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic 23.0.0", @@ -11290,14 +12476,39 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "pallet-bridge-relayers" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2faead05455a965a0a0ec69ffa779933479b599e40bda809c0aa1efa72a39281" +dependencies = [ + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-relayers 0.18.0", + "bp-runtime 0.18.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-bridge-grandpa 0.18.0", + "pallet-bridge-messages 0.18.0", + "pallet-bridge-parachains 0.18.0", + "pallet-transaction-payment 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "pallet-broker" version = "0.6.0" dependencies = [ "bitvec", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "pretty_assertions", @@ -11310,17 +12521,36 @@ dependencies = [ "sp-tracing 16.0.0", ] +[[package]] +name = "pallet-broker" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3043c90106d88cb93fcf0d9b6d19418f11f44cc2b11873414aec3b46044a24ea" +dependencies = [ + "bitvec", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-child-bounties" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-bounties", - "pallet-treasury", + "pallet-balances 28.0.0", + "pallet-bounties 27.0.0", + "pallet-treasury 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11328,40 +12558,79 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-child-bounties" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f3bc38ae6584b5f57e4de3e49e5184bfc0f20692829530ae1465ffe04e09e7" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-bounties 37.0.0", + "pallet-treasury 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-collator-selection" version = "9.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-session", - "pallet-timestamp", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "rand", "scale-info", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", ] +[[package]] +name = "pallet-collator-selection" +version = "19.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658798d70c9054165169f6a6a96cfa9d6a5e7d24a524bc19825bf17fcbc5cc5a" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "pallet-balances 39.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "rand", + "scale-info", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-collective" version = "28.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11369,13 +12638,30 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-collective" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e149f1aefd444c9a1da6ec5a94bc8a7671d7a33078f85dd19ae5b06e3438e60" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-collective-content" version = "0.6.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11383,6 +12669,21 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-collective-content" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a6a5cbe781d9c711be74855ba32ef138f3779d6c54240c08e6d1b4bbba4d1d" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-contracts" version = "27.0.0" @@ -11391,21 +12692,21 @@ dependencies = [ "assert_matches", "bitflags 1.3.2", "environmental", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-assets", - "pallet-balances", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", "pallet-contracts-fixtures", - "pallet-contracts-proc-macro", - "pallet-contracts-uapi", - "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", - "pallet-proxy", - "pallet-timestamp", - "pallet-utility", + "pallet-contracts-proc-macro 18.0.0", + "pallet-contracts-uapi 5.0.0", + "pallet-insecure-randomness-collective-flip 16.0.0", + "pallet-message-queue 31.0.0", + "pallet-proxy 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "paste", "pretty_assertions", @@ -11421,19 +12722,52 @@ dependencies = [ "sp-runtime 31.0.1", "sp-std 14.0.0", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", "wasm-instrument", "wasmi 0.32.3", "wat", ] +[[package]] +name = "pallet-contracts" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df77077745d891c822b4275f273f336077a97e69e62a30134776aa721c96fee" +dependencies = [ + "bitflags 1.3.2", + "environmental", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-balances 39.0.0", + "pallet-contracts-proc-macro 23.0.1", + "pallet-contracts-uapi 12.0.0", + "parity-scale-codec", + "paste", + "rand", + "scale-info", + "serde", + "smallvec", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "wasm-instrument", + "wasmi 0.32.3", +] + [[package]] name = "pallet-contracts-fixtures" version = "1.0.0" dependencies = [ "anyhow", - "frame-system", + "frame-system 28.0.0", "parity-wasm", "sp-runtime 31.0.1", "tempfile", @@ -11446,24 +12780,24 @@ name = "pallet-contracts-mock-network" version = "3.0.0" dependencies = [ "assert_matches", - "frame-support", - "frame-system", - "pallet-assets", - "pallet-balances", - "pallet-contracts", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-contracts 27.0.0", "pallet-contracts-fixtures", - "pallet-contracts-proc-macro", - "pallet-contracts-uapi", - "pallet-insecure-randomness-collective-flip", - "pallet-message-queue", - "pallet-proxy", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "pallet-contracts-proc-macro 18.0.0", + "pallet-contracts-uapi 5.0.0", + "pallet-insecure-randomness-collective-flip 16.0.0", + "pallet-message-queue 31.0.0", + "pallet-proxy 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "pretty_assertions", "scale-info", "sp-api 26.0.0", @@ -11472,10 +12806,46 @@ dependencies = [ "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "xcm-simulator 7.0.0", +] + +[[package]] +name = "pallet-contracts-mock-network" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "309666537ed001c61a99f59fa7b98680f4a6e4e361ed3bc64f7b0237da3e3e06" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-assets 40.0.0", + "pallet-balances 39.0.0", + "pallet-contracts 38.0.0", + "pallet-contracts-proc-macro 23.0.1", + "pallet-contracts-uapi 12.0.0", + "pallet-insecure-randomness-collective-flip 26.0.0", + "pallet-message-queue 41.0.1", + "pallet-proxy 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-utility 38.0.0", + "pallet-xcm 17.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-parachains 17.0.1", + "scale-info", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "xcm-simulator 17.0.0", ] [[package]] @@ -11487,6 +12857,17 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "pallet-contracts-proc-macro" +version = "23.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94226cbd48516b7c310eb5dae8d50798c1ce73a7421dc0977c55b7fc2237a283" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "pallet-contracts-uapi" version = "5.0.0" @@ -11497,16 +12878,29 @@ dependencies = [ "scale-info", ] +[[package]] +name = "pallet-contracts-uapi" +version = "12.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f74b000590c33fadea48585d3ae3f4b7867e99f0a524c444d5779f36b9a1b6" +dependencies = [ + "bitflags 1.3.2", + "parity-scale-codec", + "paste", + "polkavm-derive 0.9.1", + "scale-info", +] + [[package]] name = "pallet-conviction-voting" version = "28.0.0" dependencies = [ "assert_matches", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-scheduler", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-scheduler 29.0.0", "parity-scale-codec", "scale-info", "serde", @@ -11515,15 +12909,32 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-conviction-voting" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "999c242491b74395b8c5409ef644e782fe426d87ae36ad92240ffbf21ff0a76e" +dependencies = [ + "assert_matches", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-core-fellowship" version = "12.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-ranked-collective", + "pallet-ranked-collective 28.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic 23.0.0", @@ -11532,12 +12943,31 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-core-fellowship" +version = "22.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d063b41df454bd128d6fefd5800af8a71ac383c9dd6f20096832537efc110a8a" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-ranked-collective 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-default-config-example" version = "10.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -11549,36 +12979,52 @@ dependencies = [ name = "pallet-delegated-staking" version = "1.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-nomination-pools", - "pallet-staking", + "pallet-balances 28.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] +[[package]] +name = "pallet-delegated-staking" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "117f003a97f980514c6db25a50c22aaec2a9ccb5664b3cb32f52fb990e0b0c12" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-democracy" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-preimage", - "pallet-scheduler", + "pallet-balances 28.0.0", + "pallet-preimage 28.0.0", + "pallet-scheduler 29.0.0", "parity-scale-codec", "scale-info", "serde", @@ -11587,14 +13033,32 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-democracy" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6d1dc655f50b7c65bb2fb14086608ba11af02ef2936546f7a67db980ec1f133" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-dev-mode" version = "10.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11602,29 +13066,45 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-dev-mode" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae1d8050c09c5e003d502c1addc7fdfbde21a854bd57787e94447078032710c8" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-election-provider-e2e-test" version = "1.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-bags-list", - "pallet-balances", - "pallet-election-provider-multi-phase", - "pallet-nomination-pools", - "pallet-session", - "pallet-staking", - "pallet-timestamp", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-election-provider-multi-phase 27.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "parking_lot 0.12.3", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -11633,13 +13113,13 @@ dependencies = [ name = "pallet-election-provider-multi-phase" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-election-provider-support-benchmarking", + "pallet-balances 28.0.0", + "pallet-election-provider-support-benchmarking 27.0.0", "parity-scale-codec", "parking_lot 0.12.3", "rand", @@ -11647,59 +13127,115 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", "strum 0.26.3", ] [[package]] -name = "pallet-election-provider-support-benchmarking" -version = "27.0.0" +name = "pallet-election-provider-multi-phase" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f9ad5ae0c13ba3727183dadf1825b6b7b0b0598ed5c366f8697e13fd540f7d" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-system", + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-election-provider-support-benchmarking 37.0.0", "parity-scale-codec", - "sp-npos-elections", - "sp-runtime 31.0.1", -] + "rand", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-npos-elections 34.0.0", + "sp-runtime 39.0.2", + "strum 0.26.3", +] + +[[package]] +name = "pallet-election-provider-support-benchmarking" +version = "27.0.0" +dependencies = [ + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-system 28.0.0", + "parity-scale-codec", + "sp-npos-elections 26.0.0", + "sp-runtime 31.0.1", +] + +[[package]] +name = "pallet-election-provider-support-benchmarking" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4111d0d27545c260c9dd0d6fc504961db59c1ec4b42e1bcdc28ebd478895c22" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "sp-npos-elections 34.0.0", + "sp-runtime 39.0.2", +] [[package]] name = "pallet-elections-phragmen" version = "29.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] +[[package]] +name = "pallet-elections-phragmen" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "705c66d6c231340c6d085a0df0319a6ce42a150f248171e88e389ab1e3ce20f5" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-npos-elections 34.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-example-authorization-tx-extension" version = "1.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "pallet-verify-signature", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", ] @@ -11707,11 +13243,11 @@ dependencies = [ name = "pallet-example-basic" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11724,7 +13260,7 @@ name = "pallet-example-frame-crate" version = "0.0.1" dependencies = [ "parity-scale-codec", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", ] @@ -11732,11 +13268,11 @@ dependencies = [ name = "pallet-example-kitchensink" version = "4.0.0-dev" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11748,11 +13284,11 @@ dependencies = [ name = "pallet-example-mbm" version = "0.1.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-migrations", + "pallet-migrations 1.0.0", "parity-scale-codec", "scale-info", "sp-io 30.0.0", @@ -11762,8 +13298,8 @@ dependencies = [ name = "pallet-example-offchain-worker" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "lite-json", "log", "parity-scale-codec", @@ -11779,12 +13315,12 @@ name = "pallet-example-single-block-migrations" version = "0.0.1" dependencies = [ "docify", - "frame-executive", - "frame-support", - "frame-system", - "frame-try-runtime", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-try-runtime 0.34.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11797,9 +13333,9 @@ dependencies = [ name = "pallet-example-split" version = "10.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -11811,9 +13347,9 @@ dependencies = [ name = "pallet-example-tasks" version = "1.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -11827,7 +13363,7 @@ name = "pallet-examples" version = "4.0.0-dev" dependencies = [ "pallet-default-config-example", - "pallet-dev-mode", + "pallet-dev-mode 10.0.0", "pallet-example-authorization-tx-extension", "pallet-example-basic", "pallet-example-frame-crate", @@ -11843,70 +13379,131 @@ name = "pallet-fast-unstake" version = "27.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-staking", + "pallet-balances 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] +[[package]] +name = "pallet-fast-unstake" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0ee60e8ef10b3936f2700bd61fa45dcc190c61124becc63bed787addcfa0d20" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-glutton" version = "14.0.0" dependencies = [ "blake2 0.10.6", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-glutton" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1c79ab340890f6ab088a638c350ac1173a1b2a79c18004787523032025582b4" +dependencies = [ + "blake2 0.10.6", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-grandpa" version = "28.0.0" dependencies = [ "finality-grandpa", - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", - "log", - "pallet-authorship", - "pallet-balances", - "pallet-offences", - "pallet-session", - "pallet-staking", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "log", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-offences 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-grandpa" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d3a570a4aac3173ea46b600408183ca2bcfdaadc077f802f11e6055963e2449" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-consensus-grandpa 21.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", ] [[package]] @@ -11914,11 +13511,11 @@ name = "pallet-identity" version = "29.0.0" dependencies = [ "enumflags2", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11927,47 +13524,101 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-identity" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a4288548de9a755e39fcb82ffb9024b6bb1ba0f582464a44423038dd7a892e" +dependencies = [ + "enumflags2", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-im-online" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-authorship", - "pallet-session", + "pallet-authorship 28.0.0", + "pallet-session 28.0.0", "parity-scale-codec", "scale-info", "sp-application-crypto 30.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-im-online" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd95270cf029d16cb40fe6bd9f8ab9c78cd966666dccbca4d8bfec35c5bba5" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-application-crypto 38.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", ] [[package]] name = "pallet-indices" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-indices" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e4b97de630427a39d50c01c9e81ab8f029a00e56321823958b39b438f7b940" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-keyring 39.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-insecure-randomness-collective-flip" version = "16.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "safe-mix", "scale-info", @@ -11976,15 +13627,29 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-insecure-randomness-collective-flip" +version = "26.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce7ad80675d78bd38a7a66ecbbf2d218dd32955e97f8e301d0afe6c87b0f251" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "safe-mix", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-lottery" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", "frame-support-test", - "frame-system", - "pallet-balances", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -11992,13 +13657,27 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-lottery" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae0920ee53cf7b0665cfb6d275759ae0537dc3850ec78da5f118d814c99d3562" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-membership" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -12007,14 +13686,31 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-membership" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1868b5dca4bbfd1f4a222cbb80735a5197020712a71577b496bbb7e19aaa5394" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-message-queue" version = "31.0.0" dependencies = [ "environmental", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "rand", @@ -12030,23 +13726,43 @@ dependencies = [ "sp-weights 27.0.0", ] +[[package]] +name = "pallet-message-queue" +version = "41.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0faa48b29bf5a178580c164ef00de87319a37da7547a9cd6472dfd160092811a" +dependencies = [ + "environmental", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", +] + [[package]] name = "pallet-migrations" version = "1.0.0" dependencies = [ "cfg-if", "docify", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", "parity-scale-codec", "pretty_assertions", "scale-info", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", @@ -12054,12 +13770,30 @@ dependencies = [ "sp-version 29.0.0", ] +[[package]] +name = "pallet-migrations" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b417fc975636bce94e7c6d707e42d0706d67dfa513e72f5946918e1044beef1" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-minimal-template" version = "0.0.0" dependencies = [ "parity-scale-codec", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "scale-info", ] @@ -12067,9 +13801,9 @@ dependencies = [ name = "pallet-mixnet" version = "0.4.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -12077,51 +13811,105 @@ dependencies = [ "sp-application-crypto 30.0.0", "sp-arithmetic 23.0.0", "sp-io 30.0.0", - "sp-mixnet", + "sp-mixnet 0.4.0", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-mixnet" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf3fa2b7f759a47f698a403ab40c54bc8935e2969387947224cbdb4e2bc8a28a" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-application-crypto 38.0.0", + "sp-arithmetic 26.0.0", + "sp-io 38.0.0", + "sp-mixnet 0.12.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-mmr" version = "27.0.0" dependencies = [ "array-bytes", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "itertools 0.11.0", "log", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-mmr-primitives", + "sp-mmr-primitives 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", ] +[[package]] +name = "pallet-mmr" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6932dfb85f77a57c2d1fdc28a7b3a59ffe23efd8d5bb02dc3039d91347e4a3b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-mmr-primitives 34.1.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-multisig" version = "28.0.0" dependencies = [ "log", - "pallet-balances", + "pallet-balances 28.0.0", + "parity-scale-codec", + "polkadot-sdk-frame 0.1.0", + "scale-info", +] + +[[package]] +name = "pallet-multisig" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e5099c9a4442efcc1568d88ca1d22d624e81ab96358f99f616c67fbd82532d2" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", "parity-scale-codec", - "polkadot-sdk-frame", "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", ] [[package]] name = "pallet-nft-fractionalization" version = "10.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-assets", - "pallet-balances", - "pallet-nfts", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-nfts 22.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12130,16 +13918,33 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "pallet-nft-fractionalization" +version = "21.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168792cf95a32fa3baf9b874efec82a45124da0a79cee1ae3c98a823e6841959" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-assets 40.0.0", + "pallet-nfts 32.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-nfts" version = "22.0.0" dependencies = [ "enumflags2", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12148,23 +13953,52 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-nfts" +version = "32.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59e2aad461a0849d7f0471576eeb1fe3151795bcf2ec9e15eca5cca5b9d743b2" +dependencies = [ + "enumflags2", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-nfts-runtime-api" version = "14.0.0" dependencies = [ - "pallet-nfts", + "pallet-nfts 22.0.0", "parity-scale-codec", "sp-api 26.0.0", ] +[[package]] +name = "pallet-nfts-runtime-api" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a1f50c217e19dc50ff586a71eb5915df6a05bc0b25564ea20674c8cd182c1f" +dependencies = [ + "pallet-nfts 32.0.0", + "parity-scale-codec", + "sp-api 34.0.0", +] + [[package]] name = "pallet-nis" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic 23.0.0", @@ -12173,12 +14007,28 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-nis" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac349e119880b7df1a7c4c36d919b33a498d0e9548af3c237365c654ae0c73d" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-node-authorization" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -12187,56 +14037,112 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-node-authorization" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39ec3133be9e767b8feafbb26edd805824faa59956da008d2dc7fcf4b4720e56" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-nomination-pools" version = "25.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", ] +[[package]] +name = "pallet-nomination-pools" +version = "35.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c42906923f9f2b65b22f1211136b57c6878296ba6f6228a075c4442cc1fc1659" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", + "sp-tracing 17.0.1", +] + [[package]] name = "pallet-nomination-pools-benchmarking" version = "26.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", - "pallet-bags-list", - "pallet-balances", - "pallet-delegated-staking", - "pallet-nomination-pools", - "pallet-staking", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-delegated-staking 1.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-runtime-interface 24.0.0", - "sp-staking", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-nomination-pools-benchmarking" +version = "36.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d2eaca0349bcda923343226b8b64d25a80b67e0a1ebaaa5b0ab1e1b3b225bc" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-bags-list 37.0.0", + "pallet-delegated-staking 5.0.0", + "pallet-nomination-pools 35.0.0", + "pallet-staking 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-runtime-interface 28.0.0", + "sp-staking 36.0.0", ] [[package]] name = "pallet-nomination-pools-fuzzer" version = "2.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "honggfuzz", "log", - "pallet-nomination-pools", + "pallet-nomination-pools 25.0.0", "rand", "sp-io 30.0.0", "sp-runtime 31.0.1", @@ -12247,32 +14153,43 @@ dependencies = [ name = "pallet-nomination-pools-runtime-api" version = "23.0.0" dependencies = [ - "pallet-nomination-pools", + "pallet-nomination-pools 25.0.0", "parity-scale-codec", "sp-api 26.0.0", ] +[[package]] +name = "pallet-nomination-pools-runtime-api" +version = "33.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9e1cb89cc2e6df06ce274a7fc814e5e688aad04c43902a10191fa3d2a56a96" +dependencies = [ + "pallet-nomination-pools 35.0.0", + "parity-scale-codec", + "sp-api 34.0.0", +] + [[package]] name = "pallet-nomination-pools-test-delegate-stake" version = "1.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-bags-list", - "pallet-balances", - "pallet-delegated-staking", - "pallet-nomination-pools", - "pallet-staking", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-delegated-staking 1.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -12281,22 +14198,22 @@ dependencies = [ name = "pallet-nomination-pools-test-transfer-stake" version = "1.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-bags-list", - "pallet-balances", - "pallet-nomination-pools", - "pallet-staking", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -12305,53 +14222,94 @@ dependencies = [ name = "pallet-offences" version = "27.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "serde", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-offences" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c4379cf853465696c1c5c03e7e8ce80aeaca0a6139d698abe9ecb3223fd732a" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", ] [[package]] name = "pallet-offences-benchmarking" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", - "log", - "pallet-babe", - "pallet-balances", - "pallet-grandpa", - "pallet-im-online", - "pallet-offences", - "pallet-session", - "pallet-staking", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "log", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-grandpa 28.0.0", + "pallet-im-online 27.0.0", + "pallet-offences 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", ] [[package]] -name = "pallet-paged-list" +name = "pallet-offences-benchmarking" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69aa1b24cdffc3fa8c89cdea32c83f1bf9c1c82a87fa00e57ae4be8e85f5e24f" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-babe 38.0.0", + "pallet-balances 39.0.0", + "pallet-grandpa 38.0.0", + "pallet-im-online 37.0.0", + "pallet-offences 37.0.0", + "pallet-session 38.0.0", + "pallet-staking 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + +[[package]] +name = "pallet-paged-list" version = "0.6.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12360,14 +14318,32 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-paged-list" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8e099fb116068836b17ca4232dc52f762b69dc8cd4e33f509372d958de278b0" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-metadata-ir 0.7.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-paged-list-fuzzer" version = "0.1.0" dependencies = [ "arbitrary", - "frame-support", + "frame-support 28.0.0", "honggfuzz", - "pallet-paged-list", + "pallet-paged-list 0.6.0", "sp-io 30.0.0", ] @@ -12376,7 +14352,7 @@ name = "pallet-parachain-template" version = "0.0.0" dependencies = [ "parity-scale-codec", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", ] @@ -12385,10 +14361,10 @@ name = "pallet-parameters" version = "0.1.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "pallet-example-basic", "parity-scale-codec", "paste", @@ -12399,15 +14375,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-parameters" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9aba424d55e17b2a2bec766a41586eab878137704d4803c04bebd6a4743db7b" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "paste", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-preimage" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12415,24 +14409,56 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-preimage" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "407828bc48c6193ac076fdf909b2fadcaaecd65f42b0b0a04afe22fe8e563834" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-proxy" version = "28.0.0" dependencies = [ - "pallet-balances", - "pallet-utility", + "pallet-balances 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", ] +[[package]] +name = "pallet-proxy" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d39df395f0dbcf07dafe842916adea3266a87ce36ed87b5132184b6bcd746393" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-ranked-collective" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", "parity-scale-codec", @@ -12443,14 +14469,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-ranked-collective" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2b38708feaed202debf1ac6beffaa5e20c99a9825c5ca0991753c2d4eaaf3ac" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-recovery" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12458,18 +14503,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-recovery" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406a116aa6d05f88f3c10d79ff89cf577323680a48abd8e5550efb47317e67fa" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-referenda" version = "28.0.0" dependencies = [ "assert_matches", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-preimage", - "pallet-scheduler", + "pallet-balances 28.0.0", + "pallet-preimage 28.0.0", + "pallet-scheduler 29.0.0", "parity-scale-codec", "scale-info", "serde", @@ -12479,13 +14539,31 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-referenda" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3008c20531d1730c9b457ae77ecf0e3c9b07aaf8c4f5d798d61ef6f0b9e2d4b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-arithmetic 26.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-remark" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "serde", @@ -12494,6 +14572,23 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-remark" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e8cae0e20888065ec73dda417325c6ecabf797f4002329484b59c25ecc34d4" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-revive" version = "0.1.0" @@ -12501,34 +14596,34 @@ dependencies = [ "array-bytes", "assert_matches", "bitflags 1.3.2", - "derive_more", + "derive_more 0.99.17", "environmental", - "ethereum-types", - "frame-benchmarking", - "frame-support", - "frame-system", + "ethereum-types 0.15.1", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex", "hex-literal", "impl-trait-for-tuples", - "jsonrpsee 0.24.3", - "log", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-proxy", - "pallet-revive-fixtures", - "pallet-revive-proc-macro", - "pallet-revive-uapi", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-utility", + "jsonrpsee", + "log", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-proxy 28.0.0", + "pallet-revive-fixtures 0.1.0", + "pallet-revive-proc-macro 0.1.0", + "pallet-revive-uapi 0.1.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "paste", "polkavm 0.13.0", "pretty_assertions", "rlp 0.6.1", "scale-info", - "secp256k1", + "secp256k1 0.28.2", "serde", "serde_json", "sp-api 26.0.0", @@ -12540,11 +14635,42 @@ dependencies = [ "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-weights 27.0.0", - "staging-xcm", - "staging-xcm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", "subxt-signer", ] +[[package]] +name = "pallet-revive" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be02c94dcbadd206a910a244ec19b493aac793eed95e23d37d6699547234569f" +dependencies = [ + "bitflags 1.3.2", + "environmental", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-balances 39.0.0", + "pallet-revive-fixtures 0.2.0", + "pallet-revive-proc-macro 0.1.1", + "pallet-revive-uapi 0.1.1", + "parity-scale-codec", + "paste", + "polkavm 0.10.0", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", +] + [[package]] name = "pallet-revive-eth-rpc" version = "0.1.0" @@ -12552,13 +14678,14 @@ dependencies = [ "anyhow", "clap 4.5.13", "env_logger 0.11.3", + "ethabi", "futures", "hex", "hex-literal", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", - "pallet-revive", - "pallet-revive-fixtures", + "pallet-revive 0.1.0", + "pallet-revive-fixtures 0.1.0", "parity-scale-codec", "rlp 0.6.1", "sc-cli", @@ -12566,7 +14693,7 @@ dependencies = [ "sc-rpc-api", "sc-service", "scale-info", - "secp256k1", + "secp256k1 0.28.2", "serde_json", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", @@ -12585,7 +14712,7 @@ name = "pallet-revive-fixtures" version = "0.1.0" dependencies = [ "anyhow", - "frame-system", + "frame-system 28.0.0", "log", "parity-wasm", "polkavm-linker 0.14.0", @@ -12596,28 +14723,43 @@ dependencies = [ "toml 0.8.12", ] +[[package]] +name = "pallet-revive-fixtures" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a38c27f1531f36e5327f3084eb24cf1c9dd46b372e030c0169e843ce363105e" +dependencies = [ + "anyhow", + "frame-system 38.0.0", + "parity-wasm", + "polkavm-linker 0.10.0", + "sp-runtime 39.0.2", + "tempfile", + "toml 0.8.12", +] + [[package]] name = "pallet-revive-mock-network" version = "0.1.0" dependencies = [ "assert_matches", - "frame-support", - "frame-system", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-proxy", - "pallet-revive", - "pallet-revive-fixtures", - "pallet-revive-proc-macro", - "pallet-revive-uapi", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-proxy 28.0.0", + "pallet-revive 0.1.0", + "pallet-revive-fixtures 0.1.0", + "pallet-revive-proc-macro 0.1.0", + "pallet-revive-uapi 0.1.0", + "pallet-timestamp 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "pretty_assertions", "scale-info", "sp-api 26.0.0", @@ -12626,10 +14768,45 @@ dependencies = [ "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "xcm-simulator 7.0.0", +] + +[[package]] +name = "pallet-revive-mock-network" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60e74591d44dbd78db02c8593f5caa75bd61bcc4d63999302150223fb969ae37" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-assets 40.0.0", + "pallet-balances 39.0.0", + "pallet-message-queue 41.0.1", + "pallet-proxy 38.0.0", + "pallet-revive 0.2.0", + "pallet-revive-proc-macro 0.1.1", + "pallet-revive-uapi 0.1.1", + "pallet-timestamp 37.0.0", + "pallet-utility 38.0.0", + "pallet-xcm 17.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-parachains 17.0.1", + "scale-info", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "xcm-simulator 17.0.0", ] [[package]] @@ -12641,6 +14818,17 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "pallet-revive-proc-macro" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cc16d1f7cee6a1ee6e8cd710e16230d59fb4935316c1704cf770e4d2335f8d4" +dependencies = [ + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "pallet-revive-uapi" version = "0.1.0" @@ -12652,33 +14840,62 @@ dependencies = [ "scale-info", ] +[[package]] +name = "pallet-revive-uapi" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecb4686c8415619cc13e43fadef146ffff46424d9b4d037fe4c069de52708aac" +dependencies = [ + "bitflags 1.3.2", + "parity-scale-codec", + "paste", + "polkavm-derive 0.10.0", + "scale-info", +] + [[package]] name = "pallet-root-offences" version = "25.0.0" dependencies = [ - "frame-election-provider-support", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-session", - "pallet-staking", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-std 14.0.0", ] +[[package]] +name = "pallet-root-offences" +version = "35.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b35774b830928daaeeca7196cead7c56eeed952a6616ad6dc5ec068d8c85c81a" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-session 38.0.0", + "pallet-staking 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-root-testing" version = "4.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12686,17 +14903,32 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-root-testing" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95e7c320ac1d381715364cd721e67ab3152ab727f8e4defd3a92e41ebbc880" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-safe-mode" version = "9.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-proxy", - "pallet-utility", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-proxy 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic 23.0.0", @@ -12705,15 +14937,34 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-safe-mode" +version = "19.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d3e67dd4644c168cedbf257ac3dd2527aad81acf4a0d413112197094e549f76" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-balances 39.0.0", + "pallet-proxy 38.0.0", + "pallet-utility 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-salary" version = "13.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-ranked-collective", + "pallet-ranked-collective 28.0.0", "parity-scale-codec", "scale-info", "sp-arithmetic 23.0.0", @@ -12722,14 +14973,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-salary" +version = "23.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0544a71dba06a9a29da0778ba8cb37728c3b9a8377ac9737c4b1bc48c618bc2f" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-ranked-collective 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-sassafras" version = "0.3.5-dev" dependencies = [ "array-bytes", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -12745,11 +15015,11 @@ name = "pallet-scheduler" version = "29.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-preimage", + "pallet-preimage 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12759,13 +15029,31 @@ dependencies = [ "substrate-test-utils", ] +[[package]] +name = "pallet-scheduler" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26899a331e7ab5f7d5966cbf203e1cf5bd99cd110356d7ddcaa7597087cdc0b5" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", +] + [[package]] name = "pallet-scored-pool" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", - "pallet-balances", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12773,69 +15061,135 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-scored-pool" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f84b48bb4702712c902f43931c4077d3a1cb6773c8d8c290d4a6251f6bc2a5c" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-session" version = "28.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-state-machine 0.35.0", "sp-trie 29.0.0", ] +[[package]] +name = "pallet-session" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8474b62b6b7622f891e83d922a589e2ad5be5471f5ca47d45831a797dba0b3f4" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-timestamp 37.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", + "sp-state-machine 0.43.0", + "sp-trie 37.0.0", +] + [[package]] name = "pallet-session-benchmarking" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-session", - "pallet-staking", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "rand", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", +] + +[[package]] +name = "pallet-session-benchmarking" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8aadce7df0fee981721983795919642648b846dab5ab9096f82c2cea781007d0" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-session 38.0.0", + "pallet-staking 38.0.0", + "parity-scale-codec", + "rand", + "sp-runtime 39.0.2", + "sp-session 36.0.0", ] [[package]] name = "pallet-skip-feeless-payment" version = "3.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-skip-feeless-payment" +version = "13.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c2cb0dae13d2c2d2e76373f337d408468f571459df1900cbd7458f21cf6c01" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-society" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", "frame-support-test", - "frame-system", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "rand_chacha", "scale-info", @@ -12846,21 +15200,39 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-society" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1dc69fea8a8de343e71691f009d5fece6ae302ed82b7bb357882b2ea6454143" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "rand_chacha", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-staking" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-authorship", - "pallet-bags-list", - "pallet-balances", - "pallet-session", + "pallet-authorship 28.0.0", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-session 28.0.0", "pallet-staking-reward-curve", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "rand_chacha", "scale-info", @@ -12868,13 +15240,35 @@ dependencies = [ "sp-application-crypto 30.0.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] +[[package]] +name = "pallet-staking" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c870d123f4f053b56af808a4beae1ffc4309a696e829796c26837936c926db3b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-authorship 38.0.0", + "pallet-session 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-application-crypto 38.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", +] + [[package]] name = "pallet-staking-reward-curve" version = "11.0.0" @@ -12894,25 +15288,46 @@ dependencies = [ "sp-arithmetic 23.0.0", ] +[[package]] +name = "pallet-staking-reward-fn" +version = "22.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "988a7ebeacc84d4bdb0b12409681e956ffe35438447d8f8bc78db547cffb6ebc" +dependencies = [ + "log", + "sp-arithmetic 26.0.0", +] + [[package]] name = "pallet-staking-runtime-api" version = "14.0.0" dependencies = [ "parity-scale-codec", "sp-api 26.0.0", - "sp-staking", + "sp-staking 26.0.0", +] + +[[package]] +name = "pallet-staking-runtime-api" +version = "24.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7298559ef3a6b2f5dfbe9a3b8f3d22f2ff9b073c97f4c4853d2b316d973e72d" +dependencies = [ + "parity-scale-codec", + "sp-api 34.0.0", + "sp-staking 36.0.0", ] [[package]] name = "pallet-state-trie-migration" version = "29.0.0" dependencies = [ - "frame-benchmarking", + "frame-benchmarking 28.0.0", "frame-remote-externalities", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "parking_lot 0.12.3", "scale-info", @@ -12927,45 +15342,96 @@ dependencies = [ "zstd 0.12.4", ] +[[package]] +name = "pallet-state-trie-migration" +version = "40.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138c15b4200b9dc4c3e031def6a865a235cdc76ff91ee96fba19ca1787c9dda6" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-statement" version = "10.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", +] + +[[package]] +name = "pallet-statement" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e03e147efa900e75cd106337f36da3d7dcd185bd9e5f5c3df474c08c3c37d16" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-statement-store 18.0.0", +] + +[[package]] +name = "pallet-sudo" +version = "28.0.0" +dependencies = [ + "docify", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 28.0.0", + "sp-io 30.0.0", + "sp-runtime 31.0.1", ] [[package]] name = "pallet-sudo" -version = "28.0.0" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1574fe2aed3d52db4a389b77b53d8c9758257b121e3e7bbe24c4904e11681e0e" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", "parity-scale-codec", "scale-info", - "sp-core 28.0.0", - "sp-io 30.0.0", - "sp-runtime 31.0.1", + "sp-io 38.0.0", + "sp-runtime 39.0.2", ] [[package]] name = "pallet-template" version = "0.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -12978,30 +15444,50 @@ name = "pallet-timestamp" version = "27.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-storage 19.0.0", - "sp-timestamp", + "sp-timestamp 26.0.0", +] + +[[package]] +name = "pallet-timestamp" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9ba9b71bbfd33ae672f23ba7efaeed2755fdac37b8f946cb7474fc37841b7e1" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-storage 21.0.0", + "sp-timestamp 34.0.0", ] [[package]] name = "pallet-tips" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-treasury", + "pallet-balances 28.0.0", + "pallet-treasury 27.0.0", "parity-scale-codec", "scale-info", "serde", @@ -13011,14 +15497,33 @@ dependencies = [ "sp-storage 19.0.0", ] +[[package]] +name = "pallet-tips" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa1d4371a70c309ba11624933f8f5262fe4edad0149c556361d31f26190da936" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-treasury 37.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-transaction-payment" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "serde", @@ -13028,12 +15533,28 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-transaction-payment" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b1aa3498107a30237f941b0f02180db3b79012c3488878ff01a4ac3e8ee04e" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-transaction-payment-rpc" version = "30.0.0" dependencies = [ - "jsonrpsee 0.24.3", - "pallet-transaction-payment-rpc-runtime-api", + "jsonrpsee", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", "parity-scale-codec", "sp-api 26.0.0", "sp-blockchain", @@ -13047,31 +15568,64 @@ dependencies = [ name = "pallet-transaction-payment-rpc-runtime-api" version = "28.0.0" dependencies = [ - "pallet-transaction-payment", + "pallet-transaction-payment 28.0.0", "parity-scale-codec", "sp-api 26.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", ] +[[package]] +name = "pallet-transaction-payment-rpc-runtime-api" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49fdf5ab71e9dbcadcf7139736b6ea6bac8ec4a83985d46cbd130e1eec770e41" +dependencies = [ + "pallet-transaction-payment 38.0.0", + "parity-scale-codec", + "sp-api 34.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", +] + [[package]] name = "pallet-transaction-storage" version = "27.0.0" dependencies = [ "array-bytes", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "serde", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-transaction-storage-proof", + "sp-transaction-storage-proof 26.0.0", +] + +[[package]] +name = "pallet-transaction-storage" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8c337a972a6a796c0a0acc6c03b5e02901c43ad721ce79eb87b45717d75c93b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-transaction-storage-proof 34.0.0", ] [[package]] @@ -13079,13 +15633,13 @@ name = "pallet-treasury" version = "27.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-balances", - "pallet-utility", + "pallet-balances 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "serde", @@ -13094,17 +15648,36 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-treasury" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98bfdd3bb9b58fb010bcd419ff5bf940817a8e404cdbf7886a53ac730f5dda2b" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-tx-pause" version = "9.0.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-proxy", - "pallet-utility", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-proxy 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -13112,15 +15685,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-tx-pause" +version = "19.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cee153f5be5efc84ebd53aa581e5361cde17dc3669ef80d8ad327f4041d89ebe" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-balances 39.0.0", + "pallet-proxy 38.0.0", + "pallet-utility 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-uniques" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -13129,17 +15720,32 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "pallet-uniques" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2b13cdaedf2d5bd913a5f6e637cb52b5973d8ed4b8d45e56d921bc4d627006f" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-utility" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-collective", - "pallet-root-testing", - "pallet-timestamp", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-collective 28.0.0", + "pallet-root-testing 4.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -13147,17 +15753,33 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-utility" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fdcade6efc0b66fc7fc4138964802c02d0ffb7380d894e26b9dd5073727d2b3" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-verify-signature" version = "1.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-collective", - "pallet-root-testing", - "pallet-timestamp", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-collective 28.0.0", + "pallet-root-testing 4.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -13170,11 +15792,11 @@ dependencies = [ name = "pallet-vesting" version = "28.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "sp-core 28.0.0", @@ -13182,15 +15804,30 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-vesting" +version = "38.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "807df2ef13ab6bf940879352c3013bfa00b670458b4c125c2f60e5753f68e3d5" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-whitelist" version = "27.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-preimage", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-preimage 28.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", @@ -13199,88 +15836,169 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "pallet-whitelist" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ef17df925290865cf37096dd0cb76f787df11805bba01b1d0ca3e106d06280b" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "pallet-xcm" version = "7.0.0" dependencies = [ "bounded-collections", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-assets", - "pallet-balances", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-parachains", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "serde", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "tracing", - "xcm-runtime-apis", + "xcm-runtime-apis 0.1.0", +] + +[[package]] +name = "pallet-xcm" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b1760b6589e53f4ad82216c72c0e38fcb4df149c37224ab3301dc240c85d1d4" +dependencies = [ + "bounded-collections", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "xcm-runtime-apis 0.4.0", ] [[package]] name = "pallet-xcm-benchmarks" version = "7.0.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-assets", - "pallet-balances", - "pallet-xcm", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-primitives", - "polkadot-runtime-common", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "pallet-xcm-benchmarks" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da423463933b42f4a4c74175f9e9295a439de26719579b894ce533926665e4a" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "pallet-xcm-bridge-hub" version = "0.2.0" dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-runtime", - "bp-xcm-bridge-hub", - "frame-support", - "frame-system", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-runtime 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-bridge-messages", - "pallet-xcm-bridge-hub-router", + "pallet-balances 28.0.0", + "pallet-bridge-messages 0.7.0", + "pallet-xcm-bridge-hub-router 0.5.0", "parity-scale-codec", - "polkadot-parachain-primitives", + "polkadot-parachain-primitives 6.0.0", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "pallet-xcm-bridge-hub" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f9670065b7cba92771060a4a3925b6650ff67611443ccfccd5aa356f7d5aac" +dependencies = [ + "bp-messages 0.18.0", + "bp-runtime 0.18.0", + "bp-xcm-bridge-hub 0.4.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-bridge-messages 0.18.0", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "pallet-xcm-bridge-hub-router" version = "0.5.0" dependencies = [ - "bp-xcm-bridge-hub-router", - "frame-benchmarking", - "frame-support", - "frame-system", + "bp-xcm-bridge-hub-router 0.6.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", "parity-scale-codec", "scale-info", @@ -13288,8 +16006,28 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", +] + +[[package]] +name = "pallet-xcm-bridge-hub-router" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3b5347c826b721098ef39afb0d750e621c77538044fc1e865af1a8747824fdf" +dependencies = [ + "bp-xcm-bridge-hub-router 0.14.1", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", ] [[package]] @@ -13300,11 +16038,11 @@ dependencies = [ "color-print", "docify", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parachain-template-runtime", "parity-scale-codec", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "sc-tracing", "serde", "serde_json", @@ -13315,46 +16053,77 @@ dependencies = [ name = "parachain-template-runtime" version = "0.0.0" dependencies = [ - "cumulus-pallet-parachain-system", + "cumulus-pallet-parachain-system 0.7.0", "docify", "hex-literal", "log", "pallet-parachain-template", "parity-scale-codec", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "scale-info", "serde_json", "smallvec", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] name = "parachains-common" version = "7.0.0" dependencies = [ - "cumulus-primitives-core", - "cumulus-primitives-utility", - "frame-support", - "frame-system", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-utility 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-xcm", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "scale-info", - "sp-consensus-aura", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", +] + +[[package]] +name = "parachains-common" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9460a69f409be27c62161d8b4d36ffc32735d09a4f9097f9c789db0cca7196c" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "cumulus-primitives-utility 0.17.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-asset-tx-payment 38.0.0", + "pallet-assets 40.0.0", + "pallet-authorship 38.0.0", + "pallet-balances 39.0.0", + "pallet-collator-selection 19.0.0", + "pallet-message-queue 41.0.1", + "pallet-xcm 17.0.0", + "parity-scale-codec", + "polkadot-primitives 16.0.0", + "scale-info", + "sp-consensus-aura 0.40.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "staging-parachain-info 0.17.0", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", + "substrate-wasm-builder 24.0.1", ] [[package]] @@ -13363,7 +16132,7 @@ version = "0.1.0" dependencies = [ "async-std", "async-trait", - "bp-polkadot-core", + "bp-polkadot-core 0.7.0", "futures", "log", "parity-scale-codec", @@ -13376,30 +16145,61 @@ dependencies = [ name = "parachains-runtimes-test-utils" version = "7.0.0" dependencies = [ - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", - "cumulus-test-relay-sproof-builder", - "frame-support", - "frame-system", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", + "cumulus-test-relay-sproof-builder 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex-literal", - "pallet-balances", - "pallet-collator-selection", - "pallet-session", - "pallet-timestamp", - "pallet-xcm", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "sp-consensus-aura", + "polkadot-parachain-primitives 6.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", +] + +[[package]] +name = "parachains-runtimes-test-utils" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "287d2db0a2d19466caa579a69f021bfdc6fa352f382c8395dade58d1d0c6adfe" +dependencies = [ + "cumulus-pallet-parachain-system 0.17.1", + "cumulus-pallet-xcmp-queue 0.17.0", + "cumulus-primitives-core 0.16.0", + "cumulus-primitives-parachain-inherent 0.16.0", + "cumulus-test-relay-sproof-builder 0.16.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-balances 39.0.0", + "pallet-collator-selection 19.0.0", + "pallet-session 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-xcm 17.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "sp-consensus-aura 0.40.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-tracing 17.0.1", + "staging-parachain-info 0.17.0", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", + "substrate-wasm-builder 24.0.1", ] [[package]] @@ -13468,6 +16268,35 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "parity-util-mem" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d32c34f4f5ca7f9196001c0aba5a1f9a5a12382c8944b8b0f90233282d1e8f8" +dependencies = [ + "cfg-if", + "ethereum-types 0.14.1", + "hashbrown 0.12.3", + "impl-trait-for-tuples", + "lru 0.8.1", + "parity-util-mem-derive", + "parking_lot 0.12.3", + "primitive-types 0.12.2", + "smallvec", + "winapi", +] + +[[package]] +name = "parity-util-mem-derive" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f557c32c6d268a07c921471619c0295f5efad3a0e76d4f97a05c091a51d110b2" +dependencies = [ + "proc-macro2 1.0.86", + "syn 1.0.109", + "synstructure 0.12.6", +] + [[package]] name = "parity-wasm" version = "0.45.0" @@ -13558,6 +16387,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ "digest 0.10.7", + "hmac 0.12.1", "password-hash", ] @@ -13590,211 +16420,211 @@ dependencies = [ name = "penpal-emulated-chain" version = "0.0.0" dependencies = [ - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "penpal-runtime", "sp-core 28.0.0", - "sp-keyring", - "staging-xcm", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", ] [[package]] name = "penpal-runtime" version = "0.14.0" dependencies = [ - "assets-common", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "assets-common 0.7.0", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-asset-conversion", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-session", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-common", + "pallet-asset-conversion 10.0.0", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-session 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", "primitive-types 0.12.2", "scale-info", "smallvec", - "snowbridge-router-primitives", + "snowbridge-router-primitives 0.9.0", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "people-rococo-emulated-chain" version = "0.1.0" dependencies = [ - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "people-rococo-runtime", "sp-core 28.0.0", - "testnet-parachains-constants", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "people-rococo-integration-tests" version = "0.1.0" dependencies = [ - "asset-test-utils", + "asset-test-utils 7.0.0", "emulated-integration-tests-common", - "frame-support", - "pallet-balances", - "pallet-identity", - "pallet-message-queue", - "parachains-common", - "parity-scale-codec", - "polkadot-runtime-common", - "rococo-runtime-constants", + "frame-support 28.0.0", + "pallet-balances 28.0.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "rococo-system-emulated-network", "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", ] [[package]] name = "people-rococo-runtime" version = "0.1.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", "enumflags2", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-identity", - "pallet-message-queue", - "pallet-migrations", - "pallet-multisig", - "pallet-proxy", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", - "rococo-runtime-constants", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "pallet-migrations 1.0.0", + "pallet-multisig 28.0.0", + "pallet-proxy 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", + "rococo-runtime-constants 7.0.0", "scale-info", "serde", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "people-westend-emulated-chain" version = "0.1.0" dependencies = [ - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "emulated-integration-tests-common", - "frame-support", - "parachains-common", + "frame-support 28.0.0", + "parachains-common 7.0.0", "people-westend-runtime", "sp-core 28.0.0", - "testnet-parachains-constants", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "people-westend-integration-tests" version = "0.1.0" dependencies = [ - "asset-test-utils", + "asset-test-utils 7.0.0", "emulated-integration-tests-common", - "frame-support", - "pallet-balances", - "pallet-identity", - "pallet-message-queue", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-runtime-common", - "sp-runtime 31.0.1", - "staging-xcm", - "staging-xcm-executor", - "westend-runtime-constants", + "frame-support 28.0.0", + "pallet-balances 28.0.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-runtime-common 7.0.0", + "sp-runtime 31.0.1", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", + "westend-runtime-constants 7.0.0", "westend-system-emulated-network", ] @@ -13802,67 +16632,67 @@ dependencies = [ name = "people-westend-runtime" version = "0.1.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", "enumflags2", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-aura", - "pallet-authorship", - "pallet-balances", - "pallet-collator-selection", - "pallet-identity", - "pallet-message-queue", - "pallet-migrations", - "pallet-multisig", - "pallet-proxy", - "pallet-session", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-identity 29.0.0", + "pallet-message-queue 31.0.0", + "pallet-migrations 1.0.0", + "pallet-multisig 28.0.0", + "pallet-proxy 28.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "serde", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", - "westend-runtime-constants", - "xcm-runtime-apis", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -13927,18 +16757,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.3" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" +checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.3" +version = "1.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" +checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -14015,7 +16845,7 @@ dependencies = [ "color-eyre", "nix 0.28.0", "polkadot-cli", - "polkadot-core-primitives", + "polkadot-core-primitives 7.0.0", "polkadot-node-core-pvf", "polkadot-node-core-pvf-common", "polkadot-node-core-pvf-execute-worker", @@ -14044,7 +16874,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rand", "rand_chacha", @@ -14052,7 +16882,7 @@ dependencies = [ "sc-keystore", "schnorrkel 0.11.4", "sp-application-crypto 30.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-core 28.0.0", "sp-tracing 16.0.0", "tracing-gum", @@ -14072,13 +16902,13 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "rand", "rand_chacha", "sp-application-crypto 30.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "tracing-gum", @@ -14089,7 +16919,7 @@ name = "polkadot-availability-distribution" version = "7.0.0" dependencies = [ "assert_matches", - "derive_more", + "derive_more 0.99.17", "fatality", "futures", "futures-timer", @@ -14100,7 +16930,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand", @@ -14108,7 +16938,7 @@ dependencies = [ "sc-network", "schnellru", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "thiserror", @@ -14132,7 +16962,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand", @@ -14141,7 +16971,7 @@ dependencies = [ "schnellru", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-tracing 16.0.0", "thiserror", "tokio", @@ -14180,7 +17010,7 @@ dependencies = [ "sc-tracing", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-maybe-compressed-blob 11.0.0", "sp-runtime 31.0.1", "substrate-build-script-utils", @@ -14202,14 +17032,14 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rstest", "sc-keystore", "sc-network", "schnellru", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", @@ -14228,6 +17058,18 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "polkadot-core-primitives" +version = "15.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2900d3b857e34c480101618a950c3a4fbcddc8c0d50573d48553376185908b8" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "polkadot-dispute-distribution" version = "7.0.0" @@ -14235,7 +17077,7 @@ dependencies = [ "assert_matches", "async-channel 1.9.0", "async-trait", - "derive_more", + "derive_more 0.99.17", "fatality", "futures", "futures-timer", @@ -14247,13 +17089,13 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sc-keystore", "sc-network", "schnellru", "sp-application-crypto 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "thiserror", @@ -14267,7 +17109,7 @@ dependencies = [ "criterion", "parity-scale-codec", "polkadot-node-primitives", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "quickcheck", "reed-solomon-novelpoly", "sp-core 28.0.0", @@ -14288,18 +17130,18 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "quickcheck", "rand", "rand_chacha", "sc-network", "sc-network-common", "sp-application-crypto 30.0.0", - "sp-authority-discovery", - "sp-consensus-babe", + "sp-authority-discovery 26.0.0", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "tracing-gum", @@ -14324,12 +17166,12 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sc-network", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "thiserror", "tracing-gum", ] @@ -14346,12 +17188,12 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rstest", "schnellru", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-maybe-compressed-blob 11.0.0", "thiserror", "tracing-gum", @@ -14364,7 +17206,7 @@ dependencies = [ "assert_matches", "async-trait", "bitvec", - "derive_more", + "derive_more 0.99.17", "futures", "futures-timer", "itertools 0.11.0", @@ -14379,7 +17221,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand", @@ -14390,10 +17232,10 @@ dependencies = [ "schnorrkel 0.11.4", "sp-application-crypto 30.0.0", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-slots", + "sp-consensus-babe 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", @@ -14422,7 +17264,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand", @@ -14432,10 +17274,10 @@ dependencies = [ "schnorrkel 0.11.4", "sp-application-crypto 30.0.0", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-slots", + "sp-consensus-babe 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", @@ -14462,11 +17304,11 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-tracing 16.0.0", "thiserror", "tracing-gum", @@ -14485,8 +17327,8 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-statement-table", "rstest", @@ -14494,7 +17336,7 @@ dependencies = [ "schnellru", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "thiserror", @@ -14509,7 +17351,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sp-keystore 0.34.0", "thiserror", @@ -14533,13 +17375,13 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rstest", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-maybe-compressed-blob 11.0.0", "tracing-gum", @@ -14557,7 +17399,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-types", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sc-consensus-babe", "sp-blockchain", @@ -14580,7 +17422,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sp-core 28.0.0", "thiserror", "tracing-gum", @@ -14601,13 +17443,13 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sc-keystore", "schnellru", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-tracing 16.0.0", "thiserror", @@ -14623,9 +17465,9 @@ dependencies = [ "futures-timer", "polkadot-node-subsystem", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sp-blockchain", - "sp-inherents", + "sp-inherents 26.0.0", "thiserror", "tracing-gum", ] @@ -14640,7 +17482,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rand", "rstest", @@ -14662,7 +17504,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "rstest", "schnellru", @@ -14689,7 +17531,7 @@ dependencies = [ "libc", "parity-scale-codec", "pin-project", - "polkadot-core-primitives", + "polkadot-core-primitives 7.0.0", "polkadot-node-core-pvf", "polkadot-node-core-pvf-common", "polkadot-node-core-pvf-execute-worker", @@ -14698,8 +17540,8 @@ dependencies = [ "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "procfs", "rand", "rococo-runtime", @@ -14728,12 +17570,12 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "sc-keystore", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "thiserror", @@ -14751,8 +17593,8 @@ dependencies = [ "libc", "nix 0.28.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "sc-executor 0.32.0", "sc-executor-common 0.29.0", "sc-executor-wasmtime 0.29.0", @@ -14778,8 +17620,8 @@ dependencies = [ "parity-scale-codec", "polkadot-node-core-pvf-common", "polkadot-node-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "sp-maybe-compressed-blob 11.0.0", "tracing-gum", ] @@ -14796,7 +17638,7 @@ dependencies = [ "parity-scale-codec", "polkadot-node-core-pvf-common", "polkadot-node-primitives", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "rayon", "rococo-runtime", "sc-executor-common 0.29.0", @@ -14819,13 +17661,13 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-types", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "schnellru", "sp-api 26.0.0", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "tracing-gum", ] @@ -14842,14 +17684,14 @@ dependencies = [ "hyper-util", "log", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-test-service", "prioritized-metered-channel", "prometheus-parse", "sc-cli", "sc-service", "sc-tracing", - "sp-keyring", + "sp-keyring 31.0.0", "substrate-prometheus-endpoint", "substrate-test-utils", "tempfile", @@ -14864,13 +17706,13 @@ dependencies = [ "async-channel 1.9.0", "async-trait", "bitvec", - "derive_more", + "derive_more 0.99.17", "fatality", "futures", "hex", "parity-scale-codec", "polkadot-node-primitives", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "rand", "rand_chacha", "sc-authority-discovery", @@ -14892,14 +17734,14 @@ dependencies = [ "futures-timer", "parity-scale-codec", "polkadot-erasure-coding", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "sc-keystore", "schnorrkel 0.11.4", "serde", "sp-application-crypto 30.0.0", - "sp-consensus-babe", - "sp-consensus-slots", + "sp-consensus-babe 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", "sp-keystore 0.34.0", "sp-maybe-compressed-blob 11.0.0", @@ -14927,13 +17769,13 @@ dependencies = [ "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-client-api", "sc-keystore", "sc-utils", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", ] @@ -14943,13 +17785,13 @@ version = "7.0.0" dependencies = [ "async-trait", "bitvec", - "derive_more", + "derive_more 0.99.17", "fatality", "futures", "orchestra", "polkadot-node-network-protocol", "polkadot-node-primitives", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-statement-table", "sc-client-api", "sc-network", @@ -14957,9 +17799,9 @@ dependencies = [ "sc-transaction-pool-api", "smallvec", "sp-api 26.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-blockchain", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-runtime 31.0.1", "substrate-prometheus-endpoint", "thiserror", @@ -14971,7 +17813,7 @@ version = "7.0.0" dependencies = [ "assert_matches", "async-trait", - "derive_more", + "derive_more 0.99.17", "fatality", "futures", "futures-channel", @@ -14992,7 +17834,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-types", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "prioritized-metered-channel", "rand", @@ -15031,27 +17873,27 @@ dependencies = [ "cumulus-client-consensus-relay-chain", "cumulus-client-parachain-inherent", "cumulus-client-service", - "cumulus-primitives-aura", - "cumulus-primitives-core", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", "cumulus-relay-chain-interface", "docify", - "frame-benchmarking", + "frame-benchmarking 28.0.0", "frame-benchmarking-cli", - "frame-support", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-support 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "futures", "futures-timer", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "nix 0.28.0", - "pallet-transaction-payment", + "pallet-transaction-payment 28.0.0", "pallet-transaction-payment-rpc", - "pallet-transaction-payment-rpc-runtime-api", - "parachains-common", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "polkadot-cli", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-basic-authorship", "sc-chain-spec", "sc-cli", @@ -15070,16 +17912,16 @@ dependencies = [ "serde", "serde_json", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-session", - "sp-timestamp", - "sp-transaction-pool", + "sp-session 27.0.0", + "sp-timestamp 26.0.0", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", "sp-weights 27.0.0", "substrate-frame-rpc-system", @@ -15105,7 +17947,7 @@ dependencies = [ "polkadot-node-primitives", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-types", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "prioritized-metered-channel", "sc-client-api", @@ -15128,11 +17970,11 @@ dependencies = [ "contracts-rococo-runtime", "coretime-rococo-runtime", "coretime-westend-runtime", - "cumulus-primitives-core", + "cumulus-primitives-core 0.7.0", "glutton-westend-runtime", "hex-literal", "log", - "parachains-common", + "parachains-common 7.0.0", "penpal-runtime", "people-rococo-runtime", "people-westend-runtime", @@ -15144,64 +17986,135 @@ dependencies = [ "serde", "serde_json", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-keyring", - "staging-xcm", + "sp-genesis-builder 0.8.0", + "sp-keyring 31.0.0", + "staging-xcm 7.0.0", "substrate-build-script-utils", ] [[package]] -name = "polkadot-parachain-primitives" -version = "6.0.0" +name = "polkadot-parachain-primitives" +version = "6.0.0" +dependencies = [ + "bounded-collections", + "derive_more 0.99.17", + "parity-scale-codec", + "polkadot-core-primitives 7.0.0", + "scale-info", + "serde", + "sp-core 28.0.0", + "sp-runtime 31.0.1", + "sp-weights 27.0.0", +] + +[[package]] +name = "polkadot-parachain-primitives" +version = "14.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5648a2e8ce1f9a0f8c41c38def670cefd91932cd793468e1a5b0b0b4e4af1" +dependencies = [ + "bounded-collections", + "derive_more 0.99.17", + "parity-scale-codec", + "polkadot-core-primitives 15.0.0", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", +] + +[[package]] +name = "polkadot-primitives" +version = "7.0.0" +dependencies = [ + "bitvec", + "hex-literal", + "log", + "parity-scale-codec", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives-test-helpers", + "scale-info", + "serde", + "sp-api 26.0.0", + "sp-application-crypto 30.0.0", + "sp-arithmetic 23.0.0", + "sp-authority-discovery 26.0.0", + "sp-consensus-slots 0.32.0", + "sp-core 28.0.0", + "sp-inherents 26.0.0", + "sp-io 30.0.0", + "sp-keystore 0.34.0", + "sp-runtime 31.0.1", + "sp-staking 26.0.0", + "sp-std 14.0.0", + "thiserror", +] + +[[package]] +name = "polkadot-primitives" +version = "15.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b57bc055fa389372ec5fc0001b99aeffd50f3fd379280ce572d935189bb58dd8" dependencies = [ - "bounded-collections", - "derive_more", + "bitvec", + "hex-literal", + "log", "parity-scale-codec", - "polkadot-core-primitives", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", "scale-info", "serde", - "sp-core 28.0.0", - "sp-runtime 31.0.1", - "sp-weights 27.0.0", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-arithmetic 26.0.0", + "sp-authority-discovery 34.0.0", + "sp-consensus-slots 0.40.1", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-staking 34.0.0", ] [[package]] name = "polkadot-primitives" -version = "7.0.0" +version = "16.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb20b75d33212150242d39890d7ededab55f1084160c337f15d0eb8ca8c3ad4" dependencies = [ "bitvec", "hex-literal", "log", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives-test-helpers", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", "scale-info", "serde", - "sp-api 26.0.0", - "sp-application-crypto 30.0.0", - "sp-arithmetic 23.0.0", - "sp-authority-discovery", - "sp-consensus-slots", - "sp-core 28.0.0", - "sp-inherents", - "sp-io 30.0.0", - "sp-keystore 0.34.0", - "sp-runtime 31.0.1", - "sp-staking", - "sp-std 14.0.0", - "thiserror", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-arithmetic 26.0.0", + "sp-authority-discovery 34.0.0", + "sp-consensus-slots 0.40.1", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", ] [[package]] name = "polkadot-primitives-test-helpers" version = "1.0.0" dependencies = [ - "polkadot-primitives", + "polkadot-primitives 7.0.0", "rand", "sp-application-crypto 30.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", ] @@ -15209,10 +18122,10 @@ dependencies = [ name = "polkadot-rpc" version = "7.0.0" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "mmr-rpc", "pallet-transaction-payment-rpc", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sc-chain-spec", "sc-client-api", "sc-consensus-babe", @@ -15228,11 +18141,11 @@ dependencies = [ "sc-transaction-pool-api", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "substrate-frame-rpc-system", @@ -15244,53 +18157,103 @@ name = "polkadot-runtime-common" version = "7.0.0" dependencies = [ "bitvec", - "frame-benchmarking", - "frame-election-provider-support", - "frame-support", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-support 28.0.0", "frame-support-test", - "frame-system", + "frame-system 28.0.0", "hex-literal", "impl-trait-for-tuples", "libsecp256k1", "log", - "pallet-asset-rate", - "pallet-authorship", - "pallet-babe", - "pallet-balances", - "pallet-broker", - "pallet-election-provider-multi-phase", - "pallet-fast-unstake", - "pallet-identity", - "pallet-session", - "pallet-staking", - "pallet-staking-reward-fn", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-treasury", - "pallet-vesting", - "parity-scale-codec", - "polkadot-primitives", + "pallet-asset-rate 7.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-election-provider-multi-phase 27.0.0", + "pallet-fast-unstake 27.0.0", + "pallet-identity 29.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", + "pallet-staking-reward-fn 19.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-treasury 27.0.0", + "pallet-vesting 28.0.0", + "parity-scale-codec", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", - "polkadot-runtime-parachains", + "polkadot-runtime-parachains 7.0.0", "rustc-hex", "scale-info", "serde", "serde_derive", "serde_json", - "slot-range-helper", + "slot-range-helper 7.0.0", "sp-api 26.0.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "sp-session 27.0.0", + "sp-staking 26.0.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "static_assertions", +] + +[[package]] +name = "polkadot-runtime-common" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc15154ba5ca55d323fcf7af0f5dcd39d58dcb4dfac3d9b30404840a6d8bbde4" +dependencies = [ + "bitvec", + "frame-benchmarking 38.0.0", + "frame-election-provider-support 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "libsecp256k1", + "log", + "pallet-asset-rate 17.0.0", + "pallet-authorship 38.0.0", + "pallet-balances 39.0.0", + "pallet-broker 0.17.0", + "pallet-election-provider-multi-phase 37.0.0", + "pallet-fast-unstake 37.0.0", + "pallet-identity 38.0.0", + "pallet-session 38.0.0", + "pallet-staking 38.0.0", + "pallet-staking-reward-fn 22.0.0", + "pallet-timestamp 37.0.0", + "pallet-transaction-payment 38.0.0", + "pallet-treasury 37.0.0", + "pallet-vesting 38.0.0", + "parity-scale-codec", + "polkadot-primitives 16.0.0", + "polkadot-runtime-parachains 17.0.1", + "rustc-hex", + "scale-info", + "serde", + "serde_derive", + "slot-range-helper 15.0.0", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-npos-elections 34.0.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", "static_assertions", ] @@ -15299,12 +18262,25 @@ name = "polkadot-runtime-metrics" version = "7.0.0" dependencies = [ "bs58", - "frame-benchmarking", + "frame-benchmarking 28.0.0", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sp-tracing 16.0.0", ] +[[package]] +name = "polkadot-runtime-metrics" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c306f1ace7644a24de860479f92cf8d6467393bb0c9b0777c57e2d42c9d452a" +dependencies = [ + "bs58", + "frame-benchmarking 38.0.0", + "parity-scale-codec", + "polkadot-primitives 16.0.0", + "sp-tracing 17.0.1", +] + [[package]] name = "polkadot-runtime-parachains" version = "7.0.0" @@ -15312,32 +18288,32 @@ dependencies = [ "assert_matches", "bitflags 1.3.2", "bitvec", - "derive_more", - "frame-benchmarking", - "frame-support", + "derive_more 0.99.17", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", "frame-support-test", - "frame-system", + "frame-system 28.0.0", "futures", "hex-literal", "impl-trait-for-tuples", "log", - "pallet-authority-discovery", - "pallet-authorship", - "pallet-babe", - "pallet-balances", - "pallet-broker", - "pallet-message-queue", - "pallet-mmr", - "pallet-session", - "pallet-staking", - "pallet-timestamp", - "pallet-vesting", - "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", + "pallet-authority-discovery 28.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-message-queue 31.0.0", + "pallet-mmr 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-vesting 28.0.0", + "parity-scale-codec", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", - "polkadot-runtime-metrics", + "polkadot-runtime-metrics 7.0.0", "rand", "rand_chacha", "rstest", @@ -15350,41 +18326,90 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-std 14.0.0", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", "static_assertions", "thousands", ] +[[package]] +name = "polkadot-runtime-parachains" +version = "17.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd58e3a17e5df678f5737b018cbfec603af2c93bec56bbb9f8fb8b2b017b54b1" +dependencies = [ + "bitflags 1.3.2", + "bitvec", + "derive_more 0.99.17", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-authority-discovery 38.0.0", + "pallet-authorship 38.0.0", + "pallet-babe 38.0.0", + "pallet-balances 39.0.0", + "pallet-broker 0.17.0", + "pallet-message-queue 41.0.1", + "pallet-mmr 38.0.0", + "pallet-session 38.0.0", + "pallet-staking 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-vesting 38.0.0", + "parity-scale-codec", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-metrics 17.0.0", + "rand", + "rand_chacha", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-staking 36.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", +] + [[package]] name = "polkadot-sdk" version = "0.1.0" dependencies = [ - "asset-test-utils", - "assets-common", - "binary-merkle-tree", - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot", - "bp-polkadot-core", - "bp-relayers", - "bp-runtime", - "bp-test-utils", - "bp-xcm-bridge-hub", - "bp-xcm-bridge-hub-router", - "bridge-hub-common", - "bridge-hub-test-utils", - "bridge-runtime-common", + "asset-test-utils 7.0.0", + "assets-common 0.7.0", + "binary-merkle-tree 13.0.0", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot 0.5.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", + "bp-runtime 0.7.0", + "bp-test-utils 0.7.0", + "bp-xcm-bridge-hub 0.2.0", + "bp-xcm-bridge-hub-router 0.6.0", + "bridge-hub-common 0.1.0", + "bridge-hub-test-utils 0.7.0", + "bridge-runtime-common 0.7.0", "cumulus-client-cli", "cumulus-client-collator", "cumulus-client-consensus-aura", @@ -15395,168 +18420,168 @@ dependencies = [ "cumulus-client-parachain-inherent", "cumulus-client-pov-recovery", "cumulus-client-service", - "cumulus-pallet-aura-ext", - "cumulus-pallet-dmp-queue", - "cumulus-pallet-parachain-system", - "cumulus-pallet-parachain-system-proc-macro", - "cumulus-pallet-session-benchmarking", - "cumulus-pallet-solo-to-para", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-ping", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-timestamp", - "cumulus-primitives-utility", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-dmp-queue 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-parachain-system-proc-macro 0.6.0", + "cumulus-pallet-session-benchmarking 9.0.0", + "cumulus-pallet-solo-to-para 0.7.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-ping 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-timestamp 0.7.0", + "cumulus-primitives-utility 0.7.0", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", "cumulus-relay-chain-rpc-interface", - "cumulus-test-relay-sproof-builder", + "cumulus-test-relay-sproof-builder 0.7.0", "emulated-integration-tests-common", "fork-tree", - "frame-benchmarking", + "frame-benchmarking 28.0.0", "frame-benchmarking-cli", - "frame-benchmarking-pallet-pov", - "frame-election-provider-solution-type", - "frame-election-provider-support", - "frame-executive", - "frame-metadata-hash-extension", + "frame-benchmarking-pallet-pov 18.0.0", + "frame-election-provider-solution-type 13.0.0", + "frame-election-provider-support 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", "frame-remote-externalities", - "frame-support", - "frame-support-procedural", - "frame-support-procedural-tools", - "frame-support-procedural-tools-derive", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-support 28.0.0", + "frame-support-procedural 23.0.0", + "frame-support-procedural-tools 10.0.0", + "frame-support-procedural-tools-derive 11.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "generate-bags", "mmr-gadget", "mmr-rpc", - "pallet-alliance", - "pallet-asset-conversion", - "pallet-asset-conversion-ops", - "pallet-asset-conversion-tx-payment", - "pallet-asset-rate", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-assets-freezer", - "pallet-atomic-swap", - "pallet-aura", - "pallet-authority-discovery", - "pallet-authorship", - "pallet-babe", - "pallet-bags-list", - "pallet-balances", - "pallet-beefy", - "pallet-beefy-mmr", - "pallet-bounties", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-bridge-relayers", - "pallet-broker", - "pallet-child-bounties", - "pallet-collator-selection", - "pallet-collective", - "pallet-collective-content", - "pallet-contracts", - "pallet-contracts-mock-network", - "pallet-contracts-proc-macro", - "pallet-contracts-uapi", - "pallet-conviction-voting", - "pallet-core-fellowship", - "pallet-delegated-staking", - "pallet-democracy", - "pallet-dev-mode", - "pallet-election-provider-multi-phase", - "pallet-election-provider-support-benchmarking", - "pallet-elections-phragmen", - "pallet-fast-unstake", - "pallet-glutton", - "pallet-grandpa", - "pallet-identity", - "pallet-im-online", - "pallet-indices", - "pallet-insecure-randomness-collective-flip", - "pallet-lottery", - "pallet-membership", - "pallet-message-queue", - "pallet-migrations", - "pallet-mixnet", - "pallet-mmr", - "pallet-multisig", - "pallet-nft-fractionalization", - "pallet-nfts", - "pallet-nfts-runtime-api", - "pallet-nis", - "pallet-node-authorization", - "pallet-nomination-pools", - "pallet-nomination-pools-benchmarking", - "pallet-nomination-pools-runtime-api", - "pallet-offences", - "pallet-offences-benchmarking", - "pallet-paged-list", - "pallet-parameters", - "pallet-preimage", - "pallet-proxy", - "pallet-ranked-collective", - "pallet-recovery", - "pallet-referenda", - "pallet-remark", - "pallet-revive", + "pallet-alliance 27.0.0", + "pallet-asset-conversion 10.0.0", + "pallet-asset-conversion-ops 0.1.0", + "pallet-asset-conversion-tx-payment 10.0.0", + "pallet-asset-rate 7.0.0", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-assets-freezer 0.1.0", + "pallet-atomic-swap 28.0.0", + "pallet-aura 27.0.0", + "pallet-authority-discovery 28.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-beefy 28.0.0", + "pallet-beefy-mmr 28.0.0", + "pallet-bounties 27.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-bridge-relayers 0.7.0", + "pallet-broker 0.6.0", + "pallet-child-bounties 27.0.0", + "pallet-collator-selection 9.0.0", + "pallet-collective 28.0.0", + "pallet-collective-content 0.6.0", + "pallet-contracts 27.0.0", + "pallet-contracts-mock-network 3.0.0", + "pallet-contracts-proc-macro 18.0.0", + "pallet-contracts-uapi 5.0.0", + "pallet-conviction-voting 28.0.0", + "pallet-core-fellowship 12.0.0", + "pallet-delegated-staking 1.0.0", + "pallet-democracy 28.0.0", + "pallet-dev-mode 10.0.0", + "pallet-election-provider-multi-phase 27.0.0", + "pallet-election-provider-support-benchmarking 27.0.0", + "pallet-elections-phragmen 29.0.0", + "pallet-fast-unstake 27.0.0", + "pallet-glutton 14.0.0", + "pallet-grandpa 28.0.0", + "pallet-identity 29.0.0", + "pallet-im-online 27.0.0", + "pallet-indices 28.0.0", + "pallet-insecure-randomness-collective-flip 16.0.0", + "pallet-lottery 28.0.0", + "pallet-membership 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-migrations 1.0.0", + "pallet-mixnet 0.4.0", + "pallet-mmr 27.0.0", + "pallet-multisig 28.0.0", + "pallet-nft-fractionalization 10.0.0", + "pallet-nfts 22.0.0", + "pallet-nfts-runtime-api 14.0.0", + "pallet-nis 28.0.0", + "pallet-node-authorization 28.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-nomination-pools-benchmarking 26.0.0", + "pallet-nomination-pools-runtime-api 23.0.0", + "pallet-offences 27.0.0", + "pallet-offences-benchmarking 28.0.0", + "pallet-paged-list 0.6.0", + "pallet-parameters 0.1.0", + "pallet-preimage 28.0.0", + "pallet-proxy 28.0.0", + "pallet-ranked-collective 28.0.0", + "pallet-recovery 28.0.0", + "pallet-referenda 28.0.0", + "pallet-remark 28.0.0", + "pallet-revive 0.1.0", "pallet-revive-eth-rpc", - "pallet-revive-fixtures", - "pallet-revive-mock-network", - "pallet-revive-proc-macro", - "pallet-revive-uapi", - "pallet-root-offences", - "pallet-root-testing", - "pallet-safe-mode", - "pallet-salary", - "pallet-scheduler", - "pallet-scored-pool", - "pallet-session", - "pallet-session-benchmarking", - "pallet-skip-feeless-payment", - "pallet-society", - "pallet-staking", + "pallet-revive-fixtures 0.1.0", + "pallet-revive-mock-network 0.1.0", + "pallet-revive-proc-macro 0.1.0", + "pallet-revive-uapi 0.1.0", + "pallet-root-offences 25.0.0", + "pallet-root-testing 4.0.0", + "pallet-safe-mode 9.0.0", + "pallet-salary 13.0.0", + "pallet-scheduler 29.0.0", + "pallet-scored-pool 28.0.0", + "pallet-session 28.0.0", + "pallet-session-benchmarking 28.0.0", + "pallet-skip-feeless-payment 3.0.0", + "pallet-society 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-staking-reward-fn", - "pallet-staking-runtime-api", - "pallet-state-trie-migration", - "pallet-statement", - "pallet-sudo", - "pallet-timestamp", - "pallet-tips", - "pallet-transaction-payment", + "pallet-staking-reward-fn 19.0.0", + "pallet-staking-runtime-api 14.0.0", + "pallet-state-trie-migration 29.0.0", + "pallet-statement 10.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-tips 27.0.0", + "pallet-transaction-payment 28.0.0", "pallet-transaction-payment-rpc", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-transaction-storage", - "pallet-treasury", - "pallet-tx-pause", - "pallet-uniques", - "pallet-utility", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-transaction-storage 27.0.0", + "pallet-treasury 27.0.0", + "pallet-tx-pause 9.0.0", + "pallet-uniques 28.0.0", + "pallet-utility 28.0.0", "pallet-verify-signature", - "pallet-vesting", - "pallet-whitelist", - "pallet-xcm", - "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub", - "pallet-xcm-bridge-hub-router", - "parachains-common", - "parachains-runtimes-test-utils", + "pallet-vesting 28.0.0", + "pallet-whitelist 27.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "pallet-xcm-bridge-hub 0.2.0", + "pallet-xcm-bridge-hub-router 0.5.0", + "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "polkadot-approval-distribution", "polkadot-availability-bitfield-distribution", "polkadot-availability-distribution", "polkadot-availability-recovery", "polkadot-cli", "polkadot-collator-protocol", - "polkadot-core-primitives", + "polkadot-core-primitives 7.0.0", "polkadot-dispute-distribution", "polkadot-erasure-coding", "polkadot-gossip-support", @@ -15588,13 +18613,13 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-omni-node-lib", "polkadot-overseer", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-rpc", - "polkadot-runtime-common", - "polkadot-runtime-metrics", - "polkadot-runtime-parachains", - "polkadot-sdk-frame", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-metrics 7.0.0", + "polkadot-runtime-parachains 7.0.0", + "polkadot-sdk-frame 0.1.0", "polkadot-service", "polkadot-statement-distribution", "polkadot-statement-table", @@ -15652,38 +18677,38 @@ dependencies = [ "sc-transaction-pool", "sc-transaction-pool-api", "sc-utils", - "slot-range-helper", - "snowbridge-beacon-primitives", - "snowbridge-core", - "snowbridge-ethereum", - "snowbridge-outbound-queue-merkle-tree", - "snowbridge-outbound-queue-runtime-api", - "snowbridge-pallet-ethereum-client", - "snowbridge-pallet-ethereum-client-fixtures", - "snowbridge-pallet-inbound-queue", - "snowbridge-pallet-inbound-queue-fixtures", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", - "snowbridge-router-primitives", - "snowbridge-runtime-common", - "snowbridge-runtime-test-common", - "snowbridge-system-runtime-api", + "slot-range-helper 7.0.0", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", + "snowbridge-ethereum 0.3.0", + "snowbridge-outbound-queue-merkle-tree 0.3.0", + "snowbridge-outbound-queue-runtime-api 0.2.0", + "snowbridge-pallet-ethereum-client 0.2.0", + "snowbridge-pallet-ethereum-client-fixtures 0.9.0", + "snowbridge-pallet-inbound-queue 0.2.0", + "snowbridge-pallet-inbound-queue-fixtures 0.10.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", + "snowbridge-router-primitives 0.9.0", + "snowbridge-runtime-common 0.2.0", + "snowbridge-runtime-test-common 0.2.0", + "snowbridge-system-runtime-api 0.2.0", "sp-api 26.0.0", "sp-api-proc-macro 15.0.0", "sp-application-crypto 30.0.0", "sp-arithmetic 23.0.0", - "sp-authority-discovery", - "sp-block-builder", + "sp-authority-discovery 26.0.0", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-aura", - "sp-consensus-babe", - "sp-consensus-beefy", - "sp-consensus-grandpa", - "sp-consensus-pow", - "sp-consensus-slots", - "sp-core 28.0.0", - "sp-core-hashing", + "sp-consensus-aura 0.32.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", + "sp-consensus-grandpa 13.0.0", + "sp-consensus-pow 0.32.0", + "sp-consensus-slots 0.32.0", + "sp-core 28.0.0", + "sp-core-hashing 15.0.0", "sp-core-hashing-proc-macro", "sp-crypto-ec-utils 0.10.0", "sp-crypto-hashing 0.1.0", @@ -15691,32 +18716,32 @@ dependencies = [ "sp-database", "sp-debug-derive 14.0.0", "sp-externalities 0.25.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-maybe-compressed-blob 11.0.0", "sp-metadata-ir 0.6.0", - "sp-mixnet", - "sp-mmr-primitives", - "sp-npos-elections", - "sp-offchain", + "sp-mixnet 0.4.0", + "sp-mmr-primitives 26.0.0", + "sp-npos-elections 26.0.0", + "sp-offchain 26.0.0", "sp-panic-handler 13.0.0", "sp-rpc", "sp-runtime 31.0.1", "sp-runtime-interface 24.0.0", "sp-runtime-interface-proc-macro 17.0.0", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-state-machine 0.35.0", - "sp-statement-store", + "sp-statement-store 10.0.0", "sp-std 14.0.0", "sp-storage 19.0.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", - "sp-transaction-pool", - "sp-transaction-storage-proof", + "sp-transaction-pool 26.0.0", + "sp-transaction-storage-proof 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", "sp-version-proc-macro 13.0.0", @@ -15724,11 +18749,11 @@ dependencies = [ "sp-weights 27.0.0", "staging-chain-spec-builder", "staging-node-inspect", - "staging-parachain-info", + "staging-parachain-info 0.7.0", "staging-tracking-allocator", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "subkey", "substrate-bip39 0.4.7", "substrate-build-script-utils", @@ -15737,14 +18762,246 @@ dependencies = [ "substrate-prometheus-endpoint", "substrate-rpc-client", "substrate-state-trie-migration-rpc", - "substrate-wasm-builder", - "testnet-parachains-constants", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", "tracing-gum", "tracing-gum-proc-macro", "xcm-emulator", - "xcm-procedural", - "xcm-runtime-apis", - "xcm-simulator", + "xcm-procedural 7.0.0", + "xcm-runtime-apis 0.1.0", + "xcm-simulator 7.0.0", +] + +[[package]] +name = "polkadot-sdk" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb819108697967452fa6d8d96ab4c0d48cbaa423b3156499dcb24f1cf95d6775" +dependencies = [ + "asset-test-utils 18.0.0", + "assets-common 0.18.0", + "binary-merkle-tree 15.0.1", + "bp-header-chain 0.18.1", + "bp-messages 0.18.0", + "bp-parachains 0.18.0", + "bp-polkadot 0.16.0", + "bp-polkadot-core 0.18.0", + "bp-relayers 0.18.0", + "bp-runtime 0.18.0", + "bp-test-utils 0.18.0", + "bp-xcm-bridge-hub 0.4.0", + "bp-xcm-bridge-hub-router 0.14.1", + "bridge-hub-common 0.10.0", + "bridge-hub-test-utils 0.18.0", + "bridge-runtime-common 0.18.0", + "cumulus-pallet-aura-ext 0.17.0", + "cumulus-pallet-dmp-queue 0.17.0", + "cumulus-pallet-parachain-system 0.17.1", + "cumulus-pallet-parachain-system-proc-macro 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cumulus-pallet-session-benchmarking 19.0.0", + "cumulus-pallet-solo-to-para 0.17.0", + "cumulus-pallet-xcm 0.17.0", + "cumulus-pallet-xcmp-queue 0.17.0", + "cumulus-ping 0.17.0", + "cumulus-primitives-aura 0.15.0", + "cumulus-primitives-core 0.16.0", + "cumulus-primitives-parachain-inherent 0.16.0", + "cumulus-primitives-proof-size-hostfunction 0.10.0", + "cumulus-primitives-storage-weight-reclaim 8.0.0", + "cumulus-primitives-timestamp 0.16.0", + "cumulus-primitives-utility 0.17.0", + "cumulus-test-relay-sproof-builder 0.16.0", + "frame-benchmarking 38.0.0", + "frame-benchmarking-pallet-pov 28.0.0", + "frame-election-provider-support 38.0.0", + "frame-executive 38.0.0", + "frame-metadata-hash-extension 0.6.0", + "frame-support 38.0.0", + "frame-support-procedural 30.0.4", + "frame-system 38.0.0", + "frame-system-benchmarking 38.0.0", + "frame-system-rpc-runtime-api 34.0.0", + "frame-try-runtime 0.44.0", + "pallet-alliance 37.0.0", + "pallet-asset-conversion 20.0.0", + "pallet-asset-conversion-ops 0.6.0", + "pallet-asset-conversion-tx-payment 20.0.0", + "pallet-asset-rate 17.0.0", + "pallet-asset-tx-payment 38.0.0", + "pallet-assets 40.0.0", + "pallet-assets-freezer 0.5.0", + "pallet-atomic-swap 38.0.0", + "pallet-aura 37.0.0", + "pallet-authority-discovery 38.0.0", + "pallet-authorship 38.0.0", + "pallet-babe 38.0.0", + "pallet-bags-list 37.0.0", + "pallet-balances 39.0.0", + "pallet-beefy 39.0.0", + "pallet-beefy-mmr 39.0.0", + "pallet-bounties 37.0.0", + "pallet-bridge-grandpa 0.18.0", + "pallet-bridge-messages 0.18.0", + "pallet-bridge-parachains 0.18.0", + "pallet-bridge-relayers 0.18.0", + "pallet-broker 0.17.0", + "pallet-child-bounties 37.0.0", + "pallet-collator-selection 19.0.0", + "pallet-collective 38.0.0", + "pallet-collective-content 0.16.0", + "pallet-contracts 38.0.0", + "pallet-contracts-mock-network 14.0.0", + "pallet-conviction-voting 38.0.0", + "pallet-core-fellowship 22.0.0", + "pallet-delegated-staking 5.0.0", + "pallet-democracy 38.0.0", + "pallet-dev-mode 20.0.0", + "pallet-election-provider-multi-phase 37.0.0", + "pallet-election-provider-support-benchmarking 37.0.0", + "pallet-elections-phragmen 39.0.0", + "pallet-fast-unstake 37.0.0", + "pallet-glutton 24.0.0", + "pallet-grandpa 38.0.0", + "pallet-identity 38.0.0", + "pallet-im-online 37.0.0", + "pallet-indices 38.0.0", + "pallet-insecure-randomness-collective-flip 26.0.0", + "pallet-lottery 38.0.0", + "pallet-membership 38.0.0", + "pallet-message-queue 41.0.1", + "pallet-migrations 8.0.0", + "pallet-mixnet 0.14.0", + "pallet-mmr 38.0.0", + "pallet-multisig 38.0.0", + "pallet-nft-fractionalization 21.0.0", + "pallet-nfts 32.0.0", + "pallet-nfts-runtime-api 24.0.0", + "pallet-nis 38.0.0", + "pallet-node-authorization 38.0.0", + "pallet-nomination-pools 35.0.0", + "pallet-nomination-pools-benchmarking 36.0.0", + "pallet-nomination-pools-runtime-api 33.0.0", + "pallet-offences 37.0.0", + "pallet-offences-benchmarking 38.0.0", + "pallet-paged-list 0.16.0", + "pallet-parameters 0.9.0", + "pallet-preimage 38.0.0", + "pallet-proxy 38.0.0", + "pallet-ranked-collective 38.0.0", + "pallet-recovery 38.0.0", + "pallet-referenda 38.0.0", + "pallet-remark 38.0.0", + "pallet-revive 0.2.0", + "pallet-revive-fixtures 0.2.0", + "pallet-revive-mock-network 0.2.0", + "pallet-root-offences 35.0.0", + "pallet-root-testing 14.0.0", + "pallet-safe-mode 19.0.0", + "pallet-salary 23.0.0", + "pallet-scheduler 39.0.0", + "pallet-scored-pool 38.0.0", + "pallet-session 38.0.0", + "pallet-session-benchmarking 38.0.0", + "pallet-skip-feeless-payment 13.0.0", + "pallet-society 38.0.0", + "pallet-staking 38.0.0", + "pallet-staking-reward-fn 22.0.0", + "pallet-staking-runtime-api 24.0.0", + "pallet-state-trie-migration 40.0.0", + "pallet-statement 20.0.0", + "pallet-sudo 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-tips 37.0.0", + "pallet-transaction-payment 38.0.0", + "pallet-transaction-payment-rpc-runtime-api 38.0.0", + "pallet-transaction-storage 37.0.0", + "pallet-treasury 37.0.0", + "pallet-tx-pause 19.0.0", + "pallet-uniques 38.0.0", + "pallet-utility 38.0.0", + "pallet-vesting 38.0.0", + "pallet-whitelist 37.0.0", + "pallet-xcm 17.0.0", + "pallet-xcm-benchmarks 17.0.0", + "pallet-xcm-bridge-hub 0.13.0", + "pallet-xcm-bridge-hub-router 0.15.1", + "parachains-common 18.0.0", + "parachains-runtimes-test-utils 17.0.0", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-common 17.0.0", + "polkadot-runtime-metrics 17.0.0", + "polkadot-runtime-parachains 17.0.1", + "polkadot-sdk-frame 0.7.0", + "sc-executor 0.40.1", + "slot-range-helper 15.0.0", + "snowbridge-beacon-primitives 0.10.0", + "snowbridge-core 0.10.0", + "snowbridge-ethereum 0.9.0", + "snowbridge-outbound-queue-merkle-tree 0.9.1", + "snowbridge-outbound-queue-runtime-api 0.10.0", + "snowbridge-pallet-ethereum-client 0.10.0", + "snowbridge-pallet-ethereum-client-fixtures 0.18.0", + "snowbridge-pallet-inbound-queue 0.10.0", + "snowbridge-pallet-inbound-queue-fixtures 0.18.0", + "snowbridge-pallet-outbound-queue 0.10.0", + "snowbridge-pallet-system 0.10.0", + "snowbridge-router-primitives 0.16.0", + "snowbridge-runtime-common 0.10.0", + "snowbridge-runtime-test-common 0.10.0", + "snowbridge-system-runtime-api 0.10.0", + "sp-api 34.0.0", + "sp-api-proc-macro 20.0.0", + "sp-application-crypto 38.0.0", + "sp-arithmetic 26.0.0", + "sp-authority-discovery 34.0.0", + "sp-block-builder 34.0.0", + "sp-consensus-aura 0.40.0", + "sp-consensus-babe 0.40.0", + "sp-consensus-beefy 22.1.0", + "sp-consensus-grandpa 21.0.0", + "sp-consensus-pow 0.40.0", + "sp-consensus-slots 0.40.1", + "sp-core 34.0.0", + "sp-core-hashing 16.0.0", + "sp-crypto-ec-utils 0.14.0", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-externalities 0.29.0", + "sp-genesis-builder 0.15.1", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-keyring 39.0.0", + "sp-keystore 0.40.0", + "sp-metadata-ir 0.7.0", + "sp-mixnet 0.12.0", + "sp-mmr-primitives 34.1.0", + "sp-npos-elections 34.0.0", + "sp-offchain 34.0.0", + "sp-runtime 39.0.2", + "sp-runtime-interface 28.0.0", + "sp-session 36.0.0", + "sp-staking 36.0.0", + "sp-state-machine 0.43.0", + "sp-statement-store 18.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-storage 21.0.0", + "sp-timestamp 34.0.0", + "sp-tracing 17.0.1", + "sp-transaction-pool 34.0.0", + "sp-transaction-storage-proof 34.0.0", + "sp-trie 37.0.0", + "sp-version 37.0.0", + "sp-wasm-interface 21.0.1", + "sp-weights 31.0.0", + "staging-parachain-info 0.17.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", + "substrate-bip39 0.6.0", + "testnet-parachains-constants 10.0.0", + "xcm-runtime-apis 0.4.0", ] [[package]] @@ -15754,55 +19011,55 @@ dependencies = [ "assert_cmd", "chain-spec-guide-runtime", "cumulus-client-service", - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-primitives-proof-size-hostfunction", - "cumulus-primitives-storage-weight-reclaim", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-primitives-proof-size-hostfunction 0.2.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", "docify", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "kitchensink-runtime", "log", "minimal-template-runtime", - "pallet-asset-conversion-tx-payment", - "pallet-asset-tx-payment", - "pallet-assets", - "pallet-aura", - "pallet-authorship", - "pallet-babe", - "pallet-balances", - "pallet-broker", - "pallet-collective", - "pallet-contracts", + "pallet-asset-conversion-tx-payment 10.0.0", + "pallet-asset-tx-payment 28.0.0", + "pallet-assets 29.1.0", + "pallet-aura 27.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-broker 0.6.0", + "pallet-collective 28.0.0", + "pallet-contracts 27.0.0", "pallet-default-config-example", - "pallet-democracy", + "pallet-democracy 28.0.0", "pallet-example-authorization-tx-extension", "pallet-example-offchain-worker", "pallet-example-single-block-migrations", "pallet-examples", - "pallet-grandpa", - "pallet-multisig", - "pallet-nfts", - "pallet-preimage", - "pallet-proxy", - "pallet-referenda", - "pallet-scheduler", - "pallet-skip-feeless-payment", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-uniques", - "pallet-utility", - "pallet-xcm", + "pallet-grandpa 28.0.0", + "pallet-multisig 28.0.0", + "pallet-nfts 22.0.0", + "pallet-preimage 28.0.0", + "pallet-proxy 28.0.0", + "pallet-referenda 28.0.0", + "pallet-scheduler 29.0.0", + "pallet-skip-feeless-payment 3.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-uniques 28.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", "parachain-template-runtime", "parity-scale-codec", "polkadot-omni-node-lib", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "polkadot-sdk-docs-first-pallet", "polkadot-sdk-docs-first-runtime", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "rand", "sc-chain-spec", "sc-cli", @@ -15825,10 +19082,10 @@ dependencies = [ "sp-api 26.0.0", "sp-arithmetic 23.0.0", "sp-core 28.0.0", - "sp-genesis-builder", + "sp-genesis-builder 0.8.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", "sp-runtime-interface 24.0.0", "sp-std 14.0.0", @@ -15837,14 +19094,14 @@ dependencies = [ "sp-weights 27.0.0", "staging-chain-spec-builder", "staging-node-cli", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "subkey", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", "xcm-docs", - "xcm-simulator", + "xcm-simulator 7.0.0", ] [[package]] @@ -15853,7 +19110,7 @@ version = "0.0.0" dependencies = [ "docify", "parity-scale-codec", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", ] @@ -15862,18 +19119,18 @@ name = "polkadot-sdk-docs-first-runtime" version = "0.0.0" dependencies = [ "docify", - "pallet-balances", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", + "pallet-balances 28.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", "parity-scale-codec", "polkadot-sdk-docs-first-pallet", - "polkadot-sdk-frame", + "polkadot-sdk-frame 0.1.0", "scale-info", "serde_json", - "sp-keyring", - "substrate-wasm-builder", + "sp-keyring 31.0.0", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -15881,54 +19138,87 @@ name = "polkadot-sdk-frame" version = "0.1.0" dependencies = [ "docify", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "log", "pallet-examples", "parity-scale-codec", "scale-info", "sp-api 26.0.0", "sp-arithmetic 23.0.0", - "sp-block-builder", - "sp-consensus-aura", - "sp-consensus-grandpa", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", ] +[[package]] +name = "polkadot-sdk-frame" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbdeb15ce08142082461afe1a62c15f7ce10a731d91b203ad6a8dc8d2e4a6a54" +dependencies = [ + "docify", + "frame-benchmarking 38.0.0", + "frame-executive 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "frame-system-benchmarking 38.0.0", + "frame-system-rpc-runtime-api 34.0.0", + "frame-try-runtime 0.44.0", + "log", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-arithmetic 26.0.0", + "sp-block-builder 34.0.0", + "sp-consensus-aura 0.40.0", + "sp-consensus-grandpa 21.0.0", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-io 38.0.0", + "sp-offchain 34.0.0", + "sp-runtime 39.0.2", + "sp-session 36.0.0", + "sp-storage 21.0.0", + "sp-transaction-pool 34.0.0", + "sp-version 37.0.0", +] + [[package]] name = "polkadot-service" version = "7.0.0" dependencies = [ "assert_matches", "async-trait", - "frame-benchmarking", + "frame-benchmarking 28.0.0", "frame-benchmarking-cli", - "frame-metadata-hash-extension", - "frame-system", - "frame-system-rpc-runtime-api", + "frame-metadata-hash-extension 0.1.0", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", "futures", "is_executable", "kvdb", "kvdb-rocksdb", "log", "mmr-gadget", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", "parity-db", "parity-scale-codec", "parking_lot 0.12.3", @@ -15937,7 +19227,7 @@ dependencies = [ "polkadot-availability-distribution", "polkadot-availability-recovery", "polkadot-collator-protocol", - "polkadot-core-primitives", + "polkadot-core-primitives 7.0.0", "polkadot-dispute-distribution", "polkadot-gossip-support", "polkadot-network-bridge", @@ -15964,14 +19254,14 @@ dependencies = [ "polkadot-node-subsystem-types", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-rpc", - "polkadot-runtime-parachains", + "polkadot-runtime-parachains 7.0.0", "polkadot-statement-distribution", "polkadot-test-client", "rococo-runtime", - "rococo-runtime-constants", + "rococo-runtime-constants 7.0.0", "sc-authority-discovery", "sc-basic-authorship", "sc-chain-spec", @@ -15995,35 +19285,35 @@ dependencies = [ "serde", "serde_json", "sp-api 26.0.0", - "sp-authority-discovery", - "sp-block-builder", + "sp-authority-discovery 26.0.0", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-beefy", - "sp-consensus-grandpa", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-mmr-primitives", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-mmr-primitives 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-timestamp", + "sp-session 27.0.0", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", "sp-weights 27.0.0", - "staging-xcm", + "staging-xcm 7.0.0", "substrate-prometheus-endpoint", "tempfile", "thiserror", "tracing-gum", "westend-runtime", - "westend-runtime-constants", - "xcm-runtime-apis", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -16044,7 +19334,7 @@ dependencies = [ "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-subsystem-bench", "rand_chacha", @@ -16052,11 +19342,11 @@ dependencies = [ "sc-keystore", "sc-network", "sp-application-crypto 30.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", - "sp-staking", + "sp-staking 26.0.0", "sp-tracing 16.0.0", "thiserror", "tracing-gum", @@ -16067,7 +19357,7 @@ name = "polkadot-statement-table" version = "7.0.0" dependencies = [ "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "sp-core 28.0.0", "tracing-gum", ] @@ -16111,7 +19401,7 @@ dependencies = [ "polkadot-node-subsystem-types", "polkadot-node-subsystem-util", "polkadot-overseer", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-primitives-test-helpers", "polkadot-service", "polkadot-statement-distribution", @@ -16133,12 +19423,12 @@ dependencies = [ "sha1", "sp-application-crypto 30.0.0", "sp-consensus", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "strum 0.26.3", "substrate-prometheus-endpoint", @@ -16151,11 +19441,11 @@ dependencies = [ name = "polkadot-test-client" version = "1.0.0" dependencies = [ - "frame-benchmarking", + "frame-benchmarking 28.0.0", "futures", "parity-scale-codec", "polkadot-node-subsystem", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "polkadot-test-runtime", "polkadot-test-service", "sc-block-builder", @@ -16165,14 +19455,14 @@ dependencies = [ "sp-api 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", - "sp-timestamp", + "sp-timestamp 26.0.0", "substrate-test-client", ] @@ -16200,7 +19490,7 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-types", "polkadot-node-subsystem-util", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "rand", "sp-core 28.0.0", "sp-keystore 0.34.0", @@ -16212,58 +19502,58 @@ dependencies = [ name = "polkadot-test-runtime" version = "1.0.0" dependencies = [ - "frame-election-provider-support", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", + "frame-election-provider-support 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", "hex-literal", "log", - "pallet-authority-discovery", - "pallet-authorship", - "pallet-babe", - "pallet-balances", - "pallet-grandpa", - "pallet-indices", - "pallet-offences", - "pallet-session", - "pallet-staking", + "pallet-authority-discovery 28.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-grandpa 28.0.0", + "pallet-indices 28.0.0", + "pallet-offences 27.0.0", + "pallet-session 28.0.0", + "pallet-staking 28.0.0", "pallet-staking-reward-curve", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-vesting", - "pallet-xcm", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-vesting 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-primitives", - "polkadot-runtime-common", - "polkadot-runtime-parachains", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "serde", "serde_json", "sp-api 26.0.0", - "sp-authority-discovery", - "sp-block-builder", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-authority-discovery 26.0.0", + "sp-block-builder 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-mmr-primitives", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-mmr-primitives 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", - "sp-transaction-pool", + "sp-session 27.0.0", + "sp-staking 26.0.0", + "sp-transaction-pool 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", "test-runtime-constants", "tiny-keccak", ] @@ -16272,20 +19562,20 @@ dependencies = [ name = "polkadot-test-service" version = "1.0.0" dependencies = [ - "frame-system", + "frame-system 28.0.0", "futures", "hex", - "pallet-balances", - "pallet-staking", - "pallet-transaction-payment", + "pallet-balances 28.0.0", + "pallet-staking 28.0.0", + "pallet-transaction-payment 28.0.0", "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-overseer", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-rpc", - "polkadot-runtime-common", - "polkadot-runtime-parachains", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", "polkadot-service", "polkadot-test-runtime", "rand", @@ -16302,14 +19592,14 @@ dependencies = [ "sc-transaction-pool", "serde_json", "sp-arithmetic 23.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-grandpa", + "sp-consensus-babe 0.32.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-inherents", - "sp-keyring", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "substrate-test-client", @@ -16361,6 +19651,19 @@ dependencies = [ "polkavm-linux-raw 0.9.0", ] +[[package]] +name = "polkavm" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ec0c5935f2eff23cfc4653002f4f8d12b37f87a720e0631282d188c32089d6" +dependencies = [ + "libc", + "log", + "polkavm-assembler 0.10.0", + "polkavm-common 0.10.0", + "polkavm-linux-raw 0.10.0", +] + [[package]] name = "polkavm" version = "0.13.0" @@ -16383,6 +19686,15 @@ dependencies = [ "log", ] +[[package]] +name = "polkavm-assembler" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8e4fd5a43100bf1afe9727b8130d01f966f5cfc9144d5604b21e795c2bcd80e" +dependencies = [ + "log", +] + [[package]] name = "polkavm-assembler" version = "0.13.0" @@ -16407,6 +19719,16 @@ dependencies = [ "log", ] +[[package]] +name = "polkavm-common" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0097b48bc0bedf9f3f537ce8f37e8f1202d8d83f9b621bdb21ff2c59b9097c50" +dependencies = [ + "log", + "polkavm-assembler 0.10.0", +] + [[package]] name = "polkavm-common" version = "0.13.0" @@ -16441,6 +19763,15 @@ dependencies = [ "polkavm-derive-impl-macro 0.9.0", ] +[[package]] +name = "polkavm-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dcc701385c08c31bdb0569f0c51a290c580d892fa77f1dd88a7352a62679ecf" +dependencies = [ + "polkavm-derive-impl-macro 0.10.0", +] + [[package]] name = "polkavm-derive" version = "0.14.0" @@ -16474,6 +19805,18 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "polkavm-derive-impl" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7855353a5a783dd5d09e3b915474bddf66575f5a3cf45dec8d1c5e051ba320dc" +dependencies = [ + "polkavm-common 0.10.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "polkavm-derive-impl" version = "0.14.0" @@ -16506,6 +19849,16 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "polkavm-derive-impl-macro" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9324fe036de37c17829af233b46ef6b5562d4a0c09bb7fdb9f8378856dee30cf" +dependencies = [ + "polkavm-derive-impl 0.10.0", + "syn 2.0.87", +] + [[package]] name = "polkavm-derive-impl-macro" version = "0.14.0" @@ -16531,6 +19884,21 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "polkavm-linker" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d704edfe7bdcc876784f19436d53d515b65eb07bc9a0fae77085d552c2dbbb5" +dependencies = [ + "gimli 0.28.0", + "hashbrown 0.14.5", + "log", + "object 0.36.1", + "polkavm-common 0.10.0", + "regalloc2 0.9.3", + "rustc-demangle", +] + [[package]] name = "polkavm-linker" version = "0.14.0" @@ -16552,6 +19920,12 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26e85d3456948e650dff0cfc85603915847faf893ed1e66b020bb82ef4557120" +[[package]] +name = "polkavm-linux-raw" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26e45fa59c7e1bb12ef5289080601e9ec9b31435f6e32800a5c90c132453d126" + [[package]] name = "polkavm-linux-raw" version = "0.13.0" @@ -16742,6 +20116,7 @@ dependencies = [ "fixed-hash", "impl-codec 0.6.0", "impl-num-traits 0.1.2", + "impl-rlp 0.3.0", "impl-serde 0.4.0", "scale-info", "uint 0.9.5", @@ -16756,7 +20131,7 @@ dependencies = [ "fixed-hash", "impl-codec 0.7.0", "impl-num-traits 0.2.0", - "impl-rlp", + "impl-rlp 0.4.0", "impl-serde 0.5.0", "scale-info", "uint 0.10.0", @@ -16770,7 +20145,7 @@ checksum = "a172e6cc603231f2cf004232eabcecccc0da53ba576ab286ef7baa0cfc7927ad" dependencies = [ "coarsetime", "crossbeam-queue", - "derive_more", + "derive_more 0.99.17", "futures", "futures-timer", "nanorand", @@ -16978,7 +20353,7 @@ dependencies = [ "rand", "rand_chacha", "rand_xorshift", - "regex-syntax 0.8.2", + "regex-syntax 0.8.5", "rusty-fork", "tempfile", "unarray", @@ -17022,7 +20397,7 @@ checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302" dependencies = [ "bytes", "heck 0.5.0", - "itertools 0.12.1", + "itertools 0.13.0", "log", "multimap", "once_cell", @@ -17068,7 +20443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.13.0", "proc-macro2 1.0.86", "quote 1.0.37", "syn 2.0.87", @@ -17448,22 +20823,6 @@ dependencies = [ "yasna", ] -[[package]] -name = "reconnecting-jsonrpsee-ws-client" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06fa4f17e09edfc3131636082faaec633c7baa269396b4004040bc6c52f49f65" -dependencies = [ - "cfg_aliases 0.2.1", - "finito", - "futures", - "jsonrpsee 0.23.2", - "serde_json", - "thiserror", - "tokio", - "tracing", -] - [[package]] name = "redox_syscall" version = "0.2.16" @@ -17508,7 +20867,7 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87413ebb313323d431e85d0afc5a68222aaed972843537cbfe5f061cf1b4bcab" dependencies = [ - "derive_more", + "derive_more 0.99.17", "fs-err", "static_init", "thiserror", @@ -17561,14 +20920,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.6" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" +checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.7", - "regex-syntax 0.8.2", + "regex-automata 0.4.8", + "regex-syntax 0.8.5", ] [[package]] @@ -17588,13 +20947,13 @@ checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" [[package]] name = "regex-automata" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.2", + "regex-syntax 0.8.5", ] [[package]] @@ -17605,9 +20964,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "relative-path" @@ -17621,19 +20980,19 @@ version = "0.1.0" dependencies = [ "async-std", "async-trait", - "bp-header-chain", - "bp-messages", - "bp-polkadot-core", - "bp-runtime", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-runtime 0.7.0", "finality-relay", - "frame-support", + "frame-support 28.0.0", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "num-traits", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-utility", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-utility 28.0.0", "parity-scale-codec", "quick_cache", "rand", @@ -17643,14 +21002,14 @@ dependencies = [ "sc-transaction-pool-api", "scale-info", "serde_json", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-rpc", "sp-runtime 31.0.1", "sp-std 14.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", - "staging-xcm", + "staging-xcm 7.0.0", "thiserror", "tokio", ] @@ -17663,7 +21022,7 @@ dependencies = [ "async-std", "async-trait", "backoff", - "bp-runtime", + "bp-runtime 0.7.0", "console", "futures", "isahc", @@ -17686,14 +21045,14 @@ name = "remote-ext-tests-bags-list" version = "1.0.0" dependencies = [ "clap 4.5.13", - "frame-system", + "frame-system 28.0.0", "log", "pallet-bags-list-remote-tests", "sp-core 28.0.0", "sp-tracing 16.0.0", "tokio", "westend-runtime", - "westend-runtime-constants", + "westend-runtime-constants 7.0.0", ] [[package]] @@ -17897,138 +21256,138 @@ name = "rococo-emulated-chain" version = "0.0.0" dependencies = [ "emulated-integration-tests-common", - "parachains-common", - "polkadot-primitives", + "parachains-common 7.0.0", + "polkadot-primitives 7.0.0", "rococo-runtime", - "rococo-runtime-constants", + "rococo-runtime-constants 7.0.0", "sc-consensus-grandpa", - "sp-authority-discovery", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-authority-discovery 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", ] [[package]] name = "rococo-parachain-runtime" version = "0.6.0" dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcm", - "cumulus-pallet-xcmp-queue", - "cumulus-ping", - "cumulus-primitives-aura", - "cumulus-primitives-core", - "cumulus-primitives-storage-weight-reclaim", - "cumulus-primitives-utility", - "frame-benchmarking", - "frame-executive", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", - "pallet-assets", - "pallet-aura", - "pallet-balances", - "pallet-message-queue", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-xcm", - "parachains-common", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-runtime-common", + "cumulus-pallet-aura-ext 0.7.0", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcm 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-ping 0.7.0", + "cumulus-primitives-aura 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-storage-weight-reclaim 1.0.0", + "cumulus-primitives-utility 0.7.0", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "pallet-assets 29.1.0", + "pallet-aura 27.0.0", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-xcm 7.0.0", + "parachains-common 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-common 7.0.0", "scale-info", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-transaction-pool", + "sp-session 27.0.0", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", - "testnet-parachains-constants", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", + "testnet-parachains-constants 1.0.0", ] [[package]] name = "rococo-runtime" version = "7.0.0" dependencies = [ - "binary-merkle-tree", + "binary-merkle-tree 13.0.0", "bitvec", - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", "frame-remote-externalities", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-asset-rate", - "pallet-authority-discovery", - "pallet-authorship", - "pallet-babe", - "pallet-balances", - "pallet-beefy", - "pallet-beefy-mmr", - "pallet-bounties", - "pallet-child-bounties", - "pallet-collective", - "pallet-conviction-voting", - "pallet-democracy", - "pallet-elections-phragmen", - "pallet-grandpa", - "pallet-identity", - "pallet-indices", - "pallet-membership", - "pallet-message-queue", - "pallet-migrations", - "pallet-mmr", - "pallet-multisig", - "pallet-nis", - "pallet-offences", - "pallet-parameters", - "pallet-preimage", - "pallet-proxy", - "pallet-ranked-collective", - "pallet-recovery", - "pallet-referenda", - "pallet-root-testing", - "pallet-scheduler", - "pallet-session", - "pallet-society", - "pallet-staking", - "pallet-state-trie-migration", - "pallet-sudo", - "pallet-timestamp", - "pallet-tips", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury", - "pallet-utility", - "pallet-vesting", - "pallet-whitelist", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-common", - "polkadot-runtime-parachains", - "rococo-runtime-constants", + "pallet-asset-rate 7.0.0", + "pallet-authority-discovery 28.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-beefy 28.0.0", + "pallet-beefy-mmr 28.0.0", + "pallet-bounties 27.0.0", + "pallet-child-bounties 27.0.0", + "pallet-collective 28.0.0", + "pallet-conviction-voting 28.0.0", + "pallet-democracy 28.0.0", + "pallet-elections-phragmen 29.0.0", + "pallet-grandpa 28.0.0", + "pallet-identity 29.0.0", + "pallet-indices 28.0.0", + "pallet-membership 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-migrations 1.0.0", + "pallet-mmr 27.0.0", + "pallet-multisig 28.0.0", + "pallet-nis 28.0.0", + "pallet-offences 27.0.0", + "pallet-parameters 0.1.0", + "pallet-preimage 28.0.0", + "pallet-proxy 28.0.0", + "pallet-ranked-collective 28.0.0", + "pallet-recovery 28.0.0", + "pallet-referenda 28.0.0", + "pallet-root-testing 4.0.0", + "pallet-scheduler 29.0.0", + "pallet-session 28.0.0", + "pallet-society 28.0.0", + "pallet-staking 28.0.0", + "pallet-state-trie-migration 29.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-tips 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-treasury 27.0.0", + "pallet-utility 28.0.0", + "pallet-vesting 28.0.0", + "pallet-whitelist 27.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", + "rococo-runtime-constants 7.0.0", "scale-info", "separator", "serde", @@ -18037,49 +21396,66 @@ dependencies = [ "smallvec", "sp-api 26.0.0", "sp-arithmetic 23.0.0", - "sp-authority-discovery", - "sp-block-builder", - "sp-consensus-babe", - "sp-consensus-beefy", - "sp-consensus-grandpa", - "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-authority-discovery 26.0.0", + "sp-block-builder 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", + "sp-consensus-grandpa 13.0.0", + "sp-core 28.0.0", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-mmr-primitives", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-mmr-primitives 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-storage 19.0.0", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "static_assertions", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", "tiny-keccak", "tokio", - "xcm-runtime-apis", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "rococo-runtime-constants" version = "7.0.0" dependencies = [ - "frame-support", - "polkadot-primitives", - "polkadot-runtime-common", + "frame-support 28.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", "smallvec", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", - "staging-xcm", - "staging-xcm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", +] + +[[package]] +name = "rococo-runtime-constants" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1ec6683a2e52fe3be2eaf942a80619abd99eb36e973c5ab4489a2f3b100db5c" +dependencies = [ + "frame-support 38.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-common 17.0.0", + "smallvec", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", ] [[package]] @@ -18505,13 +21881,12 @@ dependencies = [ [[package]] name = "ruzstd" -version = "0.5.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58c4eb8a81997cf040a091d1f7e1938aeab6749d3a0dfa73af43cdc32393483d" +checksum = "5174a470eeb535a721ae9fdd6e291c2411a906b96592182d05217591d5c5cf7b" dependencies = [ "byteorder", - "derive_more", - "twox-hash", + "derive_more 0.99.17", ] [[package]] @@ -18549,6 +21924,15 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "same-file" version = "1.0.6" @@ -18576,7 +21960,19 @@ checksum = "a3f01218e73ea57916be5f08987995ac802d6f4ede4ea5ce0242e468c590e4e2" dependencies = [ "log", "sp-core 33.0.1", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", + "thiserror", +] + +[[package]] +name = "sc-allocator" +version = "29.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b975ee3a95eaacb611e7b415737a7fa2db4d8ad7b880cc1b97371b04e95c7903" +dependencies = [ + "log", + "sp-core 34.0.0", + "sp-wasm-interface 21.0.1", "thiserror", ] @@ -18601,7 +21997,7 @@ dependencies = [ "sc-network", "sc-network-types", "sp-api 26.0.0", - "sp-authority-discovery", + "sp-authority-discovery 26.0.0", "sp-blockchain", "sp-core 28.0.0", "sp-keystore 0.34.0", @@ -18631,7 +22027,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "substrate-prometheus-endpoint", "substrate-test-runtime-client", @@ -18643,10 +22039,10 @@ version = "0.33.0" dependencies = [ "parity-scale-codec", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-trie 29.0.0", @@ -18673,12 +22069,12 @@ dependencies = [ "serde_json", "sp-application-crypto 30.0.0", "sp-blockchain", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-genesis-builder", + "sp-genesis-builder 0.8.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-tracing 16.0.0", @@ -18728,7 +22124,7 @@ dependencies = [ "serde_json", "sp-blockchain", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-panic-handler 13.0.0", "sp-runtime 31.0.1", @@ -18759,7 +22155,7 @@ dependencies = [ "sp-externalities 0.25.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", - "sp-statement-store", + "sp-statement-store 10.0.0", "sp-storage 19.0.0", "sp-test-primitives", "sp-trie 29.0.0", @@ -18844,17 +22240,17 @@ dependencies = [ "sc-telemetry", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-aura", - "sp-consensus-slots", + "sp-consensus-aura 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-inherents", - "sp-keyring", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", @@ -18886,18 +22282,18 @@ dependencies = [ "sc-transaction-pool-api", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", - "sp-consensus-slots", + "sp-consensus-babe 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-inherents", - "sp-keyring", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "sp-tracing 16.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", @@ -18910,7 +22306,7 @@ name = "sc-consensus-babe-rpc" version = "0.34.0" dependencies = [ "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "sc-consensus", "sc-consensus-babe", "sc-consensus-epochs", @@ -18923,9 +22319,9 @@ dependencies = [ "sp-application-crypto 30.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-babe", + "sp-consensus-babe 0.32.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "substrate-test-runtime-client", @@ -18960,13 +22356,13 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-beefy", - "sp-consensus-grandpa", + "sp-consensus-beefy 13.0.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", - "sp-mmr-primitives", + "sp-mmr-primitives 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", "substrate-prometheus-endpoint", @@ -18982,7 +22378,7 @@ name = "sc-consensus-beefy-rpc" version = "13.0.0" dependencies = [ "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.3", @@ -18991,7 +22387,7 @@ dependencies = [ "serde", "serde_json", "sp-application-crypto 30.0.0", - "sp-consensus-beefy", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "substrate-test-runtime-client", @@ -19048,10 +22444,10 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", @@ -19067,7 +22463,7 @@ version = "0.19.0" dependencies = [ "finality-grandpa", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "sc-block-builder", @@ -19076,9 +22472,9 @@ dependencies = [ "sc-rpc", "serde", "sp-blockchain", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "substrate-test-runtime-client", "thiserror", @@ -19093,7 +22489,7 @@ dependencies = [ "async-trait", "futures", "futures-timer", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "sc-basic-authorship", @@ -19108,14 +22504,14 @@ dependencies = [ "sp-api 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-aura", - "sp-consensus-babe", - "sp-consensus-slots", + "sp-consensus-aura 0.32.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime-client", "substrate-test-runtime-transaction-pool", @@ -19136,12 +22532,12 @@ dependencies = [ "sc-client-api", "sc-consensus", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-pow", + "sp-consensus-pow 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "substrate-prometheus-endpoint", "thiserror", @@ -19162,9 +22558,9 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-slots", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "substrate-test-runtime-client", @@ -19229,7 +22625,31 @@ dependencies = [ "sp-runtime-interface 27.0.0", "sp-trie 35.0.0", "sp-version 35.0.0", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", + "tracing", +] + +[[package]] +name = "sc-executor" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f0cc0a3728fd033589183460c5a49b2e7545d09dc89a098216ef9e9aadcd9dc" +dependencies = [ + "parity-scale-codec", + "parking_lot 0.12.3", + "sc-executor-common 0.35.0", + "sc-executor-polkavm 0.32.0", + "sc-executor-wasmtime 0.35.0", + "schnellru", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-externalities 0.29.0", + "sp-io 38.0.0", + "sp-panic-handler 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-runtime-interface 28.0.0", + "sp-trie 37.0.0", + "sp-version 37.0.0", + "sp-wasm-interface 21.0.1", "tracing", ] @@ -19254,7 +22674,21 @@ dependencies = [ "polkavm 0.9.3", "sc-allocator 28.0.0", "sp-maybe-compressed-blob 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", + "thiserror", + "wasm-instrument", +] + +[[package]] +name = "sc-executor-common" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c3b703a33dcb7cddf19176fdf12294b9a6408125836b0f4afee3e6969e7f190" +dependencies = [ + "polkavm 0.9.3", + "sc-allocator 29.0.0", + "sp-maybe-compressed-blob 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-wasm-interface 21.0.1", "thiserror", "wasm-instrument", ] @@ -19278,7 +22712,19 @@ dependencies = [ "log", "polkavm 0.9.3", "sc-executor-common 0.34.0", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", +] + +[[package]] +name = "sc-executor-polkavm" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26fe58d9cacfab73e5595fa84b80f7bd03efebe54a0574daaeb221a1d1f7ab80" +dependencies = [ + "log", + "polkavm 0.9.3", + "sc-executor-common 0.35.0", + "sp-wasm-interface 21.0.1", ] [[package]] @@ -19302,14 +22748,33 @@ dependencies = [ "sp-wasm-interface 20.0.0", "tempfile", "wasmtime", - "wat", + "wat", +] + +[[package]] +name = "sc-executor-wasmtime" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b97b324b2737447b7b208e913fef4988d5c38ecc21f57c3dd33e3f1e1e3bb08" +dependencies = [ + "anyhow", + "cfg-if", + "libc", + "log", + "parking_lot 0.12.3", + "rustix 0.36.15", + "sc-allocator 28.0.0", + "sc-executor-common 0.34.0", + "sp-runtime-interface 27.0.0", + "sp-wasm-interface 21.0.1", + "wasmtime", ] [[package]] name = "sc-executor-wasmtime" -version = "0.34.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b97b324b2737447b7b208e913fef4988d5c38ecc21f57c3dd33e3f1e1e3bb08" +checksum = "8cd498f2f77ec1f861c30804f5bfd796d4afcc8ce44ea1f11bfbe2847551d161" dependencies = [ "anyhow", "cfg-if", @@ -19317,10 +22782,10 @@ dependencies = [ "log", "parking_lot 0.12.3", "rustix 0.36.15", - "sc-allocator 28.0.0", - "sc-executor-common 0.34.0", - "sp-runtime-interface 27.0.0", - "sp-wasm-interface 21.0.0", + "sc-allocator 29.0.0", + "sc-executor-common 0.35.0", + "sp-runtime-interface 28.0.0", + "sp-wasm-interface 21.0.1", "wasmtime", ] @@ -19377,7 +22842,7 @@ dependencies = [ "sp-consensus", "sp-core 28.0.0", "sp-keystore 0.34.0", - "sp-mixnet", + "sp-mixnet 0.4.0", "sp-runtime 31.0.1", "thiserror", ] @@ -19461,7 +22926,7 @@ dependencies = [ "sc-consensus", "sc-network-types", "sp-consensus", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-runtime 31.0.1", "tempfile", ] @@ -19524,7 +22989,7 @@ dependencies = [ "sc-network-types", "sp-consensus", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", "substrate-prometheus-endpoint", ] @@ -19556,7 +23021,7 @@ dependencies = [ "sp-arithmetic 23.0.0", "sp-blockchain", "sp-consensus", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-test-primitives", @@ -19669,7 +23134,7 @@ dependencies = [ "sp-core 28.0.0", "sp-externalities 0.25.0", "sp-keystore 0.34.0", - "sp-offchain", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", "substrate-test-runtime-client", @@ -19692,7 +23157,7 @@ version = "29.0.0" dependencies = [ "assert_matches", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.3", @@ -19716,11 +23181,11 @@ dependencies = [ "sp-crypto-hashing 0.1.0", "sp-io 30.0.0", "sp-keystore 0.34.0", - "sp-offchain", + "sp-offchain 26.0.0", "sp-rpc", "sp-runtime 31.0.1", - "sp-session", - "sp-statement-store", + "sp-session 27.0.0", + "sp-statement-store 10.0.0", "sp-version 29.0.0", "substrate-test-runtime-client", "tokio", @@ -19730,7 +23195,7 @@ dependencies = [ name = "sc-rpc-api" version = "0.33.0" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "parity-scale-codec", "sc-chain-spec", "sc-mixnet", @@ -19757,7 +23222,7 @@ dependencies = [ "http-body-util", "hyper 1.3.1", "ip_network", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "sc-rpc-api", "serde", @@ -19777,7 +23242,7 @@ dependencies = [ "futures", "futures-util", "hex", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.3", @@ -19819,7 +23284,7 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-runtime-interface 24.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -19831,7 +23296,7 @@ dependencies = [ "exit-future", "futures", "futures-timer", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "parking_lot 0.12.3", @@ -19869,11 +23334,11 @@ dependencies = [ "sp-externalities 0.25.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-state-machine 0.35.0", "sp-storage 19.0.0", - "sp-transaction-pool", - "sp-transaction-storage-proof", + "sp-transaction-pool 26.0.0", + "sp-transaction-storage-proof 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", "static_init", @@ -19946,7 +23411,7 @@ dependencies = [ "sp-blockchain", "sp-core 28.0.0", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", "sp-tracing 16.0.0", "substrate-prometheus-endpoint", "tempfile", @@ -19969,7 +23434,7 @@ dependencies = [ name = "sc-sync-state-rpc" version = "0.34.0" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "parity-scale-codec", "sc-chain-spec", "sc-client-api", @@ -19987,7 +23452,7 @@ dependencies = [ name = "sc-sysinfo" version = "27.0.0" dependencies = [ - "derive_more", + "derive_more 0.99.17", "futures", "libc", "log", @@ -20090,7 +23555,7 @@ dependencies = [ "sp-crypto-hashing 0.1.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "substrate-prometheus-endpoint", "substrate-test-runtime", "substrate-test-runtime-client", @@ -20148,9 +23613,22 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e98f3262c250d90e700bb802eb704e1f841e03331c2eb815e46516c4edbf5b27" dependencies = [ - "derive_more", + "derive_more 0.99.17", "parity-scale-codec", - "primitive-types 0.12.2", + "scale-bits", + "scale-type-resolver", + "smallvec", +] + +[[package]] +name = "scale-decode" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ae9cc099ae85ff28820210732b00f019546f36f33225f509fe25d5816864a0" +dependencies = [ + "derive_more 1.0.0", + "parity-scale-codec", + "primitive-types 0.13.1", "scale-bits", "scale-decode-derive", "scale-type-resolver", @@ -20159,25 +23637,25 @@ dependencies = [ [[package]] name = "scale-decode-derive" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb22f574168103cdd3133b19281639ca65ad985e24612728f727339dcaf4021" +checksum = "5ed9401effa946b493f9f84dc03714cca98119b230497df6f3df6b84a2b03648" dependencies = [ - "darling 0.14.4", + "darling", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 1.0.109", + "syn 2.0.87", ] [[package]] name = "scale-encode" -version = "0.7.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ba0b9c48dc0eb20c60b083c29447c0c4617cb7c4a4c9fef72aa5c5bc539e15e" +checksum = "5f9271284d05d0749c40771c46180ce89905fd95aa72a2a2fddb4b7c0aa424db" dependencies = [ - "derive_more", + "derive_more 1.0.0", "parity-scale-codec", - "primitive-types 0.12.2", + "primitive-types 0.13.1", "scale-bits", "scale-encode-derive", "scale-type-resolver", @@ -20186,26 +23664,26 @@ dependencies = [ [[package]] name = "scale-encode-derive" -version = "0.7.1" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82ab7e60e2d9c8d47105f44527b26f04418e5e624ffc034f6b4a86c0ba19c5bf" +checksum = "102fbc6236de6c53906c0b262f12c7aa69c2bdc604862c12728f5f4d370bc137" dependencies = [ - "darling 0.14.4", - "proc-macro-crate 1.3.1", + "darling", + "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 1.0.109", + "syn 2.0.87", ] [[package]] name = "scale-info" -version = "2.11.3" +version = "2.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca070c12893629e2cc820a9761bedf6ce1dcddc9852984d1dc734b8bd9bd024" +checksum = "1aa7ffc1c0ef49b0452c6e2986abf2b07743320641ffd5fc63d552458e3b779b" dependencies = [ "bitvec", "cfg-if", - "derive_more", + "derive_more 1.0.0", "parity-scale-codec", "scale-info-derive", "serde", @@ -20213,14 +23691,14 @@ dependencies = [ [[package]] name = "scale-info-derive" -version = "2.11.3" +version = "2.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d35494501194174bda522a32605929eefc9ecf7e0a326c26db1fdd85881eb62" +checksum = "46385cc24172cf615450267463f937c10072516359b3ff1cb24228a4a08bf951" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", "quote 1.0.37", - "syn 1.0.109", + "syn 2.0.87", ] [[package]] @@ -20235,9 +23713,9 @@ dependencies = [ [[package]] name = "scale-typegen" -version = "0.8.0" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "498d1aecf2ea61325d4511787c115791639c0fd21ef4f8e11e49dd09eff2bbac" +checksum = "0dc4c70c7fea2eef1740f0081d3fe385d8bee1eef11e9272d3bec7dc8e5438e0" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -20248,18 +23726,17 @@ dependencies = [ [[package]] name = "scale-value" -version = "0.16.2" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba4d772cfb7569e03868400344a1695d16560bf62b86b918604773607d39ec84" +checksum = "f5e0ef2a0ee1e02a69ada37feb87ea1616ce9808aca072befe2d3131bf28576e" dependencies = [ "base58", "blake2 0.10.6", - "derive_more", + "derive_more 1.0.0", "either", - "frame-metadata 15.1.0", "parity-scale-codec", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-type-resolver", @@ -20364,6 +23841,18 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152" +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "password-hash", + "pbkdf2", + "salsa20", + "sha2 0.10.8", +] + [[package]] name = "sct" version = "0.7.0" @@ -20404,7 +23893,18 @@ version = "0.28.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d24b59d129cdadea20aea4fb2352fa053712e5d713eee47d700cd4b2bc002f10" dependencies = [ - "secp256k1-sys", + "secp256k1-sys 0.9.2", +] + +[[package]] +name = "secp256k1" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b50c5943d326858130af85e049f2661ba3c78b26589b8ab98e65e80ae44a1252" +dependencies = [ + "bitcoin_hashes 0.14.0", + "rand", + "secp256k1-sys 0.10.1", ] [[package]] @@ -20416,6 +23916,15 @@ dependencies = [ "cc", ] +[[package]] +name = "secp256k1-sys" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4387882333d3aa8cb20530a17c69a3752e97837832f34f6dccc760e715001d9" +dependencies = [ + "cc", +] + [[package]] name = "secrecy" version = "0.8.0" @@ -20426,6 +23935,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secrecy" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" +dependencies = [ + "zeroize", +] + [[package]] name = "security-framework" version = "2.11.0" @@ -20828,6 +24346,18 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "slot-range-helper" +version = "15.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e34f1146a457a5c554dedeae6c7273aa54c3b031f3e9eb0abd037b5511e2ce9" +dependencies = [ + "enumn", + "parity-scale-codec", + "paste", + "sp-runtime 39.0.2", +] + [[package]] name = "slotmap" version = "1.0.6" @@ -20912,7 +24442,7 @@ dependencies = [ "bs58", "chacha20", "crossbeam-queue", - "derive_more", + "derive_more 0.99.17", "ed25519-zebra 4.0.3", "either", "event-listener 2.5.3", @@ -20953,34 +24483,33 @@ dependencies = [ [[package]] name = "smoldot" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d1eaa97d77be4d026a1e7ffad1bb3b78448763b357ea6f8188d3e6f736a9b9" +checksum = "966e72d77a3b2171bb7461d0cb91f43670c63558c62d7cf42809cae6c8b6b818" dependencies = [ "arrayvec 0.7.4", "async-lock 3.4.0", "atomic-take", - "base64 0.21.7", + "base64 0.22.1", "bip39", "blake2-rfc", "bs58", "chacha20", "crossbeam-queue", - "derive_more", + "derive_more 0.99.17", "ed25519-zebra 4.0.3", "either", - "event-listener 4.0.3", + "event-listener 5.3.1", "fnv", "futures-lite 2.3.0", "futures-util", "hashbrown 0.14.5", "hex", "hmac 0.12.1", - "itertools 0.12.1", + "itertools 0.13.0", "libm", "libsecp256k1", "merlin", - "no-std-net", "nom", "num-bigint", "num-rational", @@ -20990,7 +24519,7 @@ dependencies = [ "poly1305", "rand", "rand_chacha", - "ruzstd 0.5.0", + "ruzstd 0.6.0", "schnorrkel 0.11.4", "serde", "serde_json", @@ -20999,9 +24528,9 @@ dependencies = [ "siphasher 1.0.1", "slab", "smallvec", - "soketto 0.7.1", + "soketto 0.8.0", "twox-hash", - "wasmi 0.31.2", + "wasmi 0.32.3", "x25519-dalek", "zeroize", ] @@ -21016,7 +24545,7 @@ dependencies = [ "async-lock 2.8.0", "base64 0.21.7", "blake2-rfc", - "derive_more", + "derive_more 0.99.17", "either", "event-listener 2.5.3", "fnv", @@ -21044,27 +24573,27 @@ dependencies = [ [[package]] name = "smoldot-light" -version = "0.14.0" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5496f2d116b7019a526b1039ec2247dd172b8670633b1a64a614c9ea12c9d8c7" +checksum = "2a33b06891f687909632ce6a4e3fd7677b24df930365af3d0bcb078310129f3f" dependencies = [ "async-channel 2.3.0", "async-lock 3.4.0", - "base64 0.21.7", + "base64 0.22.1", "blake2-rfc", - "derive_more", + "bs58", + "derive_more 0.99.17", "either", - "event-listener 4.0.3", + "event-listener 5.3.1", "fnv", "futures-channel", "futures-lite 2.3.0", "futures-util", "hashbrown 0.14.5", "hex", - "itertools 0.12.1", + "itertools 0.13.0", "log", "lru 0.12.3", - "no-std-net", "parking_lot 0.12.3", "pin-project", "rand", @@ -21074,7 +24603,7 @@ dependencies = [ "siphasher 1.0.1", "slab", "smol 2.0.2", - "smoldot 0.16.0", + "smoldot 0.18.0", "zeroize", ] @@ -21116,14 +24645,14 @@ name = "snowbridge-beacon-primitives" version = "0.2.0" dependencies = [ "byte-slice-cast", - "frame-support", + "frame-support 28.0.0", "hex", "hex-literal", "parity-scale-codec", "rlp 0.6.1", "scale-info", "serde", - "snowbridge-ethereum", + "snowbridge-ethereum 0.3.0", "snowbridge-milagro-bls", "sp-core 28.0.0", "sp-io 30.0.0", @@ -21133,37 +24662,84 @@ dependencies = [ "ssz_rs_derive", ] +[[package]] +name = "snowbridge-beacon-primitives" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10bd720997e558beb556d354238fa90781deb38241cf31c1b6368738ef21c279" +dependencies = [ + "byte-slice-cast", + "frame-support 38.0.0", + "hex", + "parity-scale-codec", + "rlp 0.5.2", + "scale-info", + "serde", + "snowbridge-ethereum 0.9.0", + "snowbridge-milagro-bls", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "ssz_rs", + "ssz_rs_derive", +] + [[package]] name = "snowbridge-core" version = "0.2.0" dependencies = [ - "ethabi-decode", - "frame-support", - "frame-system", + "ethabi-decode 2.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex", "hex-literal", "parity-scale-codec", - "polkadot-parachain-primitives", + "polkadot-parachain-primitives 6.0.0", "scale-info", "serde", - "snowbridge-beacon-primitives", + "snowbridge-beacon-primitives 0.2.0", "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6be61e4db95d1e253a1d5e722953b2d2f6605e5f9761f0a919e5d3fbdbff9da9" +dependencies = [ + "ethabi-decode 1.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "hex-literal", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "scale-info", + "serde", + "snowbridge-beacon-primitives 0.10.0", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", ] [[package]] name = "snowbridge-ethereum" version = "0.3.0" dependencies = [ - "ethabi-decode", - "ethbloom", - "ethereum-types", + "ethabi-decode 2.0.0", + "ethbloom 0.14.1", + "ethereum-types 0.15.1", "hex-literal", "parity-bytes", "parity-scale-codec", @@ -21179,6 +24755,27 @@ dependencies = [ "wasm-bindgen-test", ] +[[package]] +name = "snowbridge-ethereum" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc3d6d549c57df27cf89ec852f932fa4008eea877a6911a87e03e8002104eabd" +dependencies = [ + "ethabi-decode 1.0.0", + "ethbloom 0.13.0", + "ethereum-types 0.14.1", + "hex-literal", + "parity-bytes", + "parity-scale-codec", + "rlp 0.5.2", + "scale-info", + "serde", + "serde-big-array", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "snowbridge-milagro-bls" version = "1.5.4" @@ -21209,83 +24806,175 @@ dependencies = [ "sp-tracing 16.0.0", ] +[[package]] +name = "snowbridge-outbound-queue-merkle-tree" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74c6a9b65fa61711b704f0c6afb3663c6288288e8822ddae5cc1146fe3ad9ce8" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "snowbridge-outbound-queue-runtime-api" version = "0.2.0" dependencies = [ - "frame-support", + "frame-support 28.0.0", "parity-scale-codec", - "snowbridge-core", - "snowbridge-outbound-queue-merkle-tree", + "snowbridge-core 0.2.0", + "snowbridge-outbound-queue-merkle-tree 0.3.0", "sp-api 26.0.0", "sp-std 14.0.0", ] +[[package]] +name = "snowbridge-outbound-queue-runtime-api" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d27b8d9cb8022637a5ce4f52692520fa75874f393e04ef5cd75bd8795087f6" +dependencies = [ + "frame-support 38.0.0", + "parity-scale-codec", + "snowbridge-core 0.10.0", + "snowbridge-outbound-queue-merkle-tree 0.9.1", + "sp-api 34.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "snowbridge-pallet-ethereum-client" version = "0.2.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex-literal", "log", - "pallet-timestamp", + "pallet-timestamp 27.0.0", "parity-scale-codec", "rand", "scale-info", "serde", "serde_json", - "snowbridge-beacon-primitives", - "snowbridge-core", - "snowbridge-ethereum", - "snowbridge-pallet-ethereum-client-fixtures", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", + "snowbridge-ethereum 0.3.0", + "snowbridge-pallet-ethereum-client-fixtures 0.9.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", "static_assertions", ] +[[package]] +name = "snowbridge-pallet-ethereum-client" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d53d32d8470c643f9f8c1f508e1e34263f76297e4c9150e10e8f2e0b63992e1" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-timestamp 37.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "snowbridge-beacon-primitives 0.10.0", + "snowbridge-core 0.10.0", + "snowbridge-ethereum 0.9.0", + "snowbridge-pallet-ethereum-client-fixtures 0.18.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "static_assertions", +] + [[package]] name = "snowbridge-pallet-ethereum-client-fixtures" version = "0.9.0" dependencies = [ "hex-literal", - "snowbridge-beacon-primitives", - "snowbridge-core", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", "sp-core 28.0.0", "sp-std 14.0.0", ] +[[package]] +name = "snowbridge-pallet-ethereum-client-fixtures" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3984b98465af1d862d4e87ba783e1731f2a3f851b148d6cb98d526cebd351185" +dependencies = [ + "hex-literal", + "snowbridge-beacon-primitives 0.10.0", + "snowbridge-core 0.10.0", + "sp-core 34.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "snowbridge-pallet-inbound-queue" version = "0.2.0" dependencies = [ "alloy-primitives", "alloy-sol-types", - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex-literal", "log", - "pallet-balances", + "pallet-balances 28.0.0", "parity-scale-codec", "scale-info", "serde", - "snowbridge-beacon-primitives", - "snowbridge-core", - "snowbridge-pallet-ethereum-client", - "snowbridge-pallet-inbound-queue-fixtures", - "snowbridge-router-primitives", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", + "snowbridge-pallet-ethereum-client 0.2.0", + "snowbridge-pallet-inbound-queue-fixtures 0.10.0", + "snowbridge-router-primitives 0.9.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-pallet-inbound-queue" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2e6a9d00e60e3744e6b6f0c21fea6694b9c6401ac40e41340a96e561dcf1935" +dependencies = [ + "alloy-primitives", + "alloy-sol-types", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "pallet-balances 39.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "snowbridge-beacon-primitives 0.10.0", + "snowbridge-core 0.10.0", + "snowbridge-pallet-inbound-queue-fixtures 0.18.0", + "snowbridge-router-primitives 0.16.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] @@ -21293,122 +24982,248 @@ name = "snowbridge-pallet-inbound-queue-fixtures" version = "0.10.0" dependencies = [ "hex-literal", - "snowbridge-beacon-primitives", - "snowbridge-core", + "snowbridge-beacon-primitives 0.2.0", + "snowbridge-core 0.2.0", "sp-core 28.0.0", "sp-std 14.0.0", ] +[[package]] +name = "snowbridge-pallet-inbound-queue-fixtures" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b099db83f4c10c0bf84e87deb1596019f91411ea1c8c9733ea9a7f2e7e967073" +dependencies = [ + "hex-literal", + "snowbridge-beacon-primitives 0.10.0", + "snowbridge-core 0.10.0", + "sp-core 34.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "snowbridge-pallet-outbound-queue" version = "0.2.0" dependencies = [ - "bridge-hub-common", - "ethabi-decode", - "frame-benchmarking", - "frame-support", - "frame-system", - "pallet-message-queue", + "bridge-hub-common 0.1.0", + "ethabi-decode 2.0.0", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-message-queue 31.0.0", "parity-scale-codec", "scale-info", "serde", - "snowbridge-core", - "snowbridge-outbound-queue-merkle-tree", + "snowbridge-core 0.2.0", + "snowbridge-outbound-queue-merkle-tree 0.3.0", "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", ] +[[package]] +name = "snowbridge-pallet-outbound-queue" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7d49478041b6512c710d0d4655675d146fe00a8e0c1624e5d8a1d6c161d490f" +dependencies = [ + "bridge-hub-common 0.10.0", + "ethabi-decode 1.0.0", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "serde", + "snowbridge-core 0.10.0", + "snowbridge-outbound-queue-merkle-tree 0.9.1", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "snowbridge-pallet-system" version = "0.2.0" dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex", "hex-literal", "log", - "pallet-balances", - "pallet-message-queue", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", "parity-scale-codec", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "scale-info", - "snowbridge-core", - "snowbridge-pallet-outbound-queue", + "snowbridge-core 0.2.0", + "snowbridge-pallet-outbound-queue 0.2.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-pallet-system" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "674db59b3c8013382e5c07243ad9439b64d81d2e8b3c4f08d752b55aa5de697e" +dependencies = [ + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "log", + "parity-scale-codec", + "scale-info", + "snowbridge-core 0.10.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] name = "snowbridge-router-primitives" version = "0.9.0" dependencies = [ - "frame-support", + "frame-support 28.0.0", "hex-literal", "log", "parity-scale-codec", "scale-info", - "snowbridge-core", + "snowbridge-core 0.2.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-router-primitives" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "025f1e6805753821b1db539369f1fb183fd59fd5df7023f7633a4c0cfd3e62f9" +dependencies = [ + "frame-support 38.0.0", + "hex-literal", + "log", + "parity-scale-codec", + "scale-info", + "snowbridge-core 0.10.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] name = "snowbridge-runtime-common" version = "0.2.0" dependencies = [ - "frame-support", + "frame-support 28.0.0", "log", "parity-scale-codec", - "snowbridge-core", + "snowbridge-core 0.2.0", "sp-arithmetic 23.0.0", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-runtime-common" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6093f0e73d6cfdd2eea8712155d1d75b5063fc9b1d854d2665b097b4bb29570d" +dependencies = [ + "frame-support 38.0.0", + "log", + "parity-scale-codec", + "snowbridge-core 0.10.0", + "sp-arithmetic 26.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "snowbridge-runtime-test-common" version = "0.2.0" dependencies = [ - "cumulus-pallet-parachain-system", - "frame-support", - "frame-system", - "pallet-balances", - "pallet-collator-selection", - "pallet-message-queue", - "pallet-session", - "pallet-timestamp", - "pallet-utility", - "pallet-xcm", - "parachains-runtimes-test-utils", - "parity-scale-codec", - "snowbridge-core", - "snowbridge-pallet-ethereum-client", - "snowbridge-pallet-ethereum-client-fixtures", - "snowbridge-pallet-outbound-queue", - "snowbridge-pallet-system", + "cumulus-pallet-parachain-system 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "pallet-balances 28.0.0", + "pallet-collator-selection 9.0.0", + "pallet-message-queue 31.0.0", + "pallet-session 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-utility 28.0.0", + "pallet-xcm 7.0.0", + "parachains-runtimes-test-utils 7.0.0", + "parity-scale-codec", + "snowbridge-core 0.2.0", + "snowbridge-pallet-ethereum-client 0.2.0", + "snowbridge-pallet-ethereum-client-fixtures 0.9.0", + "snowbridge-pallet-outbound-queue 0.2.0", + "snowbridge-pallet-system 0.2.0", "sp-core 28.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", - "staging-parachain-info", - "staging-xcm", - "staging-xcm-executor", + "staging-parachain-info 0.7.0", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "snowbridge-runtime-test-common" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "893480d6cde2489051c65efb5d27fa87efe047b3b61216d8e27bb2f0509b7faf" +dependencies = [ + "cumulus-pallet-parachain-system 0.17.1", + "frame-support 38.0.0", + "frame-system 38.0.0", + "pallet-balances 39.0.0", + "pallet-collator-selection 19.0.0", + "pallet-message-queue 41.0.1", + "pallet-session 38.0.0", + "pallet-timestamp 37.0.0", + "pallet-utility 38.0.0", + "pallet-xcm 17.0.0", + "parachains-runtimes-test-utils 17.0.0", + "parity-scale-codec", + "snowbridge-core 0.10.0", + "snowbridge-pallet-ethereum-client 0.10.0", + "snowbridge-pallet-ethereum-client-fixtures 0.18.0", + "snowbridge-pallet-outbound-queue 0.10.0", + "snowbridge-pallet-system 0.10.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-keyring 39.0.0", + "sp-runtime 39.0.2", + "staging-parachain-info 0.17.0", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] @@ -21416,10 +25231,23 @@ name = "snowbridge-system-runtime-api" version = "0.2.0" dependencies = [ "parity-scale-codec", - "snowbridge-core", + "snowbridge-core 0.2.0", "sp-api 26.0.0", "sp-std 14.0.0", - "staging-xcm", + "staging-xcm 7.0.0", +] + +[[package]] +name = "snowbridge-system-runtime-api" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68b8b83b3db781c49844312a23965073e4d93341739a35eafe526c53b578d3b7" +dependencies = [ + "parity-scale-codec", + "snowbridge-core 0.10.0", + "sp-api 34.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", ] [[package]] @@ -21479,11 +25307,11 @@ version = "0.0.0" dependencies = [ "clap 4.5.13", "frame-benchmarking-cli", - "frame-metadata-hash-extension", - "frame-system", + "frame-metadata-hash-extension 0.1.0", + "frame-system 28.0.0", "futures", - "jsonrpsee 0.24.3", - "pallet-transaction-payment", + "jsonrpsee", + "pallet-transaction-payment 28.0.0", "pallet-transaction-payment-rpc", "sc-basic-authorship", "sc-cli", @@ -21501,17 +25329,17 @@ dependencies = [ "serde_json", "solochain-template-runtime", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", - "sp-consensus-aura", - "sp-consensus-grandpa", + "sp-consensus-aura 0.32.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", "substrate-build-script-utils", "substrate-frame-rpc-system", ] @@ -21520,40 +25348,40 @@ dependencies = [ name = "solochain-template-runtime" version = "0.0.0" dependencies = [ - "frame-benchmarking", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", - "pallet-aura", - "pallet-balances", - "pallet-grandpa", - "pallet-sudo", + "frame-benchmarking 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", + "pallet-aura 27.0.0", + "pallet-balances 28.0.0", + "pallet-grandpa 28.0.0", + "pallet-sudo 28.0.0", "pallet-template", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", "parity-scale-codec", "scale-info", "serde_json", "sp-api 26.0.0", - "sp-block-builder", - "sp-consensus-aura", - "sp-consensus-grandpa", + "sp-block-builder 26.0.0", + "sp-consensus-aura 0.32.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", - "sp-keyring", - "sp-offchain", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-storage 19.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -21601,6 +25429,29 @@ dependencies = [ "thiserror", ] +[[package]] +name = "sp-api" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbce492e0482134128b7729ea36f5ef1a9f9b4de2d48ff8dde7b5e464e28ce75" +dependencies = [ + "docify", + "hash-db", + "log", + "parity-scale-codec", + "scale-info", + "sp-api-proc-macro 20.0.0", + "sp-core 34.0.0", + "sp-externalities 0.29.0", + "sp-metadata-ir 0.7.0", + "sp-runtime 39.0.2", + "sp-runtime-interface 28.0.0", + "sp-state-machine 0.43.0", + "sp-trie 37.0.0", + "sp-version 37.0.0", + "thiserror", +] + [[package]] name = "sp-api-proc-macro" version = "15.0.0" @@ -21630,6 +25481,21 @@ dependencies = [ "syn 2.0.87", ] +[[package]] +name = "sp-api-proc-macro" +version = "20.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9aadf9e97e694f0e343978aa632938c5de309cbcc8afed4136cb71596737278" +dependencies = [ + "Inflector", + "blake2 0.10.6", + "expander", + "proc-macro-crate 3.1.0", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "sp-api-test" version = "2.0.1" @@ -21666,44 +25532,43 @@ dependencies = [ [[package]] name = "sp-application-crypto" -version = "33.0.0" +version = "35.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13ca6121c22c8bd3d1dce1f05c479101fd0d7b159bef2a3e8c834138d839c75c" +checksum = "57541120624a76379cc993cbb85064a5148957a92da032567e54bce7977f51fc" dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 31.0.0", - "sp-io 33.0.0", + "sp-core 32.0.0", + "sp-io 35.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "sp-application-crypto" -version = "35.0.0" +version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57541120624a76379cc993cbb85064a5148957a92da032567e54bce7977f51fc" +checksum = "296282f718f15d4d812664415942665302a484d3495cf8d2e2ab3192b32d2c73" dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 32.0.0", - "sp-io 35.0.0", + "sp-core 33.0.1", + "sp-io 36.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "sp-application-crypto" -version = "36.0.0" +version = "38.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "296282f718f15d4d812664415942665302a484d3495cf8d2e2ab3192b32d2c73" +checksum = "0d8133012faa5f75b2f0b1619d9f720c1424ac477152c143e5f7dbde2fe1a958" dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-core 33.0.1", - "sp-io 36.0.0", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-core 34.0.0", + "sp-io 38.0.0", ] [[package]] @@ -21734,21 +25599,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "sp-arithmetic" -version = "25.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "910c07fa263b20bf7271fdd4adcb5d3217dfdac14270592e0780223542e7e114" -dependencies = [ - "integer-sqrt", - "num-traits", - "parity-scale-codec", - "scale-info", - "serde", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "static_assertions", -] - [[package]] name = "sp-arithmetic" version = "26.0.0" @@ -21805,15 +25655,39 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-authority-discovery" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "519c33af0e25ba2dd2eb3790dc404d634b6e4ce0801bcc8fa3574e07c365e734" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-block-builder" version = "26.0.0" dependencies = [ "sp-api 26.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", ] +[[package]] +name = "sp-block-builder" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74738809461e3d4bd707b5b94e0e0c064a623a74a6a8fe5c98514417a02858dd" +dependencies = [ + "sp-api 34.0.0", + "sp-inherents 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-blockchain" version = "28.0.0" @@ -21840,7 +25714,7 @@ dependencies = [ "futures", "log", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-test-primitives", @@ -21856,10 +25730,27 @@ dependencies = [ "scale-info", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-consensus-slots", - "sp-inherents", + "sp-consensus-slots 0.32.0", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", +] + +[[package]] +name = "sp-consensus-aura" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a8faaa05bbcb9c41f0cc535c4c1315abf6df472b53eae018678d1b4d811ac47" +dependencies = [ + "async-trait", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-consensus-slots 0.40.1", + "sp-inherents 34.0.0", + "sp-runtime 39.0.2", + "sp-timestamp 34.0.0", ] [[package]] @@ -21872,11 +25763,30 @@ dependencies = [ "serde", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-consensus-slots", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", - "sp-timestamp", + "sp-timestamp 26.0.0", +] + +[[package]] +name = "sp-consensus-babe" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36ee95e17ee8dcd14db7d584b899a426565ca9abe5a266ab82277977fc547f86" +dependencies = [ + "async-trait", + "parity-scale-codec", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-consensus-slots 0.40.1", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-runtime 39.0.2", + "sp-timestamp 34.0.0", ] [[package]] @@ -21893,13 +25803,35 @@ dependencies = [ "sp-crypto-hashing 0.1.0", "sp-io 30.0.0", "sp-keystore 0.34.0", - "sp-mmr-primitives", + "sp-mmr-primitives 26.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", "strum 0.26.3", "w3f-bls", ] +[[package]] +name = "sp-consensus-beefy" +version = "22.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d97e8cd75d85d15cda6f1923cf3834e848f80d5a6de1cf4edbbc5f0ad607eb" +dependencies = [ + "lazy_static", + "parity-scale-codec", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-core 34.0.0", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-io 38.0.0", + "sp-keystore 0.40.0", + "sp-mmr-primitives 34.1.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "strum 0.26.3", +] + [[package]] name = "sp-consensus-grandpa" version = "13.0.0" @@ -21916,6 +25848,24 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-consensus-grandpa" +version = "21.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "587b791efe6c5f18e09dbbaf1ece0ee7b5fe51602c233e7151a3676b0de0260b" +dependencies = [ + "finality-grandpa", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-core 34.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-consensus-pow" version = "0.32.0" @@ -21926,6 +25876,18 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-consensus-pow" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fa6b7d199a1c16cea1b74ee7cee174bf08f2120ab66a87bee7b12353100b47c" +dependencies = [ + "parity-scale-codec", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-consensus-sassafras" version = "0.3.4-dev" @@ -21935,7 +25897,7 @@ dependencies = [ "serde", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-consensus-slots", + "sp-consensus-slots 0.32.0", "sp-core 28.0.0", "sp-runtime 31.0.1", ] @@ -21947,7 +25909,19 @@ dependencies = [ "parity-scale-codec", "scale-info", "serde", - "sp-timestamp", + "sp-timestamp 26.0.0", +] + +[[package]] +name = "sp-consensus-slots" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbafb7ed44f51c22fa277fb39b33dc601fa426133a8e2b53f3f46b10f07fba43" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde", + "sp-timestamp 34.0.0", ] [[package]] @@ -21981,8 +25955,8 @@ dependencies = [ "regex", "scale-info", "schnorrkel 0.11.4", - "secp256k1", - "secrecy", + "secp256k1 0.28.2", + "secrecy 0.8.0", "serde", "serde_json", "sp-crypto-hashing 0.1.0", @@ -22029,8 +26003,8 @@ dependencies = [ "rand", "scale-info", "schnorrkel 0.11.4", - "secp256k1", - "secrecy", + "secp256k1 0.28.2", + "secrecy 0.8.0", "serde", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -22076,8 +26050,8 @@ dependencies = [ "rand", "scale-info", "schnorrkel 0.11.4", - "secp256k1", - "secrecy", + "secp256k1 0.28.2", + "secrecy 0.8.0", "serde", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -22123,8 +26097,8 @@ dependencies = [ "rand", "scale-info", "schnorrkel 0.11.4", - "secp256k1", - "secrecy", + "secp256k1 0.28.2", + "secrecy 0.8.0", "serde", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -22140,6 +26114,53 @@ dependencies = [ "zeroize", ] +[[package]] +name = "sp-core" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c961a5e33fb2962fa775c044ceba43df9c6f917e2c35d63bfe23738468fa76a7" +dependencies = [ + "array-bytes", + "bitflags 1.3.2", + "blake2 0.10.6", + "bounded-collections", + "bs58", + "dyn-clonable", + "ed25519-zebra 4.0.3", + "futures", + "hash-db", + "hash256-std-hasher", + "impl-serde 0.4.0", + "itertools 0.11.0", + "k256", + "libsecp256k1", + "log", + "merlin", + "parity-bip39", + "parity-scale-codec", + "parking_lot 0.12.3", + "paste", + "primitive-types 0.12.2", + "rand", + "scale-info", + "schnorrkel 0.11.4", + "secp256k1 0.28.2", + "secrecy 0.8.0", + "serde", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-externalities 0.29.0", + "sp-runtime-interface 28.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-storage 21.0.0", + "ss58-registry", + "substrate-bip39 0.6.0", + "thiserror", + "tracing", + "w3f-bls", + "zeroize", +] + [[package]] name = "sp-core-fuzz" version = "0.0.0" @@ -22156,6 +26177,15 @@ dependencies = [ "sp-crypto-hashing 0.1.0", ] +[[package]] +name = "sp-core-hashing" +version = "16.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f812cb2dff962eb378c507612a50f1c59f52d92eb97b710f35be3c2346a3cd7" +dependencies = [ + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "sp-core-hashing-proc-macro" version = "15.0.0" @@ -22203,6 +26233,27 @@ dependencies = [ "sp-runtime-interface 24.0.0", ] +[[package]] +name = "sp-crypto-ec-utils" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acb24f8a607a48a87f0ee4c090fc5d577eee49ff39ced6a3c491e06eca03c37" +dependencies = [ + "ark-bls12-377", + "ark-bls12-377-ext", + "ark-bls12-381", + "ark-bls12-381-ext", + "ark-bw6-761", + "ark-bw6-761-ext", + "ark-ec", + "ark-ed-on-bls12-377", + "ark-ed-on-bls12-377-ext", + "ark-ed-on-bls12-381-bandersnatch", + "ark-ed-on-bls12-381-bandersnatch-ext", + "ark-scale 0.0.12", + "sp-runtime-interface 28.0.0", +] + [[package]] name = "sp-crypto-hashing" version = "0.1.0" @@ -22332,27 +26383,65 @@ dependencies = [ "sp-storage 21.0.0", ] +[[package]] +name = "sp-externalities" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a904407d61cb94228c71b55a9d3708e9d6558991f9e83bd42bd91df37a159d30" +dependencies = [ + "environmental", + "parity-scale-codec", + "sp-storage 21.0.0", +] + [[package]] name = "sp-genesis-builder" version = "0.8.0" dependencies = [ "parity-scale-codec", "scale-info", - "serde_json", - "sp-api 26.0.0", + "serde_json", + "sp-api 26.0.0", + "sp-runtime 31.0.1", +] + +[[package]] +name = "sp-genesis-builder" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a646ed222fd86d5680faa4a8967980eb32f644cae6c8523e1c689a6deda3e8" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde_json", + "sp-api 34.0.0", + "sp-runtime 39.0.2", +] + +[[package]] +name = "sp-inherents" +version = "26.0.0" +dependencies = [ + "async-trait", + "futures", + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", "sp-runtime 31.0.1", + "thiserror", ] [[package]] name = "sp-inherents" -version = "26.0.0" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afffbddc380d99a90c459ba1554bbbc01d62e892de9f1485af6940b89c4c0d57" dependencies = [ "async-trait", - "futures", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", - "sp-runtime 31.0.1", + "sp-runtime 39.0.2", "thiserror", ] @@ -22368,7 +26457,7 @@ dependencies = [ "parity-scale-codec", "polkavm-derive 0.9.1", "rustversion", - "secp256k1", + "secp256k1 0.28.2", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", "sp-externalities 0.25.0", @@ -22383,9 +26472,9 @@ dependencies = [ [[package]] name = "sp-io" -version = "33.0.0" +version = "35.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e09bba780b55bd9e67979cd8f654a31e4a6cf45426ff371394a65953d2177f2" +checksum = "8b64ab18a0e29def6511139a8c45a59c14a846105aab6f9cc653523bd3b81f55" dependencies = [ "bytes", "ed25519-dalek", @@ -22394,25 +26483,25 @@ dependencies = [ "parity-scale-codec", "polkavm-derive 0.9.1", "rustversion", - "secp256k1", - "sp-core 31.0.0", + "secp256k1 0.28.2", + "sp-core 32.0.0", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-externalities 0.27.0", - "sp-keystore 0.37.0", - "sp-runtime-interface 26.0.0", - "sp-state-machine 0.38.0", + "sp-externalities 0.28.0", + "sp-keystore 0.38.0", + "sp-runtime-interface 27.0.0", + "sp-state-machine 0.40.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-tracing 16.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-trie 32.0.0", + "sp-tracing 17.0.1", + "sp-trie 34.0.0", "tracing", "tracing-core", ] [[package]] name = "sp-io" -version = "35.0.0" +version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b64ab18a0e29def6511139a8c45a59c14a846105aab6f9cc653523bd3b81f55" +checksum = "e7a31ce27358b73656a09b4933f09a700019d63afa15ede966f7c9893c1d4db5" dependencies = [ "bytes", "ed25519-dalek", @@ -22421,43 +26510,43 @@ dependencies = [ "parity-scale-codec", "polkavm-derive 0.9.1", "rustversion", - "secp256k1", - "sp-core 32.0.0", + "secp256k1 0.28.2", + "sp-core 33.0.1", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-externalities 0.28.0", - "sp-keystore 0.38.0", + "sp-keystore 0.39.0", "sp-runtime-interface 27.0.0", - "sp-state-machine 0.40.0", + "sp-state-machine 0.41.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-tracing 17.0.0", - "sp-trie 34.0.0", + "sp-tracing 17.0.1", + "sp-trie 35.0.0", "tracing", "tracing-core", ] [[package]] name = "sp-io" -version = "36.0.0" +version = "38.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a31ce27358b73656a09b4933f09a700019d63afa15ede966f7c9893c1d4db5" +checksum = "59ef7eb561bb4839cc8424ce58c5ea236cbcca83f26fcc0426d8decfe8aa97d4" dependencies = [ "bytes", + "docify", "ed25519-dalek", "libsecp256k1", "log", "parity-scale-codec", "polkavm-derive 0.9.1", "rustversion", - "secp256k1", - "sp-core 33.0.1", + "secp256k1 0.28.2", + "sp-core 34.0.0", "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-externalities 0.28.0", - "sp-keystore 0.39.0", - "sp-runtime-interface 27.0.0", - "sp-state-machine 0.41.0", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-tracing 17.0.0", - "sp-trie 35.0.0", + "sp-externalities 0.29.0", + "sp-keystore 0.40.0", + "sp-runtime-interface 28.0.0", + "sp-state-machine 0.43.0", + "sp-tracing 17.0.1", + "sp-trie 37.0.0", "tracing", "tracing-core", ] @@ -22471,6 +26560,17 @@ dependencies = [ "strum 0.26.3", ] +[[package]] +name = "sp-keyring" +version = "39.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c0e20624277f578b27f44ecfbe2ebc2e908488511ee2c900c5281599f700ab3" +dependencies = [ + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "strum 0.26.3", +] + [[package]] name = "sp-keystore" version = "0.34.0" @@ -22485,38 +26585,38 @@ dependencies = [ [[package]] name = "sp-keystore" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdbab8b61bd61d5f8625a0c75753b5d5a23be55d3445419acd42caf59cf6236b" +checksum = "4e6c7a7abd860a5211a356cf9d5fcabf0eb37d997985e5d722b6b33dcc815528" dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", - "sp-core 31.0.0", - "sp-externalities 0.27.0", + "sp-core 32.0.0", + "sp-externalities 0.28.0", ] [[package]] name = "sp-keystore" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e6c7a7abd860a5211a356cf9d5fcabf0eb37d997985e5d722b6b33dcc815528" +checksum = "92a909528663a80829b95d582a20dd4c9acd6e575650dee2bcaf56f4740b305e" dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", - "sp-core 32.0.0", + "sp-core 33.0.1", "sp-externalities 0.28.0", ] [[package]] name = "sp-keystore" -version = "0.39.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92a909528663a80829b95d582a20dd4c9acd6e575650dee2bcaf56f4740b305e" +checksum = "0248b4d784cb4a01472276928977121fa39d977a5bb24793b6b15e64b046df42" dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", - "sp-core 33.0.1", - "sp-externalities 0.28.0", + "sp-core 34.0.0", + "sp-externalities 0.29.0", ] [[package]] @@ -22567,6 +26667,18 @@ dependencies = [ "sp-application-crypto 30.0.0", ] +[[package]] +name = "sp-mixnet" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0b017dd54823b6e62f9f7171a1df350972e5c6d0bf17e0c2f78680b5c31942" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", +] + [[package]] name = "sp-mmr-primitives" version = "26.0.0" @@ -22584,6 +26696,24 @@ dependencies = [ "thiserror", ] +[[package]] +name = "sp-mmr-primitives" +version = "34.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a12dd76e368f1e48144a84b4735218b712f84b3f976970e2f25a29b30440e10" +dependencies = [ + "log", + "parity-scale-codec", + "polkadot-ckb-merkle-mountain-range", + "scale-info", + "serde", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-runtime 39.0.2", + "thiserror", +] + [[package]] name = "sp-npos-elections" version = "26.0.0" @@ -22598,6 +26728,20 @@ dependencies = [ "substrate-test-utils", ] +[[package]] +name = "sp-npos-elections" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af922f112c7c1ed199eabe14f12a82ceb75e1adf0804870eccfbcf3399492847" +dependencies = [ + "parity-scale-codec", + "scale-info", + "serde", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-npos-elections-fuzzer" version = "2.0.0-alpha.5" @@ -22605,7 +26749,7 @@ dependencies = [ "clap 4.5.13", "honggfuzz", "rand", - "sp-npos-elections", + "sp-npos-elections 26.0.0", "sp-runtime 31.0.1", ] @@ -22618,6 +26762,17 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-offchain" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9de237d72ecffd07f90826eef18360208b16d8de939d54e61591fac0fcbf99" +dependencies = [ + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-panic-handler" version = "13.0.0" @@ -22651,7 +26806,7 @@ dependencies = [ name = "sp-runtime" version = "31.0.1" dependencies = [ - "binary-merkle-tree", + "binary-merkle-tree 13.0.0", "docify", "either", "hash256-std-hasher", @@ -22683,9 +26838,9 @@ dependencies = [ [[package]] name = "sp-runtime" -version = "34.0.0" +version = "36.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec3cb126971e7db2f0fcf8053dce740684c438c7180cfca1959598230f342c58" +checksum = "a6b85cb874b78ebb17307a910fc27edf259a0455ac5155d87eaed8754c037e07" dependencies = [ "docify", "either", @@ -22698,44 +26853,45 @@ dependencies = [ "scale-info", "serde", "simple-mermaid 0.1.1", - "sp-application-crypto 33.0.0", - "sp-arithmetic 25.0.0", - "sp-core 31.0.0", - "sp-io 33.0.0", + "sp-application-crypto 35.0.0", + "sp-arithmetic 26.0.0", + "sp-core 32.0.0", + "sp-io 35.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-weights 30.0.0", + "sp-weights 31.0.0", ] [[package]] name = "sp-runtime" -version = "36.0.0" +version = "37.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6b85cb874b78ebb17307a910fc27edf259a0455ac5155d87eaed8754c037e07" +checksum = "1c2a6148bf0ba74999ecfea9b4c1ade544f0663e0baba19630bb7761b2142b19" dependencies = [ "docify", "either", "hash256-std-hasher", "impl-trait-for-tuples", "log", + "num-traits", "parity-scale-codec", "paste", "rand", "scale-info", "serde", "simple-mermaid 0.1.1", - "sp-application-crypto 35.0.0", + "sp-application-crypto 36.0.0", "sp-arithmetic 26.0.0", - "sp-core 32.0.0", - "sp-io 35.0.0", + "sp-core 33.0.1", + "sp-io 36.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-weights 31.0.0", ] [[package]] name = "sp-runtime" -version = "37.0.0" +version = "39.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c2a6148bf0ba74999ecfea9b4c1ade544f0663e0baba19630bb7761b2142b19" +checksum = "658f23be7c79a85581029676a73265c107c5469157e3444c8c640fdbaa8bfed0" dependencies = [ "docify", "either", @@ -22749,12 +26905,13 @@ dependencies = [ "scale-info", "serde", "simple-mermaid 0.1.1", - "sp-application-crypto 36.0.0", + "sp-application-crypto 38.0.0", "sp-arithmetic 26.0.0", - "sp-core 33.0.1", - "sp-io 36.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-weights 31.0.0", + "tracing", ] [[package]] @@ -22834,8 +26991,28 @@ dependencies = [ "sp-runtime-interface-proc-macro 18.0.0", "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "sp-storage 21.0.0", - "sp-tracing 17.0.0", - "sp-wasm-interface 21.0.0", + "sp-tracing 17.0.1", + "sp-wasm-interface 21.0.1", + "static_assertions", +] + +[[package]] +name = "sp-runtime-interface" +version = "28.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985eb981f40c689c6a0012c937b68ed58dabb4341d06f2dfe4dfd5ed72fa4017" +dependencies = [ + "bytes", + "impl-trait-for-tuples", + "parity-scale-codec", + "polkavm-derive 0.9.1", + "primitive-types 0.12.2", + "sp-externalities 0.29.0", + "sp-runtime-interface-proc-macro 18.0.0", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-storage 21.0.0", + "sp-tracing 17.0.1", + "sp-wasm-interface 21.0.1", "static_assertions", ] @@ -22901,7 +27078,7 @@ dependencies = [ "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime-interface 24.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -22911,7 +27088,7 @@ dependencies = [ "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime-interface 24.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -22924,7 +27101,22 @@ dependencies = [ "sp-core 28.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", - "sp-staking", + "sp-staking 26.0.0", +] + +[[package]] +name = "sp-session" +version = "36.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00a3a307fedc423fb8cd2a7726a3bbb99014f1b4b52f26153993e2aae3338fe6" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-core 34.0.0", + "sp-keystore 0.40.0", + "sp-runtime 39.0.2", + "sp-staking 36.0.0", ] [[package]] @@ -22939,6 +27131,34 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-staking" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "143a764cacbab58347d8b2fd4c8909031fb0888d7b02a0ec9fa44f81f780d732" +dependencies = [ + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + +[[package]] +name = "sp-staking" +version = "36.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a73eedb4b85f4cd420d31764827546aa22f82ce1646d0fd258993d051de7a90" +dependencies = [ + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "serde", + "sp-core 34.0.0", + "sp-runtime 39.0.2", +] + [[package]] name = "sp-state-machine" version = "0.35.0" @@ -22960,14 +27180,14 @@ dependencies = [ "sp-trie 29.0.0", "thiserror", "tracing", - "trie-db 0.29.1", + "trie-db", ] [[package]] name = "sp-state-machine" -version = "0.38.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1eae0eac8034ba14437e772366336f579398a46d101de13dbb781ab1e35e67c5" +checksum = "18084cb996c27d5d99a88750e0a8eb4af6870a40df97872a5923e6d293d95fb9" dependencies = [ "hash-db", "log", @@ -22975,21 +27195,20 @@ dependencies = [ "parking_lot 0.12.3", "rand", "smallvec", - "sp-core 31.0.0", - "sp-externalities 0.27.0", + "sp-core 32.0.0", + "sp-externalities 0.28.0", "sp-panic-handler 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-trie 32.0.0", + "sp-trie 34.0.0", "thiserror", "tracing", - "trie-db 0.28.0", + "trie-db", ] [[package]] name = "sp-state-machine" -version = "0.40.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18084cb996c27d5d99a88750e0a8eb4af6870a40df97872a5923e6d293d95fb9" +checksum = "6f6ac196ea92c4d0613c071e1a050765dbfa30107a990224a4aba02c7dbcd063" dependencies = [ "hash-db", "log", @@ -22997,20 +27216,20 @@ dependencies = [ "parking_lot 0.12.3", "rand", "smallvec", - "sp-core 32.0.0", + "sp-core 33.0.1", "sp-externalities 0.28.0", "sp-panic-handler 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-trie 34.0.0", + "sp-trie 35.0.0", "thiserror", "tracing", - "trie-db 0.29.1", + "trie-db", ] [[package]] name = "sp-state-machine" -version = "0.41.0" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f6ac196ea92c4d0613c071e1a050765dbfa30107a990224a4aba02c7dbcd063" +checksum = "930104d6ae882626e8880d9b1578da9300655d337a3ffb45e130c608b6c89660" dependencies = [ "hash-db", "log", @@ -23018,13 +27237,13 @@ dependencies = [ "parking_lot 0.12.3", "rand", "smallvec", - "sp-core 33.0.1", - "sp-externalities 0.28.0", + "sp-core 34.0.0", + "sp-externalities 0.29.0", "sp-panic-handler 13.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-trie 35.0.0", + "sp-trie 37.0.0", "thiserror", "tracing", - "trie-db 0.29.1", + "trie-db", ] [[package]] @@ -23050,6 +27269,31 @@ dependencies = [ "x25519-dalek", ] +[[package]] +name = "sp-statement-store" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c219bc34ef4d1f9835f3ed881f965643c32034fcc030eb33b759dadbc802c1c2" +dependencies = [ + "aes-gcm", + "curve25519-dalek 4.1.3", + "ed25519-dalek", + "hkdf", + "parity-scale-codec", + "rand", + "scale-info", + "sha2 0.10.8", + "sp-api 34.0.0", + "sp-application-crypto 38.0.0", + "sp-core 34.0.0", + "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-externalities 0.29.0", + "sp-runtime 39.0.2", + "sp-runtime-interface 28.0.0", + "thiserror", + "x25519-dalek", +] + [[package]] name = "sp-std" version = "8.0.0" @@ -23134,11 +27378,24 @@ version = "26.0.0" dependencies = [ "async-trait", "parity-scale-codec", - "sp-inherents", + "sp-inherents 26.0.0", "sp-runtime 31.0.1", "thiserror", ] +[[package]] +name = "sp-timestamp" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a1cb4df653d62ccc0dbce1db45d1c9443ec60247ee9576962d24da4c9c6f07" +dependencies = [ + "async-trait", + "parity-scale-codec", + "sp-inherents 34.0.0", + "sp-runtime 39.0.2", + "thiserror", +] + [[package]] name = "sp-tracing" version = "10.0.0" @@ -23176,14 +27433,14 @@ dependencies = [ [[package]] name = "sp-tracing" -version = "17.0.0" +version = "17.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90b3decf116db9f1dfaf1f1597096b043d0e12c952d3bcdc018c6d6b77deec7e" +checksum = "cf641a1d17268c8fcfdb8e0fa51a79c2d4222f4cfda5f3944dbdbc384dced8d5" dependencies = [ "parity-scale-codec", "tracing", "tracing-core", - "tracing-subscriber 0.2.25", + "tracing-subscriber 0.3.18", ] [[package]] @@ -23194,17 +27451,42 @@ dependencies = [ "sp-runtime 31.0.1", ] +[[package]] +name = "sp-transaction-pool" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4bf251059485a7dd38fe4afeda8792983511cc47f342ff4695e2dcae6b5247" +dependencies = [ + "sp-api 34.0.0", + "sp-runtime 39.0.2", +] + +[[package]] +name = "sp-transaction-storage-proof" +version = "26.0.0" +dependencies = [ + "async-trait", + "parity-scale-codec", + "scale-info", + "sp-core 28.0.0", + "sp-inherents 26.0.0", + "sp-runtime 31.0.1", + "sp-trie 29.0.0", +] + [[package]] name = "sp-transaction-storage-proof" -version = "26.0.0" +version = "34.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c765c2e9817d95f13d42a9f2295c60723464669765c6e5acbacebd2f54932f67" dependencies = [ "async-trait", "parity-scale-codec", "scale-info", - "sp-core 28.0.0", - "sp-inherents", - "sp-runtime 31.0.1", - "sp-trie 29.0.0", + "sp-core 34.0.0", + "sp-inherents 34.0.0", + "sp-runtime 39.0.2", + "sp-trie 37.0.0", ] [[package]] @@ -23228,16 +27510,16 @@ dependencies = [ "thiserror", "tracing", "trie-bench", - "trie-db 0.29.1", + "trie-db", "trie-root", "trie-standardmap", ] [[package]] name = "sp-trie" -version = "32.0.0" +version = "34.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1aa91ad26c62b93d73e65f9ce7ebd04459c4bad086599348846a81988d6faa4" +checksum = "87727eced997f14d0f79e3a5186a80e38a9de87f6e9dc0baea5ebf8b7f9d8b66" dependencies = [ "ahash 0.8.11", "hash-db", @@ -23249,20 +27531,19 @@ dependencies = [ "rand", "scale-info", "schnellru", - "sp-core 31.0.0", - "sp-externalities 0.27.0", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-core 32.0.0", + "sp-externalities 0.28.0", "thiserror", "tracing", - "trie-db 0.28.0", + "trie-db", "trie-root", ] [[package]] name = "sp-trie" -version = "34.0.0" +version = "35.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87727eced997f14d0f79e3a5186a80e38a9de87f6e9dc0baea5ebf8b7f9d8b66" +checksum = "a61ab0c3e003f457203702e4753aa5fe9e762380543fada44650b1217e4aa5a5" dependencies = [ "ahash 0.8.11", "hash-db", @@ -23274,19 +27555,19 @@ dependencies = [ "rand", "scale-info", "schnellru", - "sp-core 32.0.0", + "sp-core 33.0.1", "sp-externalities 0.28.0", "thiserror", "tracing", - "trie-db 0.29.1", + "trie-db", "trie-root", ] [[package]] name = "sp-trie" -version = "35.0.0" +version = "37.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a61ab0c3e003f457203702e4753aa5fe9e762380543fada44650b1217e4aa5a5" +checksum = "6282aef9f4b6ecd95a67a45bcdb67a71f4a4155c09a53c10add4ffe823db18cd" dependencies = [ "ahash 0.8.11", "hash-db", @@ -23298,11 +27579,11 @@ dependencies = [ "rand", "scale-info", "schnellru", - "sp-core 33.0.1", - "sp-externalities 0.28.0", + "sp-core 34.0.0", + "sp-externalities 0.29.0", "thiserror", "tracing", - "trie-db 0.29.1", + "trie-db", "trie-root", ] @@ -23340,6 +27621,24 @@ dependencies = [ "thiserror", ] +[[package]] +name = "sp-version" +version = "37.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d521a405707b5be561367cd3d442ff67588993de24062ce3adefcf8437ee9fe1" +dependencies = [ + "impl-serde 0.4.0", + "parity-scale-codec", + "parity-wasm", + "scale-info", + "serde", + "sp-crypto-hashing-proc-macro 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "sp-version-proc-macro 14.0.0", + "thiserror", +] + [[package]] name = "sp-version-proc-macro" version = "13.0.0" @@ -23404,9 +27703,9 @@ dependencies = [ [[package]] name = "sp-wasm-interface" -version = "21.0.0" +version = "21.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b04b919e150b4736d85089d49327eab65507deb1485eec929af69daa2278eb3" +checksum = "b066baa6d57951600b14ffe1243f54c47f9c23dd89c262e17ca00ae8dca58be9" dependencies = [ "anyhow", "impl-trait-for-tuples", @@ -23429,22 +27728,6 @@ dependencies = [ "sp-debug-derive 14.0.0", ] -[[package]] -name = "sp-weights" -version = "30.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9af6c661fe3066b29f9e1d258000f402ff5cc2529a9191972d214e5871d0ba87" -dependencies = [ - "bounded-collections", - "parity-scale-codec", - "scale-info", - "serde", - "smallvec", - "sp-arithmetic 25.0.0", - "sp-debug-derive 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "sp-weights" version = "31.0.0" @@ -23562,7 +27845,7 @@ dependencies = [ "clap_complete", "criterion", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "kitchensink-runtime", "log", "nix 0.28.0", @@ -23571,7 +27854,7 @@ dependencies = [ "node-testing", "parity-scale-codec", "platforms", - "polkadot-sdk", + "polkadot-sdk 0.1.0", "pretty_assertions", "rand", "regex", @@ -23580,7 +27863,7 @@ dependencies = [ "serde", "serde_json", "soketto 0.8.0", - "sp-keyring", + "sp-keyring 31.0.0", "staging-node-inspect", "substrate-cli-test-utils", "subxt-signer", @@ -23604,7 +27887,7 @@ dependencies = [ "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "sp-statement-store", + "sp-statement-store 10.0.0", "thiserror", ] @@ -23612,14 +27895,28 @@ dependencies = [ name = "staging-parachain-info" version = "0.7.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", - "frame-system", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "scale-info", "sp-runtime 31.0.1", ] +[[package]] +name = "staging-parachain-info" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d28266dfddbfff721d70ad2f873380845b569adfab32f257cf97d9cedd894b68" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-runtime 39.0.2", +] + [[package]] name = "staging-tracking-allocator" version = "2.0.0" @@ -23632,7 +27929,7 @@ dependencies = [ "bounded-collections", "derivative", "environmental", - "frame-support", + "frame-support 28.0.0", "hex", "hex-literal", "impl-trait-for-tuples", @@ -23644,7 +27941,27 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", - "xcm-procedural", + "xcm-procedural 7.0.0", +] + +[[package]] +name = "staging-xcm" +version = "14.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bee7cd999e9cdf10f8db72342070d456e21e82a0f5962ff3b87edbd5f2b20e" +dependencies = [ + "array-bytes", + "bounded-collections", + "derivative", + "environmental", + "impl-trait-for-tuples", + "log", + "parity-scale-codec", + "scale-info", + "serde", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "xcm-procedural 10.1.0", ] [[package]] @@ -23652,20 +27969,20 @@ name = "staging-xcm-builder" version = "7.0.0" dependencies = [ "assert_matches", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-asset-conversion", - "pallet-assets", - "pallet-balances", - "pallet-salary", - "pallet-transaction-payment", - "pallet-xcm", + "pallet-asset-conversion 10.0.0", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-salary 13.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "polkadot-test-runtime", "primitive-types 0.13.1", "scale-info", @@ -23674,8 +27991,31 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "staging-xcm-builder" +version = "17.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3746adbbae27b1e6763f0cca622e15482ebcb94835a9e078c212dd7be896e35" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "impl-trait-for-tuples", + "log", + "pallet-asset-conversion 20.0.0", + "pallet-transaction-payment 38.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 14.0.0", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] @@ -23683,8 +28023,8 @@ name = "staging-xcm-executor" version = "7.0.0" dependencies = [ "environmental", - "frame-benchmarking", - "frame-support", + "frame-benchmarking 28.0.0", + "frame-support 28.0.0", "impl-trait-for-tuples", "parity-scale-codec", "scale-info", @@ -23693,7 +28033,28 @@ dependencies = [ "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", - "staging-xcm", + "staging-xcm 7.0.0", + "tracing", +] + +[[package]] +name = "staging-xcm-executor" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79dd0c5332a5318e58f0300b20768b71cf9427c906f94a743c9dc7c3ee9e7fa9" +dependencies = [ + "environmental", + "frame-benchmarking 38.0.0", + "frame-support 38.0.0", + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "sp-arithmetic 26.0.0", + "sp-core 34.0.0", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "staging-xcm 14.2.0", "tracing", ] @@ -23710,7 +28071,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a2a1c578e98c1c16fc3b8ec1328f7659a500737d7a0c6d625e73e830ff9c1f6" dependencies = [ "bitflags 1.3.2", - "cfg_aliases 0.1.1", + "cfg_aliases", "libc", "parking_lot 0.11.2", "parking_lot_core 0.8.6", @@ -23724,7 +28085,7 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70a2595fc3aa78f2d0e45dd425b22282dd863273761cc77780914b2cf3003acf" dependencies = [ - "cfg_aliases 0.1.1", + "cfg_aliases", "memchr", "proc-macro2 1.0.86", "quote 1.0.37", @@ -23947,9 +28308,9 @@ dependencies = [ name = "substrate-frame-rpc-support" version = "29.0.0" dependencies = [ - "frame-support", - "frame-system", - "jsonrpsee 0.24.3", + "frame-support 28.0.0", + "frame-system 28.0.0", + "jsonrpsee", "parity-scale-codec", "sc-rpc-api", "scale-info", @@ -23966,16 +28327,16 @@ version = "28.0.0" dependencies = [ "assert_matches", "docify", - "frame-system-rpc-runtime-api", + "frame-system-rpc-runtime-api 26.0.0", "futures", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "parity-scale-codec", "sc-rpc-api", "sc-transaction-pool", "sc-transaction-pool-api", "sp-api 26.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-blockchain", "sp-core 28.0.0", "sp-runtime 31.0.1", @@ -24004,34 +28365,34 @@ dependencies = [ "anyhow", "async-std", "async-trait", - "bp-header-chain", - "bp-messages", - "bp-parachains", - "bp-polkadot-core", - "bp-relayers", - "bp-runtime", + "bp-header-chain 0.7.0", + "bp-messages 0.7.0", + "bp-parachains 0.7.0", + "bp-polkadot-core 0.7.0", + "bp-relayers 0.7.0", + "bp-runtime 0.7.0", "equivocation-detector", "finality-relay", - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "futures", "hex", "log", "messages-relay", "num-traits", - "pallet-balances", - "pallet-bridge-grandpa", - "pallet-bridge-messages", - "pallet-bridge-parachains", - "pallet-grandpa", - "pallet-transaction-payment", + "pallet-balances 28.0.0", + "pallet-bridge-grandpa 0.7.0", + "pallet-bridge-messages 0.7.0", + "pallet-bridge-parachains 0.7.0", + "pallet-grandpa 28.0.0", + "pallet-transaction-payment 28.0.0", "parachains-relay", "parity-scale-codec", "rbtag", "relay-substrate-client", "relay-utils", "scale-info", - "sp-consensus-grandpa", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-trie 29.0.0", @@ -24045,7 +28406,7 @@ name = "substrate-rpc-client" version = "0.33.0" dependencies = [ "async-trait", - "jsonrpsee 0.24.3", + "jsonrpsee", "log", "sc-rpc-api", "serde", @@ -24066,7 +28427,7 @@ dependencies = [ "sp-core 32.0.0", "sp-io 35.0.0", "sp-runtime 36.0.0", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", "thiserror", ] @@ -24074,7 +28435,7 @@ dependencies = [ name = "substrate-state-trie-migration-rpc" version = "27.0.0" dependencies = [ - "jsonrpsee 0.24.3", + "jsonrpsee", "parity-scale-codec", "sc-client-api", "sc-rpc-api", @@ -24084,7 +28445,7 @@ dependencies = [ "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-trie 29.0.0", - "trie-db 0.29.1", + "trie-db", ] [[package]] @@ -24106,7 +28467,7 @@ dependencies = [ "sp-blockchain", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", @@ -24118,16 +28479,16 @@ name = "substrate-test-runtime" version = "2.0.0" dependencies = [ "array-bytes", - "frame-executive", - "frame-metadata-hash-extension", - "frame-support", - "frame-system", - "frame-system-rpc-runtime-api", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", "futures", "log", - "pallet-babe", - "pallet-balances", - "pallet-timestamp", + "pallet-babe 28.0.0", + "pallet-balances 28.0.0", + "pallet-timestamp 27.0.0", "parity-scale-codec", "sc-block-builder", "sc-chain-spec", @@ -24139,30 +28500,30 @@ dependencies = [ "serde_json", "sp-api 26.0.0", "sp-application-crypto 30.0.0", - "sp-block-builder", + "sp-block-builder 26.0.0", "sp-consensus", - "sp-consensus-aura", - "sp-consensus-babe", - "sp-consensus-grandpa", + "sp-consensus-aura 0.32.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-grandpa 13.0.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", "sp-externalities 0.25.0", - "sp-genesis-builder", - "sp-inherents", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", + "sp-session 27.0.0", "sp-state-machine 0.35.0", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-trie 29.0.0", "sp-version 29.0.0", "substrate-test-runtime-client", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", "tracing", - "trie-db 0.29.1", + "trie-db", ] [[package]] @@ -24237,6 +28598,27 @@ dependencies = [ "wasm-opt", ] +[[package]] +name = "substrate-wasm-builder" +version = "24.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf035ffe7335fb24053edfe4d0a5780250eda772082a1b80ae25835dd4c09265" +dependencies = [ + "build-helper", + "cargo_metadata", + "console", + "filetime", + "jobserver", + "parity-wasm", + "polkavm-linker 0.9.2", + "sp-maybe-compressed-blob 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "strum 0.26.3", + "tempfile", + "toml 0.8.12", + "walkdir", + "wasm-opt", +] + [[package]] name = "subtle" version = "1.0.0" @@ -24283,50 +28665,49 @@ dependencies = [ [[package]] name = "subxt" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a160cba1edbf3ec4fbbeaea3f1a185f70448116a6bccc8276bb39adb3b3053bd" +checksum = "c53029d133e4e0cb7933f1fe06f2c68804b956de9bb8fa930ffca44e9e5e4230" dependencies = [ "async-trait", "derive-where", "either", - "frame-metadata 16.0.0", + "finito", + "frame-metadata 17.0.0", "futures", "hex", - "impl-serde 0.4.0", - "instant", - "jsonrpsee 0.22.5", + "impl-serde 0.5.0", + "jsonrpsee", "parity-scale-codec", - "primitive-types 0.12.2", - "reconnecting-jsonrpsee-ws-client", + "polkadot-sdk 0.7.0", + "primitive-types 0.13.1", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-value", "serde", "serde_json", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "subxt-core", "subxt-lightclient", "subxt-macro", "subxt-metadata", "thiserror", + "tokio", "tokio-util", "tracing", "url", + "wasm-bindgen-futures", + "web-time", ] [[package]] name = "subxt-codegen" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d703dca0905cc5272d7cc27a4ac5f37dcaae7671acc7fef0200057cc8c317786" +checksum = "3cfcfb7d9589f3df0ac87c4988661cf3fb370761fcb19f2fd33104cc59daf22a" dependencies = [ - "frame-metadata 16.0.0", "heck 0.5.0", - "hex", - "jsonrpsee 0.22.5", "parity-scale-codec", "proc-macro2 1.0.86", "quote 1.0.37", @@ -24335,49 +28716,48 @@ dependencies = [ "subxt-metadata", "syn 2.0.87", "thiserror", - "tokio", ] [[package]] name = "subxt-core" -version = "0.37.1" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3af3b36405538a36b424d229dc908d1396ceb0994c90825ce928709eac1a159a" +checksum = "7ea28114366780d23684bd55ab879cd04c9d4cbba3b727a3854a3eca6bf29a1a" dependencies = [ "base58", "blake2 0.10.6", "derive-where", - "frame-metadata 16.0.0", + "frame-decode", + "frame-metadata 17.0.0", "hashbrown 0.14.5", "hex", - "impl-serde 0.4.0", + "impl-serde 0.5.0", + "keccak-hash", "parity-scale-codec", - "primitive-types 0.12.2", + "polkadot-sdk 0.7.0", + "primitive-types 0.13.1", "scale-bits", - "scale-decode", + "scale-decode 0.14.0", "scale-encode", "scale-info", "scale-value", "serde", "serde_json", - "sp-core 31.0.0", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "sp-runtime 34.0.0", "subxt-metadata", "tracing", ] [[package]] name = "subxt-lightclient" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d9406fbdb9548c110803cb8afa750f8b911d51eefdf95474b11319591d225d9" +checksum = "534d4b725183a9fa09ce0e0f135674473297fdd97dee4d683f41117f365ae997" dependencies = [ "futures", "futures-util", "serde", "serde_json", - "smoldot-light 0.14.0", + "smoldot-light 0.16.2", "thiserror", "tokio", "tokio-stream", @@ -24386,56 +28766,74 @@ dependencies = [ [[package]] name = "subxt-macro" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c195f803d70687e409aba9be6c87115b5da8952cd83c4d13f2e043239818fcd" +checksum = "228db9a5c95a6d8dc6152b4d6cdcbabc4f60821dd3f482a4f8791e022b7caadb" dependencies = [ - "darling 0.20.10", + "darling", "parity-scale-codec", - "proc-macro-error", + "proc-macro-error2", "quote 1.0.37", "scale-typegen", "subxt-codegen", + "subxt-utils-fetchmetadata", "syn 2.0.87", ] [[package]] name = "subxt-metadata" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "738be5890fdeff899bbffff4d9c0f244fe2a952fb861301b937e3aa40ebb55da" +checksum = "ee13e6862eda035557d9a2871955306aff540d2b89c06e0a62a1136a700aed28" dependencies = [ - "frame-metadata 16.0.0", + "frame-decode", + "frame-metadata 17.0.0", "hashbrown 0.14.5", "parity-scale-codec", + "polkadot-sdk 0.7.0", "scale-info", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "subxt-signer" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49888ae6ae90fe01b471193528eea5bd4ed52d8eecd2d13f4a2333b87388850" +checksum = "1e7a336d6a1f86f126100a4a717be58352de4c8214300c4f7807f974494efdb9" dependencies = [ + "base64 0.22.1", "bip32", "bip39", "cfg-if", + "crypto_secretbox", "hex", "hmac 0.12.1", "keccak-hash", "parity-scale-codec", "pbkdf2", + "polkadot-sdk 0.7.0", "regex", "schnorrkel 0.11.4", - "secp256k1", - "secrecy", + "scrypt", + "secp256k1 0.30.0", + "secrecy 0.10.3", + "serde", + "serde_json", "sha2 0.10.8", - "sp-crypto-hashing 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "subxt-core", "zeroize", ] +[[package]] +name = "subxt-utils-fetchmetadata" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3082b17a86e3c3fe45d858d94d68f6b5247caace193dad6201688f24db8ba9bb" +dependencies = [ + "hex", + "parity-scale-codec", + "thiserror", +] + [[package]] name = "sval" version = "2.6.1" @@ -24737,9 +29135,9 @@ version = "1.0.0" dependencies = [ "dlmalloc", "parity-scale-codec", - "polkadot-parachain-primitives", + "polkadot-parachain-primitives 6.0.0", "sp-io 30.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", "tiny-keccak", ] @@ -24756,14 +29154,14 @@ dependencies = [ "polkadot-node-core-pvf", "polkadot-node-primitives", "polkadot-node-subsystem", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-service", "polkadot-test-service", "sc-cli", "sc-service", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "substrate-test-utils", "test-parachain-adder", "tokio", @@ -24774,7 +29172,7 @@ name = "test-parachain-halt" version = "1.0.0" dependencies = [ "rustversion", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", ] [[package]] @@ -24784,9 +29182,9 @@ dependencies = [ "dlmalloc", "log", "parity-scale-codec", - "polkadot-parachain-primitives", + "polkadot-parachain-primitives 6.0.0", "sp-io 30.0.0", - "substrate-wasm-builder", + "substrate-wasm-builder 17.0.0", "tiny-keccak", ] @@ -24803,14 +29201,14 @@ dependencies = [ "polkadot-node-core-pvf", "polkadot-node-primitives", "polkadot-node-subsystem", - "polkadot-parachain-primitives", - "polkadot-primitives", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", "polkadot-service", "polkadot-test-service", "sc-cli", "sc-service", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "substrate-test-utils", "test-parachain-undying", "tokio", @@ -24831,8 +29229,8 @@ dependencies = [ name = "test-runtime-constants" version = "1.0.0" dependencies = [ - "frame-support", - "polkadot-primitives", + "frame-support 28.0.0", + "polkadot-primitives 7.0.0", "smallvec", "sp-runtime 31.0.1", ] @@ -24841,14 +29239,30 @@ dependencies = [ name = "testnet-parachains-constants" version = "1.0.0" dependencies = [ - "cumulus-primitives-core", - "frame-support", - "polkadot-core-primitives", - "rococo-runtime-constants", + "cumulus-primitives-core 0.7.0", + "frame-support 28.0.0", + "polkadot-core-primitives 7.0.0", + "rococo-runtime-constants 7.0.0", "smallvec", "sp-runtime 31.0.1", - "staging-xcm", - "westend-runtime-constants", + "staging-xcm 7.0.0", + "westend-runtime-constants 7.0.0", +] + +[[package]] +name = "testnet-parachains-constants" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94bceae6f7c89d47daff6c7e05f712551a01379f61b07d494661941144878589" +dependencies = [ + "cumulus-primitives-core 0.16.0", + "frame-support 38.0.0", + "polkadot-core-primitives 15.0.0", + "rococo-runtime-constants 17.0.0", + "smallvec", + "sp-runtime 39.0.2", + "staging-xcm 14.2.0", + "westend-runtime-constants 17.0.0", ] [[package]] @@ -25099,17 +29513,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "tokio-rustls" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" -dependencies = [ - "rustls 0.22.4", - "rustls-pki-types", - "tokio", -] - [[package]] name = "tokio-rustls" version = "0.26.0" @@ -25163,9 +29566,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" +checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" dependencies = [ "bytes", "futures-core", @@ -25369,7 +29772,7 @@ name = "tracing-gum" version = "7.0.0" dependencies = [ "coarsetime", - "polkadot-primitives", + "polkadot-primitives 7.0.0", "tracing", "tracing-gum-proc-macro", ] @@ -25472,24 +29875,11 @@ dependencies = [ "keccak-hasher", "memory-db", "parity-scale-codec", - "trie-db 0.29.1", + "trie-db", "trie-root", "trie-standardmap", ] -[[package]] -name = "trie-db" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff28e0f815c2fea41ebddf148e008b077d2faddb026c9555b29696114d602642" -dependencies = [ - "hash-db", - "hashbrown 0.13.2", - "log", - "rustc-hex", - "smallvec", -] - [[package]] name = "trie-db" version = "0.29.1" @@ -26013,9 +30403,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" dependencies = [ "cfg-if", "once_cell", @@ -26026,9 +30416,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" dependencies = [ "bumpalo", "log", @@ -26041,9 +30431,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.37" +version = "0.4.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" +checksum = "cc7ec4f8827a71586374db3e87abdb5a2bb3a15afed140221307c3ec06b1f63b" dependencies = [ "cfg-if", "js-sys", @@ -26053,9 +30443,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" dependencies = [ "quote 1.0.37", "wasm-bindgen-macro-support", @@ -26063,9 +30453,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2 1.0.86", "quote 1.0.37", @@ -26076,9 +30466,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" [[package]] name = "wasm-bindgen-test" @@ -26198,7 +30588,7 @@ dependencies = [ "sp-runtime 37.0.0", "sp-state-machine 0.41.0", "sp-version 35.0.0", - "sp-wasm-interface 21.0.0", + "sp-wasm-interface 21.0.1", "substrate-runtime-proposal-hash", "thiserror", "wasm-loader", @@ -26535,6 +30925,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki" version = "0.22.4" @@ -26565,19 +30965,19 @@ name = "westend-emulated-chain" version = "0.0.0" dependencies = [ "emulated-integration-tests-common", - "pallet-staking", - "parachains-common", - "polkadot-primitives", + "pallet-staking 28.0.0", + "parachains-common 7.0.0", + "polkadot-primitives 7.0.0", "sc-consensus-grandpa", - "sp-authority-discovery", - "sp-consensus-babe", - "sp-consensus-beefy", + "sp-authority-discovery 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", "sp-core 28.0.0", "sp-runtime 31.0.1", - "staging-xcm", + "staging-xcm 7.0.0", "westend-runtime", - "westend-runtime-constants", - "xcm-runtime-apis", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -26585,77 +30985,77 @@ name = "westend-runtime" version = "7.0.0" dependencies = [ "approx", - "binary-merkle-tree", + "binary-merkle-tree 13.0.0", "bitvec", - "frame-benchmarking", - "frame-election-provider-support", - "frame-executive", - "frame-metadata-hash-extension", + "frame-benchmarking 28.0.0", + "frame-election-provider-support 28.0.0", + "frame-executive 28.0.0", + "frame-metadata-hash-extension 0.1.0", "frame-remote-externalities", - "frame-support", - "frame-system", - "frame-system-benchmarking", - "frame-system-rpc-runtime-api", - "frame-try-runtime", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-system-benchmarking 28.0.0", + "frame-system-rpc-runtime-api 26.0.0", + "frame-try-runtime 0.34.0", "hex-literal", "log", - "pallet-asset-rate", - "pallet-authority-discovery", - "pallet-authorship", - "pallet-babe", - "pallet-bags-list", - "pallet-balances", - "pallet-beefy", - "pallet-beefy-mmr", - "pallet-collective", - "pallet-conviction-voting", - "pallet-delegated-staking", - "pallet-democracy", - "pallet-election-provider-multi-phase", - "pallet-election-provider-support-benchmarking", - "pallet-elections-phragmen", - "pallet-fast-unstake", - "pallet-grandpa", - "pallet-identity", - "pallet-indices", - "pallet-membership", - "pallet-message-queue", - "pallet-migrations", - "pallet-mmr", - "pallet-multisig", - "pallet-nomination-pools", - "pallet-nomination-pools-benchmarking", - "pallet-nomination-pools-runtime-api", - "pallet-offences", - "pallet-offences-benchmarking", - "pallet-parameters", - "pallet-preimage", - "pallet-proxy", - "pallet-recovery", - "pallet-referenda", - "pallet-root-testing", - "pallet-scheduler", - "pallet-session", - "pallet-session-benchmarking", - "pallet-society", - "pallet-staking", - "pallet-staking-runtime-api", - "pallet-state-trie-migration", - "pallet-sudo", - "pallet-timestamp", - "pallet-transaction-payment", - "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury", - "pallet-utility", - "pallet-vesting", - "pallet-whitelist", - "pallet-xcm", - "pallet-xcm-benchmarks", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-common", - "polkadot-runtime-parachains", + "pallet-asset-rate 7.0.0", + "pallet-authority-discovery 28.0.0", + "pallet-authorship 28.0.0", + "pallet-babe 28.0.0", + "pallet-bags-list 27.0.0", + "pallet-balances 28.0.0", + "pallet-beefy 28.0.0", + "pallet-beefy-mmr 28.0.0", + "pallet-collective 28.0.0", + "pallet-conviction-voting 28.0.0", + "pallet-delegated-staking 1.0.0", + "pallet-democracy 28.0.0", + "pallet-election-provider-multi-phase 27.0.0", + "pallet-election-provider-support-benchmarking 27.0.0", + "pallet-elections-phragmen 29.0.0", + "pallet-fast-unstake 27.0.0", + "pallet-grandpa 28.0.0", + "pallet-identity 29.0.0", + "pallet-indices 28.0.0", + "pallet-membership 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-migrations 1.0.0", + "pallet-mmr 27.0.0", + "pallet-multisig 28.0.0", + "pallet-nomination-pools 25.0.0", + "pallet-nomination-pools-benchmarking 26.0.0", + "pallet-nomination-pools-runtime-api 23.0.0", + "pallet-offences 27.0.0", + "pallet-offences-benchmarking 28.0.0", + "pallet-parameters 0.1.0", + "pallet-preimage 28.0.0", + "pallet-proxy 28.0.0", + "pallet-recovery 28.0.0", + "pallet-referenda 28.0.0", + "pallet-root-testing 4.0.0", + "pallet-scheduler 29.0.0", + "pallet-session 28.0.0", + "pallet-session-benchmarking 28.0.0", + "pallet-society 28.0.0", + "pallet-staking 28.0.0", + "pallet-staking-runtime-api 14.0.0", + "pallet-state-trie-migration 29.0.0", + "pallet-sudo 28.0.0", + "pallet-timestamp 27.0.0", + "pallet-transaction-payment 28.0.0", + "pallet-transaction-payment-rpc-runtime-api 28.0.0", + "pallet-treasury 27.0.0", + "pallet-utility 28.0.0", + "pallet-vesting 28.0.0", + "pallet-whitelist 27.0.0", + "pallet-xcm 7.0.0", + "pallet-xcm-benchmarks 7.0.0", + "parity-scale-codec", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "serde", "serde_derive", @@ -26664,49 +31064,66 @@ dependencies = [ "sp-api 26.0.0", "sp-application-crypto 30.0.0", "sp-arithmetic 23.0.0", - "sp-authority-discovery", - "sp-block-builder", - "sp-consensus-babe", - "sp-consensus-beefy", - "sp-consensus-grandpa", - "sp-core 28.0.0", - "sp-genesis-builder", - "sp-inherents", + "sp-authority-discovery 26.0.0", + "sp-block-builder 26.0.0", + "sp-consensus-babe 0.32.0", + "sp-consensus-beefy 13.0.0", + "sp-consensus-grandpa 13.0.0", + "sp-core 28.0.0", + "sp-genesis-builder 0.8.0", + "sp-inherents 26.0.0", "sp-io 30.0.0", - "sp-keyring", - "sp-mmr-primitives", - "sp-npos-elections", - "sp-offchain", + "sp-keyring 31.0.0", + "sp-mmr-primitives 26.0.0", + "sp-npos-elections 26.0.0", + "sp-offchain 26.0.0", "sp-runtime 31.0.1", - "sp-session", - "sp-staking", + "sp-session 27.0.0", + "sp-staking 26.0.0", "sp-storage 19.0.0", "sp-tracing 16.0.0", - "sp-transaction-pool", + "sp-transaction-pool 26.0.0", "sp-version 29.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "substrate-wasm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "substrate-wasm-builder 17.0.0", "tiny-keccak", "tokio", - "westend-runtime-constants", - "xcm-runtime-apis", + "westend-runtime-constants 7.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] name = "westend-runtime-constants" version = "7.0.0" dependencies = [ - "frame-support", - "polkadot-primitives", - "polkadot-runtime-common", + "frame-support 28.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-common 7.0.0", "smallvec", "sp-core 28.0.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", - "staging-xcm", - "staging-xcm-builder", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", +] + +[[package]] +name = "westend-runtime-constants" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06861bf945aadac59f4be23b44c85573029520ea9bd3d6c9ab21c8b306e81cdc" +dependencies = [ + "frame-support 38.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-common 17.0.0", + "smallvec", + "sp-core 34.0.0", + "sp-runtime 39.0.2", + "sp-weights 31.0.0", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", ] [[package]] @@ -27138,24 +31555,24 @@ name = "xcm-docs" version = "0.1.0" dependencies = [ "docify", - "pallet-balances", - "pallet-message-queue", - "pallet-xcm", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", - "polkadot-sdk-frame", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", + "polkadot-sdk-frame 0.1.0", "scale-info", "simple-mermaid 0.1.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", "test-log", - "xcm-simulator", + "xcm-simulator 7.0.0", ] [[package]] @@ -27163,23 +31580,23 @@ name = "xcm-emulator" version = "0.5.0" dependencies = [ "array-bytes", - "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", - "cumulus-primitives-core", - "cumulus-primitives-parachain-inherent", - "cumulus-test-relay-sproof-builder", - "frame-support", - "frame-system", + "cumulus-pallet-parachain-system 0.7.0", + "cumulus-pallet-xcmp-queue 0.7.0", + "cumulus-primitives-core 0.7.0", + "cumulus-primitives-parachain-inherent 0.7.0", + "cumulus-test-relay-sproof-builder 0.7.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "impl-trait-for-tuples", "log", - "pallet-balances", - "pallet-message-queue", - "parachains-common", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "paste", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "sp-arithmetic 23.0.0", "sp-core 28.0.0", "sp-crypto-hashing 0.1.0", @@ -27187,30 +31604,30 @@ dependencies = [ "sp-runtime 31.0.1", "sp-std 14.0.0", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", ] [[package]] name = "xcm-executor-integration-tests" version = "1.0.0" dependencies = [ - "frame-support", + "frame-support 28.0.0", "futures", - "pallet-transaction-payment", - "pallet-xcm", + "pallet-transaction-payment 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", "polkadot-test-client", "polkadot-test-runtime", "polkadot-test-service", "sp-consensus", "sp-core 28.0.0", - "sp-keyring", + "sp-keyring 31.0.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-executor 7.0.0", ] [[package]] @@ -27220,80 +31637,130 @@ dependencies = [ "Inflector", "proc-macro2 1.0.86", "quote 1.0.37", - "staging-xcm", + "staging-xcm 7.0.0", "syn 2.0.87", "trybuild", ] +[[package]] +name = "xcm-procedural" +version = "10.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87fb4f14094d65c500a59bcf540cf42b99ee82c706edd6226a92e769ad60563e" +dependencies = [ + "Inflector", + "proc-macro2 1.0.86", + "quote 1.0.37", + "syn 2.0.87", +] + [[package]] name = "xcm-runtime-apis" version = "0.1.0" dependencies = [ - "frame-executive", - "frame-support", - "frame-system", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", "hex-literal", "log", - "pallet-assets", - "pallet-balances", - "pallet-xcm", + "pallet-assets 29.1.0", + "pallet-balances 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", "scale-info", "sp-api 26.0.0", "sp-io 30.0.0", "sp-tracing 16.0.0", "sp-weights 27.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "xcm-runtime-apis" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69d4473a5d157e4d437d9ebcb1b99f9693a64983877ee57d97005f0167869935" +dependencies = [ + "frame-support 38.0.0", + "parity-scale-codec", + "scale-info", + "sp-api 34.0.0", + "sp-weights 31.0.0", + "staging-xcm 14.2.0", + "staging-xcm-executor 17.0.0", ] [[package]] name = "xcm-simulator" version = "7.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "parity-scale-codec", "paste", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-primitives 7.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", +] + +[[package]] +name = "xcm-simulator" +version = "17.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "058e21bfc3e1180bbd83cad3690d0e63f34f43ab309e338afe988160aa776fcf" +dependencies = [ + "frame-support 38.0.0", + "frame-system 38.0.0", + "parity-scale-codec", + "paste", + "polkadot-core-primitives 15.0.0", + "polkadot-parachain-primitives 14.0.0", + "polkadot-primitives 16.0.0", + "polkadot-runtime-parachains 17.0.1", + "scale-info", + "sp-io 38.0.0", + "sp-runtime 39.0.2", + "sp-std 14.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "staging-xcm 14.2.0", + "staging-xcm-builder 17.0.1", + "staging-xcm-executor 17.0.0", ] [[package]] name = "xcm-simulator-example" version = "7.0.0" dependencies = [ - "frame-support", - "frame-system", + "frame-support 28.0.0", + "frame-system 28.0.0", "log", - "pallet-balances", - "pallet-message-queue", - "pallet-uniques", - "pallet-xcm", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-uniques 28.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-runtime-parachains", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "xcm-simulator 7.0.0", ] [[package]] @@ -27301,27 +31768,27 @@ name = "xcm-simulator-fuzzer" version = "1.0.0" dependencies = [ "arbitrary", - "frame-executive", - "frame-support", - "frame-system", - "frame-try-runtime", + "frame-executive 28.0.0", + "frame-support 28.0.0", + "frame-system 28.0.0", + "frame-try-runtime 0.34.0", "honggfuzz", - "pallet-balances", - "pallet-message-queue", - "pallet-xcm", + "pallet-balances 28.0.0", + "pallet-message-queue 31.0.0", + "pallet-xcm 7.0.0", "parity-scale-codec", - "polkadot-core-primitives", - "polkadot-parachain-primitives", - "polkadot-runtime-parachains", + "polkadot-core-primitives 7.0.0", + "polkadot-parachain-primitives 6.0.0", + "polkadot-runtime-parachains 7.0.0", "scale-info", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", "sp-std 14.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", + "staging-xcm 7.0.0", + "staging-xcm-builder 7.0.0", + "staging-xcm-executor 7.0.0", + "xcm-simulator 7.0.0", ] [[package]] @@ -27433,9 +31900,9 @@ dependencies = [ [[package]] name = "zombienet-configuration" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebbfc98adb25076777967f7aad078e74029e129b102eb0812c425432f8c2be7b" +checksum = "7d7a8cc4f8e8bb3f40757b62d3b054da5c95f43321c775eb321edc89d431583e" dependencies = [ "anyhow", "lazy_static", @@ -27453,9 +31920,9 @@ dependencies = [ [[package]] name = "zombienet-orchestrator" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b17f4d1d05b3aedf02818eb0f4d5a76664da0e07bb2f7e7d02613e0ef0f316a" +checksum = "3d32fa87851f41443a78971bd7110274f9a66d139ac834de159adc08f90cf8e3" dependencies = [ "anyhow", "async-trait", @@ -27486,9 +31953,9 @@ dependencies = [ [[package]] name = "zombienet-prom-metrics-parser" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7203390ab88919240da3a3eb06b625b6e300e94f98e04ba5141e9138dc663b7d" +checksum = "9acb9c94bc7c2c83f8eb8e26ed403f757af1632f22b89394d8876412ede990ca" dependencies = [ "pest", "pest_derive", @@ -27497,9 +31964,9 @@ dependencies = [ [[package]] name = "zombienet-provider" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee02ee957ec39b698798fa6dc2a0d5ba4524198471c37d57755e9685b67fb50c" +checksum = "dc8f3f71d4d974fc4a2262fa9293c2eedc423540378bd7c1dc1b66cc95d1d1af" dependencies = [ "anyhow", "async-trait", @@ -27528,9 +31995,9 @@ dependencies = [ [[package]] name = "zombienet-sdk" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f594e67922182277a3da0926f21b693eb5a0c38b32ca7fd6ef16167809fe5064" +checksum = "5dbfddce7a6100cdc930b93301f1b6381e6577ecc013d6802258ea6902a2bebd" dependencies = [ "async-trait", "futures", @@ -27545,9 +32012,9 @@ dependencies = [ [[package]] name = "zombienet-support" -version = "0.2.13" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93d3144537df7c8939bbb355cc5245a6dc0078446a6cdaf9272268bd1043c788" +checksum = "d20567c52b4fd46b600cda254dedb6a6dc30cabf512de91e4f6f78f0f7f4644b" dependencies = [ "anyhow", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index c00276724333..345b9cd78a1f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -754,7 +754,7 @@ enumn = { version = "0.1.13" } env_logger = { version = "0.11.2" } environmental = { version = "1.1.4", default-features = false } equivocation-detector = { path = "bridges/relays/equivocation" } -ethabi = { version = "1.0.0", default-features = false, package = "ethabi-decode" } +ethabi = { version = "2.0.0", default-features = false, package = "ethabi-decode" } ethbloom = { version = "0.14.1", default-features = false } ethereum-types = { version = "0.15.1", default-features = false } exit-future = { version = "0.2.0" } @@ -1316,8 +1316,8 @@ substrate-test-runtime-client = { path = "substrate/test-utils/runtime/client" } substrate-test-runtime-transaction-pool = { path = "substrate/test-utils/runtime/transaction-pool" } substrate-test-utils = { path = "substrate/test-utils" } substrate-wasm-builder = { path = "substrate/utils/wasm-builder", default-features = false } -subxt = { version = "0.37", default-features = false } -subxt-signer = { version = "0.37" } +subxt = { version = "0.38", default-features = false } +subxt-signer = { version = "0.38" } syn = { version = "2.0.87" } sysinfo = { version = "0.30" } tar = { version = "0.4" } @@ -1387,7 +1387,7 @@ xcm-procedural = { path = "polkadot/xcm/procedural", default-features = false } xcm-runtime-apis = { path = "polkadot/xcm/xcm-runtime-apis", default-features = false } xcm-simulator = { path = "polkadot/xcm/xcm-simulator", default-features = false } zeroize = { version = "1.7.0", default-features = false } -zombienet-sdk = { version = "0.2.13" } +zombienet-sdk = { version = "0.2.15" } zstd = { version = "0.12.4", default-features = false } [profile.release] 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 63175222cc26..e66c4f27fbe8 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -127,7 +127,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: alloc::borrow::Cow::Borrowed("westmint"), impl_name: alloc::borrow::Cow::Borrowed("westmint"), authoring_version: 1, - spec_version: 1_016_004, + spec_version: 1_016_005, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, diff --git a/prdoc/pr_6393.prdoc b/prdoc/pr_6393.prdoc new file mode 100644 index 000000000000..fc8fe9bd8576 --- /dev/null +++ b/prdoc/pr_6393.prdoc @@ -0,0 +1,16 @@ +title: '[pallet-revive] adjust fee dry-run calculation' +doc: +- audience: Runtime Dev + description: |- + - Fix bare_eth_transact so that it estimate more precisely the transaction fee + - Add some context to the build.rs to make it easier to troubleshoot errors + - Add TransactionBuilder for the RPC tests. + - Tweaked some error message, We will need to wait for the next subxt release to properly downcast some errors and + adopt MM error code (https://eips.ethereum.org/EIPS/eip-1474#error-codes) +crates: +- name: pallet-revive-eth-rpc + bump: minor +- name: pallet-revive + bump: minor +- name: pallet-revive-fixtures + bump: minor diff --git a/substrate/bin/node/cli/src/chain_spec.rs b/substrate/bin/node/cli/src/chain_spec.rs index 0c4a48a19260..038aa2f60928 100644 --- a/substrate/bin/node/cli/src/chain_spec.rs +++ b/substrate/bin/node/cli/src/chain_spec.rs @@ -427,7 +427,7 @@ fn props() -> Properties { fn eth_account(from: subxt_signer::eth::Keypair) -> AccountId32 { let mut account_id = AccountId32::new([0xEE; 32]); >::as_mut(&mut account_id)[..20] - .copy_from_slice(&from.account_id().0); + .copy_from_slice(&from.public_key().to_account_id().as_ref()); account_id } diff --git a/substrate/frame/revive/fixtures/build.rs b/substrate/frame/revive/fixtures/build.rs index a5b23e58c0d6..3472e0846efd 100644 --- a/substrate/frame/revive/fixtures/build.rs +++ b/substrate/frame/revive/fixtures/build.rs @@ -106,7 +106,9 @@ fn create_cargo_toml<'a>( ); let cargo_toml = toml::to_string_pretty(&cargo_toml)?; - fs::write(output_dir.join("Cargo.toml"), cargo_toml).map_err(Into::into) + fs::write(output_dir.join("Cargo.toml"), cargo_toml.clone()) + .with_context(|| format!("Failed to write {cargo_toml:?}"))?; + Ok(()) } fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { @@ -154,10 +156,11 @@ fn post_process(input_path: &Path, output_path: &Path) -> Result<()> { let mut config = polkavm_linker::Config::default(); config.set_strip(strip); config.set_optimize(optimize); - let orig = fs::read(input_path).with_context(|| format!("Failed to read {:?}", input_path))?; + let orig = fs::read(input_path).with_context(|| format!("Failed to read {input_path:?}"))?; let linked = polkavm_linker::program_from_elf(config, orig.as_ref()) .map_err(|err| anyhow::format_err!("Failed to link polkavm program: {}", err))?; - fs::write(output_path, linked).map_err(Into::into) + fs::write(output_path, linked).with_context(|| format!("Failed to write {output_path:?}"))?; + Ok(()) } /// Write the compiled contracts to the given output directory. @@ -209,9 +212,11 @@ pub fn main() -> Result<()> { let symlink_dir: PathBuf = symlink_dir.into(); let symlink_dir: PathBuf = symlink_dir.join("target").join("pallet-revive-fixtures"); if symlink_dir.is_symlink() { - fs::remove_file(&symlink_dir)? + fs::remove_file(&symlink_dir) + .with_context(|| format!("Failed to remove_file {symlink_dir:?}"))?; } - std::os::unix::fs::symlink(&out_dir, &symlink_dir)?; + std::os::unix::fs::symlink(&out_dir, &symlink_dir) + .with_context(|| format!("Failed to symlink {out_dir:?} -> {symlink_dir:?}"))?; } Ok(()) diff --git a/substrate/frame/revive/fixtures/contracts/rpc_demo.rs b/substrate/frame/revive/fixtures/contracts/rpc_demo.rs index 0d75c6eb8df6..4c61f2ea82ec 100644 --- a/substrate/frame/revive/fixtures/contracts/rpc_demo.rs +++ b/substrate/frame/revive/fixtures/contracts/rpc_demo.rs @@ -18,7 +18,7 @@ #![no_std] #![no_main] -use common::input; +use common::{input, u64_output}; use uapi::{HostFn, HostFnImpl as api}; #[no_mangle] @@ -31,6 +31,12 @@ pub extern "C" fn deploy() { #[no_mangle] #[polkavm_derive::polkavm_export] pub extern "C" fn call() { + // Not payable + let value = u64_output!(api::value_transferred,); + if value > 0 { + panic!(); + } + input!(128, data: [u8],); api::deposit_event(&[], data); } diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 8bf930240240..9faf05885dfe 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -45,9 +45,7 @@ jsonrpsee = { workspace = true, features = ["full"] } serde_json = { workspace = true } thiserror = { workspace = true } sp-crypto-hashing = { workspace = true } -subxt = { workspace = true, default-features = true, features = [ - "unstable-reconnecting-rpc-client", -] } +subxt = { workspace = true, default-features = true, features = ["reconnecting-rpc-client"] } tokio = { workspace = true, features = ["full"] } codec = { workspace = true, features = ["derive"] } log.workspace = true @@ -65,14 +63,15 @@ rlp = { workspace = true, optional = true } subxt-signer = { workspace = true, optional = true, features = [ "unstable-eth", ] } -hex = { workspace = true, optional = true } +hex = { workspace = true } hex-literal = { workspace = true, optional = true } scale-info = { workspace = true } secp256k1 = { workspace = true, optional = true, features = ["recovery"] } env_logger = { workspace = true } +ethabi = { version = "18.0.0" } [features] -example = ["hex", "hex-literal", "rlp", "secp256k1", "subxt-signer"] +example = ["hex-literal", "rlp", "secp256k1", "subxt-signer"] [dev-dependencies] hex-literal = { workspace = true } diff --git a/substrate/frame/revive/rpc/examples/README.md b/substrate/frame/revive/rpc/examples/README.md index bf30426648ba..b9a2756b381d 100644 --- a/substrate/frame/revive/rpc/examples/README.md +++ b/substrate/frame/revive/rpc/examples/README.md @@ -34,7 +34,7 @@ zombienet spawn --provider native westend_local_network.toml This command starts the Ethereum JSON-RPC server, which runs on `localhost:8545` by default: ```bash -RUST_LOG="info,eth-rpc=debug" cargo run -p pallet-revive-eth-rpc --features dev +RUST_LOG="info,eth-rpc=debug" cargo run -p pallet-revive-eth-rpc -- --dev ``` ## Rust examples @@ -65,34 +65,6 @@ bun src/script.ts ### Configure MetaMask -You can use the following instructions to setup [MetaMask] with the local chain. +See the doc [here](https://contracts.polkadot.io/work-with-a-local-node#metemask-configuration) for more +information on how to configure MetaMask. -> **Note**: When you interact with MetaMask and restart the chain, you need to clear the activity tab (Settings > -Advanced > Clear activity tab data), and in some cases lock/unlock MetaMask to reset the nonce. -See [this guide][reset-account] for more info on how to reset the account activity. - -#### Add a new network - -To interact with the local chain, add a new network in [MetaMask]. -See [this guide][add-network] for more info on how to add a custom network. - -Make sure the node and the RPC server are started, and use the following settings to configure the network -(MetaMask > Networks > Add a network manually): - -- Network name: KitchenSink -- RPC URL: -- Chain ID: 420420420 -- Currency Symbol: `DEV` - -#### Import Dev account - -You will need to import the following account, endowed with some balance at genesis, to interact with the chain. -See [this guide][import-account] for more info on how to import an account. - -- Account: `0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac` -- Private Key: `5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133` - -[MetaMask]: https://metamask.io -[add-network]: https://support.metamask.io/networks-and-sidechains/managing-networks/how-to-add-a-custom-network-rpc/#adding-a-network-manually -[import-account]: https://support.metamask.io/managing-my-wallet/accounts-and-addresses/how-to-import-an-account/ -[reset-account]: https://support.metamask.io/managing-my-wallet/resetting-deleting-and-restoring/how-to-clear-your-account-activity-reset-account diff --git a/substrate/frame/revive/rpc/examples/bun.lockb b/substrate/frame/revive/rpc/examples/bun.lockb new file mode 100755 index 0000000000000000000000000000000000000000..3a7a0df5cea48f9e639655bd11d1b9b94751e6b1 GIT binary patch literal 10962 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 Contract - + diff --git a/substrate/frame/revive/rpc/examples/js/package-lock.json b/substrate/frame/revive/rpc/examples/js/package-lock.json new file mode 100644 index 000000000000..f1453eae64cc --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/package-lock.json @@ -0,0 +1,443 @@ +{ + "name": "demo", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "demo", + "version": "0.0.0", + "dependencies": { + "ethers": "^6.13.1", + "solc": "^0.8.28" + }, + "devDependencies": { + "typescript": "^5.5.3", + "vite": "^5.4.8" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.10.1", + "license": "MIT" + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.2", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.24.0", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.24.0", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "18.15.13", + "license": "MIT" + }, + "node_modules/aes-js": { + "version": "4.0.0-beta.5", + "license": "MIT" + }, + "node_modules/command-exists": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz", + "integrity": "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", + "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/ethers": { + "version": "6.13.3", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "1.10.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "18.15.13", + "aes-js": "4.0.0-beta.5", + "tslib": "2.4.0", + "ws": "8.17.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==", + "license": "MIT" + }, + "node_modules/memorystream": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", + "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.4.47", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.24.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.6" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.24.0", + "@rollup/rollup-android-arm64": "4.24.0", + "@rollup/rollup-darwin-arm64": "4.24.0", + "@rollup/rollup-darwin-x64": "4.24.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", + "@rollup/rollup-linux-arm-musleabihf": "4.24.0", + "@rollup/rollup-linux-arm64-gnu": "4.24.0", + "@rollup/rollup-linux-arm64-musl": "4.24.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", + "@rollup/rollup-linux-riscv64-gnu": "4.24.0", + "@rollup/rollup-linux-s390x-gnu": "4.24.0", + "@rollup/rollup-linux-x64-gnu": "4.24.0", + "@rollup/rollup-linux-x64-musl": "4.24.0", + "@rollup/rollup-win32-arm64-msvc": "4.24.0", + "@rollup/rollup-win32-ia32-msvc": "4.24.0", + "@rollup/rollup-win32-x64-msvc": "4.24.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/solc": { + "version": "0.8.28", + "resolved": "https://registry.npmjs.org/solc/-/solc-0.8.28.tgz", + "integrity": "sha512-AFCiJ+b4RosyyNhnfdVH4ZR1+TxiL91iluPjw0EJslIu4LXGM9NYqi2z5y8TqochC4tcH9QsHfwWhOIC9jPDKA==", + "license": "MIT", + "dependencies": { + "command-exists": "^1.2.8", + "commander": "^8.1.0", + "follow-redirects": "^1.12.1", + "js-sha3": "0.8.0", + "memorystream": "^0.3.1", + "semver": "^5.5.0", + "tmp": "0.0.33" + }, + "bin": { + "solcjs": "solc.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tslib": { + "version": "2.4.0", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.6.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "5.4.8", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.17.1", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/substrate/frame/revive/rpc/examples/js/package.json b/substrate/frame/revive/rpc/examples/js/package.json index 4d7136606b65..ec05cb74f7d1 100644 --- a/substrate/frame/revive/rpc/examples/js/package.json +++ b/substrate/frame/revive/rpc/examples/js/package.json @@ -9,7 +9,8 @@ "preview": "vite preview" }, "dependencies": { - "ethers": "^6.13.1" + "ethers": "^6.13.1", + "solc": "^0.8.28" }, "devDependencies": { "typescript": "^5.5.3", diff --git a/substrate/frame/revive/rpc/examples/js/pvm-contracts.json b/substrate/frame/revive/rpc/examples/js/pvm-contracts.json new file mode 100644 index 000000000000..be58e88a9a63 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/pvm-contracts.json @@ -0,0 +1,56 @@ +{ + "event": { + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "string", + "name": "message", + "type": "string" + } + ], + "name": "ExampleEvent", + "type": "event" + }, + { + "inputs": [], + "name": "triggerEvent", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "bytecode": "50564d00014214000000000000010700c13004c00040045f0600000000060000001300000018000000230000003500000063616c6c65726465706f7369745f6576656e74696e7075747365616c5f72657475726e7365745f696d6d757461626c655f6461746176616c75655f7472616e73666572726564051102912c0463616c6c9133066465706c6f790693b42602913cc8000c0111013001cb010a0327034303570374030c05270530054b055605d505e905f7050b062f06a7075d09e109460a9c0b400c730cdf0c710e800ef70ed20f2610bb10e710131133113b1152790e7a1004070f0a41040a0000012f8a3908890802871f1277e03b370000010a040713000a08000002297814160700000252780407100002088707130004071000020887071300130018875e08970a14a80b099c0128cc29bc1d29873107094a5279110b8b028801029c01109b52c91eacf405350709335279110b8b028801029c01109b52c91eacf4051e07091c027aff0288ff1108980b0bbb029cff089a09109b52c90f0cf113000211e003101c0315180316140215201211e0127601040704080610023dff16070800020d010004040710000352184e0211011726032c040326032804032603240403260320040326031c0403260318040326031404031607100403070607061004090610064b020211c003103c0315380316340215401211e05216040740040820061008d5fe070716020408080002260364000200000080260360000226035c000226035800022603540002260350000226034c000203681826034800020217e01277e003671c52710d171c0d17180d17140d17100d170c0d17080d17040d074e051101681c0182100183018914018a1c018b0c018c040187180188080cba0a0cc9090ca9090c87070c23080c87070c97070f077e0104074004082006100a3afe07077b01016718017450017040017b58017c48017a5401724c0173440e2808128800ff000e29180c9808122900ff000999080922180c92090c980803681c0e3808128800ff000e39180c9808123900ff000999080933180c93090c89030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c89020ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c98080e0908129900ff000e0b180cb909120b00ff0009bb080900180cb00b0cb9090e4b0812bb00ff000e4a180cba0a124b00ff0009bb080944180cb40b0cba0a0ca9090cc8080c98080c3209016a1c0ca9090c98080f086e01681801885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970703671c040806100cfbfc07073c0a080c000207080b04073004034e041101671c040806100edefc07071f01681801671c087808040704094e031104070408061010c2fc0f070400040808000204070104090400124e03110211a003105c0315580316540215601211e004074004082006101491fc0f07040004061004030a0710040303171c0a041404030a031804030a092c04030a082804030a002004030a0c2404032797278a54970a27cb270754cb070c980b54ba070316180a0b1c04032742011a1c1baa041faa0154420a27b2273654b2060cb30b54b60a0cc9090c80080c980854870a0409080002260364000200000080260360000226035c000226035800022603540002260350000226034c00022603480002070a0b010a071000030f47ede48fb7020103191c0d113c0d11380d11340d11300d112c0d11280d11240d11200217204e0511011230011820011934011a3c011b2c011c240116380117280cba0a0cc9090ca9090c67070c28080c87070c97070f07b10001171801721c017318017414017a100178017c0c017604017708028bfc248b0808860b02bbff1c6b09246b0b53980b0278ff08b8092479002489081b7601146c060868081cc80624c8085360081c97070c6707537b0802a7ff0878082478071ba8011484080878092489085377080c4a071b77011473090898082498082473071472070887072d074604070408061016f9fa07076bfe040808000204070104094e0304001805ca00061018c7000407040806101ad5fa070747fe040808000204070104094e0304001c05c80006101cc50004074004082006101eaffa070721fe011b1c01b24c01b34401ba5401b94801bc4001b65001b8580c6c0c0c98080cc8080c3a090c29090c98080e8908129900ff000e8a180ca909098a18128800ff000988080ca8080c98080f08d4fd01b85c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c9707031718040852b606102030fa0707a2fd011818086808040704090400224e03110211fc0310040704080610240efa0f070400040808000204070104090400264e0311021140ff0310bc000315b8000316b4000215c0001211e05216040740040820061028d6f90707e70a04040800020a036400020a084800020a0a6000020a025000020a0c4c00020e8b0812b900ff000e8b180cb909128b00ff0009bb080988180cb8080c98080368780ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c89000ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c890a0e3808128800ff000e39180c9808123900ff000999080933180c93090c890902a801036a6c1baaff0369741b99c0548a090e2808128800ff000e2a180ca808122a00ff0009aa080a0b5400020922180ca20a0c8a020eb808128800ff000eba180ca80812ba00ff0009aa080a0c58000209bb180cba0a0c8a030ec808128800ff000eca180ca80812ca00ff0009aa0803647c0a0b5c000209cc180cca0a0c8a0c0eb808128800ff000eba180ca80812b700ff0009770809bb180cb7070c870a0362680167780c72070360700363640c03080c8707036c60036a5c0cca08036854568903675856790709190904074004082006102a5ef807076f0901677402784003685024780701686c08780903694824890b53770b01675c08b70024700701686008780224820c53770c53bb0c016764087c0c247c0b01676808b70424740853bb0801677008870a247a080163780883030e3708127700ff000e38180c7808123700ff000977080933180c73070c870703674c0ea708127700ff000ea9180c970712a900ff0009990809aa180ca9090c97070367440e4708127700ff000e49180c9707124900ff000999080944180c94090c79040ec708127700ff000ec9180c970712c900ff0009990809cc180cc9090c79030e2708127700ff000e29180c9707122900ff000999080922180c92090c79020e0908129900ff000e0a180ca909120a00ff0009aa080900180ca00a0ca9090167480e7a0812aa00ff000e78180ca808127a00ff0009aa08097c180cca0a0ca8080167500e7a0812aa00ff000e7c180cca0a127b00ff0009bb08097c180ccb0b0cba0a016b7c03ba5c03b85803b95403b25003b34c03b44801674403b74401676c0168680c87070168600169780c98080c870701685c0169700c98080169640c98080c870701684c03b8400f07c80704082001677406102ca8f60707b9070162741b27e01f770101696c279854980701685c2788016a6027a953a8090168545387090167642777016a6827a853a708016c7027c7016b7827ba53b70a0cbc0753780a01675853790a01677c0827080d181c0000000b0d18180d18140d18100d180c0d18080d18040368440d080f0a470702272004082003676006102e24f60707350701687c0167600878080d181c0d18180d18140d18100d180c0d1808726c640d18046f20776f0368340d0848656c6c026780004e0167900003671401678c000367180167880003671c0167840003672001678000036724040740040820061030bff50707d00601677c017250017340017458017048017c54017b4c0179440eb808128800ff000eba180ca80812ba00ff0009aa0809bb180cba0a0ca8080368700e9808128800ff000e9a180ca808129a00ff0009aa080999180ca9090c98080368680ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890b0e0808128800ff000e09180c9808120900ff000999080900180c90090c89000e4808128800ff000e49180c9808124900ff000999080944180c94090c890c0e3808128800ff000e39180c9808123900ff000999080933180c93090c890a0e2808128800ff000e29180c9808122900ff000999080922180c92090c9808036a5c0368540ca808036058036c6c0c0c090c9808036b640169680cb909016a700ca9090c98080f08ae0501687c01885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970704082003677806103269f407077a05016a7c016778087a0a527b0d1a1c000030390d1a180d1a140d1a100d1a0c0d1a080d1a0401686c27891bb7e01f7c0103694854890c01676427780160542704530804016770277801635827325338020169682798016b5c27b753b8070cb9085382070168700c98080cb3090c98080169640c090903694c03644054940c03685003673c54870c036a100d0a0168780f0ce804028720040820036738061034c5f30707d60401677c0168380887070d171c000000400d17180d17140d17100d170c0d17080d17040d0704082001677406103692f30707a3040169781b97c01f770101686c016a48548a0701684c016a40548a07016850016a3c548a070f077b0401674401781c03684801781803687401781403684001781003683c01780c03683801780803683001780403682c017703674402974004082003672806103826f3070737040167781b77a001686c568701684c5687016850568701687c016928089808016c2c038c04016a44038a016b30038b0801643803840c01623c03821001604003801401697403891801694803891c0707e6030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c98080368500ec808128800ff000ec9180c980812c900ff0009990809ca180ca9090c890c0eb808128800ff000eb9180c980812b900ff0009990809ba180ca9090c89030e4808128800ff000e49180c9808124900ff00099908094a180ca9090c89040e2808128800ff000e29180c9808122900ff00099908092a180ca9090c89020e0808128800ff000e09180c9808120900ff00099908090a180ca9090c8900016a740ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c980803684403633c0c38080362300169500c92090c9808036c4003602c0cc0090364380c49090c98080f08dc02016a480ea808128800ff000ea9180c980812a700ff0009770809a9180c97070c780801677802776003674c03687406103a94f10707a50201676001687406103c85f10707960201677801684c247807528b01686c08780903690c24890853770801676408870903692824790701695408790a036a48249a0953770953880901677008790903696024790701685808780903696424890853770801676808780803686c24780703676801677c08b70701683401697406103e58f101684c016974089808016a4401670c08a7070368702498080887021ca20924a20a53980a01682c016928088909016730016c48087c0c24890b08cb0b08a904249409089b031c730c24730b24840753c70b1c84070cc707537a0b01683801676008870724870a01683c016c64088c0c08ac0c1c8c09248c08539a08087b0b247b07087c0024c00953770901675c016a5008a707016a6808a707016a40016c6c08ac0c24ac0a08a70708c80824c80a08a7070889092489080887070cb4080c98080c73070c02090c98080c87070f07530104082001677006104033f00707440101687c0167700878080d181c0d18180d18140d18100d180c0d18080d180401697402971f249709016a4408a909129901127be01bbaa01faa0154990a0d080167780f0aff0002b86003687c061042dfef0707f0000217c01277e052710d171c8c16c7d00d1718622fa9a50d1714af827c120d17104a032b310d170cec4214070d1708f0370dae0d170487296ff20d071585375401681403783c01681803783801681c03783401682003783001682403782c0d17280d17240d1720040802016910016a7c4e01025140ff0110bc000115b8000116b4000211c000130004082004070610444aef07075b01687c0d181c0d18180d18140d18100d180c0d18080d18040d084e487b710407040408200610461eef07072f01687c0d1820000000410d181c0d18180d18140d18100d180c0d18080d18040408240407061048f2ee0f07040004080800020407010409244e03040704004a0581ef040706104a7cef04070106104c74ef00a58424092a241452482549495a52292da994644a2a2549920a21422d8410420821119224290911028410420809494a92243529499224491249882449928424244912929024094948928424244942129224210949929084244992244912929024292424348524a956c890d2244992902124841042a854928492a492244908104208218408014992244993244992244924494a9224499224499224499224499224a9102195840a115249484224499224499290242489242421495221924a53850c298d8888948408218410129290244948429224242149129290244992242421214942121292242421094912929024499224494a91844892244992244992244992242421499290842449421292242109499290842449484292242109499284242449922449922449922449242192a4a49424a5a4942449024992a448122249922408248891482412494224499224242149929084244942129224210949929084244948429224242149922449922491242421499210490a2449929224a5a494949224499224494a2409912490244949882449922489244992244952928448524a4992942449922491908424494212922421094992908424494842922424214992908424499224499244129290244912220991a424499224499224499224499284244992244992244992244992244992244992244992244992248924449224499224499294484224050281402010089224499224498a8888524892244990842490244952c8905452480800" + }, + "revert": { + "abi": [ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "doRevert", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "bytecode": "50564d0001ba09000000000000010700c13004c0004004440400000000050000001000000022000000696e7075747365616c5f72657475726e7365745f696d6d757461626c655f6461746176616c75655f7472616e7366657272656405110288020463616c6c8809066465706c6f79068947170288126700aa00af00ce006901a802c502e102f5021303ab04c604cf04eb043d06d50632078f07c907dc07ea070908110852790e7a1004070f0a41040a0000012f8a3908890802871f1277e03b370000010a040713000a0800000229781416070000025278040710000208870713000407100002088707130013000211e003101c0315180316140215201211e0127601040704080610029d16070400020d010004040710000352184e11011726032c040326032804032603240403260320040326031c0403260318040326031404031607100403070607061004090610064b020211c003103c0315380316340215401211e0521604074004082006100837ff07071602040804000226036000020000008026035c000226035800022603540002260350000226034c0002260348000203681826034400020217e01277e003671c52710d171c0d17180d17140d17100d170c0d17080d17040d074e031101681c0182100183018914018a1c018b0c018c040187180188080cba0a0cc9090ca9090c87070c23080c87070c97070f077e0104074004082006100a9cfe07077b01016718017450017040017b58017c48017a5401724c0173440e2808128800ff000e29180c9808122900ff000999080922180c92090c980803681c0e3808128800ff000e39180c9808123900ff000999080933180c93090c89030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c89020ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c98080e0908129900ff000e0b180cb909120b00ff0009bb080900180cb00b0cb9090e4b0812bb00ff000e4a180cba0a124b00ff0009bb080944180cb40b0cba0a0ca9090cc8080c98080c3209016a1c0ca9090c98080f086e01681801885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970703671c040806100c5dfd07073c0a0808000207080b04073004034e021101671c040806100e40fd07071f01681801671c087808040704094e01110407040806101024fd0f070400040804000204070104090400124e011102118003107c031578031674021580001211e0040740040820061014f2fc0f07040004061004030a0710040303173c0a041404030a031804030a092c04030a082804030a002004030a0c2404032797278a54970a27cb270754cb070c980b54ba070316380a0b1c04032742011a3c1baa041faa0154420a27b2273654b2060cb30b54b60a0cc9090c80080c980854870a040904000226036000020000008026035c000226035800022603540002260350000226034c000226034800022603440002070a0b010a071000030f47afc874d2020103193c0d115c0d11580d11540d11500d114c0d11480d11440d11400217404e0311011250011840011954011a5c011b4c011c440116580117480cba0a0cc9090ca9090c67070c28080c87070c97070f07b10001173801721c017318017414017a100178017c0c017604017708028bfc248b0808860b02bbff1c6b09246b0b53980b0278ff08b8092479002489081b7601146c060868081cc80624c8085360081c97070c6707537b0802a7ff0878082478071ba8011484080878092489085377080c4a071b77011473090898082498082473071472070887072d0741040704080610165afb07076bfe040804000204070104094e01040018051e030610181b030407040806101a36fb070747fe040804000204070104094e011104074004082006101c1afb07072bfe01103c010250010340010458010b48010c54010a4c0108440ea608126600ff000ea9180c690912a600ff0009660809aa180c6a0a0ca9090319380e8908129900ff000e8a180ca909128a00ff0009aa080988180ca8080c98080318340ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c890a0e4808128800ff000e49180c9808124900ff000999080944180c94090c89040e3808128800ff000e39180c9808123900ff000999080933180c93090c89030e2808128800ff000e29180c9808122900ff000999080922180c92060c860b0c3b080ca4090c98080119340cc9090116380c69090c98080f0818fd52b6031320031a24031c2803142c01085c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970704082003173006101ec8f90707d9fc011230011a3c082a0a0d0a08c379a00113382737011424274b53470b011c3427c701182027895387090c8c07537b09011b2827b727605367000cb6060cc3070d1a1c0d1a180d1a140d1a100d1a0c0d1a080c8408011b2c27bc0c78081b27fc1f770154bc070316385460075489070d1a040f0764fc031c20031824031028031934031a1c011730027704040820527606102030f9070741fc01173c0867070d171c000000200d17180d17140d17100d170c0d17080d17040118301b88dc1f880101192c011a20549a08011928011a3854a908011934011a2454a9080d070f08f8fb0117300276240408205267061022d3f80707e4fb01173c0867070d171c0000000e0d17180d17140d17100d170c0d17080d17040118301b88bc1f880101192c011a20549a08011928011a3854a908011934011a2454a9080d070f089bfb011730027644040820526706102476f8070787fb01173c0867070d171c0d17180d17140d17100d170c67650d1708657373610d17047274206d0d07726576650408640117300610263cf807074dfb04070104096401181c0400284e01110211fc03100407040806102a1bf80f070400040804000204070104094e01040704002c054bf8040706102c46f804070106102e3ef800a58424092a241452482549928a10a10b21841042488424494a4284002184104242929224494d4a9224499244122249922421094992842424494212922421094992908424494842922424214992244992842424490a09094d2149aa1532a434492249c81012420821542a494249524992240408218410428480244992a449922449922492242549922449922449922449922449925488904a428508a9498824499284242449129290244948429224242149129290240949489284242449922449942449484292242192042925a524a924499224254992449224492192409224499224495224294412489224499224498a24854892240402411222499a2a64489514120200" + } +} \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts b/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts new file mode 100644 index 000000000000..3e9d036d1b7d --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts @@ -0,0 +1,56 @@ +import { compile } from '@parity/revive' +import solc from 'solc' +import { readFileSync, writeFileSync } from 'fs' +import { join } from 'path' + +type CompileInput = Parameters[0] +type CompileOutput = Awaited> +type Abi = CompileOutput['contracts'][string][string]['abi'] + +function evmCompile(sources: CompileInput) { + const input = { + language: 'Solidity', + sources, + settings: { + outputSelection: { + '*': { + '*': ['*'], + }, + }, + }, + } + + return solc.compile(JSON.stringify(input)) +} + +console.log('Compiling contracts...') + +let pvmContracts: Map = new Map() +let evmContracts: Map = new Map() +const input = [ + { file: 'Event.sol', contract: 'EventExample', keypath: 'event' }, + { file: 'Revert.sol', contract: 'RevertExample', keypath: 'revert' }, +] + +for (const { keypath, contract, file } of input) { + const input = { + [file]: { content: readFileSync(join('contracts', file), 'utf8') }, + } + + { + console.log(`Compile with solc ${file}`) + const out = JSON.parse(evmCompile(input)) + const entry = out.contracts[file][contract] + evmContracts.set(keypath, { abi: entry.abi, bytecode: entry.evm.bytecode.object }) + } + + { + console.log(`Compile with revive ${file}`) + const out = await compile(input) + const entry = out.contracts[file][contract] + pvmContracts.set(keypath, { abi: entry.abi, bytecode: entry.evm.bytecode.object }) + } +} + +writeFileSync('pvm-contracts.json', JSON.stringify(Object.fromEntries(pvmContracts), null, 2)) +writeFileSync('evm-contracts.json', JSON.stringify(Object.fromEntries(evmContracts), null, 2)) diff --git a/substrate/frame/revive/rpc/examples/js/src/event.ts b/substrate/frame/revive/rpc/examples/js/src/event.ts new file mode 100644 index 000000000000..95e630a43461 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/event.ts @@ -0,0 +1,15 @@ +//! Run with bun run script-event.ts +import { call, getContract, deploy } from './lib.ts' + +try { + const { abi, bytecode } = getContract('event') + const address = await deploy(bytecode, abi) + const receipt = await call('triggerEvent', address, abi) + if (receipt) { + for (const log of receipt.logs) { + console.log('Event log:', JSON.stringify(log, null, 2)) + } + } +} catch (err) { + console.error(err) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts new file mode 100644 index 000000000000..9db9d36cf56c --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/lib.ts @@ -0,0 +1,85 @@ +import { + Contract, + ContractFactory, + JsonRpcProvider, + TransactionReceipt, + TransactionResponse, +} from 'ethers' +import { readFileSync } from 'node:fs' +import type { compile } from '@parity/revive' +import { spawn } from 'node:child_process' + +type CompileOutput = Awaited> +type Abi = CompileOutput['contracts'][string][string]['abi'] + +const geth = process.argv.includes('--geth') +if (geth) { + console.log('Testing with Geth') + const child = spawn( + 'geth', + [ + '--http', + '--http.api', + 'web3,eth,debug,personal,net', + '--http.port', + '8545', + '--dev', + '--verbosity', + '0', + ], + { stdio: 'inherit' } + ) + + process.on('exit', () => child.kill()) + + child.unref() + await new Promise((resolve) => setTimeout(resolve, 500)) +} + +const provider = new JsonRpcProvider('http://localhost:8545') +const signer = await provider.getSigner() +console.log(`Signer address: ${await signer.getAddress()}, Nonce: ${await signer.getNonce()}`) + +/** + * Get one of the pre-built contracts + * @param name - the contract name + */ +export function getContract(name: string): { abi: Abi; bytecode: string } { + const file = geth + ? readFileSync('evm-contracts.json', 'utf8') + : readFileSync('pvm-contracts.json', 'utf8') + const contracts = JSON.parse(file) as Record + return contracts[name] +} + +/** + * Deploy a contract + * @returns the contract address + **/ +export async function deploy(bytecode: string, abi: Abi, args: any[] = []): Promise { + console.log('Deploying contract with', args) + const contractFactory = new ContractFactory(abi, bytecode, signer) + + const contract = await contractFactory.deploy(args) + await contract.waitForDeployment() + const address = await contract.getAddress() + console.log(`Contract deployed: ${address}`) + return address +} + +/** + * Call a contract + **/ +export async function call( + method: string, + address: string, + abi: Abi, + args: any[] = [], + opts: { value?: bigint } = {} +): Promise { + console.log(`Calling ${method} at ${address} with`, args, opts) + const contract = new Contract(address, abi, signer) + const tx = (await contract[method](...args, opts)) as TransactionResponse + console.log('Call transaction hash:', tx.hash) + return tx.wait() +} diff --git a/substrate/frame/revive/rpc/examples/js/src/main.ts b/substrate/frame/revive/rpc/examples/js/src/main.ts deleted file mode 100644 index 88b72755aae9..000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/main.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { - AddressLike, - BrowserProvider, - Contract, - ContractFactory, - Eip1193Provider, - JsonRpcSigner, - parseEther, -} from "ethers"; - -declare global { - interface Window { - ethereum?: Eip1193Provider; - } -} - -function str_to_bytes(str: string): Uint8Array { - return new TextEncoder().encode(str); -} - -document.addEventListener("DOMContentLoaded", async () => { - if (typeof window.ethereum == "undefined") { - return console.log("MetaMask is not installed"); - } - - console.log("MetaMask is installed!"); - const provider = new BrowserProvider(window.ethereum); - - console.log("Getting signer..."); - let signer: JsonRpcSigner; - try { - signer = await provider.getSigner(); - console.log(`Signer: ${signer.address}`); - } catch (e) { - console.error("Failed to get signer", e); - return; - } - - console.log("Getting block number..."); - try { - const blockNumber = await provider.getBlockNumber(); - console.log(`Block number: ${blockNumber}`); - } catch (e) { - console.error("Failed to get block number", e); - return; - } - - const nonce = await signer.getNonce(); - console.log(`Nonce: ${nonce}`); - - document.getElementById("transferButton")?.addEventListener( - "click", - async () => { - const address = - (document.getElementById("transferInput") as HTMLInputElement).value; - await transfer(address); - }, - ); - - document.getElementById("deployButton")?.addEventListener( - "click", - async () => { - await deploy(); - }, - ); - document.getElementById("deployAndCallButton")?.addEventListener( - "click", - async () => { - const nonce = await signer.getNonce(); - console.log(`deploy with nonce: ${nonce}`); - - const address = await deploy(); - if (address) { - const nonce = await signer.getNonce(); - console.log(`call with nonce: ${nonce}`); - await call(address); - } - }, - ); - document.getElementById("callButton")?.addEventListener("click", async () => { - const address = - (document.getElementById("callInput") as HTMLInputElement).value; - await call(address); - }); - - async function deploy() { - console.log("Deploying contract..."); - - const bytecode = await fetch("rpc_demo.polkavm").then((response) => { - if (!response.ok) { - throw new Error("Network response was not ok"); - } - return response.arrayBuffer(); - }) - .then((arrayBuffer) => new Uint8Array(arrayBuffer)); - - const contractFactory = new ContractFactory( - [ - "constructor(bytes memory _data)", - ], - bytecode, - signer, - ); - - try { - const args = str_to_bytes("hello"); - const contract = await contractFactory.deploy(args); - await contract.waitForDeployment(); - const address = await contract.getAddress(); - console.log(`Contract deployed: ${address}`); - return address; - } catch (e) { - console.error("Failed to deploy contract", e); - return; - } - } - - async function call(address: string) { - const abi = ["function call(bytes data)"]; - const contract = new Contract(address, abi, signer); - const tx = await contract.call(str_to_bytes("world")); - - console.log("Transaction hash:", tx.hash); - } - - async function transfer(to: AddressLike) { - console.log(`transferring 1 DOT to ${to}...`); - try { - const tx = await signer.sendTransaction({ - to, - value: parseEther("1.0"), - }); - - const receipt = await tx.wait(); - console.log(`Transaction hash: ${receipt?.hash}`); - } catch (e) { - console.error("Failed to send transaction", e); - return; - } - } -}); diff --git a/substrate/frame/revive/rpc/examples/js/src/revert.ts b/substrate/frame/revive/rpc/examples/js/src/revert.ts new file mode 100644 index 000000000000..5fb3ccde6fae --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/revert.ts @@ -0,0 +1,10 @@ +//! Run with bun run script-revert.ts +import { call, getContract, deploy } from './lib.ts' + +try { + const { abi, bytecode } = getContract('revert') + const address = await deploy(bytecode, abi) + await call('doRevert', address, abi) +} catch (err) { + console.error(err) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/script.ts b/substrate/frame/revive/rpc/examples/js/src/script.ts deleted file mode 100644 index 999312f0fd5b..000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/script.ts +++ /dev/null @@ -1,49 +0,0 @@ -//! Run with bun run script.ts - -import { readFileSync } from "fs"; -import { Contract, ContractFactory, JsonRpcProvider } from "ethers"; - -const provider = new JsonRpcProvider("http://localhost:8545"); -const signer = await provider.getSigner(); -console.log( - `Signer address: ${await signer.getAddress()}, Nonce: ${await signer - .getNonce()}`, -); - -function str_to_bytes(str: string): Uint8Array { - return new TextEncoder().encode(str); -} - -// deploy -async function deploy() { - console.log(`Deploying Contract...`); - - const bytecode = readFileSync("../rpc_demo.polkavm"); - const contractFactory = new ContractFactory( - [ - "constructor(bytes memory _data)", - ], - bytecode, - signer, - ); - - const args = str_to_bytes("hello"); - console.log("Deploying contract with args:", args); - const contract = await contractFactory.deploy(args); - await contract.waitForDeployment(); - const address = await contract.getAddress(); - console.log(`Contract deployed: ${address}`); - return address; -} - -async function call(address: string) { - console.log(`Calling Contract at ${address}...`); - - const abi = ["function call(bytes data)"]; - const contract = new Contract(address, abi, signer); - const tx = await contract.call(str_to_bytes("world")); - console.log("Call transaction hash:", tx.hash); -} - -const address = await deploy(); -await call(address); diff --git a/substrate/frame/revive/rpc/examples/js/src/solc.d.ts b/substrate/frame/revive/rpc/examples/js/src/solc.d.ts new file mode 100644 index 000000000000..813829f40b6d --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/solc.d.ts @@ -0,0 +1,83 @@ +declare module 'solc' { + // Basic types for input/output handling + export interface CompileInput { + language: string + sources: { + [fileName: string]: { + content: string + } + } + settings?: { + optimizer?: { + enabled: boolean + runs: number + } + outputSelection: { + [fileName: string]: { + [contractName: string]: string[] + } + } + } + } + + export interface CompileOutput { + errors?: Array<{ + component: string + errorCode: string + formattedMessage: string + message: string + severity: string + sourceLocation?: { + file: string + start: number + end: number + } + type: string + }> + sources?: { + [fileName: string]: { + id: number + ast: object + } + } + contracts?: { + [fileName: string]: { + [contractName: string]: { + abi: object[] + evm: { + bytecode: { + object: string + sourceMap: string + linkReferences: { + [fileName: string]: { + [libraryName: string]: Array<{ + start: number + length: number + }> + } + } + } + deployedBytecode: { + object: string + sourceMap: string + linkReferences: { + [fileName: string]: { + [libraryName: string]: Array<{ + start: number + length: number + }> + } + } + } + } + } + } + } + } + + // Main exported functions + export function compile( + input: string | CompileInput, + options?: { import: (path: string) => { contents: string } } + ): string +} diff --git a/substrate/frame/revive/rpc/examples/js/src/web.ts b/substrate/frame/revive/rpc/examples/js/src/web.ts new file mode 100644 index 000000000000..ee7c8ed034da --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/web.ts @@ -0,0 +1,129 @@ +import { + AddressLike, + BrowserProvider, + Contract, + ContractFactory, + Eip1193Provider, + JsonRpcSigner, + parseEther, +} from 'ethers' + +declare global { + interface Window { + ethereum?: Eip1193Provider + } +} + +function str_to_bytes(str: string): Uint8Array { + return new TextEncoder().encode(str) +} + +document.addEventListener('DOMContentLoaded', async () => { + if (typeof window.ethereum == 'undefined') { + return console.log('MetaMask is not installed') + } + + console.log('MetaMask is installed!') + const provider = new BrowserProvider(window.ethereum) + + console.log('Getting signer...') + let signer: JsonRpcSigner + try { + signer = await provider.getSigner() + console.log(`Signer: ${signer.address}`) + } catch (e) { + console.error('Failed to get signer', e) + return + } + + console.log('Getting block number...') + try { + const blockNumber = await provider.getBlockNumber() + console.log(`Block number: ${blockNumber}`) + } catch (e) { + console.error('Failed to get block number', e) + return + } + + const nonce = await signer.getNonce() + console.log(`Nonce: ${nonce}`) + + document.getElementById('transferButton')?.addEventListener('click', async () => { + const address = (document.getElementById('transferInput') as HTMLInputElement).value + await transfer(address) + }) + + document.getElementById('deployButton')?.addEventListener('click', async () => { + await deploy() + }) + document.getElementById('deployAndCallButton')?.addEventListener('click', async () => { + const nonce = await signer.getNonce() + console.log(`deploy with nonce: ${nonce}`) + + const address = await deploy() + if (address) { + const nonce = await signer.getNonce() + console.log(`call with nonce: ${nonce}`) + await call(address) + } + }) + document.getElementById('callButton')?.addEventListener('click', async () => { + const address = (document.getElementById('callInput') as HTMLInputElement).value + await call(address) + }) + + async function deploy() { + console.log('Deploying contract...') + + const bytecode = await fetch('rpc_demo.polkavm') + .then((response) => { + if (!response.ok) { + throw new Error('Network response was not ok') + } + return response.arrayBuffer() + }) + .then((arrayBuffer) => new Uint8Array(arrayBuffer)) + + const contractFactory = new ContractFactory( + ['constructor(bytes memory _data)'], + bytecode, + signer + ) + + try { + const args = str_to_bytes('hello') + const contract = await contractFactory.deploy(args) + await contract.waitForDeployment() + const address = await contract.getAddress() + console.log(`Contract deployed: ${address}`) + return address + } catch (e) { + console.error('Failed to deploy contract', e) + return + } + } + + async function call(address: string) { + const abi = ['function call(bytes data)'] + const contract = new Contract(address, abi, signer) + const tx = await contract.call(str_to_bytes('world')) + + console.log('Transaction hash:', tx.hash) + } + + async function transfer(to: AddressLike) { + console.log(`transferring 1 DOT to ${to}...`) + try { + const tx = await signer.sendTransaction({ + to, + value: parseEther('1.0'), + }) + + const receipt = await tx.wait() + console.log(`Transaction hash: ${receipt?.hash}`) + } catch (e) { + console.error('Failed to send transaction', e) + return + } + } +}) diff --git a/substrate/frame/revive/rpc/examples/package.json b/substrate/frame/revive/rpc/examples/package.json new file mode 100644 index 000000000000..37d819aaa481 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/package.json @@ -0,0 +1 @@ +{ "dependencies": { "@parity/revive": "^0.0.5" } } \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/rust/deploy.rs b/substrate/frame/revive/rpc/examples/rust/deploy.rs index f2be5d233f6d..b74d7ea18d41 100644 --- a/substrate/frame/revive/rpc/examples/rust/deploy.rs +++ b/substrate/frame/revive/rpc/examples/rust/deploy.rs @@ -17,10 +17,10 @@ use jsonrpsee::http_client::HttpClientBuilder; use pallet_revive::{ create1, - evm::{Account, BlockTag, Bytes, ReceiptInfo, U256}, + evm::{Account, BlockTag, ReceiptInfo, U256}, }; use pallet_revive_eth_rpc::{ - example::{send_transaction, wait_for_receipt}, + example::{wait_for_receipt, TransactionBuilder}, EthRpcClient, }; @@ -41,9 +41,11 @@ async fn main() -> anyhow::Result<()> { println!("\n\n=== Deploying contract ===\n\n"); let nonce = client.get_transaction_count(account.address(), BlockTag::Latest.into()).await?; - let hash = - send_transaction(&account, &client, 5_000_000_000_000u128.into(), input.into(), None) - .await?; + let hash = TransactionBuilder::default() + .value(5_000_000_000_000u128.into()) + .input(input) + .send(&client) + .await?; println!("Deploy Tx hash: {hash:?}"); let ReceiptInfo { block_number, gas_used, contract_address, .. } = @@ -60,9 +62,11 @@ async fn main() -> anyhow::Result<()> { println!("- Contract balance: {balance:?}"); println!("\n\n=== Calling contract ===\n\n"); - let hash = - send_transaction(&account, &client, U256::zero(), Bytes::default(), Some(contract_address)) - .await?; + let hash = TransactionBuilder::default() + .value(U256::from(1_000_000u32)) + .to(contract_address) + .send(&client) + .await?; println!("Contract call tx hash: {hash:?}"); let ReceiptInfo { block_number, gas_used, to, .. } = wait_for_receipt(&client, hash).await?; diff --git a/substrate/frame/revive/rpc/examples/rust/transfer.rs b/substrate/frame/revive/rpc/examples/rust/transfer.rs index b99d48a2f78e..1d67a2dba28f 100644 --- a/substrate/frame/revive/rpc/examples/rust/transfer.rs +++ b/substrate/frame/revive/rpc/examples/rust/transfer.rs @@ -15,23 +15,24 @@ // See the License for the specific language governing permissions and // limitations under the License. use jsonrpsee::http_client::HttpClientBuilder; -use pallet_revive::evm::{Account, BlockTag, Bytes, ReceiptInfo}; +use pallet_revive::evm::{Account, BlockTag, ReceiptInfo}; use pallet_revive_eth_rpc::{ - example::{send_transaction, wait_for_receipt}, + example::{wait_for_receipt, TransactionBuilder}, EthRpcClient, }; #[tokio::main] async fn main() -> anyhow::Result<()> { - let alith = Account::default(); let client = HttpClientBuilder::default().build("http://localhost:8545")?; + let alith = Account::default(); + let alith_address = alith.address(); let ethan = Account::from(subxt_signer::eth::dev::ethan()); let value = 1_000_000_000_000_000_000_000u128.into(); let print_balance = || async { - let balance = client.get_balance(alith.address(), BlockTag::Latest.into()).await?; - println!("Alith {:?} balance: {balance:?}", alith.address()); + let balance = client.get_balance(alith_address, BlockTag::Latest.into()).await?; + println!("Alith {:?} balance: {balance:?}", alith_address); let balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; println!("ethan {:?} balance: {balance:?}", ethan.address()); anyhow::Result::<()>::Ok(()) @@ -40,8 +41,12 @@ async fn main() -> anyhow::Result<()> { print_balance().await?; println!("\n\n=== Transferring ===\n\n"); - let hash = - send_transaction(&alith, &client, value, Bytes::default(), Some(ethan.address())).await?; + let hash = TransactionBuilder::default() + .signer(alith) + .value(value) + .to(ethan.address()) + .send(&client) + .await?; println!("Transaction hash: {hash:?}"); let ReceiptInfo { block_number, gas_used, status, .. } = diff --git a/substrate/frame/revive/rpc/revive_chain.metadata b/substrate/frame/revive/rpc/revive_chain.metadata index 305d079f9bd86786d1cd00fadac152eb856b26ee..e5bfa0820b100bce59107541915f9352fce1c99a 100644 GIT binary patch delta 2124 zcmcgtT}%{L6rM9X?93H$hX}YT$R)-WQo)6?7E!c-o2c;zaSgEv?#{9!J7ITcotdrO zMq^tw+NO$1>`5Qmt`C|fO_SO*9TR&C2@3B0l;UG`qLB`78#6{S6gAsf=D82#(7#a4psYMRRTnpRstuogtOY6;4D3LHi zDML$Wm>w2uAb?*Ci|^EJ%%eXxll|B%@+}w`5jW1?E`x7}YMM-sj+kOH9k%1y5m9g2 znMbzE$yJ%|#;zH;Ds0bQA?Jwimbq@+aF=PW;P-dMuGK0dc`mj#TL&$Nb{0M%bL`71 zZu*pPdvU|4xE#`$9u;4mlX2`-5_dqxQ*BUYUmg|Z^X$s3+b@-clK{SFNmHOZTuTlhAtEAYd(Y{Bz;L zbsP>Kms(y4oAff)zI`Pn-u~l zT&Ka9N+V3yzGONPVQM*ASnMp$+^J<~y}hczl%3R{rW~kk^h-R1y)WaHX?$@}N&%HK z`~v&LNvRAVd-U8X$v$_A3~zu(_|Y%qF#ptJ%fFJtzy|D@n}oWE%;B{mvc&%BCW-M- zit7f+2s17lBJTpRvqPkdhYI`gZSs(ZW%i#VL?lpy-+OCw<^YyicyoYmrOX zU!1-tAa9gQ#_`!0S!5sio7oFzSnMZbojUbQ0Y31^XaIhreKYXOzINejhnXk9@xEUv z5dLx{;9PpZGKt{bZOWM};4*L_ncoh<2Jv)J8Ft~zV#kly2Hg(1RJroRpj+D_Y53y0 z7Le?cer=!yy!c>3OFGCz{s0Wu3q7U1nafw#)EnJKPlqXwl@Z!}Vb%k^hs;=_J6?0d z?5Iijcb2W)9g0Pact>X-8nvQ337Pe%-V8@qTfnadpc8a`f0s)9L|!h*Q%NTwK*+p} zy5Py;E_l8qFL+$&ctwlw_6TjM1fHE`T9eW|zLaNLThZq6&zbT#dS277aaWSoplg(F zz*|Wg1~0VfcM@Q-RrK_ap{zyDz^{BG)LTSgFtsYaF@xxZwR7qjRtT3%wkIzTx zPr)LarZ`tqoYAC%s(Zbp#3tC7E7+J8;Nlqd;=M5%gi?fY`mmzh)^L^Vw{p4Ps+D#t zGubLJHBKL0*lN@GvNgUO&2}5PmS?kTrS0ZTR0qT zi$p`=5U!h~rO=4`CTVX)lg+*_+r2Nx{2=}}NgKav<={JP#$s|J2ReIqZ z%w~2nU8}kLHcn>MYRbL*&eD)#a5Sc90n#aY0!-|fqQM;@>9aENaPBa|8H03C&Tt}c z*|h&RMiMwXMa$qUuA8RcInSrhOLTIHV}CuY7NKd%?|Qve2clNQiW%JvR-z{kgiD$< zz#p#bwV+~ozy6C1T{rZ{gXacxP+Wyr*QAe5fU^(Uoox;{FaB{jtHE)JlTUC;Oz!{y diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index a0552189f443..ba2398141bec 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -20,22 +20,21 @@ use crate::{ rlp, runtime::GAS_PRICE, subxt_client::{ - revive::calls::types::EthTransact, runtime_types::pallet_revive::storage::ContractInfo, + revive::{calls::types::EthTransact, events::ContractEmitted}, + runtime_types::pallet_revive::storage::ContractInfo, }, TransactionLegacySigned, LOG_TARGET, }; -use codec::Encode; use futures::{stream, StreamExt}; -use jsonrpsee::types::{ErrorCode, ErrorObjectOwned}; +use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObjectOwned}; use pallet_revive::{ create1, evm::{ - Block, BlockNumberOrTag, BlockNumberOrTagOrHash, Bytes256, GenericTransaction, ReceiptInfo, - SyncingProgress, SyncingStatus, TransactionSigned, H160, H256, U256, + Block, BlockNumberOrTag, BlockNumberOrTagOrHash, Bytes256, GenericTransaction, Log, + ReceiptInfo, SyncingProgress, SyncingStatus, TransactionSigned, H160, H256, U256, }, EthContractResult, }; -use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_weights::Weight; use std::{ collections::{HashMap, VecDeque}, @@ -46,7 +45,7 @@ use subxt::{ backend::{ legacy::{rpc_methods::SystemHealth, LegacyRpcMethods}, rpc::{ - reconnecting_rpc_client::{Client as ReconnectingRpcClient, ExponentialBackoff}, + reconnecting_rpc_client::{ExponentialBackoff, RpcClient as ReconnectingRpcClient}, RpcClient, }, }, @@ -99,42 +98,60 @@ struct BlockCache { tx_hashes_by_block_and_index: HashMap>, } -fn unwrap_subxt_err(err: &subxt::Error) -> String { +/// Unwrap the original `jsonrpsee::core::client::Error::Call` error. +fn unwrap_call_err(err: &subxt::error::RpcError) -> Option { + use subxt::backend::rpc::reconnecting_rpc_client; match err { - subxt::Error::Rpc(err) => unwrap_rpc_err(err), - _ => err.to_string(), + subxt::error::RpcError::ClientError(err) => { + match err.downcast_ref::() { + Some(reconnecting_rpc_client::Error::RpcError( + jsonrpsee::core::client::Error::Call(err), + )) => Some(err.clone().into_owned()), + _ => None, + } + }, + _ => None, } } -fn unwrap_rpc_err(err: &subxt::error::RpcError) -> String { - match err { - subxt::error::RpcError::ClientError(err) => match err - // TODO use the re-export from subxt once available - .downcast_ref::() - { - Some(jsonrpsee::core::ClientError::Call(call_err)) => call_err.message().to_string(), - Some(other_err) => other_err.to_string(), - None => err.to_string(), - }, - _ => err.to_string(), +/// Extract the revert message from a revert("msg") solidity statement. +fn extract_revert_message(exec_data: &[u8]) -> Option { + let function_selector = exec_data.get(0..4)?; + + // keccak256("Error(string)") + let expected_selector = [0x08, 0xC3, 0x79, 0xA0]; + if function_selector != expected_selector { + return None; + } + + let decoded = ethabi::decode(&[ethabi::ParamType::String], &exec_data[4..]).ok()?; + match decoded.first()? { + ethabi::Token::String(msg) => Some(msg.to_string()), + _ => None, } } /// The error type for the client. #[derive(Error, Debug)] pub enum ClientError { + /// A [`jsonrpsee::core::ClientError`] wrapper error. + #[error(transparent)] + Jsonrpsee(#[from] jsonrpsee::core::ClientError), /// A [`subxt::Error`] wrapper error. - #[error("{}",unwrap_subxt_err(.0))] + #[error(transparent)] SubxtError(#[from] subxt::Error), /// A [`RpcError`] wrapper error. - #[error("{}",unwrap_rpc_err(.0))] + #[error(transparent)] RpcError(#[from] RpcError), /// A [`codec::Error`] wrapper error. #[error(transparent)] CodecError(#[from] codec::Error), /// The dry run failed. - #[error("Dry run failed")] - DryRunFailed, + #[error("Dry run failed: {0}")] + DryRunFailed(String), + /// Contract reverted + #[error("Execution reverted: {}", extract_revert_message(.0).unwrap_or_default())] + Reverted(Vec), /// A decimal conversion failed. #[error("Conversion failed")] ConversionFailed, @@ -149,13 +166,23 @@ pub enum ClientError { CacheEmpty, } -const GENERIC_ERROR_CODE: ErrorCode = ErrorCode::ServerError(-32000); - -// Convert a `ClientError` to an RPC `ErrorObjectOwned`. +// TODO convert error code to https://eips.ethereum.org/EIPS/eip-1474#error-codes impl From for ErrorObjectOwned { - fn from(value: ClientError) -> Self { - log::debug!(target: LOG_TARGET, "ClientError: {value:?}"); - ErrorObjectOwned::owned::<()>(GENERIC_ERROR_CODE.code(), value.to_string(), None) + fn from(err: ClientError) -> Self { + let msg = err.to_string(); + match err { + ClientError::SubxtError(subxt::Error::Rpc(err)) | ClientError::RpcError(err) => { + if let Some(err) = unwrap_call_err(&err) { + return err; + } + ErrorObjectOwned::owned::>(CALL_EXECUTION_FAILED_CODE, msg, None) + }, + ClientError::Reverted(data) => { + let data = format!("0x{}", hex::encode(data)); + ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, Some(data)) + }, + _ => ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, None), + } } } @@ -250,8 +277,6 @@ impl ClientInner { // Filter extrinsics from pallet_revive let extrinsics = extrinsics.iter().flat_map(|ext| { - let ext = ext.ok()?; - let call = ext.as_extrinsic::().ok()??; let tx = rlp::decode::(&call.payload).ok()?; let from = tx.recover_eth_address().ok()?; @@ -278,15 +303,37 @@ impl ClientInner { let success = events.has::()?; let transaction_index = ext.index(); - let transaction_hash = BlakeTwo256::hash(&Vec::from(ext.bytes()).encode()); let block_hash = block.hash(); let block_number = block.number().into(); - + let transaction_hash= ext.hash(); + + // get logs from ContractEmitted event + let logs = events.iter() + .filter_map(|event_details| { + let event_details = event_details.ok()?; + let event = event_details.as_event::().ok()??; + + Some(Log { + address: Some(event.contract), + topics: Some(event.topics), + data: Some(event.data.into()), + block_number: Some(block_number), + transaction_hash, + transaction_index: Some(transaction_index.into()), + block_hash: Some(block_hash), + log_index: Some(event_details.index().into()), + ..Default::default() + }) + }).collect(); + + + log::debug!(target: LOG_TARGET, "Adding receipt for tx hash: {transaction_hash:?} - block: {block_number:?}"); let receipt = ReceiptInfo { block_hash, block_number, contract_address, from, + logs, to: tx.transaction_legacy_unsigned.to, effective_gas_price: gas_price, gas_used: gas_used.into(), @@ -351,7 +398,6 @@ impl Client { let (tx, mut updates) = tokio::sync::watch::channel(()); spawn_handle.spawn("subscribe-blocks", None, Self::subscribe_blocks(inner.clone(), tx)); - spawn_handle.spawn("subscribe-reconnect", None, Self::subscribe_reconnect(inner.clone())); updates.changed().await.expect("tx is not dropped"); Ok(Self { inner, updates }) @@ -409,18 +455,6 @@ impl Client { } } - /// Subscribe and log reconnection events. - async fn subscribe_reconnect(inner: Arc) { - let rpc = inner.as_ref().rpc_client.clone(); - loop { - let reconnected = rpc.reconnect_initiated().await; - log::info!(target: LOG_TARGET, "RPC client connection lost"); - let now = std::time::Instant::now(); - reconnected.await; - log::info!(target: LOG_TARGET, "RPC client reconnection took `{}s`", now.elapsed().as_secs()); - } - } - /// Subscribe to new blocks and update the cache. async fn subscribe_blocks(inner: Arc, tx: Sender<()>) { log::info!(target: LOG_TARGET, "Subscribing to new blocks"); @@ -428,7 +462,7 @@ impl Client { Ok(s) => s, Err(err) => { log::error!(target: LOG_TARGET, "Failed to subscribe to blocks: {err:?}"); - return + return; }, }; @@ -445,7 +479,7 @@ impl Client { } log::error!(target: LOG_TARGET, "Failed to fetch block: {err:?}"); - return + return; }, }; @@ -461,7 +495,6 @@ impl Client { .unwrap_or_default(); if !receipts.is_empty() { - log::debug!(target: LOG_TARGET, "Adding {} receipts", receipts.len()); let values = receipts .iter() .map(|(hash, (_, receipt))| (receipt.transaction_index, *hash)) @@ -622,7 +655,7 @@ impl Client { &self, tx: &GenericTransaction, block: BlockNumberOrTagOrHash, - ) -> Result, ClientError> { + ) -> Result>, ClientError> { let runtime_api = self.runtime_api(&block).await?; let value = self @@ -643,8 +676,21 @@ impl Client { None, None, ); - let res = runtime_api.call(payload).await?.0; - Ok(res) + + let EthContractResult { fee, gas_required, storage_deposit, result } = + runtime_api.call(payload).await?.0; + match result { + Err(err) => { + log::debug!(target: LOG_TARGET, "Dry run failed {err:?}"); + Err(ClientError::DryRunFailed(format!("{err:?}"))) + }, + Ok(result) if result.did_revert() => { + log::debug!(target: LOG_TARGET, "Dry run reverted"); + Err(ClientError::Reverted(result.0.data)) + }, + Ok(result) => + Ok(EthContractResult { fee, gas_required, storage_deposit, result: result.0.data }), + } } /// Dry run a transaction and returns the gas estimate for the transaction. diff --git a/substrate/frame/revive/rpc/src/example.rs b/substrate/frame/revive/rpc/src/example.rs index cdf5ce9d1b98..d2f9b509f4d2 100644 --- a/substrate/frame/revive/rpc/src/example.rs +++ b/substrate/frame/revive/rpc/src/example.rs @@ -40,57 +40,127 @@ pub async fn wait_for_receipt( anyhow::bail!("Failed to get receipt") } -/// Send a transaction. -pub async fn send_transaction( - signer: &Account, +/// Wait for a successful transaction receipt. +pub async fn wait_for_successful_receipt( client: &(impl EthRpcClient + Send + Sync), + hash: H256, +) -> anyhow::Result { + let receipt = wait_for_receipt(client, hash).await?; + if receipt.is_success() { + Ok(receipt) + } else { + anyhow::bail!("Transaction failed") + } +} + +/// Transaction builder. +pub struct TransactionBuilder { + signer: Account, value: U256, input: Bytes, to: Option, -) -> anyhow::Result { - let from = signer.address(); - - let chain_id = Some(client.chain_id().await?); - - let gas_price = client.gas_price().await?; - let nonce = client - .get_transaction_count(from, BlockTag::Latest.into()) - .await - .with_context(|| "Failed to fetch account nonce")?; - - let gas = client - .estimate_gas( - GenericTransaction { - from: Some(from), - input: Some(input.clone()), - value: Some(value), - gas_price: Some(gas_price), - to, - ..Default::default() - }, - None, - ) - .await - .with_context(|| "Failed to fetch gas estimate")?; - - let unsigned_tx = TransactionLegacyUnsigned { - gas, - nonce, - to, - value, - input, - gas_price, - chain_id, - ..Default::default() - }; - - let tx = signer.sign_transaction(unsigned_tx.clone()); - let bytes = tx.rlp_bytes().to_vec(); - - let hash = client - .send_raw_transaction(bytes.clone().into()) - .await - .with_context(|| "transaction failed")?; - - Ok(hash) + mutate: Box, +} + +impl Default for TransactionBuilder { + fn default() -> Self { + Self { + signer: Account::default(), + value: U256::zero(), + input: Bytes::default(), + to: None, + mutate: Box::new(|_| {}), + } + } +} + +impl TransactionBuilder { + /// Set the signer. + pub fn signer(mut self, signer: Account) -> Self { + self.signer = signer; + self + } + + /// Set the value. + pub fn value(mut self, value: U256) -> Self { + self.value = value; + self + } + + /// Set the input. + pub fn input(mut self, input: Vec) -> Self { + self.input = Bytes(input); + self + } + + /// Set the destination. + pub fn to(mut self, to: H160) -> Self { + self.to = Some(to); + self + } + + /// Set a mutation function, that mutates the transaction before sending. + pub fn mutate(mut self, mutate: impl FnOnce(&mut TransactionLegacyUnsigned) + 'static) -> Self { + self.mutate = Box::new(mutate); + self + } + + /// Send the transaction. + pub async fn send(self, client: &(impl EthRpcClient + Send + Sync)) -> anyhow::Result { + let TransactionBuilder { signer, value, input, to, mutate } = self; + + let from = signer.address(); + let chain_id = Some(client.chain_id().await?); + let gas_price = client.gas_price().await?; + let nonce = client + .get_transaction_count(from, BlockTag::Latest.into()) + .await + .with_context(|| "Failed to fetch account nonce")?; + + let gas = client + .estimate_gas( + GenericTransaction { + from: Some(from), + input: Some(input.clone()), + value: Some(value), + gas_price: Some(gas_price), + to, + ..Default::default() + }, + None, + ) + .await + .with_context(|| "Failed to fetch gas estimate")?; + + let mut unsigned_tx = TransactionLegacyUnsigned { + gas, + nonce, + to, + value, + input, + gas_price, + chain_id, + ..Default::default() + }; + + mutate(&mut unsigned_tx); + + let tx = signer.sign_transaction(unsigned_tx.clone()); + let bytes = tx.rlp_bytes().to_vec(); + + let hash = client + .send_raw_transaction(bytes.clone().into()) + .await + .with_context(|| "transaction failed")?; + + Ok(hash) + } + + pub async fn send_and_wait_for_receipt( + self, + client: &(impl EthRpcClient + Send + Sync), + ) -> anyhow::Result { + let hash = self.send(client).await?; + wait_for_successful_receipt(client, hash).await + } } diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index 88a3cb641784..f6709edc96c9 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -91,13 +91,13 @@ pub enum EthRpcError { TransactionTypeNotSupported(Byte), } +// TODO use https://eips.ethereum.org/EIPS/eip-1474#error-codes impl From for ErrorObjectOwned { fn from(value: EthRpcError) -> Self { - let code = match value { - EthRpcError::ClientError(_) => ErrorCode::InternalError, - _ => ErrorCode::InvalidRequest, - }; - Self::owned::(code.code(), value.to_string(), None) + match value { + EthRpcError::ClientError(err) => Self::from(err), + _ => Self::owned::(ErrorCode::InvalidRequest.code(), value.to_string(), None), + } } } @@ -121,6 +121,7 @@ impl EthRpcServer for EthRpcServerImpl { transaction_hash: H256, ) -> RpcResult> { let receipt = self.client.receipt(&transaction_hash).await; + log::debug!(target: LOG_TARGET, "transaction_receipt for {transaction_hash:?}: {}", receipt.is_some()); Ok(receipt) } @@ -167,6 +168,7 @@ impl EthRpcServer for EthRpcServerImpl { storage_deposit, ); let hash = self.client.submit(call).await?; + log::debug!(target: LOG_TARGET, "send_raw_transaction hash: {hash:?}"); Ok(hash) } @@ -252,12 +254,7 @@ impl EthRpcServer for EthRpcServerImpl { .client .dry_run(&transaction, block.unwrap_or_else(|| BlockTag::Latest.into())) .await?; - let output = dry_run.result.map_err(|err| { - log::debug!(target: LOG_TARGET, "Dry run failed: {err:?}"); - ClientError::DryRunFailed - })?; - - Ok(output.into()) + Ok(dry_run.result.into()) } async fn get_block_by_number( diff --git a/substrate/frame/revive/rpc/src/subxt_client.rs b/substrate/frame/revive/rpc/src/subxt_client.rs index cb2737beae70..11a0d51ed03e 100644 --- a/substrate/frame/revive/rpc/src/subxt_client.rs +++ b/substrate/frame/revive/rpc/src/subxt_client.rs @@ -22,8 +22,12 @@ use subxt::config::{signed_extensions, Config, PolkadotConfig}; #[subxt::subxt( runtime_metadata_path = "revive_chain.metadata", substitute_type( - path = "pallet_revive::primitives::EthContractResult", - with = "::subxt::utils::Static<::pallet_revive::EthContractResult>" + path = "pallet_revive::primitives::EthContractResult", + with = "::subxt::utils::Static<::pallet_revive::EthContractResult>" + ), + substitute_type( + path = "pallet_revive::primitives::ExecReturnValue", + with = "::subxt::utils::Static<::pallet_revive::ExecReturnValue>" ), substitute_type( path = "sp_weights::weight_v2::Weight", diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 01fcb6ae3bd2..537cfd07964f 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -18,14 +18,14 @@ use crate::{ cli::{self, CliCommand}, - example::{send_transaction, wait_for_receipt}, + example::{wait_for_successful_receipt, TransactionBuilder}, EthRpcClient, }; use clap::Parser; use jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use pallet_revive::{ create1, - evm::{Account, BlockTag, Bytes, U256}, + evm::{Account, BlockTag, U256}, }; use std::thread; use substrate_cli_test_utils::*; @@ -46,6 +46,29 @@ async fn ws_client_with_retry(url: &str) -> WsClient { .expect("Hit timeout") } +fn get_contract(name: &str) -> anyhow::Result<(Vec, ethabi::Contract)> { + const PVM_CONTRACTS: &str = include_str!("../examples/js/pvm-contracts.json"); + let pvm_contract: serde_json::Value = serde_json::from_str(PVM_CONTRACTS)?; + let pvm_contract = pvm_contract[name].as_object().unwrap(); + let bytecode = pvm_contract["bytecode"].as_str().unwrap(); + let bytecode = hex::decode(bytecode)?; + + let abi = pvm_contract["abi"].clone(); + let abi = serde_json::to_string(&abi)?; + let contract = ethabi::Contract::load(abi.as_bytes())?; + + Ok((bytecode, contract)) +} + +macro_rules! unwrap_call_err( + ($err:expr) => { + match $err.downcast_ref::().unwrap() { + jsonrpsee::core::client::Error::Call(call) => call, + _ => panic!("Expected Call error"), + } + } +); + #[tokio::test] async fn test_jsonrpsee_server() -> anyhow::Result<()> { // Start the node. @@ -55,7 +78,7 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { "--rpc-port=45789", "--no-telemetry", "--no-prometheus", - "-lerror,evm=debug,sc_rpc_server=info,runtime::revive=debug", + "-lerror,evm=debug,sc_rpc_server=info,runtime::revive=trace", ]) { panic!("Node exited with error: {e:?}"); } @@ -84,10 +107,13 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { assert_eq!(U256::zero(), ethan_balance); let value = 1_000_000_000_000_000_000_000u128.into(); - let hash = - send_transaction(&account, &client, value, Bytes::default(), Some(ethan.address())).await?; + let hash = TransactionBuilder::default() + .value(value) + .to(ethan.address()) + .send(&client) + .await?; - let receipt = wait_for_receipt(&client, hash).await?; + let receipt = wait_for_successful_receipt(&client, hash).await?; assert_eq!( Some(ethan.address()), receipt.to, @@ -103,8 +129,8 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { let (bytes, _) = pallet_revive_fixtures::compile_module("dummy")?; let input = bytes.into_iter().chain(data.clone()).collect::>(); let nonce = client.get_transaction_count(account.address(), BlockTag::Latest.into()).await?; - let hash = send_transaction(&account, &client, value, input.into(), None).await?; - let receipt = wait_for_receipt(&client, hash).await?; + let hash = TransactionBuilder::default().value(value).input(input).send(&client).await?; + let receipt = wait_for_successful_receipt(&client, hash).await?; let contract_address = create1(&account.address(), nonce.try_into().unwrap()); assert_eq!( Some(contract_address), @@ -116,15 +142,78 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { assert_eq!(value, balance, "Contract balance should be the same as the value sent."); // Call contract - let hash = - send_transaction(&account, &client, U256::zero(), Bytes::default(), Some(contract_address)) - .await?; - let receipt = wait_for_receipt(&client, hash).await?; + let hash = TransactionBuilder::default() + .value(value) + .to(contract_address) + .send(&client) + .await?; + let receipt = wait_for_successful_receipt(&client, hash).await?; + assert_eq!( Some(contract_address), receipt.to, "Receipt should have the correct contract address." ); + let increase = client.get_balance(contract_address, BlockTag::Latest.into()).await? - balance; + assert_eq!(value, increase, "contract's balance should have increased by the value sent."); + + // Balance transfer to contract + let balance = client.get_balance(contract_address, BlockTag::Latest.into()).await?; + let hash = TransactionBuilder::default() + .value(value) + .to(contract_address) + .send(&client) + .await?; + + wait_for_successful_receipt(&client, hash).await?; + let increase = client.get_balance(contract_address, BlockTag::Latest.into()).await? - balance; + assert_eq!(value, increase, "contract's balance should have increased by the value sent."); + + // Deploy revert + let (bytecode, contract) = get_contract("revert")?; + let receipt = TransactionBuilder::default() + .input(contract.constructor.clone().unwrap().encode_input(bytecode, &[]).unwrap()) + .send_and_wait_for_receipt(&client) + .await?; + + // Call doRevert + let err = TransactionBuilder::default() + .to(receipt.contract_address.unwrap()) + .input(contract.function("doRevert")?.encode_input(&[])?.to_vec()) + .send(&client) + .await + .unwrap_err(); + + let call_err = unwrap_call_err!(err.source().unwrap()); + assert_eq!(call_err.message(), "Execution reverted: revert message"); + + // Deploy event + let (bytecode, contract) = get_contract("event")?; + let receipt = TransactionBuilder::default() + .input(bytecode) + .send_and_wait_for_receipt(&client) + .await?; + + // Call triggerEvent + let receipt = TransactionBuilder::default() + .to(receipt.contract_address.unwrap()) + .input(contract.function("triggerEvent")?.encode_input(&[])?.to_vec()) + .send_and_wait_for_receipt(&client) + .await?; + assert_eq!(receipt.logs.len(), 1, "There should be one log."); + + // Invalid transaction + let err = TransactionBuilder::default() + .value(value) + .to(ethan.address()) + .mutate(|tx| tx.chain_id = Some(42u32.into())) + .send(&client) + .await + .unwrap_err(); + + let call_err = unwrap_call_err!(err.source().unwrap()); + assert_eq!(call_err.message(), "Invalid Transaction"); + Ok(()) } diff --git a/substrate/frame/revive/src/evm/api/account.rs b/substrate/frame/revive/src/evm/api/account.rs index 06fb6e7e9c21..8365ebf83cae 100644 --- a/substrate/frame/revive/src/evm/api/account.rs +++ b/substrate/frame/revive/src/evm/api/account.rs @@ -40,7 +40,7 @@ impl From for Account { impl Account { /// Get the [`H160`] address of the account. pub fn address(&self) -> H160 { - H160::from_slice(&self.0.account_id().as_ref()) + H160::from_slice(&self.0.public_key().to_account_id().as_ref()) } /// Get the substrate [`AccountId32`] of the account. diff --git a/substrate/frame/revive/src/evm/api/rpc_types.rs b/substrate/frame/revive/src/evm/api/rpc_types.rs index b15a0a53cd07..84390563d05a 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types.rs @@ -16,6 +16,7 @@ // limitations under the License. //! Utility impl for the RPC types. use super::{ReceiptInfo, TransactionInfo, TransactionSigned}; +use sp_core::U256; impl TransactionInfo { /// Create a new [`TransactionInfo`] from a receipt and a signed transaction. @@ -30,3 +31,10 @@ impl TransactionInfo { } } } + +impl ReceiptInfo { + /// Returns `true` if the transaction was successful. + pub fn is_success(&self) -> bool { + self.status.map_or(false, |status| status == U256::one()) + } +} diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index d4c3440a3ea7..bfff5e79e3ae 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -351,7 +351,8 @@ pub trait EthExtra { let nonce = nonce.try_into().map_err(|_| InvalidTransaction::Call)?; - // Fees calculated with the fixed `GAS_PRICE` that should be used to estimate the gas. + // Fees calculated with the fixed `GAS_PRICE` + // When we dry-run the transaction, we set the gas to `Fee / GAS_PRICE` let eth_fee_no_tip = U256::from(GAS_PRICE) .saturating_mul(gas) .try_into() @@ -376,6 +377,8 @@ pub trait EthExtra { .into(); log::trace!(target: LOG_TARGET, "try_into_checked_extrinsic: encoded_len: {encoded_len:?} actual_fee: {actual_fee:?} eth_fee: {eth_fee:?}"); + // The fees from the Ethereum transaction should be greater or equal to the actual fees paid + // by the account. if eth_fee < actual_fee { log::debug!(target: LOG_TARGET, "fees {eth_fee:?} too low for the extrinsic {actual_fee:?}"); return Err(InvalidTransaction::Payment.into()) @@ -417,41 +420,6 @@ mod test { }; type AccountIdOf = ::AccountId; - /// A simple account that can sign transactions - pub struct Account(subxt_signer::eth::Keypair); - - impl Default for Account { - fn default() -> Self { - Self(subxt_signer::eth::dev::alith()) - } - } - - impl From for Account { - fn from(kp: subxt_signer::eth::Keypair) -> Self { - Self(kp) - } - } - - impl Account { - /// Get the [`AccountId`] of the account. - pub fn account_id(&self) -> AccountIdOf { - let address = self.address(); - ::AddressMapper::to_fallback_account_id(&address) - } - - /// Get the [`H160`] address of the account. - pub fn address(&self) -> H160 { - H160::from_slice(&self.0.account_id().as_ref()) - } - - /// Sign a transaction. - pub fn sign_transaction(&self, tx: TransactionLegacyUnsigned) -> TransactionLegacySigned { - let rlp_encoded = tx.rlp_bytes(); - let signature = self.0.sign(&rlp_encoded); - TransactionLegacySigned::from(tx, signature.as_ref()) - } - } - #[derive(Clone, PartialEq, Eq, Debug)] pub struct Extra; type SignedExtra = (frame_system::CheckNonce, ChargeTransactionPayment); @@ -504,7 +472,7 @@ mod test { fn estimate_gas(&mut self) { let dry_run = crate::Pallet::::bare_eth_transact( - Account::default().account_id(), + Account::default().substrate_account(), self.tx.to, self.tx.value.try_into().unwrap(), self.tx.input.clone().0, @@ -550,7 +518,7 @@ mod test { // Fund the account. let account = Account::default(); let _ = ::Currency::set_balance( - &account.account_id(), + &account.substrate_account(), 100_000_000_000_000, ); @@ -631,7 +599,7 @@ mod test { Err(TransactionValidityError::Invalid(InvalidTransaction::Future)) ); - >::inc_account_nonce(Account::default().account_id()); + >::inc_account_nonce(Account::default().substrate_account()); let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])); assert_eq!( diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index 5038ae44afad..5ca0042d929b 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -1244,134 +1244,115 @@ where T::Nonce: Into, T::Hash: frame_support::traits::IsType, { - log::debug!(target: LOG_TARGET, "bare_eth_transact: dest: {dest:?} value: {value:?} gas_limit: {gas_limit:?} storage_deposit_limit: {storage_deposit_limit:?}"); + log::debug!(target: LOG_TARGET, "bare_eth_transact: dest: {dest:?} value: {value:?} + gas_limit: {gas_limit:?} storage_deposit_limit: {storage_deposit_limit:?}"); + // Get the nonce to encode in the tx. let nonce: T::Nonce = >::account_nonce(&origin); - // Use a big enough gas price to ensure that the encoded size is large enough. - let max_gas_fee: BalanceOf = - (pallet_transaction_payment::Pallet::::weight_to_fee(Weight::MAX) / - GAS_PRICE.into()) - .into(); - - // A contract call. - if let Some(dest) = dest { - // Dry run the call. - let result = crate::Pallet::::bare_call( - T::RuntimeOrigin::signed(origin), - dest, - value, - gas_limit, - storage_deposit_limit, - input.clone(), - debug, - collect_events, - ); - - // Get the encoded size of the transaction. - let tx = TransactionLegacyUnsigned { - value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), - input: input.into(), - nonce: nonce.into(), - chain_id: Some(T::ChainId::get().into()), - gas_price: GAS_PRICE.into(), - gas: max_gas_fee.into(), - to: Some(dest), - ..Default::default() - }; - - let eth_dispatch_call = crate::Call::::eth_transact { - payload: tx.dummy_signed_payload(), - gas_limit: result.gas_required, - storage_deposit_limit: result.storage_deposit.charge_or_zero(), - }; - let encoded_len = utx_encoded_size(eth_dispatch_call); - - // Get the dispatch info of the call. - let dispatch_call: ::RuntimeCall = crate::Call::::call { - dest, - value, - gas_limit: result.gas_required, - storage_deposit_limit: result.storage_deposit.charge_or_zero(), - data: tx.input.0, - } - .into(); - let dispatch_info = dispatch_call.get_dispatch_info(); + // Dry run the call + let (mut result, dispatch_info) = match dest { + // A contract call. + Some(dest) => { + // Dry run the call. + let result = crate::Pallet::::bare_call( + T::RuntimeOrigin::signed(origin), + dest, + value, + gas_limit, + storage_deposit_limit, + input.clone(), + debug, + collect_events, + ); + let result = EthContractResult { + gas_required: result.gas_required, + storage_deposit: result.storage_deposit.charge_or_zero(), + result: result.result, + fee: Default::default(), + }; + // Get the dispatch info of the call. + let dispatch_call: ::RuntimeCall = crate::Call::::call { + dest, + value, + gas_limit: result.gas_required, + storage_deposit_limit: result.storage_deposit, + data: input.clone(), + } + .into(); + (result, dispatch_call.get_dispatch_info()) + }, + // A contract deployment + None => { + // Extract code and data from the input. + let (code, data) = match polkavm::ProgramBlob::blob_length(&input) { + Some(blob_len) => blob_len + .try_into() + .ok() + .and_then(|blob_len| (input.split_at_checked(blob_len))) + .unwrap_or_else(|| (&input[..], &[][..])), + _ => { + log::debug!(target: LOG_TARGET, "Failed to extract polkavm blob length"); + (&input[..], &[][..]) + }, + }; - // Compute the fee. - let fee = pallet_transaction_payment::Pallet::::compute_fee( - encoded_len, - &dispatch_info, - 0u32.into(), - ) - .into(); + // Dry run the call. + let result = crate::Pallet::::bare_instantiate( + T::RuntimeOrigin::signed(origin), + value, + gas_limit, + storage_deposit_limit, + Code::Upload(code.to_vec()), + data.to_vec(), + None, + debug, + collect_events, + ); + + let result = EthContractResult { + gas_required: result.gas_required, + storage_deposit: result.storage_deposit.charge_or_zero(), + result: result.result.map(|v| v.result), + fee: Default::default(), + }; - log::trace!(target: LOG_TARGET, "bare_eth_call: len: {encoded_len:?} fee: {fee:?}"); - EthContractResult { - gas_required: result.gas_required, - storage_deposit: result.storage_deposit.charge_or_zero(), - result: result.result.map(|v| v.data), - fee, - } - // A contract deployment - } else { - // Extract code and data from the input. - let (code, data) = match polkavm::ProgramBlob::blob_length(&input) { - Some(blob_len) => blob_len - .try_into() - .ok() - .and_then(|blob_len| (input.split_at_checked(blob_len))) - .unwrap_or_else(|| (&input[..], &[][..])), - _ => { - log::debug!(target: LOG_TARGET, "Failed to extract polkavm blob length"); - (&input[..], &[][..]) - }, - }; + // Get the dispatch info of the call. + let dispatch_call: ::RuntimeCall = + crate::Call::::instantiate_with_code { + value, + gas_limit: result.gas_required, + storage_deposit_limit: result.storage_deposit, + code: code.to_vec(), + data: data.to_vec(), + salt: None, + } + .into(); + (result, dispatch_call.get_dispatch_info()) + }, + }; - // Dry run the call. - let result = crate::Pallet::::bare_instantiate( - T::RuntimeOrigin::signed(origin), - value, - gas_limit, - storage_deposit_limit, - Code::Upload(code.to_vec()), - data.to_vec(), - None, - debug, - collect_events, - ); + let mut tx = TransactionLegacyUnsigned { + value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), + input: input.into(), + nonce: nonce.into(), + chain_id: Some(T::ChainId::get().into()), + gas_price: GAS_PRICE.into(), + to: dest, + ..Default::default() + }; - // Get the encoded size of the transaction. - let tx = TransactionLegacyUnsigned { - gas: max_gas_fee.into(), - nonce: nonce.into(), - value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), - input: input.clone().into(), - gas_price: GAS_PRICE.into(), - chain_id: Some(T::ChainId::get().into()), - ..Default::default() - }; + // The transaction fees depend on the extrinsic's length, which in turn is influenced by + // the encoded length of the gas limit specified in the transaction (tx.gas). + // We iteratively compute the fee by adjusting tx.gas until the fee stabilizes. + // with a maximum of 3 iterations to avoid an infinite loop. + for _ in 0..3 { let eth_dispatch_call = crate::Call::::eth_transact { payload: tx.dummy_signed_payload(), gas_limit: result.gas_required, - storage_deposit_limit: result.storage_deposit.charge_or_zero(), + storage_deposit_limit: result.storage_deposit, }; let encoded_len = utx_encoded_size(eth_dispatch_call); - - // Get the dispatch info of the call. - let dispatch_call: ::RuntimeCall = - crate::Call::::instantiate_with_code { - value, - gas_limit: result.gas_required, - storage_deposit_limit: result.storage_deposit.charge_or_zero(), - code: code.to_vec(), - data: data.to_vec(), - salt: None, - } - .into(); - let dispatch_info = dispatch_call.get_dispatch_info(); - - // Compute the fee. let fee = pallet_transaction_payment::Pallet::::compute_fee( encoded_len, &dispatch_info, @@ -1379,14 +1360,16 @@ where ) .into(); - log::trace!(target: LOG_TARGET, "bare_eth_call: len: {encoded_len:?} fee: {fee:?}"); - EthContractResult { - gas_required: result.gas_required, - storage_deposit: result.storage_deposit.charge_or_zero(), - result: result.result.map(|v| v.result.data), - fee, + if fee == result.fee { + log::trace!(target: LOG_TARGET, "bare_eth_call: encoded_len: {encoded_len:?} fee: {fee:?}"); + break; } + result.fee = fee; + tx.gas = (fee / GAS_PRICE.into()).into(); + log::debug!(target: LOG_TARGET, "Adjusting Eth gas to: {:?}", tx.gas); } + + result } /// A generalized version of [`Self::upload_code`]. diff --git a/substrate/frame/revive/src/primitives.rs b/substrate/frame/revive/src/primitives.rs index af0100d59cbe..024b1f3448e1 100644 --- a/substrate/frame/revive/src/primitives.rs +++ b/substrate/frame/revive/src/primitives.rs @@ -84,7 +84,7 @@ pub struct ContractResult { /// The result of the execution of a `eth_transact` call. #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct EthContractResult { +pub struct EthContractResult> { /// The fee charged for the execution. pub fee: Balance, /// The amount of gas that was necessary to execute the transaction. @@ -92,7 +92,7 @@ pub struct EthContractResult { /// Storage deposit charged. pub storage_deposit: Balance, /// The execution result. - pub result: Result, DispatchError>, + pub result: R, } /// Result type of a `bare_code_upload` call. From 9f603b1a7f3ca3fcfa7ea2d146cac5e011f523a9 Mon Sep 17 00:00:00 2001 From: Doordashcon Date: Tue, 12 Nov 2024 00:49:52 -0800 Subject: [PATCH 075/166] NoOp Impl Polling Trait (#5311) Adds NoOp implementation for the `Polling` trait and updates benchmarks in `pallet-ranked-collective`. --------- Co-authored-by: Oliver Tale-Yazdi --- prdoc/pr_5311.prdoc | 16 + .../core-fellowship/src/tests/integration.rs | 47 +-- .../ranked-collective/src/benchmarking.rs | 273 +++++++++++++----- .../frame/salary/src/tests/integration.rs | 52 +--- substrate/frame/support/src/traits.rs | 2 +- substrate/frame/support/src/traits/voting.rs | 48 ++- 6 files changed, 282 insertions(+), 156 deletions(-) create mode 100644 prdoc/pr_5311.prdoc diff --git a/prdoc/pr_5311.prdoc b/prdoc/pr_5311.prdoc new file mode 100644 index 000000000000..07affa5cb2ee --- /dev/null +++ b/prdoc/pr_5311.prdoc @@ -0,0 +1,16 @@ +title: No-op Impl Polling Trait + +doc: + - audience: Runtime Dev + description: | + Provide a NoOp implementation of the Polling trait for unit where the trait is defined and skiping benchmarks that necessitate it's definition. + +crates: + - name: pallet-core-fellowship + bump: minor + - name: pallet-ranked-collective + bump: minor + - name: pallet-salary + bump: minor + - name: frame-support + bump: minor diff --git a/substrate/frame/core-fellowship/src/tests/integration.rs b/substrate/frame/core-fellowship/src/tests/integration.rs index bcf70c7beb10..7a48ed9783e7 100644 --- a/substrate/frame/core-fellowship/src/tests/integration.rs +++ b/substrate/frame/core-fellowship/src/tests/integration.rs @@ -21,15 +21,15 @@ use frame_support::{ assert_noop, assert_ok, derive_impl, hypothetically, ord_parameter_types, pallet_prelude::Weight, parameter_types, - traits::{ConstU16, EitherOf, IsInVec, MapSuccess, PollStatus, Polling, TryMapSuccess}, + traits::{ConstU16, EitherOf, IsInVec, MapSuccess, NoOpPoll, TryMapSuccess}, }; use frame_system::EnsureSignedBy; -use pallet_ranked_collective::{EnsureRanked, Geometric, Rank, TallyOf, Votes}; +use pallet_ranked_collective::{EnsureRanked, Geometric, Rank}; use sp_core::{ConstU32, Get}; use sp_runtime::{ bounded_vec, traits::{Convert, ReduceBy, ReplaceWithDefault, TryMorphInto}, - BuildStorage, DispatchError, + BuildStorage, }; type Class = Rank; @@ -83,45 +83,6 @@ impl Config for Test { type MaxRank = ConstU32<9>; } -pub struct TestPolls; -impl Polling> for TestPolls { - type Index = u8; - type Votes = Votes; - type Moment = u64; - type Class = Class; - - fn classes() -> Vec { - unimplemented!() - } - fn as_ongoing(_: u8) -> Option<(TallyOf, Self::Class)> { - unimplemented!() - } - fn access_poll( - _: Self::Index, - _: impl FnOnce(PollStatus<&mut TallyOf, Self::Moment, Self::Class>) -> R, - ) -> R { - unimplemented!() - } - fn try_access_poll( - _: Self::Index, - _: impl FnOnce( - PollStatus<&mut TallyOf, Self::Moment, Self::Class>, - ) -> Result, - ) -> Result { - unimplemented!() - } - - #[cfg(feature = "runtime-benchmarks")] - fn create_ongoing(_: Self::Class) -> Result { - unimplemented!() - } - - #[cfg(feature = "runtime-benchmarks")] - fn end_ongoing(_: Self::Index, _: bool) -> Result<(), ()> { - unimplemented!() - } -} - /// Convert the tally class into the minimum rank required to vote on the poll. /// MinRank(Class) = Class - Delta pub struct MinRankOfClass(PhantomData); @@ -154,7 +115,7 @@ impl pallet_ranked_collective::Config for Test { // Members can exchange up to the rank of 2 below them. MapSuccess, ReduceBy>>, >; - type Polls = TestPolls; + type Polls = NoOpPoll; type MinRankOfClass = MinRankOfClass; type MemberSwappedHandler = CoreFellowship; type VoteWeight = Geometric; diff --git a/substrate/frame/ranked-collective/src/benchmarking.rs b/substrate/frame/ranked-collective/src/benchmarking.rs index dc7f4aaca773..978489fb8485 100644 --- a/substrate/frame/ranked-collective/src/benchmarking.rs +++ b/substrate/frame/ranked-collective/src/benchmarking.rs @@ -21,11 +21,12 @@ use super::*; #[allow(unused_imports)] use crate::Pallet as RankedCollective; use alloc::vec::Vec; - -use frame_benchmarking::v1::{ - account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, +use frame_benchmarking::{ + v1::{account, BenchmarkError}, + v2::*, }; -use frame_support::{assert_ok, traits::UnfilteredDispatchable}; + +use frame_support::{assert_err, assert_ok, traits::NoOpPoll}; use frame_system::RawOrigin as SystemOrigin; const SEED: u32 = 0; @@ -56,131 +57,273 @@ fn make_member, I: 'static>(rank: Rank) -> T::AccountId { who } -benchmarks_instance_pallet! { - add_member { +#[instance_benchmarks( +where <>::Polls as frame_support::traits::Polling>>>::Index: From +)] +mod benchmarks { + use super::*; + + #[benchmark] + fn add_member() -> Result<(), BenchmarkError> { + // Generate a test account for the new member. let who = account::("member", 0, SEED); let who_lookup = T::Lookup::unlookup(who.clone()); + + // Attempt to get the successful origin for adding a member. let origin = T::AddOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::add_member { who: who_lookup }; - }: { call.dispatch_bypass_filter(origin)? } - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, who_lookup); + + // Ensure the member count has increased (or is 1 for rank 0). assert_eq!(MemberCount::::get(0), 1); + + // Check that the correct event was emitted. assert_last_event::(Event::MemberAdded { who }.into()); + + Ok(()) } - remove_member { - let r in 0 .. 10; + #[benchmark] + fn remove_member(r: Linear<0, 10>) -> Result<(), BenchmarkError> { + // Convert `r` to a rank and create members. let rank = r as u16; - let first = make_member::(rank); let who = make_member::(rank); let who_lookup = T::Lookup::unlookup(who.clone()); let last = make_member::(rank); - let last_index = (0..=rank).map(|r| IdToIndex::::get(r, &last).unwrap()).collect::>(); + + // Collect the index of the `last` member for each rank. + let last_index: Vec<_> = + (0..=rank).map(|r| IdToIndex::::get(r, &last).unwrap()).collect(); + + // Fetch the remove origin. let origin = T::RemoveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::remove_member { who: who_lookup, min_rank: rank }; - }: { call.dispatch_bypass_filter(origin)? } - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, who_lookup, rank); + for r in 0..=rank { - assert_eq!(MemberCount::::get(r), 2); + assert_eq!(MemberCount::::get(r), 1); assert_ne!(last_index[r as usize], IdToIndex::::get(r, &last).unwrap()); } + + // Ensure the correct event was emitted for the member removal. assert_last_event::(Event::MemberRemoved { who, rank }.into()); + + Ok(()) } - promote_member { - let r in 0 .. 10; + #[benchmark] + fn promote_member(r: Linear<0, 10>) -> Result<(), BenchmarkError> { + // Convert `r` to a rank and create the member. let rank = r as u16; let who = make_member::(rank); let who_lookup = T::Lookup::unlookup(who.clone()); + + // Try to fetch the promotion origin. let origin = T::PromoteOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::promote_member { who: who_lookup }; - }: { call.dispatch_bypass_filter(origin)? } - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, who_lookup); + + // Ensure the member's rank has increased by 1. assert_eq!(Members::::get(&who).unwrap().rank, rank + 1); + + // Ensure the correct event was emitted for the rank change. assert_last_event::(Event::RankChanged { who, rank: rank + 1 }.into()); + + Ok(()) } - demote_member { - let r in 0 .. 10; + #[benchmark] + fn demote_member(r: Linear<0, 10>) -> Result<(), BenchmarkError> { + // Convert `r` to a rank and create necessary members for the benchmark. let rank = r as u16; - let first = make_member::(rank); let who = make_member::(rank); let who_lookup = T::Lookup::unlookup(who.clone()); let last = make_member::(rank); + + // Get the last index for the member. let last_index = IdToIndex::::get(rank, &last).unwrap(); + + // Try to fetch the demotion origin. let origin = T::DemoteOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::demote_member { who: who_lookup }; - }: { call.dispatch_bypass_filter(origin)? } - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, who_lookup); + + // Ensure the member's rank has decreased by 1. assert_eq!(Members::::get(&who).map(|x| x.rank), rank.checked_sub(1)); - assert_eq!(MemberCount::::get(rank), 2); + + // Ensure the member count remains as expected. + assert_eq!(MemberCount::::get(rank), 1); + + // Ensure the index of the last member has changed. assert_ne!(last_index, IdToIndex::::get(rank, &last).unwrap()); - assert_last_event::(match rank { - 0 => Event::MemberRemoved { who, rank: 0 }, - r => Event::RankChanged { who, rank: r - 1 }, - }.into()); + + // Ensure the correct event was emitted depending on the member's rank. + assert_last_event::( + match rank { + 0 => Event::MemberRemoved { who, rank: 0 }, + r => Event::RankChanged { who, rank: r - 1 }, + } + .into(), + ); + + Ok(()) } - vote { - let class = T::Polls::classes().into_iter().next().unwrap(); - let rank = T::MinRankOfClass::convert(class.clone()); + #[benchmark] + fn vote() -> Result<(), BenchmarkError> { + // Get the first available class or set it to None if no class exists. + let class = T::Polls::classes().into_iter().next(); + + // Convert the class to a rank if it exists, otherwise use the default rank. + let rank = class.as_ref().map_or( + as frame_support::traits::RankedMembers>::Rank::default(), + |class| T::MinRankOfClass::convert(class.clone()), + ); + // Create a caller based on the rank. let caller = make_member::(rank); - let caller_lookup = T::Lookup::unlookup(caller.clone()); - let poll = T::Polls::create_ongoing(class).expect("Must always be able to create a poll for rank 0"); + // Determine the poll to use: create an ongoing poll if class exists, or use an invalid + // poll. + let poll = if let Some(ref class) = class { + T::Polls::create_ongoing(class.clone()) + .expect("Poll creation should succeed for rank 0") + } else { + >::Index::MAX.into() + }; + + // Benchmark the vote logic for a positive vote (true). + #[block] + { + let vote_result = + Pallet::::vote(SystemOrigin::Signed(caller.clone()).into(), poll, true); + + // If the class exists, expect success; otherwise expect a "NotPolling" error. + if class.is_some() { + assert_ok!(vote_result); + } else { + assert_err!(vote_result, crate::Error::::NotPolling); + }; + } + + // Vote logic for a negative vote (false). + let vote_result = + Pallet::::vote(SystemOrigin::Signed(caller.clone()).into(), poll, false); + + // Check the result of the negative vote. + if class.is_some() { + assert_ok!(vote_result); + } else { + assert_err!(vote_result, crate::Error::::NotPolling); + }; + + // If the class exists, verify the vote event and tally. + if let Some(_) = class { + let tally = Tally::from_parts(0, 0, 1); + let vote_event = Event::Voted { who: caller, poll, vote: VoteRecord::Nay(1), tally }; + assert_last_event::(vote_event.into()); + } - // Vote once. - assert_ok!(Pallet::::vote(SystemOrigin::Signed(caller.clone()).into(), poll, true)); - }: _(SystemOrigin::Signed(caller.clone()), poll, false) - verify { - let tally = Tally::from_parts(0, 0, 1); - let ev = Event::Voted { who: caller, poll, vote: VoteRecord::Nay(1), tally }; - assert_last_event::(ev.into()); + Ok(()) } - cleanup_poll { - let n in 0 .. 100; + #[benchmark] + fn cleanup_poll(n: Linear<0, 100>) -> Result<(), BenchmarkError> { + let alice: T::AccountId = whitelisted_caller(); + let origin = SystemOrigin::Signed(alice.clone()); + + // Try to retrieve the first class if it exists. + let class = T::Polls::classes().into_iter().next(); + + // Convert the class to a rank, or use a default rank if no class exists. + let rank = class.as_ref().map_or( + as frame_support::traits::RankedMembers>::Rank::default(), + |class| T::MinRankOfClass::convert(class.clone()), + ); - // Create a poll - let class = T::Polls::classes().into_iter().next().unwrap(); - let rank = T::MinRankOfClass::convert(class.clone()); - let poll = T::Polls::create_ongoing(class).expect("Must always be able to create a poll"); + // Determine the poll to use: create an ongoing poll if class exists, or use an invalid + // poll. + let poll = if let Some(ref class) = class { + T::Polls::create_ongoing(class.clone()) + .expect("Poll creation should succeed for rank 0") + } else { + >::Index::MAX.into() + }; - // Vote in the poll by each of `n` members - for i in 0..n { - let who = make_member::(rank); - assert_ok!(Pallet::::vote(SystemOrigin::Signed(who).into(), poll, true)); + // Simulate voting by `n` members. + for _ in 0..n { + let voter = make_member::(rank); + let result = Pallet::::vote(SystemOrigin::Signed(voter).into(), poll, true); + + // Check voting results based on class existence. + if class.is_some() { + assert_ok!(result); + } else { + assert_err!(result, crate::Error::::NotPolling); + } + } + + // End the poll if the class exists. + if class.is_some() { + T::Polls::end_ongoing(poll, false) + .map_err(|_| BenchmarkError::Stop("Failed to end poll"))?; } - // End the poll. - T::Polls::end_ongoing(poll, false).expect("Must always be able to end a poll"); + // Verify the number of votes cast. + let expected_votes = if class.is_some() { n as usize } else { 0 }; + assert_eq!(Voting::::iter_prefix(poll).count(), expected_votes); - assert_eq!(Voting::::iter_prefix(poll).count(), n as usize); - }: _(SystemOrigin::Signed(whitelisted_caller()), poll, n) - verify { + // Benchmark the cleanup function. + #[extrinsic_call] + _(origin, poll, n); + + // Ensure all votes are cleaned up after the extrinsic call. assert_eq!(Voting::::iter().count(), 0); + + Ok(()) } - exchange_member { + #[benchmark] + fn exchange_member() -> Result<(), BenchmarkError> { + // Create an existing member. let who = make_member::(1); T::BenchmarkSetup::ensure_member(&who); let who_lookup = T::Lookup::unlookup(who.clone()); + + // Create a new account for the new member. let new_who = account::("new-member", 0, SEED); let new_who_lookup = T::Lookup::unlookup(new_who.clone()); + + // Attempt to get the successful origin for exchanging a member. let origin = T::ExchangeOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - let call = Call::::exchange_member { who: who_lookup, new_who: new_who_lookup }; - }: { call.dispatch_bypass_filter(origin)? } - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, who_lookup, new_who_lookup); + + // Check that the new member was successfully exchanged and holds the correct rank. assert_eq!(Members::::get(&new_who).unwrap().rank, 1); + + // Ensure the old member no longer exists. assert_eq!(Members::::get(&who), None); + + // Ensure the correct event was emitted. assert_has_event::(Event::MemberExchanged { who, new_who }.into()); + + Ok(()) } - impl_benchmark_test_suite!(RankedCollective, crate::tests::ExtBuilder::default().build(), crate::tests::Test); + impl_benchmark_test_suite!( + RankedCollective, + crate::tests::ExtBuilder::default().build(), + crate::tests::Test + ); } diff --git a/substrate/frame/salary/src/tests/integration.rs b/substrate/frame/salary/src/tests/integration.rs index 69f218943ade..0c1fb8bbdcba 100644 --- a/substrate/frame/salary/src/tests/integration.rs +++ b/substrate/frame/salary/src/tests/integration.rs @@ -17,22 +17,21 @@ //! The crate's tests. +use crate as pallet_salary; +use crate::*; use frame_support::{ assert_noop, assert_ok, derive_impl, hypothetically, pallet_prelude::Weight, parameter_types, - traits::{ConstU64, EitherOf, MapSuccess, PollStatus, Polling}, + traits::{ConstU64, EitherOf, MapSuccess, NoOpPoll}, }; -use pallet_ranked_collective::{EnsureRanked, Geometric, TallyOf, Votes}; +use pallet_ranked_collective::{EnsureRanked, Geometric}; use sp_core::{ConstU16, Get}; use sp_runtime::{ traits::{Convert, ReduceBy, ReplaceWithDefault}, - BuildStorage, DispatchError, + BuildStorage, }; -use crate as pallet_salary; -use crate::*; - type Rank = u16; type Block = frame_system::mocking::MockBlock; @@ -55,45 +54,6 @@ impl frame_system::Config for Test { type Block = Block; } -pub struct TestPolls; -impl Polling> for TestPolls { - type Index = u8; - type Votes = Votes; - type Moment = u64; - type Class = Rank; - - fn classes() -> Vec { - unimplemented!() - } - fn as_ongoing(_index: u8) -> Option<(TallyOf, Self::Class)> { - unimplemented!() - } - fn access_poll( - _index: Self::Index, - _f: impl FnOnce(PollStatus<&mut TallyOf, Self::Moment, Self::Class>) -> R, - ) -> R { - unimplemented!() - } - fn try_access_poll( - _index: Self::Index, - _f: impl FnOnce( - PollStatus<&mut TallyOf, Self::Moment, Self::Class>, - ) -> Result, - ) -> Result { - unimplemented!() - } - - #[cfg(feature = "runtime-benchmarks")] - fn create_ongoing(_class: Self::Class) -> Result { - unimplemented!() - } - - #[cfg(feature = "runtime-benchmarks")] - fn end_ongoing(_index: Self::Index, _approved: bool) -> Result<(), ()> { - unimplemented!() - } -} - pub struct MinRankOfClass(PhantomData); impl> Convert for MinRankOfClass { fn convert(a: u16) -> Rank { @@ -176,7 +136,7 @@ impl pallet_ranked_collective::Config for Test { // Members can exchange up to the rank of 2 below them. MapSuccess, ReduceBy>>, >; - type Polls = TestPolls; + type Polls = NoOpPoll; type MinRankOfClass = MinRankOfClass; type MemberSwappedHandler = Salary; type VoteWeight = Geometric; diff --git a/substrate/frame/support/src/traits.rs b/substrate/frame/support/src/traits.rs index 635036d488df..2c580ea6ed61 100644 --- a/substrate/frame/support/src/traits.rs +++ b/substrate/frame/support/src/traits.rs @@ -110,7 +110,7 @@ pub use dispatch::{ }; mod voting; -pub use voting::{ClassCountOf, PollStatus, Polling, VoteTally}; +pub use voting::{ClassCountOf, NoOpPoll, PollStatus, Polling, VoteTally}; mod preimages; pub use preimages::{Bounded, BoundedInline, FetchResult, QueryPreimage, StorePreimage}; diff --git a/substrate/frame/support/src/traits/voting.rs b/substrate/frame/support/src/traits/voting.rs index 958ef5dce6c1..697134e4ca47 100644 --- a/substrate/frame/support/src/traits/voting.rs +++ b/substrate/frame/support/src/traits/voting.rs @@ -19,7 +19,7 @@ //! votes. use crate::dispatch::Parameter; -use alloc::vec::Vec; +use alloc::{vec, vec::Vec}; use codec::{HasCompact, MaxEncodedLen}; use sp_arithmetic::Perbill; use sp_runtime::{traits::Member, DispatchError}; @@ -126,3 +126,49 @@ pub trait Polling { (Self::classes().into_iter().next().expect("Always one class"), u32::max_value()) } } + +/// NoOp polling is required if pallet-referenda functionality not needed. +pub struct NoOpPoll; +impl Polling for NoOpPoll { + type Index = u8; + type Votes = u32; + type Class = u16; + type Moment = u64; + + fn classes() -> Vec { + vec![] + } + + fn as_ongoing(_index: Self::Index) -> Option<(Tally, Self::Class)> { + None + } + + fn access_poll( + _index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R, + ) -> R { + f(PollStatus::None) + } + + fn try_access_poll( + _index: Self::Index, + f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result, + ) -> Result { + f(PollStatus::None) + } + + #[cfg(feature = "runtime-benchmarks")] + fn create_ongoing(_class: Self::Class) -> Result { + Err(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn end_ongoing(_index: Self::Index, _approved: bool) -> Result<(), ()> { + Err(()) + } + + #[cfg(feature = "runtime-benchmarks")] + fn max_ongoing() -> (Self::Class, u32) { + (0, 0) + } +} From b570baf33ff0390b49a90c8d36b0621e3c9582c2 Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Tue, 12 Nov 2024 18:42:59 +0800 Subject: [PATCH 076/166] Migrate pallet-child-bounties benchmark to v2 (#6310) Part of: - #6202. --------- Co-authored-by: GitHub Action Co-authored-by: Giuseppe Re --- prdoc/pr_6310.prdoc | 12 + .../frame/child-bounties/src/benchmarking.rs | 234 ++++++++++++------ 2 files changed, 169 insertions(+), 77 deletions(-) create mode 100644 prdoc/pr_6310.prdoc diff --git a/prdoc/pr_6310.prdoc b/prdoc/pr_6310.prdoc new file mode 100644 index 000000000000..ab421791dc72 --- /dev/null +++ b/prdoc/pr_6310.prdoc @@ -0,0 +1,12 @@ +title: Migrate pallet-child-bounties benchmark to v2 +doc: +- audience: Runtime Dev + description: |- + Part of: + + - #6202. +crates: +- name: pallet-utility + bump: patch +- name: pallet-child-bounties + bump: patch diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index 67074f90cbf6..4b2d62cd920e 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -19,17 +19,15 @@ #![cfg(feature = "runtime-benchmarks")] -use super::*; - -use alloc::{vec, vec::Vec}; - -use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; +use alloc::vec; +use frame_benchmarking::{v2::*, BenchmarkError}; +use frame_support::ensure; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; -use sp_runtime::traits::BlockNumberProvider; - -use crate::Pallet as ChildBounties; use pallet_bounties::Pallet as Bounties; use pallet_treasury::Pallet as Treasury; +use sp_runtime::traits::BlockNumberProvider; + +use crate::*; const SEED: u32 = 0; @@ -144,7 +142,7 @@ fn activate_child_bounty( let mut bounty_setup = activate_bounty::(user, description)?; let child_curator_lookup = T::Lookup::unlookup(bounty_setup.child_curator.clone()); - ChildBounties::::add_child_bounty( + Pallet::::add_child_bounty( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_value, @@ -153,7 +151,7 @@ fn activate_child_bounty( bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; - ChildBounties::::propose_curator( + Pallet::::propose_curator( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, @@ -161,7 +159,7 @@ fn activate_child_bounty( bounty_setup.child_bounty_fee, )?; - ChildBounties::::accept_curator( + Pallet::::accept_curator( RawOrigin::Signed(bounty_setup.child_curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, @@ -180,26 +178,43 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); } -benchmarks! { - add_child_bounty { - let d in 0 .. T::MaximumReasonLength::get(); +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn add_child_bounty( + d: Linear<0, { T::MaximumReasonLength::get() }>, + ) -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_bounty::(0, d)?; - }: _(RawOrigin::Signed(bounty_setup.curator), bounty_setup.bounty_id, - bounty_setup.child_bounty_value, bounty_setup.reason.clone()) - verify { - assert_last_event::(Event::Added { - index: bounty_setup.bounty_id, - child_index: bounty_setup.child_bounty_id, - }.into()) + + #[extrinsic_call] + _( + RawOrigin::Signed(bounty_setup.curator), + bounty_setup.bounty_id, + bounty_setup.child_bounty_value, + bounty_setup.reason.clone(), + ); + + assert_last_event::( + Event::Added { + index: bounty_setup.bounty_id, + child_index: bounty_setup.child_bounty_id, + } + .into(), + ); + + Ok(()) } - propose_curator { + #[benchmark] + fn propose_curator() -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_bounty::(0, T::MaximumReasonLength::get())?; let child_curator_lookup = T::Lookup::unlookup(bounty_setup.child_curator.clone()); - ChildBounties::::add_child_bounty( + Pallet::::add_child_bounty( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_value, @@ -207,118 +222,183 @@ benchmarks! { )?; let child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; - }: _(RawOrigin::Signed(bounty_setup.curator), bounty_setup.bounty_id, - child_bounty_id, child_curator_lookup, bounty_setup.child_bounty_fee) + #[extrinsic_call] + _( + RawOrigin::Signed(bounty_setup.curator), + bounty_setup.bounty_id, + child_bounty_id, + child_curator_lookup, + bounty_setup.child_bounty_fee, + ); + + Ok(()) + } - accept_curator { + #[benchmark] + fn accept_curator() -> Result<(), BenchmarkError> { setup_pot_account::(); let mut bounty_setup = activate_bounty::(0, T::MaximumReasonLength::get())?; let child_curator_lookup = T::Lookup::unlookup(bounty_setup.child_curator.clone()); - ChildBounties::::add_child_bounty( + Pallet::::add_child_bounty( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_value, bounty_setup.reason.clone(), )?; - bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; + bounty_setup.child_bounty_id = + ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; - ChildBounties::::propose_curator( + Pallet::::propose_curator( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, child_curator_lookup, bounty_setup.child_bounty_fee, )?; - }: _(RawOrigin::Signed(bounty_setup.child_curator), bounty_setup.bounty_id, - bounty_setup.child_bounty_id) + + #[extrinsic_call] + _( + RawOrigin::Signed(bounty_setup.child_curator), + bounty_setup.bounty_id, + bounty_setup.child_bounty_id, + ); + + Ok(()) + } // Worst case when curator is inactive and any sender un-assigns the curator. - unassign_curator { + #[benchmark] + fn unassign_curator() -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; Treasury::::on_initialize(frame_system::Pallet::::block_number()); set_block_number::(T::SpendPeriod::get() + T::BountyUpdatePeriod::get() + 1u32.into()); let caller = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), bounty_setup.bounty_id, - bounty_setup.child_bounty_id) - award_child_bounty { + #[extrinsic_call] + _(RawOrigin::Signed(caller), bounty_setup.bounty_id, bounty_setup.child_bounty_id); + + Ok(()) + } + + #[benchmark] + fn award_child_bounty() -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED); + let beneficiary_account = account::("beneficiary", 0, SEED); let beneficiary = T::Lookup::unlookup(beneficiary_account.clone()); - }: _(RawOrigin::Signed(bounty_setup.child_curator), bounty_setup.bounty_id, - bounty_setup.child_bounty_id, beneficiary) - verify { - assert_last_event::(Event::Awarded { - index: bounty_setup.bounty_id, - child_index: bounty_setup.child_bounty_id, - beneficiary: beneficiary_account - }.into()) + + #[extrinsic_call] + _( + RawOrigin::Signed(bounty_setup.child_curator), + bounty_setup.bounty_id, + bounty_setup.child_bounty_id, + beneficiary, + ); + + assert_last_event::( + Event::Awarded { + index: bounty_setup.bounty_id, + child_index: bounty_setup.child_bounty_id, + beneficiary: beneficiary_account, + } + .into(), + ); + + Ok(()) } - claim_child_bounty { + #[benchmark] + fn claim_child_bounty() -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; - let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED); + let beneficiary_account = account("beneficiary", 0, SEED); let beneficiary = T::Lookup::unlookup(beneficiary_account); - ChildBounties::::award_child_bounty( + Pallet::::award_child_bounty( RawOrigin::Signed(bounty_setup.child_curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, - beneficiary + beneficiary, )?; - let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED); - let beneficiary = T::Lookup::unlookup(beneficiary_account.clone()); + let beneficiary_account = account("beneficiary", 0, SEED); set_block_number::(T::SpendPeriod::get() + T::BountyDepositPayoutDelay::get()); - ensure!(T::Currency::free_balance(&beneficiary_account).is_zero(), - "Beneficiary already has balance."); - - }: _(RawOrigin::Signed(bounty_setup.curator), bounty_setup.bounty_id, - bounty_setup.child_bounty_id) - verify { - ensure!(!T::Currency::free_balance(&beneficiary_account).is_zero(), - "Beneficiary didn't get paid."); + ensure!( + T::Currency::free_balance(&beneficiary_account).is_zero(), + "Beneficiary already has balance." + ); + + #[extrinsic_call] + _( + RawOrigin::Signed(bounty_setup.curator), + bounty_setup.bounty_id, + bounty_setup.child_bounty_id, + ); + + ensure!( + !T::Currency::free_balance(&beneficiary_account).is_zero(), + "Beneficiary didn't get paid." + ); + + Ok(()) } // Best case scenario. - close_child_bounty_added { + #[benchmark] + fn close_child_bounty_added() -> Result<(), BenchmarkError> { setup_pot_account::(); let mut bounty_setup = activate_bounty::(0, T::MaximumReasonLength::get())?; - ChildBounties::::add_child_bounty( + Pallet::::add_child_bounty( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_value, bounty_setup.reason.clone(), )?; - bounty_setup.child_bounty_id = ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; - - }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, - bounty_setup.child_bounty_id) - verify { - assert_last_event::(Event::Canceled { - index: bounty_setup.bounty_id, - child_index: bounty_setup.child_bounty_id - }.into()) + bounty_setup.child_bounty_id = + ParentTotalChildBounties::::get(bounty_setup.bounty_id) - 1; + + #[extrinsic_call] + close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id); + + assert_last_event::( + Event::Canceled { + index: bounty_setup.bounty_id, + child_index: bounty_setup.child_bounty_id, + } + .into(), + ); + + Ok(()) } // Worst case scenario. - close_child_bounty_active { + #[benchmark] + fn close_child_bounty_active() -> Result<(), BenchmarkError> { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; Treasury::::on_initialize(frame_system::Pallet::::block_number()); - }: close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id) - verify { - assert_last_event::(Event::Canceled { - index: bounty_setup.bounty_id, - child_index: bounty_setup.child_bounty_id, - }.into()) + + #[extrinsic_call] + close_child_bounty(RawOrigin::Root, bounty_setup.bounty_id, bounty_setup.child_bounty_id); + + assert_last_event::( + Event::Canceled { + index: bounty_setup.bounty_id, + child_index: bounty_setup.child_bounty_id, + } + .into(), + ); + + Ok(()) } - impl_benchmark_test_suite!(ChildBounties, crate::tests::new_test_ext(), crate::tests::Test) + impl_benchmark_test_suite! { + Pallet, + tests::new_test_ext(), + tests::Test + } } From 872d9491e2b3217092a914013f5e8c5d384309a0 Mon Sep 17 00:00:00 2001 From: Jeeyong Um Date: Tue, 12 Nov 2024 19:57:28 +0900 Subject: [PATCH 077/166] Introduce `ConstUint` to make dependent types in `DefaultConfig` more adaptable (#6425) # Description Resolves #6193 This PR introduces `ConstUint` as a replacement for existing constant getter types like `ConstU8`, `ConstU16`, etc., providing a more flexible and unified approach. ## Integration This update is backward compatible, so developers can choose to adopt `ConstUint` in new implementations or continue using the existing types as needed. ## Review Notes `ConstUint` is a convenient alternative to `ConstU8`, `ConstU16`, and similar types, particularly useful for configuring `DefaultConfig` in pallets. It enables configuring the underlying integer for a specific type without the need to update all dependent types, offering enhanced flexibility in type management. # Checklist * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. * [ ] My PR follows the [labeling requirements]( https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process ) of this project (at minimum one label for `T` required) * External contributors: ask maintainers to put the right label on your PR. * [ ] I have made corresponding changes to the documentation (if applicable) * [ ] I have added tests that prove my fix is effective or that my feature works (if applicable) --- Cargo.lock | 4 +-- Cargo.toml | 2 +- prdoc/pr_6425.prdoc | 27 +++++++++++++++++++ substrate/frame/assets/src/lib.rs | 12 ++++----- substrate/frame/balances/src/lib.rs | 4 +-- substrate/frame/support/src/lib.rs | 5 ++-- substrate/frame/support/src/traits.rs | 14 +++++----- substrate/frame/support/src/traits/misc.rs | 4 +-- substrate/frame/system/src/lib.rs | 2 +- substrate/frame/timestamp/src/lib.rs | 2 +- substrate/primitives/core/src/lib.rs | 5 ++-- .../primitives/runtime/src/traits/mod.rs | 5 ++-- 12 files changed, 58 insertions(+), 28 deletions(-) create mode 100644 prdoc/pr_6425.prdoc diff --git a/Cargo.lock b/Cargo.lock index fdaaf2f3b45f..eaa0d2667c73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1905,9 +1905,9 @@ dependencies = [ [[package]] name = "bounded-collections" -version = "0.2.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32385ecb91a31bddaf908e8dcf4a15aef1bcd3913cc03ebfad02ff6d568abc1" +checksum = "3d077619e9c237a5d1875166f5e8033e8f6bff0c96f8caf81e1c2d7738c431bf" dependencies = [ "log", "parity-scale-codec", diff --git a/Cargo.toml b/Cargo.toml index 345b9cd78a1f..b0be2950641d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -637,7 +637,7 @@ bitvec = { version = "1.0.1", default-features = false } blake2 = { version = "0.10.4", default-features = false } blake2b_simd = { version = "1.0.2", default-features = false } blake3 = { version = "1.5" } -bounded-collections = { version = "0.2.0", default-features = false } +bounded-collections = { version = "0.2.2", default-features = false } bounded-vec = { version = "0.7" } bp-asset-hub-rococo = { path = "bridges/chains/chain-asset-hub-rococo", default-features = false } bp-asset-hub-westend = { path = "bridges/chains/chain-asset-hub-westend", default-features = false } diff --git a/prdoc/pr_6425.prdoc b/prdoc/pr_6425.prdoc new file mode 100644 index 000000000000..57e759bf3376 --- /dev/null +++ b/prdoc/pr_6425.prdoc @@ -0,0 +1,27 @@ +title: Introduce `ConstUint` to make dependent types in `DefaultConfig` more adaptable +author: conr2d +topic: runtime + +doc: +- audience: Runtime Dev + description: |- + Introduce `ConstUint` that is a unified alternative to `ConstU8`, `ConstU16`, and + similar types, particularly useful for configuring `DefaultConfig` in pallets. + It enables configuring the underlying integer for a specific type without the need + to update all dependent types, offering enhanced flexibility in type management. + +crates: + - name: frame-support + bump: patch + - name: frame-system + bump: none + - name: pallet-assets + bump: none + - name: pallet-balances + bump: none + - name: pallet-timestamp + bump: none + - name: sp-core + bump: patch + - name: sp-runtime + bump: patch diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index e909932bfc82..a9b0dc950a61 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -275,7 +275,7 @@ pub mod pallet { /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. pub mod config_preludes { use super::*; - use frame_support::{derive_impl, traits::ConstU64}; + use frame_support::derive_impl; pub struct TestDefaultConfig; #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)] @@ -289,11 +289,11 @@ pub mod pallet { type RemoveItemsLimit = ConstU32<5>; type AssetId = u32; type AssetIdParameter = u32; - type AssetDeposit = ConstU64<1>; - type AssetAccountDeposit = ConstU64<10>; - type MetadataDepositBase = ConstU64<1>; - type MetadataDepositPerByte = ConstU64<1>; - type ApprovalDeposit = ConstU64<1>; + type AssetDeposit = ConstUint<1>; + type AssetAccountDeposit = ConstUint<10>; + type MetadataDepositBase = ConstUint<1>; + type MetadataDepositPerByte = ConstUint<1>; + type ApprovalDeposit = ConstUint<1>; type StringLimit = ConstU32<50>; type Extra = (); type CallbackHandle = (); diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 65e594a904f9..9d7401452101 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -205,7 +205,7 @@ pub mod pallet { /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. pub mod config_preludes { use super::*; - use frame_support::{derive_impl, traits::ConstU64}; + use frame_support::derive_impl; pub struct TestDefaultConfig; @@ -222,7 +222,7 @@ pub mod pallet { type RuntimeFreezeReason = (); type Balance = u64; - type ExistentialDeposit = ConstU64<1>; + type ExistentialDeposit = ConstUint<1>; type ReserveIdentifier = (); type FreezeIdentifier = Self::RuntimeFreezeReason; diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 2e7ea0a07d7d..6d8b772d9d4a 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -904,8 +904,9 @@ pub mod pallet_prelude { StorageList, }, traits::{ - BuildGenesisConfig, ConstU32, EnsureOrigin, Get, GetDefault, GetStorageVersion, Hooks, - IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, Task, TypedGet, + BuildGenesisConfig, ConstU32, ConstUint, EnsureOrigin, Get, GetDefault, + GetStorageVersion, Hooks, IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, + Task, TypedGet, }, Blake2_128, Blake2_128Concat, Blake2_256, CloneNoBound, DebugNoBound, EqNoBound, Identity, PartialEqNoBound, RuntimeDebugNoBound, Twox128, Twox256, Twox64Concat, diff --git a/substrate/frame/support/src/traits.rs b/substrate/frame/support/src/traits.rs index 2c580ea6ed61..728426cc84c7 100644 --- a/substrate/frame/support/src/traits.rs +++ b/substrate/frame/support/src/traits.rs @@ -57,13 +57,13 @@ pub use filter::{ClearFilterGuard, FilterStack, FilterStackGuard, InstanceFilter mod misc; pub use misc::{ defensive_prelude::{self, *}, - AccountTouch, Backing, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, - ConstU16, ConstU32, ConstU64, ConstU8, DefensiveMax, DefensiveMin, DefensiveSaturating, - DefensiveTruncateFrom, EnsureInherentsAreFirst, EqualPrivilegeOnly, EstimateCallFee, - ExecuteBlock, ExtrinsicCall, Get, GetBacking, GetDefault, HandleLifetime, InherentBuilder, - IsInherent, IsSubType, IsType, Len, OffchainWorker, OnKilledAccount, OnNewAccount, - PrivilegeCmp, SameOrOther, SignedTransactionBuilder, Time, TryCollect, TryDrop, TypedGet, - UnixTime, VariantCount, VariantCountOf, WrapperKeepOpaque, WrapperOpaque, + AccountTouch, Backing, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt, + ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, DefensiveMax, DefensiveMin, + DefensiveSaturating, DefensiveTruncateFrom, EnsureInherentsAreFirst, EqualPrivilegeOnly, + EstimateCallFee, ExecuteBlock, ExtrinsicCall, Get, GetBacking, GetDefault, HandleLifetime, + InherentBuilder, IsInherent, IsSubType, IsType, Len, OffchainWorker, OnKilledAccount, + OnNewAccount, PrivilegeCmp, SameOrOther, SignedTransactionBuilder, Time, TryCollect, TryDrop, + TypedGet, UnixTime, VariantCount, VariantCountOf, WrapperKeepOpaque, WrapperOpaque, }; #[allow(deprecated)] pub use misc::{PreimageProvider, PreimageRecipient}; diff --git a/substrate/frame/support/src/traits/misc.rs b/substrate/frame/support/src/traits/misc.rs index a914b3a914c1..0dc3abdce956 100644 --- a/substrate/frame/support/src/traits/misc.rs +++ b/substrate/frame/support/src/traits/misc.rs @@ -28,8 +28,8 @@ use sp_core::bounded::bounded_vec::TruncateFrom; use core::cmp::Ordering; #[doc(hidden)] pub use sp_runtime::traits::{ - ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, ConstU16, ConstU32, - ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet, + ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt, ConstU128, ConstU16, + ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect, TypedGet, }; use sp_runtime::{traits::Block as BlockT, DispatchError}; diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 04bedd78cc12..3c0c9eb1bf15 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -311,7 +311,7 @@ pub mod pallet { type Hash = sp_core::hash::H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; - type Lookup = sp_runtime::traits::IdentityLookup; + type Lookup = sp_runtime::traits::IdentityLookup; type MaxConsumers = frame_support::traits::ConstU32<16>; type AccountData = (); type OnNewAccount = (); diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index 78e2939e65b9..5cb6c859c417 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -161,7 +161,7 @@ pub mod pallet { impl DefaultConfig for TestDefaultConfig { type Moment = u64; type OnTimestampSet = (); - type MinimumPeriod = frame_support::traits::ConstU64<1>; + type MinimumPeriod = ConstUint<1>; type WeightInfo = (); } } diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index bb05bebc6274..454f61df7941 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -101,8 +101,9 @@ pub use bounded_collections as bounded; #[cfg(feature = "std")] pub use bounded_collections::{bounded_btree_map, bounded_vec}; pub use bounded_collections::{ - parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, - ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet, + parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt, + ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect, + TypedGet, }; pub use sp_storage as storage; diff --git a/substrate/primitives/runtime/src/traits/mod.rs b/substrate/primitives/runtime/src/traits/mod.rs index e6906cdb3877..01bdcca86b6f 100644 --- a/substrate/primitives/runtime/src/traits/mod.rs +++ b/substrate/primitives/runtime/src/traits/mod.rs @@ -44,8 +44,9 @@ pub use sp_arithmetic::traits::{ use sp_core::{self, storage::StateVersion, Hasher, RuntimeDebug, TypeId, U256}; #[doc(hidden)] pub use sp_core::{ - parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, - ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet, + parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstInt, + ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, ConstUint, Get, GetDefault, TryCollect, + TypedGet, }; #[cfg(feature = "std")] use std::fmt::Display; From a875f1803253e469288f1a905e73861fb600bb28 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Tue, 12 Nov 2024 13:38:15 +0200 Subject: [PATCH 078/166] Use type alias for transactions (#6431) Very tiny change that helps with debugging of transactions propagation by referring to the same type alias not only at receiving side, but also on the sending size for symmetry --- substrate/client/network/transactions/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/substrate/client/network/transactions/src/lib.rs b/substrate/client/network/transactions/src/lib.rs index 2b5297fe0e13..44fa702ef6d4 100644 --- a/substrate/client/network/transactions/src/lib.rs +++ b/substrate/client/network/transactions/src/lib.rs @@ -480,7 +480,7 @@ where continue } - let (hashes, to_send): (Vec<_>, Vec<_>) = transactions + let (hashes, to_send): (Vec<_>, Transactions<_>) = transactions .iter() .filter(|(hash, _)| peer.known_transactions.insert(hash.clone())) .cloned() From 34d2ff854b8f33bf44f3f03d6c81838893d101cc Mon Sep 17 00:00:00 2001 From: Egor_P Date: Tue, 12 Nov 2024 16:55:30 +0100 Subject: [PATCH 079/166] [Release|CI/CD] Fix audiences changelog template (#6444) This PR addresses an issue mentioned [here](https://github.com/paritytech/polkadot-sdk/issues/6424#issuecomment-2467042441). The problem was that when the prdoc file has two audiences, but only one description like in [prdoc_5660](https://github.com/paritytech/polkadot-sdk/blob/master/prdoc/1.16.0/pr_5660.prdoc) it was ignored by the template. --- .github/workflows/release-30_publish_release_draft.yml | 2 +- scripts/release/templates/audience.md.tera | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-30_publish_release_draft.yml b/.github/workflows/release-30_publish_release_draft.yml index 73d1aeaa4009..376f5fbce909 100644 --- a/.github/workflows/release-30_publish_release_draft.yml +++ b/.github/workflows/release-30_publish_release_draft.yml @@ -71,7 +71,7 @@ jobs: - name: Prepare tooling run: | - URL=https://github.com/chevdor/tera-cli/releases/download/v0.2.4/tera-cli_linux_amd64.deb + URL=https://github.com/chevdor/tera-cli/releases/download/v0.4.0/tera-cli_linux_amd64.deb wget $URL -O tera.deb sudo dpkg -i tera.deb diff --git a/scripts/release/templates/audience.md.tera b/scripts/release/templates/audience.md.tera index 237643cfa392..d962030d0225 100644 --- a/scripts/release/templates/audience.md.tera +++ b/scripts/release/templates/audience.md.tera @@ -4,7 +4,7 @@ {% for file in prdoc -%} {% for doc_item in file.content.doc %} -{%- if doc_item.audience == env.TARGET_AUDIENCE %} +{%- if doc_item.audience is containing(env.TARGET_AUDIENCE) %} #### [#{{file.doc_filename.number}}]: {{ file.content.title }} {{ doc_item.description }} {% endif -%} From 4c059c02f45370f284b0e2ba0f0ca8e02400e2d5 Mon Sep 17 00:00:00 2001 From: Francisco Aguirre Date: Tue, 12 Nov 2024 14:05:52 -0300 Subject: [PATCH 080/166] XCMv5: add ExecuteWithOrigin instruction (#6304) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Added `ExecuteWithOrigin` instruction according to the old XCM RFC 38: https://github.com/polkadot-fellows/xcm-format/pull/38. This instruction allows you to descend or clear while going back again. ## TODO - [x] Implementation - [x] Unit tests - [x] Integration tests - [x] Benchmarks - [x] PRDoc ## Future work Modify `WithComputedOrigin` barrier to allow, for example, fees to be paid with a descendant origin using this instruction. --------- Signed-off-by: Adrian Catangiu Co-authored-by: Adrian Catangiu Co-authored-by: Andrii Co-authored-by: Branislav Kontur Co-authored-by: Joseph Zhao <65984904+programskillforverification@users.noreply.github.com> Co-authored-by: Nazar Mokrynskyi Co-authored-by: Bastian Köcher Co-authored-by: Shawn Tabrizi Co-authored-by: command-bot <> --- Cargo.lock | 11 +- .../tests/assets/asset-hub-westend/Cargo.toml | 1 + .../src/tests/claim_assets.rs | 82 ++++++++ .../asset-hub-rococo/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../asset-hub-westend/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../bridge-hub-rococo/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../bridge-hub-westend/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../coretime-rococo/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../coretime-westend/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../people-rococo/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../people-westend/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 7 + .../weights/pallet_xcm_benchmarks_generic.rs | 7 + .../runtime/rococo/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 137 +++++++------- .../runtime/westend/src/weights/xcm/mod.rs | 3 + .../xcm/pallet_xcm_benchmarks_generic.rs | 131 +++++++------ .../src/generic/benchmarking.rs | 17 ++ polkadot/xcm/src/v4/mod.rs | 7 +- polkadot/xcm/src/v5/mod.rs | 23 +++ polkadot/xcm/xcm-builder/src/weight.rs | 3 +- polkadot/xcm/xcm-executor/src/lib.rs | 51 +++-- .../src/tests/execute_with_origin.rs | 177 ++++++++++++++++++ polkadot/xcm/xcm-executor/src/tests/mod.rs | 1 + prdoc/pr_6304.prdoc | 45 +++++ 32 files changed, 630 insertions(+), 149 deletions(-) create mode 100644 polkadot/xcm/xcm-executor/src/tests/execute_with_origin.rs create mode 100644 prdoc/pr_6304.prdoc diff --git a/Cargo.lock b/Cargo.lock index eaa0d2667c73..c1eda1b0fb01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -953,6 +953,7 @@ version = "1.0.0" dependencies = [ "assert_matches", "asset-test-utils 7.0.0", + "assets-common 0.7.0", "cumulus-pallet-parachain-system 0.7.0", "cumulus-pallet-xcmp-queue 0.7.0", "emulated-integration-tests-common", @@ -20397,7 +20398,7 @@ checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302" dependencies = [ "bytes", "heck 0.5.0", - "itertools 0.13.0", + "itertools 0.12.1", "log", "multimap", "once_cell", @@ -20443,7 +20444,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac" dependencies = [ "anyhow", - "itertools 0.13.0", + "itertools 0.12.1", "proc-macro2 1.0.86", "quote 1.0.37", "syn 2.0.87", @@ -20926,7 +20927,7 @@ checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.8", + "regex-automata 0.4.9", "regex-syntax 0.8.5", ] @@ -20947,9 +20948,9 @@ checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" [[package]] name = "regex-automata" -version = "0.4.8" +version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" +checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml index 71e44e5cee7d..7117124b1d1f 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml @@ -37,6 +37,7 @@ pallet-xcm = { workspace = true } xcm-runtime-apis = { workspace = true } # Cumulus +assets-common = { workspace = true } parachains-common = { workspace = true, default-features = true } asset-test-utils = { workspace = true, default-features = true } cumulus-pallet-xcmp-queue = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs index 90af907654f9..a7f52eb7e09d 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs @@ -17,7 +17,9 @@ use crate::imports::*; +use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApiV2; use emulated_integration_tests_common::test_chain_can_claim_assets; +use frame_support::traits::fungible::Mutate; use xcm_executor::traits::DropAssets; #[test] @@ -33,3 +35,83 @@ fn assets_can_be_claimed() { amount ); } + +#[test] +fn chain_can_claim_assets_for_its_users() { + // Many Penpal users have assets trapped in AssetHubWestend. + let beneficiaries: Vec<(Location, Assets)> = vec![ + // Some WND. + ( + Location::new(1, [Parachain(2000), AccountId32 { id: [0u8; 32], network: None }]), + (Parent, 10_000_000_000_000u128).into(), + ), + // Some USDT. + ( + Location::new(1, [Parachain(2000), AccountId32 { id: [1u8; 32], network: None }]), + ([PalletInstance(ASSETS_PALLET_ID), GeneralIndex(USDT_ID.into())], 100_000_000u128) + .into(), + ), + ]; + + // Start with those assets trapped. + AssetHubWestend::execute_with(|| { + for (location, assets) in &beneficiaries { + ::PolkadotXcm::drop_assets( + location, + assets.clone().into(), + &XcmContext { origin: None, message_id: [0u8; 32], topic: None }, + ); + } + }); + + let penpal_to_asset_hub = PenpalA::sibling_location_of(AssetHubWestend::para_id()); + let mut builder = Xcm::<()>::builder() + .withdraw_asset((Parent, 1_000_000_000_000u128)) + .pay_fees((Parent, 100_000_000_000u128)); + + // Loop through all beneficiaries. + for (location, assets) in &beneficiaries { + builder = builder.execute_with_origin( + // We take only the last part, the `AccountId32` junction. + Some((*location.interior().last().unwrap()).into()), + Xcm::<()>::builder_unsafe() + .claim_asset(assets.clone(), Location::new(0, [GeneralIndex(5)])) // Means lost assets were version 5. + .deposit_asset(assets.clone(), location.clone()) + .build(), + ) + } + + // Finish assembling the message. + let message = builder.build(); + + // Fund PenpalA's sovereign account on AssetHubWestend so it can pay for fees. + AssetHubWestend::execute_with(|| { + let penpal_as_seen_by_asset_hub = AssetHubWestend::sibling_location_of(PenpalA::para_id()); + let penpal_sov_account_on_asset_hub = + AssetHubWestend::sovereign_account_id_of(penpal_as_seen_by_asset_hub); + type Balances = ::Balances; + assert_ok!(>::mint_into( + &penpal_sov_account_on_asset_hub, + 2_000_000_000_000u128, + )); + }); + + // We can send a message from Penpal root that claims all those assets for each beneficiary. + PenpalA::execute_with(|| { + assert_ok!(::PolkadotXcm::send( + ::RuntimeOrigin::root(), + bx!(penpal_to_asset_hub.into()), + bx!(VersionedXcm::from(message)), + )); + }); + + // We assert beneficiaries have received their funds. + AssetHubWestend::execute_with(|| { + for (location, expected_assets) in &beneficiaries { + let sov_account = AssetHubWestend::sovereign_account_id_of(location.clone()); + let actual_assets = + ::Runtime::query_account_balances(sov_account).unwrap(); + assert_eq!(VersionedAssets::from(expected_assets.clone()), actual_assets); + } + }); +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs index bf374fc415ce..025c39bcee07 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs @@ -253,4 +253,7 @@ impl XcmWeightInfo for AssetHubRococoXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index ef08b432e5c7..b69c136b29d9 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -373,4 +373,11 @@ impl WeightInfo { // Minimum execution time: 668_000 picoseconds. Weight::from_parts(726_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs index 928f1910cbd2..35ff2dc367c0 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs @@ -253,4 +253,7 @@ impl XcmWeightInfo for AssetHubWestendXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 7098f175d421..528694123115 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -373,4 +373,11 @@ impl WeightInfo { // Minimum execution time: 638_000 picoseconds. Weight::from_parts(708_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs index 60a0fc005ca1..288aac38563c 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs @@ -256,4 +256,7 @@ impl XcmWeightInfo for BridgeHubRococoXcmWeight { fn set_asset_claimer(_location: &Location) -> Weight { XcmGeneric::::set_asset_claimer() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index b8bd4c4e2d44..bac73e0e0567 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -380,4 +380,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs index 473807ea5eb1..fa1304d11c6f 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs @@ -257,4 +257,7 @@ impl XcmWeightInfo for BridgeHubWestendXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 849456af9255..6434f6206fbe 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -380,4 +380,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs index 48f1366e2c5f..f69736e31451 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs @@ -254,4 +254,7 @@ impl XcmWeightInfo for CoretimeRococoXcmWeight { fn set_asset_claimer(_location: &Location) -> Weight { XcmGeneric::::set_asset_claimer() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 229dafb7c5ed..d207c09ffcd8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -338,4 +338,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs index 1f4b4aa5c5a8..1640baa38c99 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs @@ -254,4 +254,7 @@ impl XcmWeightInfo for CoretimeWestendXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index bd70bc4f4bd9..fb6e4631736d 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -338,4 +338,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs index b82872a1cbf2..631cc7b7f0b0 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs @@ -253,4 +253,7 @@ impl XcmWeightInfo for PeopleRococoXcmWeight { fn set_asset_claimer(_location: &Location) -> Weight { XcmGeneric::::set_asset_claimer() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 30e28fac7e57..6aac6119e7ec 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -338,4 +338,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs index 8ca9771dca46..4b51a3ba411b 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs @@ -253,4 +253,7 @@ impl XcmWeightInfo for PeopleWestendXcmWeight { fn set_asset_claimer(_location: &Location) -> Weight { XcmGeneric::::set_asset_claimer() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 3c539902abc8..36400f2c1e66 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -338,4 +338,11 @@ impl WeightInfo { // Minimum execution time: 707_000 picoseconds. Weight::from_parts(749_000, 0) } + pub fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/polkadot/runtime/rococo/src/weights/pallet_xcm_benchmarks_generic.rs b/polkadot/runtime/rococo/src/weights/pallet_xcm_benchmarks_generic.rs index b62f36172baf..1595a6dfbe4b 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_xcm_benchmarks_generic.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_xcm_benchmarks_generic.rs @@ -344,4 +344,11 @@ impl pallet_xcm_benchmarks::generic::WeightInfo for Wei Weight::from_parts(1_354_000, 0) .saturating_add(Weight::from_parts(0, 0)) } + fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(776_000, 0) + } } diff --git a/polkadot/runtime/rococo/src/weights/xcm/mod.rs b/polkadot/runtime/rococo/src/weights/xcm/mod.rs index 007002bf27bb..a28b46800874 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/mod.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/mod.rs @@ -289,6 +289,9 @@ impl XcmWeightInfo for RococoXcmWeight { fn set_asset_claimer(_location: &Location) -> Weight { XcmGeneric::::set_asset_claimer() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } #[test] diff --git a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 677640b45331..e5915a7986bf 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-vcatxqpx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -63,8 +63,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `3746` - // Minimum execution time: 64_284_000 picoseconds. - Weight::from_parts(65_590_000, 3746) + // Minimum execution time: 65_164_000 picoseconds. + Weight::from_parts(66_965_000, 3746) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -72,15 +72,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 777_000 picoseconds. - Weight::from_parts(825_000, 0) + // Minimum execution time: 675_000 picoseconds. + Weight::from_parts(745_000, 0) } pub(crate) fn pay_fees() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_543_000 picoseconds. - Weight::from_parts(1_627_000, 0) + // Minimum execution time: 2_899_000 picoseconds. + Weight::from_parts(3_090_000, 0) + } + pub(crate) fn set_asset_claimer() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 669_000 picoseconds. + Weight::from_parts(714_000, 0) } /// Storage: `XcmPallet::Queries` (r:1 w:0) /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -88,58 +95,65 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3465` - // Minimum execution time: 5_995_000 picoseconds. - Weight::from_parts(6_151_000, 3465) + // Minimum execution time: 6_004_000 picoseconds. + Weight::from_parts(6_152_000, 3465) .saturating_add(T::DbWeight::get().reads(1)) } pub(crate) fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_567_000 picoseconds. - Weight::from_parts(7_779_000, 0) + // Minimum execution time: 7_296_000 picoseconds. + Weight::from_parts(7_533_000, 0) } pub(crate) fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_226_000 picoseconds. - Weight::from_parts(1_322_000, 0) + // Minimum execution time: 1_292_000 picoseconds. + Weight::from_parts(1_414_000, 0) } pub(crate) fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 768_000 picoseconds. - Weight::from_parts(828_000, 0) + // Minimum execution time: 741_000 picoseconds. + Weight::from_parts(775_000, 0) } pub(crate) fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 765_000 picoseconds. - Weight::from_parts(814_000, 0) + // Minimum execution time: 702_000 picoseconds. + Weight::from_parts(770_000, 0) } pub(crate) fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 739_000 picoseconds. - Weight::from_parts(820_000, 0) + // Minimum execution time: 648_000 picoseconds. + Weight::from_parts(744_000, 0) } pub(crate) fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 806_000 picoseconds. - Weight::from_parts(849_000, 0) + // Minimum execution time: 731_000 picoseconds. + Weight::from_parts(772_000, 0) + } + pub(crate) fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 790_000 picoseconds. + Weight::from_parts(843_000, 0) } pub(crate) fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 782_000 picoseconds. - Weight::from_parts(820_000, 0) + // Minimum execution time: 647_000 picoseconds. + Weight::from_parts(731_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -155,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `3746` - // Minimum execution time: 61_410_000 picoseconds. - Weight::from_parts(62_813_000, 3746) + // Minimum execution time: 62_808_000 picoseconds. + Weight::from_parts(64_413_000, 3746) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -166,8 +180,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `23` // Estimated: `3488` - // Minimum execution time: 9_315_000 picoseconds. - Weight::from_parts(9_575_000, 3488) + // Minimum execution time: 9_298_000 picoseconds. + Weight::from_parts(9_541_000, 3488) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -175,8 +189,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 733_000 picoseconds. - Weight::from_parts(813_000, 0) + // Minimum execution time: 696_000 picoseconds. + Weight::from_parts(732_000, 0) } /// Storage: `XcmPallet::VersionNotifyTargets` (r:1 w:1) /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -192,8 +206,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `180` // Estimated: `3645` - // Minimum execution time: 30_641_000 picoseconds. - Weight::from_parts(31_822_000, 3645) + // Minimum execution time: 30_585_000 picoseconds. + Weight::from_parts(31_622_000, 3645) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -203,44 +217,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_978_000 picoseconds. - Weight::from_parts(3_260_000, 0) + // Minimum execution time: 3_036_000 picoseconds. + Weight::from_parts(3_196_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub(crate) fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_139_000 picoseconds. - Weight::from_parts(1_272_000, 0) + // Minimum execution time: 1_035_000 picoseconds. + Weight::from_parts(1_133_000, 0) } pub(crate) fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 850_000 picoseconds. - Weight::from_parts(879_000, 0) + // Minimum execution time: 764_000 picoseconds. + Weight::from_parts(802_000, 0) } pub(crate) fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 770_000 picoseconds. - Weight::from_parts(834_000, 0) + // Minimum execution time: 682_000 picoseconds. + Weight::from_parts(724_000, 0) } pub(crate) fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 756_000 picoseconds. - Weight::from_parts(797_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(713_000, 0) } pub(crate) fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 888_000 picoseconds. - Weight::from_parts(1_000_000, 0) + // Minimum execution time: 857_000 picoseconds. + Weight::from_parts(917_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -256,8 +270,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `3746` - // Minimum execution time: 72_138_000 picoseconds. - Weight::from_parts(73_728_000, 3746) + // Minimum execution time: 72_331_000 picoseconds. + Weight::from_parts(74_740_000, 3746) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -265,8 +279,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_482_000 picoseconds. - Weight::from_parts(8_667_000, 0) + // Minimum execution time: 8_963_000 picoseconds. + Weight::from_parts(9_183_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -282,8 +296,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `281` // Estimated: `3746` - // Minimum execution time: 61_580_000 picoseconds. - Weight::from_parts(62_928_000, 3746) + // Minimum execution time: 62_555_000 picoseconds. + Weight::from_parts(64_824_000, 3746) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -291,29 +305,29 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 807_000 picoseconds. - Weight::from_parts(844_000, 0) + // Minimum execution time: 740_000 picoseconds. + Weight::from_parts(773_000, 0) } pub(crate) fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 757_000 picoseconds. - Weight::from_parts(808_000, 0) + // Minimum execution time: 678_000 picoseconds. + Weight::from_parts(714_000, 0) } pub(crate) fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 740_000 picoseconds. - Weight::from_parts(810_000, 0) + // Minimum execution time: 656_000 picoseconds. + Weight::from_parts(703_000, 0) } pub(crate) fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 752_000 picoseconds. - Weight::from_parts(786_000, 0) + // Minimum execution time: 672_000 picoseconds. + Weight::from_parts(725_000, 0) } pub(crate) fn unpaid_execution() -> Weight { // Proof Size summary in bytes: @@ -322,11 +336,4 @@ impl WeightInfo { // Minimum execution time: 798_000 picoseconds. Weight::from_parts(845_000, 0) } - pub(crate) fn set_asset_claimer() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 707_000 picoseconds. - Weight::from_parts(749_000, 0) - } } diff --git a/polkadot/runtime/westend/src/weights/xcm/mod.rs b/polkadot/runtime/westend/src/weights/xcm/mod.rs index e5f4a0d7ca8e..5be9bad824da 100644 --- a/polkadot/runtime/westend/src/weights/xcm/mod.rs +++ b/polkadot/runtime/westend/src/weights/xcm/mod.rs @@ -294,6 +294,9 @@ impl XcmWeightInfo for WestendXcmWeight { fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { XcmGeneric::::unpaid_execution() } + fn execute_with_origin(_: &Option, _: &Xcm) -> Weight { + XcmGeneric::::execute_with_origin() + } } #[test] diff --git a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 2ad1cd6359a6..076744a59753 100644 --- a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-09-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-vcatxqpx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 // Executed Command: @@ -63,8 +63,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `6196` - // Minimum execution time: 67_813_000 picoseconds. - Weight::from_parts(69_357_000, 6196) + // Minimum execution time: 69_051_000 picoseconds. + Weight::from_parts(71_282_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -72,22 +72,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 716_000 picoseconds. - Weight::from_parts(780_000, 0) + // Minimum execution time: 660_000 picoseconds. + Weight::from_parts(695_000, 0) } pub(crate) fn pay_fees() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_601_000 picoseconds. - Weight::from_parts(1_680_000, 0) + // Minimum execution time: 3_096_000 picoseconds. + Weight::from_parts(3_313_000, 0) } pub(crate) fn set_asset_claimer() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 707_000 picoseconds. - Weight::from_parts(749_000, 0) + // Minimum execution time: 661_000 picoseconds. + Weight::from_parts(707_000, 0) } /// Storage: `XcmPallet::Queries` (r:1 w:0) /// Proof: `XcmPallet::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -95,58 +95,65 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3465` - // Minimum execution time: 6_574_000 picoseconds. - Weight::from_parts(6_790_000, 3465) + // Minimum execution time: 6_054_000 picoseconds. + Weight::from_parts(6_151_000, 3465) .saturating_add(T::DbWeight::get().reads(1)) } pub(crate) fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_232_000 picoseconds. - Weight::from_parts(7_422_000, 0) + // Minimum execution time: 7_462_000 picoseconds. + Weight::from_parts(7_750_000, 0) } pub(crate) fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_180_000 picoseconds. - Weight::from_parts(1_250_000, 0) + // Minimum execution time: 1_378_000 picoseconds. + Weight::from_parts(1_454_000, 0) } pub(crate) fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 702_000 picoseconds. - Weight::from_parts(766_000, 0) + // Minimum execution time: 660_000 picoseconds. + Weight::from_parts(744_000, 0) } pub(crate) fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 700_000 picoseconds. - Weight::from_parts(757_000, 0) + // Minimum execution time: 713_000 picoseconds. + Weight::from_parts(755_000, 0) } pub(crate) fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 686_000 picoseconds. - Weight::from_parts(751_000, 0) + // Minimum execution time: 632_000 picoseconds. + Weight::from_parts(703_000, 0) } pub(crate) fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 705_000 picoseconds. - Weight::from_parts(765_000, 0) + // Minimum execution time: 712_000 picoseconds. + Weight::from_parts(771_000, 0) + } + pub(crate) fn execute_with_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 740_000 picoseconds. + Weight::from_parts(826_000, 0) } pub(crate) fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 687_000 picoseconds. - Weight::from_parts(741_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(707_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -162,8 +169,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `6196` - // Minimum execution time: 65_398_000 picoseconds. - Weight::from_parts(67_140_000, 6196) + // Minimum execution time: 66_765_000 picoseconds. + Weight::from_parts(69_016_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -173,8 +180,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `23` // Estimated: `3488` - // Minimum execution time: 9_653_000 picoseconds. - Weight::from_parts(9_944_000, 3488) + // Minimum execution time: 9_545_000 picoseconds. + Weight::from_parts(9_853_000, 3488) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -182,8 +189,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 698_000 picoseconds. - Weight::from_parts(759_000, 0) + // Minimum execution time: 676_000 picoseconds. + Weight::from_parts(723_000, 0) } /// Storage: `XcmPallet::VersionNotifyTargets` (r:1 w:1) /// Proof: `XcmPallet::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -199,8 +206,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `147` // Estimated: `3612` - // Minimum execution time: 31_300_000 picoseconds. - Weight::from_parts(31_989_000, 3612) + // Minimum execution time: 31_324_000 picoseconds. + Weight::from_parts(32_023_000, 3612) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -210,44 +217,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_863_000 picoseconds. - Weight::from_parts(3_027_000, 0) + // Minimum execution time: 3_058_000 picoseconds. + Weight::from_parts(3_199_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub(crate) fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_046_000 picoseconds. - Weight::from_parts(1_125_000, 0) + // Minimum execution time: 994_000 picoseconds. + Weight::from_parts(1_115_000, 0) } pub(crate) fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 811_000 picoseconds. - Weight::from_parts(871_000, 0) + // Minimum execution time: 763_000 picoseconds. + Weight::from_parts(824_000, 0) } pub(crate) fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 707_000 picoseconds. - Weight::from_parts(741_000, 0) + // Minimum execution time: 665_000 picoseconds. + Weight::from_parts(712_000, 0) } pub(crate) fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 687_000 picoseconds. - Weight::from_parts(741_000, 0) + // Minimum execution time: 627_000 picoseconds. + Weight::from_parts(695_000, 0) } pub(crate) fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 861_000 picoseconds. - Weight::from_parts(931_000, 0) + // Minimum execution time: 839_000 picoseconds. + Weight::from_parts(889_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -263,8 +270,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `6196` - // Minimum execution time: 74_622_000 picoseconds. - Weight::from_parts(77_059_000, 6196) + // Minimum execution time: 75_853_000 picoseconds. + Weight::from_parts(77_515_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -272,8 +279,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_603_000 picoseconds. - Weight::from_parts(7_871_000, 0) + // Minimum execution time: 8_183_000 picoseconds. + Weight::from_parts(8_378_000, 0) } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -289,8 +296,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `351` // Estimated: `6196` - // Minimum execution time: 65_617_000 picoseconds. - Weight::from_parts(66_719_000, 6196) + // Minimum execution time: 66_576_000 picoseconds. + Weight::from_parts(69_465_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -298,35 +305,35 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 738_000 picoseconds. - Weight::from_parts(779_000, 0) + // Minimum execution time: 739_000 picoseconds. + Weight::from_parts(773_000, 0) } pub(crate) fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 688_000 picoseconds. - Weight::from_parts(755_000, 0) + // Minimum execution time: 648_000 picoseconds. + Weight::from_parts(693_000, 0) } pub(crate) fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 684_000 picoseconds. - Weight::from_parts(722_000, 0) + // Minimum execution time: 654_000 picoseconds. + Weight::from_parts(700_000, 0) } pub(crate) fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 694_000 picoseconds. - Weight::from_parts(738_000, 0) + // Minimum execution time: 646_000 picoseconds. + Weight::from_parts(702_000, 0) } pub(crate) fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 713_000 picoseconds. - Weight::from_parts(776_000, 0) + // Minimum execution time: 665_000 picoseconds. + Weight::from_parts(714_000, 0) } } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 0d80ef89a1ce..87bf27e4ff18 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -229,6 +229,23 @@ benchmarks! { ); } + execute_with_origin { + let mut executor = new_executor::(Default::default()); + let who: Junctions = Junctions::from([AccountId32 { id: [0u8; 32], network: None }]); + let instruction = Instruction::ExecuteWithOrigin { descendant_origin: Some(who.clone()), xcm: Xcm(vec![]) }; + let xcm = Xcm(vec![instruction]); + }: { + executor.bench_process(xcm)?; + } verify { + assert_eq!( + executor.origin(), + &Some(Location { + parents: 0, + interior: Here, + }), + ); + } + clear_origin { let mut executor = new_executor::(Default::default()); let instruction = Instruction::ClearOrigin; diff --git a/polkadot/xcm/src/v4/mod.rs b/polkadot/xcm/src/v4/mod.rs index 545b75a99ff3..9baf58eacfb0 100644 --- a/polkadot/xcm/src/v4/mod.rs +++ b/polkadot/xcm/src/v4/mod.rs @@ -1421,8 +1421,11 @@ impl TryFrom> for Instructi weight_limit, check_origin: check_origin.map(|origin| origin.try_into()).transpose()?, }, - InitiateTransfer { .. } | PayFees { .. } | SetAssetClaimer { .. } => { - log::debug!(target: "xcm::v5tov4", "`{new_instruction:?}` not supported by v4"); + InitiateTransfer { .. } | + PayFees { .. } | + SetAssetClaimer { .. } | + ExecuteWithOrigin { .. } => { + log::debug!(target: "xcm::versions::v5tov4", "`{new_instruction:?}` not supported by v4"); return Err(()); }, }) diff --git a/polkadot/xcm/src/v5/mod.rs b/polkadot/xcm/src/v5/mod.rs index d455fa48adae..830b23cc44b7 100644 --- a/polkadot/xcm/src/v5/mod.rs +++ b/polkadot/xcm/src/v5/mod.rs @@ -1109,6 +1109,25 @@ pub enum Instruction { assets: Vec, remote_xcm: Xcm<()>, }, + + /// Executes inner `xcm` with origin set to the provided `descendant_origin`. Once the inner + /// `xcm` is executed, the original origin (the one active for this instruction) is restored. + /// + /// Parameters: + /// - `descendant_origin`: The origin that will be used during the execution of the inner + /// `xcm`. If set to `None`, the inner `xcm` is executed with no origin. If set to `Some(o)`, + /// the inner `xcm` is executed as if there was a `DescendOrigin(o)` executed before it, and + /// runs the inner xcm with origin: `original_origin.append_with(o)`. + /// - `xcm`: Inner instructions that will be executed with the origin modified according to + /// `descendant_origin`. + /// + /// Safety: No concerns. + /// + /// Kind: *Command* + /// + /// Errors: + /// - `BadOrigin` + ExecuteWithOrigin { descendant_origin: Option, xcm: Xcm }, } impl Xcm { @@ -1189,6 +1208,8 @@ impl Instruction { PayFees { asset } => PayFees { asset }, InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm }, + ExecuteWithOrigin { descendant_origin, xcm } => + ExecuteWithOrigin { descendant_origin, xcm: xcm.into() }, } } } @@ -1261,6 +1282,8 @@ impl> GetWeight for Instruction { PayFees { asset } => W::pay_fees(asset), InitiateTransfer { destination, remote_fees, preserve_origin, assets, remote_xcm } => W::initiate_transfer(destination, remote_fees, preserve_origin, assets, remote_xcm), + ExecuteWithOrigin { descendant_origin, xcm } => + W::execute_with_origin(descendant_origin, xcm), } } } diff --git a/polkadot/xcm/xcm-builder/src/weight.rs b/polkadot/xcm/xcm-builder/src/weight.rs index f8c0275d0f54..6521121f2c94 100644 --- a/polkadot/xcm/xcm-builder/src/weight.rs +++ b/polkadot/xcm/xcm-builder/src/weight.rs @@ -65,7 +65,8 @@ impl, C: Decode + GetDispatchInfo, M> FixedWeightBounds ) -> Result { let instr_weight = match instruction { Transact { ref mut call, .. } => call.ensure_decoded()?.get_dispatch_info().call_weight, - SetErrorHandler(xcm) | SetAppendix(xcm) => Self::weight_with_limit(xcm, instrs_limit)?, + SetErrorHandler(xcm) | SetAppendix(xcm) | ExecuteWithOrigin { xcm, .. } => + Self::weight_with_limit(xcm, instrs_limit)?, _ => Weight::zero(), }; T::get().checked_add(&instr_weight).ok_or(()) diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs index e33f94389b21..4e051f24050c 100644 --- a/polkadot/xcm/xcm-executor/src/lib.rs +++ b/polkadot/xcm/xcm-executor/src/lib.rs @@ -314,7 +314,7 @@ impl FeeManager for XcmExecutor { } } -#[derive(Debug)] +#[derive(Debug, PartialEq)] pub struct ExecutorError { pub index: u32, pub xcm_error: XcmError, @@ -1041,19 +1041,25 @@ impl XcmExecutor { ); Ok(()) }, - DescendOrigin(who) => self - .context - .origin - .as_mut() - .ok_or(XcmError::BadOrigin)? - .append_with(who) - .map_err(|e| { - tracing::error!(target: "xcm::process_instruction::descend_origin", ?e, "Failed to append junctions"); - XcmError::LocationFull - }), - ClearOrigin => { - self.context.origin = None; - Ok(()) + DescendOrigin(who) => self.do_descend_origin(who), + ClearOrigin => self.do_clear_origin(), + ExecuteWithOrigin { descendant_origin, xcm } => { + let previous_origin = self.context.origin.clone(); + + // Set new temporary origin. + if let Some(who) = descendant_origin { + self.do_descend_origin(who)?; + } else { + self.do_clear_origin()?; + } + // Process instructions. + let result = self.process(xcm).map_err(|error| { + tracing::error!(target: "xcm::execute", ?error, actual_origin = ?self.context.origin, original_origin = ?previous_origin, "ExecuteWithOrigin inner xcm failure"); + error.xcm_error + }); + // Reset origin to previous one. + self.context.origin = previous_origin; + result }, ReportError(response_info) => { // Report the given result by sending a QueryResponse XCM to a previously given @@ -1643,6 +1649,23 @@ impl XcmExecutor { } } + fn do_descend_origin(&mut self, who: InteriorLocation) -> XcmResult { + self.context + .origin + .as_mut() + .ok_or(XcmError::BadOrigin)? + .append_with(who) + .map_err(|e| { + tracing::error!(target: "xcm::do_descend_origin", ?e, "Failed to append junctions"); + XcmError::LocationFull + }) + } + + fn do_clear_origin(&mut self) -> XcmResult { + self.context.origin = None; + Ok(()) + } + /// Deposit `to_deposit` assets to `beneficiary`, without giving up on the first (transient) /// error, and retrying once just in case one of the subsequently deposited assets satisfy some /// requirement. diff --git a/polkadot/xcm/xcm-executor/src/tests/execute_with_origin.rs b/polkadot/xcm/xcm-executor/src/tests/execute_with_origin.rs new file mode 100644 index 000000000000..daba8ae1c036 --- /dev/null +++ b/polkadot/xcm/xcm-executor/src/tests/execute_with_origin.rs @@ -0,0 +1,177 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot 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. + +// Polkadot 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 Polkadot. If not, see . + +//! Unit tests for the `ExecuteWithOrigin` instruction. +//! +//! See the [XCM RFC](https://github.com/polkadot-fellows/xcm-format/pull/38) +//! and the [specification](https://github.com/polkadot-fellows/xcm-format/tree/8cef08e375c6f6d3966909ccf773ed46ac703917) for more information. +//! +//! The XCM RFCs were moved to the fellowship RFCs but this one was approved and merged before that. + +use xcm::prelude::*; + +use super::mock::*; +use crate::ExecutorError; + +// The sender and recipient we use across these tests. +const SENDER_1: [u8; 32] = [0; 32]; +const SENDER_2: [u8; 32] = [1; 32]; +const RECIPIENT: [u8; 32] = [2; 32]; + +// ===== Happy path ===== + +// In this test, root descends into one account to pay fees, pops that origin +// and descends into a second account to withdraw funds. +// These assets can now be used to perform actions as root. +#[test] +fn root_can_descend_into_more_than_one_account() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER_1, (Here, 10u128)); + add_asset(SENDER_2, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + .execute_with_origin( + Some(SENDER_1.into()), + Xcm::::builder_unsafe() + .withdraw_asset((Here, 10u128)) + .pay_fees((Here, 10u128)) + .build(), + ) + .execute_with_origin( + Some(SENDER_2.into()), + Xcm::::builder_unsafe().withdraw_asset((Here, 100u128)).build(), + ) + .expect_origin(Some(Here.into())) + .deposit_asset(All, RECIPIENT) + .build(); + + let (mut vm, weight) = instantiate_executor(Here, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + assert!(vm.bench_post_process(weight).ensure_complete().is_ok()); + + // RECIPIENT gets the funds. + assert_eq!(asset_list(RECIPIENT), [(Here, 100u128).into()]); +} + +// ExecuteWithOrigin works for clearing the origin as well. +#[test] +fn works_for_clearing_origin() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER_1, (Here, 100u128)); + + // Build xcm. + let xcm = Xcm::::builder_unsafe() + // Root code. + .expect_origin(Some(Here.into())) + .execute_with_origin( + None, + // User code, we run it with no origin. + Xcm::::builder_unsafe().expect_origin(None).build(), + ) + // We go back to root code. + .build(); + + let (mut vm, weight) = instantiate_executor(Here, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + assert!(vm.bench_post_process(weight).ensure_complete().is_ok()); +} + +// Setting the error handler or appendix inside of `ExecuteWithOrigin` +// will work as expected. +#[test] +fn set_error_handler_and_appendix_work() { + add_asset(SENDER_1, (Here, 110u128)); + + let xcm = Xcm::::builder_unsafe() + .execute_with_origin( + Some(SENDER_1.into()), + Xcm::::builder_unsafe() + .withdraw_asset((Here, 110u128)) + .pay_fees((Here, 10u128)) + .set_error_handler( + Xcm::::builder_unsafe() + .deposit_asset(vec![(Here, 10u128).into()], SENDER_2) + .build(), + ) + .set_appendix( + Xcm::::builder_unsafe().deposit_asset(All, RECIPIENT).build(), + ) + .build(), + ) + .build(); + + let (mut vm, weight) = instantiate_executor(Here, xcm.clone()); + + // Program runs successfully. + assert!(vm.bench_process(xcm).is_ok()); + + assert_eq!( + vm.error_handler(), + &Xcm::(vec![DepositAsset { + assets: vec![Asset { id: AssetId(Location::new(0, [])), fun: Fungible(10) }].into(), + beneficiary: Location::new(0, [AccountId32 { id: SENDER_2, network: None }]), + },]) + ); + assert_eq!( + vm.appendix(), + &Xcm::(vec![DepositAsset { + assets: All.into(), + beneficiary: Location::new(0, [AccountId32 { id: RECIPIENT, network: None }]), + },]) + ); + + assert!(vm.bench_post_process(weight).ensure_complete().is_ok()); +} + +// ===== Unhappy path ===== + +// Processing still can't be called recursively more than the limit. +#[test] +fn recursion_exceeds_limit() { + // Make sure the sender has enough funds to withdraw. + add_asset(SENDER_1, (Here, 10u128)); + add_asset(SENDER_2, (Here, 100u128)); + + let mut xcm = Xcm::::builder_unsafe() + .execute_with_origin(None, Xcm::::builder_unsafe().clear_origin().build()) + .build(); + + // 10 is the RECURSION_LIMIT. + for _ in 0..10 { + let clone_of_xcm = xcm.clone(); + if let ExecuteWithOrigin { xcm: ref mut inner, .. } = xcm.inner_mut()[0] { + *inner = clone_of_xcm; + } + } + + let (mut vm, weight) = instantiate_executor(Here, xcm.clone()); + + // Program errors with `ExceedsStackLimit`. + assert_eq!( + vm.bench_process(xcm), + Err(ExecutorError { + index: 0, + xcm_error: XcmError::ExceedsStackLimit, + weight: Weight::zero(), + }) + ); + assert!(vm.bench_post_process(weight).ensure_complete().is_ok()); +} diff --git a/polkadot/xcm/xcm-executor/src/tests/mod.rs b/polkadot/xcm/xcm-executor/src/tests/mod.rs index 5c133871f0bf..15a0565e357c 100644 --- a/polkadot/xcm/xcm-executor/src/tests/mod.rs +++ b/polkadot/xcm/xcm-executor/src/tests/mod.rs @@ -20,6 +20,7 @@ //! `xcm-emulator` based tests in the cumulus folder. //! These tests deal with internal state changes of the XCVM. +mod execute_with_origin; mod initiate_transfer; mod mock; mod pay_fees; diff --git a/prdoc/pr_6304.prdoc b/prdoc/pr_6304.prdoc new file mode 100644 index 000000000000..1c8f1bb25deb --- /dev/null +++ b/prdoc/pr_6304.prdoc @@ -0,0 +1,45 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: XCMv5 - Add ExecuteWithOrigin instruction + +doc: + - audience: [Runtime User, Runtime Dev] + description: | + Added a new instruction to XCMv5, ExecuteWithOrigin, that allows you to specify an interior origin + and a set of instructions that will be executed using that origin. + The origins you can choose are `None` to clear it during the execution of the inner instructions, + or `Some(InteriorLocation)` to descend into an interior location. + These two options mimic the behaviour of `ClearOrigin` and `DescendOrigin` respectively. + Crucially, this instruction goes back to the previous origin once the execution of those inner + instructions end. + This allows use-cases like a parent location paying fees with one interior location, fetching funds + with another, claiming assets on behalf of many different ones, etc. + +crates: + - name: staging-xcm + bump: major + - name: staging-xcm-executor + bump: minor + - name: staging-xcm-builder + bump: minor + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor From 0a0af0ecde8b0152e408f3a9340e7daab56626fb Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Tue, 12 Nov 2024 18:07:21 +0100 Subject: [PATCH 081/166] rpc server: fix host filter for localhost on ipv6 (#6454) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR fixes an issue that I discovered using connecting to the RPC via localhost using cURL, where cURL tries to connect to via ipv6 before ipv4 when querying `localhost` which messed up the http host filter whereas it would connect to the address `[::1]::9944 host_header: localhost:9944` but the ipv6 interface only whitelisted `[::1]:9944` which this fixes. So let's whitelist all localhost interfaces to avoid such weird edge-cases. ### Behavior before this PR ```bash $ polkadot --chain westend-dev & $ curl -v \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":"id","method":"system_name"}' \ http://localhost:9944 * Host localhost:9944 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:9944... * Connected to localhost (::1) port 9944 > POST / HTTP/1.1 > Host: localhost:9944 > User-Agent: curl/8.5.0 > Accept: */* > Content-Type: application/json > Content-Length: 50 > < HTTP/1.1 403 Forbidden < content-type: text/plain < content-length: 41 < date: Tue, 12 Nov 2024 13:03:49 GMT < Provided Host header is not whitelisted. * Connection #0 to host localhost left intact ``` ### Behavior after this PR ```bash $ polkadot --chain westend-dev & ➜ wasm-tests (update-artifacts-1731284930) ✗ curl -v \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":"id","method":"system_name"}' \ http://localhost:9944 * Host localhost:9944 was resolved. * IPv6: ::1 * IPv4: 127.0.0.1 * Trying [::1]:9944... * Connected to localhost (::1) port 9944 > POST / HTTP/1.1 > Host: localhost:9944 > User-Agent: curl/8.5.0 > Accept: */* > Content-Type: application/json > Content-Length: 50 > < HTTP/1.1 200 OK < content-type: application/json; charset=utf-8 < vary: origin, access-control-request-method, access-control-request-headers < content-length: 54 < date: Tue, 12 Nov 2024 13:02:57 GMT < * Connection #0 to host localhost left intact {"jsonrpc":"2.0","id":"id","result":"Parity Polkadot"}% ``` --------- Co-authored-by: GitHub Action Co-authored-by: command-bot <> --- prdoc/pr_6454.prdoc | 7 +++++++ substrate/client/rpc-servers/src/utils.rs | 13 +++++-------- 2 files changed, 12 insertions(+), 8 deletions(-) create mode 100644 prdoc/pr_6454.prdoc diff --git a/prdoc/pr_6454.prdoc b/prdoc/pr_6454.prdoc new file mode 100644 index 000000000000..3fd3e39db604 --- /dev/null +++ b/prdoc/pr_6454.prdoc @@ -0,0 +1,7 @@ +title: 'rpc server: fix ipv6 host filter for localhost' +doc: +- audience: Node Operator + description: "This PR fixes that ipv6 connections to localhost was faulty rejected by the host filter because only [::1] was allowed" +crates: +- name: sc-rpc-server + bump: minor diff --git a/substrate/client/rpc-servers/src/utils.rs b/substrate/client/rpc-servers/src/utils.rs index d9b2db7af133..51cce6224298 100644 --- a/substrate/client/rpc-servers/src/utils.rs +++ b/substrate/client/rpc-servers/src/utils.rs @@ -193,14 +193,11 @@ pub(crate) fn host_filtering(enabled: bool, addr: SocketAddr) -> Option Date: Tue, 12 Nov 2024 19:33:41 +0100 Subject: [PATCH 082/166] [pallet-revive] eth-rpc fixes (#6453) - Breaking down the integration-test into multiple tests - Fix tx hash to use expected keccak-256 - Add option to ethers.js example to connect to westend and use a private key --------- Co-authored-by: GitHub Action --- .config/nextest.toml | 7 + Cargo.lock | 1 + prdoc/pr_6453.prdoc | 7 + substrate/frame/revive/rpc/Cargo.toml | 1 + .../frame/revive/rpc/examples/js/src/lib.ts | 29 +++- substrate/frame/revive/rpc/src/client.rs | 7 +- substrate/frame/revive/rpc/src/lib.rs | 6 +- substrate/frame/revive/rpc/src/tests.rs | 139 +++++++++++++----- 8 files changed, 150 insertions(+), 47 deletions(-) create mode 100644 prdoc/pr_6453.prdoc diff --git a/.config/nextest.toml b/.config/nextest.toml index 1e18f8b5589c..912bf2514a77 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -124,3 +124,10 @@ serial-integration = { max-threads = 1 } [[profile.default.overrides]] filter = 'test(/(^ui$|_ui|ui_)/)' test-group = 'serial-integration' + +# Running eth-rpc tests sequentially +# These tests rely on a shared resource (the RPC and Node) +# and would cause race conditions due to transaction nonces if run in parallel. +[[profile.default.overrides]] +filter = 'package(pallet-revive-eth-rpc) and test(/^tests::/)' +test-group = 'serial-integration' diff --git a/Cargo.lock b/Cargo.lock index c1eda1b0fb01..e36f252ecb39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14700,6 +14700,7 @@ dependencies = [ "sp-crypto-hashing 0.1.0", "sp-runtime 31.0.1", "sp-weights 27.0.0", + "static_init", "substrate-cli-test-utils", "substrate-prometheus-endpoint", "subxt", diff --git a/prdoc/pr_6453.prdoc b/prdoc/pr_6453.prdoc new file mode 100644 index 000000000000..5df44f11296d --- /dev/null +++ b/prdoc/pr_6453.prdoc @@ -0,0 +1,7 @@ +title: '[pallet-revive] breakdown integration tests' +doc: +- audience: Runtime Dev + description: Break down the single integration tests into multiple tests, use keccak-256 for tx.hash +crates: +- name: pallet-revive-eth-rpc + bump: minor diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 9faf05885dfe..9f89b74c668f 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -74,6 +74,7 @@ ethabi = { version = "18.0.0" } example = ["hex-literal", "rlp", "secp256k1", "subxt-signer"] [dev-dependencies] +static_init = { workspace = true } hex-literal = { workspace = true } pallet-revive-fixtures = { workspace = true } substrate-cli-test-utils = { workspace = true } diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts index 9db9d36cf56c..7f6fc19aea75 100644 --- a/substrate/frame/revive/rpc/examples/js/src/lib.ts +++ b/substrate/frame/revive/rpc/examples/js/src/lib.ts @@ -4,15 +4,34 @@ import { JsonRpcProvider, TransactionReceipt, TransactionResponse, + Wallet, } from 'ethers' import { readFileSync } from 'node:fs' import type { compile } from '@parity/revive' import { spawn } from 'node:child_process' +import { parseArgs } from 'node:util' type CompileOutput = Awaited> type Abi = CompileOutput['contracts'][string][string]['abi'] -const geth = process.argv.includes('--geth') +const { + values: { geth, westend, ['private-key']: privateKey }, +} = parseArgs({ + args: process.argv.slice(2), + options: { + ['private-key']: { + type: 'string', + short: 'k', + }, + geth: { + type: 'boolean', + }, + westend: { + type: 'boolean', + }, + }, +}) + if (geth) { console.log('Testing with Geth') const child = spawn( @@ -31,13 +50,15 @@ if (geth) { ) process.on('exit', () => child.kill()) - child.unref() await new Promise((resolve) => setTimeout(resolve, 500)) } -const provider = new JsonRpcProvider('http://localhost:8545') -const signer = await provider.getSigner() +const provider = new JsonRpcProvider( + westend ? 'https://westend-asset-hub-eth-rpc.polkadot.io' : 'http://localhost:8545' +) + +const signer = privateKey ? new Wallet(privateKey, provider) : await provider.getSigner() console.log(`Signer address: ${await signer.getAddress()}, Nonce: ${await signer.getNonce()}`) /** diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index ba2398141bec..bc4f59b5e26e 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -35,6 +35,7 @@ use pallet_revive::{ }, EthContractResult, }; +use sp_core::keccak_256; use sp_weights::Weight; use std::{ collections::{HashMap, VecDeque}, @@ -278,6 +279,7 @@ impl ClientInner { // Filter extrinsics from pallet_revive let extrinsics = extrinsics.iter().flat_map(|ext| { let call = ext.as_extrinsic::().ok()??; + let transaction_hash = H256(keccak_256(&call.payload)); let tx = rlp::decode::(&call.payload).ok()?; let from = tx.recover_eth_address().ok()?; let contract_address = if tx.transaction_legacy_unsigned.to.is_none() { @@ -286,12 +288,12 @@ impl ClientInner { None }; - Some((from, tx, contract_address, ext)) + Some((from, tx, transaction_hash, contract_address, ext)) }); // Map each extrinsic to a receipt stream::iter(extrinsics) - .map(|(from, tx, contract_address, ext)| async move { + .map(|(from, tx, transaction_hash, contract_address, ext)| async move { let events = ext.events().await?; let tx_fees = events.find_first::()?.ok_or(ClientError::TxFeeNotFound)?; @@ -305,7 +307,6 @@ impl ClientInner { let transaction_index = ext.index(); let block_hash = block.hash(); let block_number = block.number().into(); - let transaction_hash= ext.hash(); // get logs from ContractEmitted event let logs = events.iter() diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index f6709edc96c9..8d9d6fab829e 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -24,7 +24,7 @@ use jsonrpsee::{ types::{ErrorCode, ErrorObjectOwned}, }; use pallet_revive::{evm::*, EthContractResult}; -use sp_core::{H160, H256, U256}; +use sp_core::{keccak_256, H160, H256, U256}; use thiserror::Error; pub mod cli; @@ -135,6 +135,8 @@ impl EthRpcServer for EthRpcServerImpl { } async fn send_raw_transaction(&self, transaction: Bytes) -> RpcResult { + let hash = H256(keccak_256(&transaction.0)); + let tx = rlp::decode::(&transaction.0).map_err(|err| { log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}"); EthRpcError::from(err) @@ -167,7 +169,7 @@ impl EthRpcServer for EthRpcServerImpl { gas_required.into(), storage_deposit, ); - let hash = self.client.submit(call).await?; + self.client.submit(call).await?; log::debug!(target: LOG_TARGET, "send_raw_transaction hash: {hash:?}"); Ok(hash) } diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 537cfd07964f..3d2cbe42be8e 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -27,6 +27,7 @@ use pallet_revive::{ create1, evm::{Account, BlockTag, U256}, }; +use static_init::dynamic; use std::thread; use substrate_cli_test_utils::*; @@ -60,6 +61,52 @@ fn get_contract(name: &str) -> anyhow::Result<(Vec, ethabi::Contract)> { Ok((bytecode, contract)) } +struct SharedResources { + _node_handle: std::thread::JoinHandle<()>, + _rpc_handle: std::thread::JoinHandle<()>, +} + +impl SharedResources { + fn start() -> Self { + // Start the node. + let _node_handle = thread::spawn(move || { + if let Err(e) = start_node_inline(vec![ + "--dev", + "--rpc-port=45789", + "--no-telemetry", + "--no-prometheus", + "-lerror,evm=debug,sc_rpc_server=info,runtime::revive=trace", + ]) { + panic!("Node exited with error: {e:?}"); + } + }); + + // Start the rpc server. + let args = CliCommand::parse_from([ + "--dev", + "--rpc-port=45788", + "--node-rpc-url=ws://localhost:45789", + "--no-prometheus", + "-linfo,eth-rpc=debug", + ]); + + let _rpc_handle = thread::spawn(move || { + if let Err(e) = cli::run(args) { + panic!("eth-rpc exited with error: {e:?}"); + } + }); + + Self { _node_handle, _rpc_handle } + } + + async fn client() -> WsClient { + ws_client_with_retry("ws://localhost:45788").await + } +} + +#[dynamic(lazy)] +static mut SHARED_RESOURCES: SharedResources = SharedResources::start(); + macro_rules! unwrap_call_err( ($err:expr) => { match $err.downcast_ref::().unwrap() { @@ -70,41 +117,42 @@ macro_rules! unwrap_call_err( ); #[tokio::test] -async fn test_jsonrpsee_server() -> anyhow::Result<()> { - // Start the node. - let _ = thread::spawn(move || { - if let Err(e) = start_node_inline(vec![ - "--dev", - "--rpc-port=45789", - "--no-telemetry", - "--no-prometheus", - "-lerror,evm=debug,sc_rpc_server=info,runtime::revive=trace", - ]) { - panic!("Node exited with error: {e:?}"); - } - }); - - // Start the rpc server. - let args = CliCommand::parse_from([ - "--dev", - "--rpc-port=45788", - "--node-rpc-url=ws://localhost:45789", - "--no-prometheus", - "-linfo,eth-rpc=debug", - ]); - let _ = thread::spawn(move || { - if let Err(e) = cli::run(args) { - panic!("eth-rpc exited with error: {e:?}"); - } - }); +async fn transfer() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; - let client = ws_client_with_retry("ws://localhost:45788").await; + let ethan = Account::from(subxt_signer::eth::dev::ethan()); + let initial_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; + + let value = 1_000_000_000_000_000_000_000u128.into(); + let hash = TransactionBuilder::default() + .value(value) + .to(ethan.address()) + .send(&client) + .await?; + + let receipt = wait_for_successful_receipt(&client, hash).await?; + assert_eq!( + Some(ethan.address()), + receipt.to, + "Receipt should have the correct contract address." + ); + + let increase = + client.get_balance(ethan.address(), BlockTag::Latest.into()).await? - initial_balance; + assert_eq!(value, increase); + Ok(()) +} + +#[tokio::test] +async fn deploy_and_call() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; let account = Account::default(); // Balance transfer let ethan = Account::from(subxt_signer::eth::dev::ethan()); - let ethan_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; - assert_eq!(U256::zero(), ethan_balance); + let initial_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; let value = 1_000_000_000_000_000_000_000u128.into(); let hash = TransactionBuilder::default() @@ -120,8 +168,8 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { "Receipt should have the correct contract address." ); - let ethan_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; - assert_eq!(value, ethan_balance, "ethan's balance should be the same as the value sent."); + let updated_balance = client.get_balance(ethan.address(), BlockTag::Latest.into()).await?; + assert_eq!(value, updated_balance - initial_balance); // Deploy contract let data = b"hello world".to_vec(); @@ -169,15 +217,19 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { wait_for_successful_receipt(&client, hash).await?; let increase = client.get_balance(contract_address, BlockTag::Latest.into()).await? - balance; assert_eq!(value, increase, "contract's balance should have increased by the value sent."); + Ok(()) +} - // Deploy revert +#[tokio::test] +async fn revert_call() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; let (bytecode, contract) = get_contract("revert")?; let receipt = TransactionBuilder::default() .input(contract.constructor.clone().unwrap().encode_input(bytecode, &[]).unwrap()) .send_and_wait_for_receipt(&client) .await?; - // Call doRevert let err = TransactionBuilder::default() .to(receipt.contract_address.unwrap()) .input(contract.function("doRevert")?.encode_input(&[])?.to_vec()) @@ -187,25 +239,36 @@ async fn test_jsonrpsee_server() -> anyhow::Result<()> { let call_err = unwrap_call_err!(err.source().unwrap()); assert_eq!(call_err.message(), "Execution reverted: revert message"); + Ok(()) +} - // Deploy event +#[tokio::test] +async fn event_logs() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; let (bytecode, contract) = get_contract("event")?; let receipt = TransactionBuilder::default() .input(bytecode) .send_and_wait_for_receipt(&client) .await?; - // Call triggerEvent let receipt = TransactionBuilder::default() .to(receipt.contract_address.unwrap()) .input(contract.function("triggerEvent")?.encode_input(&[])?.to_vec()) .send_and_wait_for_receipt(&client) .await?; assert_eq!(receipt.logs.len(), 1, "There should be one log."); + Ok(()) +} + +#[tokio::test] +async fn invalid_transaction() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; + let ethan = Account::from(subxt_signer::eth::dev::ethan()); - // Invalid transaction let err = TransactionBuilder::default() - .value(value) + .value(U256::from(1_000_000_000_000u128)) .to(ethan.address()) .mutate(|tx| tx.chain_id = Some(42u32.into())) .send(&client) From 5aeaa6646cc0ead984cc0b12dd9ea5a8fca56687 Mon Sep 17 00:00:00 2001 From: Andrei Eres Date: Wed, 13 Nov 2024 10:18:38 +0100 Subject: [PATCH 083/166] Remove debug message about pruning active leaves (#6440) # Description The debug message was added to identify a potential memory leak. However, recent observations show that pruning works as expected. Therefore, it is best to remove this line, as it generates quite annoying logs. ## Integration Doesn't affect downstream projects. --------- Co-authored-by: GitHub Action --- polkadot/node/core/pvf/src/execute/queue.rs | 2 -- prdoc/pr_6440.prdoc | 8 ++++++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 prdoc/pr_6440.prdoc diff --git a/polkadot/node/core/pvf/src/execute/queue.rs b/polkadot/node/core/pvf/src/execute/queue.rs index 6d27ab0261d9..69355b8fd55d 100644 --- a/polkadot/node/core/pvf/src/execute/queue.rs +++ b/polkadot/node/core/pvf/src/execute/queue.rs @@ -305,8 +305,6 @@ impl Queue { for hash in &update.deactivated { let _ = self.active_leaves.remove(&hash); } - - gum::debug!(target: LOG_TARGET, size = ?self.active_leaves.len(), "Active leaves pruned"); } fn insert_active_leaf(&mut self, update: ActiveLeavesUpdate, ancestors: Vec) { diff --git a/prdoc/pr_6440.prdoc b/prdoc/pr_6440.prdoc new file mode 100644 index 000000000000..376e59fa752e --- /dev/null +++ b/prdoc/pr_6440.prdoc @@ -0,0 +1,8 @@ +title: Remove debug message about pruning active leaves +doc: +- audience: Node Dev + description: |- + Removed useless debug message +crates: +- name: polkadot-node-core-pvf + validate: false From 8e3d929623d43398ed3ab8c9ca813aff32588011 Mon Sep 17 00:00:00 2001 From: Guillaume Thiolliere Date: Wed, 13 Nov 2024 18:20:25 +0900 Subject: [PATCH 084/166] [Tx ext stage 2: 1/4] Add `TransactionSource` as argument in `TransactionExtension::validate` (#6323) ## Meta This PR is part of 4 PR: * https://github.com/paritytech/polkadot-sdk/pull/6323 * https://github.com/paritytech/polkadot-sdk/pull/6324 * https://github.com/paritytech/polkadot-sdk/pull/6325 * https://github.com/paritytech/polkadot-sdk/pull/6326 ## Description One goal of transaction extension is to get rid or unsigned transactions. But unsigned transaction validation has access to the `TransactionSource`. The source is used for unsigned transactions that the node trust and don't want to pay upfront. Instead of using transaction source we could do: the transaction is valid if it is signed by the block author, conceptually it should work, but it doesn't look so easy. This PR add `TransactionSource` to the validate function for transaction extensions --- bridges/bin/runtime-common/src/extensions.rs | 13 ++++-- bridges/modules/relayers/src/extension/mod.rs | 9 +++- polkadot/runtime/common/src/claims.rs | 11 +++-- prdoc/pr_6323.prdoc | 32 ++++++++++++++ .../src/extensions.rs | 3 +- substrate/frame/examples/basic/src/lib.rs | 2 + substrate/frame/examples/basic/src/tests.rs | 5 ++- substrate/frame/sudo/src/extension.rs | 3 +- .../system/src/extensions/check_mortality.rs | 11 ++++- .../src/extensions/check_non_zero_sender.rs | 12 +++--- .../system/src/extensions/check_nonce.rs | 30 ++++++++----- .../system/src/extensions/check_weight.rs | 2 + .../asset-conversion-tx-payment/src/lib.rs | 2 + .../asset-tx-payment/src/lib.rs | 3 +- .../skip-feeless-payment/src/lib.rs | 13 +++++- .../skip-feeless-payment/src/mock.rs | 1 + .../skip-feeless-payment/src/tests.rs | 18 ++++++-- .../frame/transaction-payment/src/lib.rs | 2 + .../frame/transaction-payment/src/tests.rs | 43 ++++++++++++++----- .../verify-signature/src/benchmarking.rs | 17 +++++++- .../frame/verify-signature/src/extension.rs | 3 +- substrate/frame/verify-signature/src/tests.rs | 10 ++--- .../runtime/src/generic/checked_extrinsic.rs | 7 +-- .../as_transaction_extension.rs | 3 +- .../dispatch_transaction.rs | 12 ++++-- .../src/traits/transaction_extension/mod.rs | 10 ++++- substrate/test-utils/runtime/src/lib.rs | 5 ++- 27 files changed, 217 insertions(+), 65 deletions(-) create mode 100644 prdoc/pr_6323.prdoc diff --git a/bridges/bin/runtime-common/src/extensions.rs b/bridges/bin/runtime-common/src/extensions.rs index 19d1554c668b..256e975f44c3 100644 --- a/bridges/bin/runtime-common/src/extensions.rs +++ b/bridges/bin/runtime-common/src/extensions.rs @@ -299,6 +299,7 @@ macro_rules! generate_bridge_reject_obsolete_headers_and_messages { _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl codec::Encode, + _source: sp_runtime::transaction_validity::TransactionSource, ) -> Result< ( sp_runtime::transaction_validity::ValidTransaction, @@ -390,7 +391,9 @@ mod tests { parameter_types, AsSystemOriginSigner, AsTransactionAuthorizedOrigin, ConstU64, DispatchTransaction, Header as _, TransactionExtension, }, - transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, + transaction_validity::{ + InvalidTransaction, TransactionSource::External, TransactionValidity, ValidTransaction, + }, DispatchError, }; @@ -610,7 +613,8 @@ mod tests { 42u64.into(), &MockCall { data: 1 }, &(), - 0 + 0, + External, ), InvalidTransaction::Custom(1) ); @@ -629,7 +633,8 @@ mod tests { 42u64.into(), &MockCall { data: 2 }, &(), - 0 + 0, + External, ), InvalidTransaction::Custom(2) ); @@ -645,7 +650,7 @@ mod tests { assert_eq!( BridgeRejectObsoleteHeadersAndMessages - .validate_only(42u64.into(), &MockCall { data: 3 }, &(), 0) + .validate_only(42u64.into(), &MockCall { data: 3 }, &(), 0, External) .unwrap() .0, ValidTransaction { priority: 3, ..Default::default() }, diff --git a/bridges/modules/relayers/src/extension/mod.rs b/bridges/modules/relayers/src/extension/mod.rs index 710533c223a0..a400aeaee074 100644 --- a/bridges/modules/relayers/src/extension/mod.rs +++ b/bridges/modules/relayers/src/extension/mod.rs @@ -33,6 +33,7 @@ use bp_runtime::{Chain, RangeInclusiveExt, StaticStrProvider}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, PostDispatchInfo}, + pallet_prelude::TransactionSource, weights::Weight, CloneNoBound, DefaultNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; @@ -304,6 +305,7 @@ where _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { // Prepare relevant data for `prepare` let parsed_call = match C::parse_and_check_for_obsolete_call(call)? { @@ -463,7 +465,9 @@ mod tests { use pallet_utility::Call as UtilityCall; use sp_runtime::{ traits::{ConstU64, DispatchTransaction, Header as HeaderT}, - transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, + transaction_validity::{ + InvalidTransaction, TransactionSource::External, TransactionValidity, ValidTransaction, + }, DispatchError, }; @@ -1076,6 +1080,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + External, ) .map(|t| t.0) } @@ -1088,6 +1093,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + External, ) .map(|t| t.0) } @@ -1100,6 +1106,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + External, ) .map(|t| t.0) } diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index b77cbfeff77c..5383fe41d487 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -39,7 +39,8 @@ use sp_runtime::{ Dispatchable, TransactionExtension, Zero, }, transaction_validity::{ - InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction, + InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, + ValidTransaction, }, RuntimeDebug, }; @@ -663,6 +664,7 @@ where _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, @@ -716,6 +718,7 @@ mod tests { use super::*; use hex_literal::hex; use secp_utils::*; + use sp_runtime::transaction_validity::TransactionSource::External; use codec::Encode; // The testing primitives are very useful for avoiding having to work with signatures @@ -1075,7 +1078,7 @@ mod tests { }); let di = c.get_dispatch_info(); assert_eq!(di.pays_fee, Pays::No); - let r = p.validate_only(Some(42).into(), &c, &di, 20); + let r = p.validate_only(Some(42).into(), &c, &di, 20, External); assert_eq!(r.unwrap().0, ValidTransaction::default()); }); } @@ -1088,13 +1091,13 @@ mod tests { statement: StatementKind::Regular.to_text().to_vec(), }); let di = c.get_dispatch_info(); - let r = p.validate_only(Some(42).into(), &c, &di, 20); + let r = p.validate_only(Some(42).into(), &c, &di, 20, External); assert!(r.is_err()); let c = RuntimeCall::Claims(ClaimsCall::attest { statement: StatementKind::Saft.to_text().to_vec(), }); let di = c.get_dispatch_info(); - let r = p.validate_only(Some(69).into(), &c, &di, 20); + let r = p.validate_only(Some(69).into(), &c, &di, 20, External); assert!(r.is_err()); }); } diff --git a/prdoc/pr_6323.prdoc b/prdoc/pr_6323.prdoc new file mode 100644 index 000000000000..ec632a14f946 --- /dev/null +++ b/prdoc/pr_6323.prdoc @@ -0,0 +1,32 @@ +title: add `TransactionSource` to `TransactionExtension::validate` +doc: +- audience: Runtime Dev + description: | + Add a the source of the extrinsic as an argument in `TransactionExtension::validate`. + The transaction source can be useful for transactions that should only be valid if it comes from the node. For example from offchain worker. + To update the current code. The transaction source can simply be ignored: `_source: TransactionSource` + + +crates: +- name: sp-runtime + bump: major +- name: bridge-runtime-common + bump: patch +- name: frame-system + bump: patch +- name: pallet-transaction-payment + bump: patch +- name: polkadot-runtime-common + bump: patch +- name: pallet-sudo + bump: patch +- name: pallet-verify-signature + bump: patch +- name: pallet-asset-tx-payment + bump: patch +- name: pallet-bridge-relayers + bump: patch +- name: pallet-asset-conversion-tx-payment + bump: patch +- name: pallet-skip-feeless-payment + bump: patch diff --git a/substrate/frame/examples/authorization-tx-extension/src/extensions.rs b/substrate/frame/examples/authorization-tx-extension/src/extensions.rs index d1e56916d3a2..dcbe171c183a 100644 --- a/substrate/frame/examples/authorization-tx-extension/src/extensions.rs +++ b/substrate/frame/examples/authorization-tx-extension/src/extensions.rs @@ -18,7 +18,7 @@ use core::{fmt, marker::PhantomData}; use codec::{Decode, Encode}; -use frame_support::{traits::OriginTrait, Parameter}; +use frame_support::{pallet_prelude::TransactionSource, traits::OriginTrait, Parameter}; use scale_info::TypeInfo; use sp_runtime::{ impl_tx_ext_default, @@ -94,6 +94,7 @@ where _len: usize, _self_implicit: Self::Implicit, inherited_implication: &impl codec::Encode, + _source: TransactionSource, ) -> ValidateResult { // If the extension is inactive, just move on in the pipeline. let Some(auth) = &self.inner else { diff --git a/substrate/frame/examples/basic/src/lib.rs b/substrate/frame/examples/basic/src/lib.rs index 2f1b32d964e4..efdf4332e329 100644 --- a/substrate/frame/examples/basic/src/lib.rs +++ b/substrate/frame/examples/basic/src/lib.rs @@ -61,6 +61,7 @@ use codec::{Decode, Encode}; use core::marker::PhantomData; use frame_support::{ dispatch::{ClassifyDispatch, DispatchClass, DispatchResult, Pays, PaysFee, WeighData}, + pallet_prelude::TransactionSource, traits::IsSubType, weights::Weight, }; @@ -508,6 +509,7 @@ where len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult::RuntimeCall> { // if the transaction is too big, just drop it. if len > 200 { diff --git a/substrate/frame/examples/basic/src/tests.rs b/substrate/frame/examples/basic/src/tests.rs index 8e33d3d0a348..8008f9264c7b 100644 --- a/substrate/frame/examples/basic/src/tests.rs +++ b/substrate/frame/examples/basic/src/tests.rs @@ -28,6 +28,7 @@ use sp_core::H256; // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use sp_runtime::{ traits::{BlakeTwo256, DispatchTransaction, IdentityLookup}, + transaction_validity::TransactionSource::External, BuildStorage, }; // Reexport crate as its pallet name for construct_runtime. @@ -146,7 +147,7 @@ fn signed_ext_watch_dummy_works() { assert_eq!( WatchDummy::(PhantomData) - .validate_only(Some(1).into(), &call, &info, 150) + .validate_only(Some(1).into(), &call, &info, 150, External) .unwrap() .0 .priority, @@ -154,7 +155,7 @@ fn signed_ext_watch_dummy_works() { ); assert_eq!( WatchDummy::(PhantomData) - .validate_only(Some(1).into(), &call, &info, 250) + .validate_only(Some(1).into(), &call, &info, 250, External) .unwrap_err(), InvalidTransaction::ExhaustsResources.into(), ); diff --git a/substrate/frame/sudo/src/extension.rs b/substrate/frame/sudo/src/extension.rs index 573de45ba32d..d2669de79e54 100644 --- a/substrate/frame/sudo/src/extension.rs +++ b/substrate/frame/sudo/src/extension.rs @@ -18,7 +18,7 @@ use crate::{Config, Key}; use codec::{Decode, Encode}; use core::{fmt, marker::PhantomData}; -use frame_support::{dispatch::DispatchInfo, ensure}; +use frame_support::{dispatch::DispatchInfo, ensure, pallet_prelude::TransactionSource}; use scale_info::TypeInfo; use sp_runtime::{ impl_tx_ext_default, @@ -94,6 +94,7 @@ where _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< ( ValidTransaction, diff --git a/substrate/frame/system/src/extensions/check_mortality.rs b/substrate/frame/system/src/extensions/check_mortality.rs index 7da5521f353d..75e1fc2fc11a 100644 --- a/substrate/frame/system/src/extensions/check_mortality.rs +++ b/substrate/frame/system/src/extensions/check_mortality.rs @@ -17,6 +17,7 @@ use crate::{pallet_prelude::BlockNumberFor, BlockHash, Config, Pallet}; use codec::{Decode, Encode}; +use frame_support::pallet_prelude::TransactionSource; use scale_info::TypeInfo; use sp_runtime::{ generic::Era, @@ -91,6 +92,7 @@ impl TransactionExtension for CheckMort _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { let current_u64 = >::block_number().saturated_into::(); let valid_till = self.0.death(current_u64); @@ -115,7 +117,9 @@ mod tests { weights::Weight, }; use sp_core::H256; - use sp_runtime::traits::DispatchTransaction; + use sp_runtime::{ + traits::DispatchTransaction, transaction_validity::TransactionSource::External, + }; #[test] fn signed_ext_check_era_should_work() { @@ -151,7 +155,10 @@ mod tests { >::insert(16, H256::repeat_byte(1)); assert_eq!( - ext.validate_only(Some(1).into(), CALL, &normal, len).unwrap().0.longevity, + ext.validate_only(Some(1).into(), CALL, &normal, len, External) + .unwrap() + .0 + .longevity, 15 ); }) diff --git a/substrate/frame/system/src/extensions/check_non_zero_sender.rs b/substrate/frame/system/src/extensions/check_non_zero_sender.rs index ec8c12b790d2..a4e54954dc2c 100644 --- a/substrate/frame/system/src/extensions/check_non_zero_sender.rs +++ b/substrate/frame/system/src/extensions/check_non_zero_sender.rs @@ -18,7 +18,7 @@ use crate::Config; use codec::{Decode, Encode}; use core::marker::PhantomData; -use frame_support::{traits::OriginTrait, DefaultNoBound}; +use frame_support::{pallet_prelude::TransactionSource, traits::OriginTrait, DefaultNoBound}; use scale_info::TypeInfo; use sp_runtime::{ impl_tx_ext_default, @@ -68,6 +68,7 @@ impl TransactionExtension for CheckNonZ _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> sp_runtime::traits::ValidateResult { if let Some(who) = origin.as_signer() { if who.using_encoded(|d| d.iter().all(|x| *x == 0)) { @@ -86,7 +87,7 @@ mod tests { use frame_support::{assert_ok, dispatch::DispatchInfo}; use sp_runtime::{ traits::{AsTransactionAuthorizedOrigin, DispatchTransaction}, - transaction_validity::TransactionValidityError, + transaction_validity::{TransactionSource::External, TransactionValidityError}, }; #[test] @@ -96,7 +97,7 @@ mod tests { let len = 0_usize; assert_eq!( CheckNonZeroSender::::new() - .validate_only(Some(0).into(), CALL, &info, len) + .validate_only(Some(0).into(), CALL, &info, len, External) .unwrap_err(), TransactionValidityError::from(InvalidTransaction::BadSigner) ); @@ -104,7 +105,8 @@ mod tests { Some(1).into(), CALL, &info, - len + len, + External, )); }) } @@ -115,7 +117,7 @@ mod tests { let info = DispatchInfo::default(); let len = 0_usize; let (_, _, origin) = CheckNonZeroSender::::new() - .validate(None.into(), CALL, &info, len, (), CALL) + .validate(None.into(), CALL, &info, len, (), CALL, External) .unwrap(); assert!(!origin.is_transaction_authorized()); }) diff --git a/substrate/frame/system/src/extensions/check_nonce.rs b/substrate/frame/system/src/extensions/check_nonce.rs index d96d2c2c0662..eed08050338b 100644 --- a/substrate/frame/system/src/extensions/check_nonce.rs +++ b/substrate/frame/system/src/extensions/check_nonce.rs @@ -18,7 +18,9 @@ use crate::Config; use alloc::vec; use codec::{Decode, Encode}; -use frame_support::{dispatch::DispatchInfo, RuntimeDebugNoBound}; +use frame_support::{ + dispatch::DispatchInfo, pallet_prelude::TransactionSource, RuntimeDebugNoBound, +}; use scale_info::TypeInfo; use sp_runtime::{ traits::{ @@ -108,6 +110,7 @@ where _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { let Some(who) = origin.as_system_origin_signer() else { return Ok((Default::default(), Val::Refund(self.weight(call)), origin)) @@ -182,7 +185,10 @@ mod tests { use frame_support::{ assert_ok, assert_storage_noop, dispatch::GetDispatchInfo, traits::OriginTrait, }; - use sp_runtime::traits::{AsTransactionAuthorizedOrigin, DispatchTransaction}; + use sp_runtime::{ + traits::{AsTransactionAuthorizedOrigin, DispatchTransaction}, + transaction_validity::TransactionSource::External, + }; #[test] fn signed_ext_check_nonce_works() { @@ -203,7 +209,7 @@ mod tests { assert_storage_noop!({ assert_eq!( CheckNonce::(0u64.into()) - .validate_only(Some(1).into(), CALL, &info, len) + .validate_only(Some(1).into(), CALL, &info, len, External) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Stale) ); @@ -219,7 +225,8 @@ mod tests { Some(1).into(), CALL, &info, - len + len, + External, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(1).into(), @@ -232,7 +239,8 @@ mod tests { Some(1).into(), CALL, &info, - len + len, + External, )); assert_eq!( CheckNonce::(5u64.into()) @@ -272,7 +280,7 @@ mod tests { assert_storage_noop!({ assert_eq!( CheckNonce::(1u64.into()) - .validate_only(Some(1).into(), CALL, &info, len) + .validate_only(Some(1).into(), CALL, &info, len, External) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Payment) ); @@ -288,7 +296,8 @@ mod tests { Some(2).into(), CALL, &info, - len + len, + External, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(2).into(), @@ -301,7 +310,8 @@ mod tests { Some(3).into(), CALL, &info, - len + len, + External, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(3).into(), @@ -318,7 +328,7 @@ mod tests { let info = DispatchInfo::default(); let len = 0_usize; let (_, val, origin) = CheckNonce::(1u64.into()) - .validate(None.into(), CALL, &info, len, (), CALL) + .validate(None.into(), CALL, &info, len, (), CALL, External) .unwrap(); assert!(!origin.is_transaction_authorized()); assert_ok!(CheckNonce::(1u64.into()).prepare(val, &origin, CALL, &info, len)); @@ -342,7 +352,7 @@ mod tests { let len = 0_usize; // run the validation step let (_, val, origin) = CheckNonce::(1u64.into()) - .validate(Some(1).into(), CALL, &info, len, (), CALL) + .validate(Some(1).into(), CALL, &info, len, (), CALL, External) .unwrap(); // mutate `AccountData` for the caller crate::Account::::mutate(1, |info| { diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index 131057f54a78..435c96c8741f 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -19,6 +19,7 @@ use crate::{limits::BlockWeights, Config, Pallet, LOG_TARGET}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, PostDispatchInfo}, + pallet_prelude::TransactionSource, traits::Get, }; use scale_info::TypeInfo; @@ -254,6 +255,7 @@ where len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { let (validity, next_len) = Self::do_validate(info, len)?; Ok((validity, next_len, origin)) diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs index 787f6b122e86..d6721c46422b 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs @@ -47,6 +47,7 @@ extern crate alloc; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, DispatchResult, PostDispatchInfo}, + pallet_prelude::TransactionSource, traits::IsType, DefaultNoBound, }; @@ -308,6 +309,7 @@ where len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { let Some(who) = origin.as_system_origin_signer() else { return Ok((ValidTransaction::default(), Val::NoCharge, origin)) diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs index 25aa272ba01b..dd752989c366 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs @@ -38,7 +38,7 @@ use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, DispatchResult, PostDispatchInfo}, - pallet_prelude::Weight, + pallet_prelude::{TransactionSource, Weight}, traits::{ tokens::{ fungibles::{Balanced, Credit, Inspect}, @@ -324,6 +324,7 @@ where len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs index d6ac648cefd4..dd907f6fcbb7 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs @@ -39,6 +39,7 @@ use codec::{Decode, Encode}; use frame_support::{ dispatch::{CheckIfFeeless, DispatchResult}, + pallet_prelude::TransactionSource, traits::{IsType, OriginTrait}, weights::Weight, }; @@ -147,12 +148,20 @@ where len: usize, self_implicit: S::Implicit, inherited_implication: &impl Encode, + source: TransactionSource, ) -> ValidateResult { if call.is_feeless(&origin) { Ok((Default::default(), Skip(origin.caller().clone()), origin)) } else { - let (x, y, z) = - self.0.validate(origin, call, info, len, self_implicit, inherited_implication)?; + let (x, y, z) = self.0.validate( + origin, + call, + info, + len, + self_implicit, + inherited_implication, + source, + )?; Ok((x, Apply(y), z)) } } diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs index 83f7b7dfe2b5..cff232a0cae3 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs @@ -60,6 +60,7 @@ impl TransactionExtension for DummyExtension { _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { ValidateCount::mutate(|c| *c += 1); Ok((ValidTransaction::default(), (), origin)) diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs index 666844c883bd..1940110a1f1d 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs @@ -18,7 +18,7 @@ use crate::mock::{ pallet_dummy::Call, DummyExtension, PrepareCount, Runtime, RuntimeCall, ValidateCount, }; use frame_support::dispatch::DispatchInfo; -use sp_runtime::traits::DispatchTransaction; +use sp_runtime::{traits::DispatchTransaction, transaction_validity::TransactionSource}; #[test] fn skip_feeless_payment_works() { @@ -41,14 +41,26 @@ fn validate_works() { let call = RuntimeCall::DummyPallet(Call::::aux { data: 1 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_only(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_only( + Some(0).into(), + &call, + &DispatchInfo::default(), + 0, + TransactionSource::External, + ) .unwrap(); assert_eq!(ValidateCount::get(), 1); assert_eq!(PrepareCount::get(), 0); let call = RuntimeCall::DummyPallet(Call::::aux { data: 0 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_only(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_only( + Some(0).into(), + &call, + &DispatchInfo::default(), + 0, + TransactionSource::External, + ) .unwrap(); assert_eq!(ValidateCount::get(), 1); assert_eq!(PrepareCount::get(), 0); diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 711189be8d07..018c2f6b5919 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -54,6 +54,7 @@ use frame_support::{ dispatch::{ DispatchClass, DispatchInfo, DispatchResult, GetDispatchInfo, Pays, PostDispatchInfo, }, + pallet_prelude::TransactionSource, traits::{Defensive, EstimateCallFee, Get}, weights::{Weight, WeightToFee}, RuntimeDebugNoBound, @@ -916,6 +917,7 @@ where len: usize, _: (), _implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, diff --git a/substrate/frame/transaction-payment/src/tests.rs b/substrate/frame/transaction-payment/src/tests.rs index e8f5ab99529f..dde696f09c2a 100644 --- a/substrate/frame/transaction-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/src/tests.rs @@ -23,7 +23,7 @@ use codec::Encode; use sp_runtime::{ generic::UncheckedExtrinsic, traits::{DispatchTransaction, One}, - transaction_validity::InvalidTransaction, + transaction_validity::{InvalidTransaction, TransactionSource::External}, BuildStorage, }; @@ -235,7 +235,7 @@ fn transaction_extension_allows_free_transactions() { class: DispatchClass::Operational, pays_fee: Pays::No, }; - assert_ok!(Ext::from(0).validate_only(Some(1).into(), CALL, &op_tx, len)); + assert_ok!(Ext::from(0).validate_only(Some(1).into(), CALL, &op_tx, len, External)); // like a InsecureFreeNormal let free_tx = DispatchInfo { @@ -245,7 +245,9 @@ fn transaction_extension_allows_free_transactions() { pays_fee: Pays::Yes, }; assert_eq!( - Ext::from(0).validate_only(Some(1).into(), CALL, &free_tx, len).unwrap_err(), + Ext::from(0) + .validate_only(Some(1).into(), CALL, &free_tx, len, External) + .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Payment), ); }); @@ -659,11 +661,19 @@ fn should_alter_operational_priority() { }; let ext = Ext::from(tip); - let priority = ext.validate_only(Some(2).into(), CALL, &normal, len).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &normal, len, External) + .unwrap() + .0 + .priority; assert_eq!(priority, 60); let ext = Ext::from(2 * tip); - let priority = ext.validate_only(Some(2).into(), CALL, &normal, len).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &normal, len, External) + .unwrap() + .0 + .priority; assert_eq!(priority, 110); }); @@ -676,11 +686,13 @@ fn should_alter_operational_priority() { }; let ext = Ext::from(tip); - let priority = ext.validate_only(Some(2).into(), CALL, &op, len).unwrap().0.priority; + let priority = + ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; assert_eq!(priority, 5810); let ext = Ext::from(2 * tip); - let priority = ext.validate_only(Some(2).into(), CALL, &op, len).unwrap().0.priority; + let priority = + ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; assert_eq!(priority, 6110); }); } @@ -698,7 +710,11 @@ fn no_tip_has_some_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - let priority = ext.validate_only(Some(2).into(), CALL, &normal, len).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &normal, len, External) + .unwrap() + .0 + .priority; assert_eq!(priority, 10); }); @@ -710,7 +726,8 @@ fn no_tip_has_some_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - let priority = ext.validate_only(Some(2).into(), CALL, &op, len).unwrap().0.priority; + let priority = + ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; assert_eq!(priority, 5510); }); } @@ -729,7 +746,11 @@ fn higher_tip_have_higher_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - pri1 = ext.validate_only(Some(2).into(), CALL, &normal, len).unwrap().0.priority; + pri1 = ext + .validate_only(Some(2).into(), CALL, &normal, len, External) + .unwrap() + .0 + .priority; }); ExtBuilder::default().balance_factor(100).build().execute_with(|| { @@ -740,7 +761,7 @@ fn higher_tip_have_higher_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - pri2 = ext.validate_only(Some(2).into(), CALL, &op, len).unwrap().0.priority; + pri2 = ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; }); (pri1, pri2) diff --git a/substrate/frame/verify-signature/src/benchmarking.rs b/substrate/frame/verify-signature/src/benchmarking.rs index 2b592a4023ec..475cf4cec591 100644 --- a/substrate/frame/verify-signature/src/benchmarking.rs +++ b/substrate/frame/verify-signature/src/benchmarking.rs @@ -27,7 +27,10 @@ use super::*; use crate::{extension::VerifySignature, Config, Pallet as VerifySignaturePallet}; use alloc::vec; use frame_benchmarking::{v2::*, BenchmarkError}; -use frame_support::dispatch::{DispatchInfo, GetDispatchInfo}; +use frame_support::{ + dispatch::{DispatchInfo, GetDispatchInfo}, + pallet_prelude::TransactionSource, +}; use frame_system::{Call as SystemCall, RawOrigin}; use sp_io::hashing::blake2_256; use sp_runtime::traits::{AsTransactionAuthorizedOrigin, Dispatchable, TransactionExtension}; @@ -55,7 +58,17 @@ mod benchmarks { #[block] { - assert!(ext.validate(RawOrigin::None.into(), &call, &info, 0, (), &call).is_ok()); + assert!(ext + .validate( + RawOrigin::None.into(), + &call, + &info, + 0, + (), + &call, + TransactionSource::External + ) + .is_ok()); } Ok(()) diff --git a/substrate/frame/verify-signature/src/extension.rs b/substrate/frame/verify-signature/src/extension.rs index 4490a0a600bb..d48991e7a1da 100644 --- a/substrate/frame/verify-signature/src/extension.rs +++ b/substrate/frame/verify-signature/src/extension.rs @@ -20,7 +20,7 @@ use crate::{Config, WeightInfo}; use codec::{Decode, Encode}; -use frame_support::traits::OriginTrait; +use frame_support::{pallet_prelude::TransactionSource, traits::OriginTrait}; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::{ @@ -113,6 +113,7 @@ where _len: usize, _: (), inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, diff --git a/substrate/frame/verify-signature/src/tests.rs b/substrate/frame/verify-signature/src/tests.rs index 3e4c8db12fe2..505a33a883c2 100644 --- a/substrate/frame/verify-signature/src/tests.rs +++ b/substrate/frame/verify-signature/src/tests.rs @@ -25,7 +25,7 @@ use extension::VerifySignature; use frame_support::{ derive_impl, dispatch::GetDispatchInfo, - pallet_prelude::{InvalidTransaction, TransactionValidityError}, + pallet_prelude::{InvalidTransaction, TransactionSource, TransactionValidityError}, traits::OriginTrait, }; use frame_system::Call as SystemCall; @@ -84,7 +84,7 @@ fn verification_works() { let info = call.get_dispatch_info(); let (_, _, origin) = VerifySignature::::new_with_signature(sig, who) - .validate_only(None.into(), &call, &info, 0) + .validate_only(None.into(), &call, &info, 0, TransactionSource::External) .unwrap(); assert_eq!(origin.as_signer().unwrap(), &who) } @@ -98,7 +98,7 @@ fn bad_signature() { assert_eq!( VerifySignature::::new_with_signature(sig, who) - .validate_only(None.into(), &call, &info, 0) + .validate_only(None.into(), &call, &info, 0, TransactionSource::External) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::BadProof) ); @@ -113,7 +113,7 @@ fn bad_starting_origin() { assert_eq!( VerifySignature::::new_with_signature(sig, who) - .validate_only(Some(42).into(), &call, &info, 0) + .validate_only(Some(42).into(), &call, &info, 0, TransactionSource::External) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::BadSigner) ); @@ -126,7 +126,7 @@ fn disabled_extension_works() { let info = call.get_dispatch_info(); let (_, _, origin) = VerifySignature::::new_disabled() - .validate_only(Some(who).into(), &call, &info, 0) + .validate_only(Some(who).into(), &call, &info, 0, TransactionSource::External) .unwrap(); assert_eq!(origin.as_signer().unwrap(), &who) } diff --git a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs index e2ecd5ed6da7..521f54bf4afd 100644 --- a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs @@ -85,10 +85,11 @@ where }, ExtrinsicFormat::Signed(ref signer, ref extension) => { let origin = Some(signer.clone()).into(); - extension.validate_only(origin, &self.function, info, len).map(|x| x.0) + extension.validate_only(origin, &self.function, info, len, source).map(|x| x.0) }, - ExtrinsicFormat::General(ref extension) => - extension.validate_only(None.into(), &self.function, info, len).map(|x| x.0), + ExtrinsicFormat::General(ref extension) => extension + .validate_only(None.into(), &self.function, info, len, source) + .map(|x| x.0), } } diff --git a/substrate/primitives/runtime/src/traits/transaction_extension/as_transaction_extension.rs b/substrate/primitives/runtime/src/traits/transaction_extension/as_transaction_extension.rs index a5179748673f..282064078fe3 100644 --- a/substrate/primitives/runtime/src/traits/transaction_extension/as_transaction_extension.rs +++ b/substrate/primitives/runtime/src/traits/transaction_extension/as_transaction_extension.rs @@ -25,7 +25,7 @@ use sp_core::RuntimeDebug; use crate::{ traits::{AsSystemOriginSigner, SignedExtension, ValidateResult}, - transaction_validity::InvalidTransaction, + transaction_validity::{InvalidTransaction, TransactionSource}, }; use super::*; @@ -74,6 +74,7 @@ where len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> ValidateResult { let who = origin.as_system_origin_signer().ok_or(InvalidTransaction::BadSigner)?; let r = self.0.validate(who, call, info, len)?; diff --git a/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs b/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs index e2fb556bf9d3..19c8a2b2d496 100644 --- a/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs +++ b/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs @@ -17,7 +17,10 @@ //! The [DispatchTransaction] trait. -use crate::{traits::AsTransactionAuthorizedOrigin, transaction_validity::InvalidTransaction}; +use crate::{ + traits::AsTransactionAuthorizedOrigin, + transaction_validity::{InvalidTransaction, TransactionSource}, +}; use super::*; @@ -45,6 +48,7 @@ pub trait DispatchTransaction { call: &Call, info: &Self::Info, len: usize, + source: TransactionSource, ) -> Result<(ValidTransaction, Self::Val, Self::Origin), TransactionValidityError>; /// Validate and prepare a transaction, ready for dispatch. fn validate_and_prepare( @@ -93,8 +97,9 @@ where call: &Call, info: &DispatchInfoOf, len: usize, + source: TransactionSource, ) -> Result<(ValidTransaction, T::Val, Self::Origin), TransactionValidityError> { - match self.validate(origin, call, info, len, self.implicit()?, call) { + match self.validate(origin, call, info, len, self.implicit()?, call, source) { // After validation, some origin must have been authorized. Ok((_, _, origin)) if !origin.is_transaction_authorized() => Err(InvalidTransaction::UnknownOrigin.into()), @@ -108,7 +113,8 @@ where info: &DispatchInfoOf, len: usize, ) -> Result<(T::Pre, Self::Origin), TransactionValidityError> { - let (_, val, origin) = self.validate_only(origin, call, info, len)?; + let (_, val, origin) = + self.validate_only(origin, call, info, len, TransactionSource::InBlock)?; let pre = self.prepare(val, &origin, &call, info, len)?; Ok((pre, origin)) } diff --git a/substrate/primitives/runtime/src/traits/transaction_extension/mod.rs b/substrate/primitives/runtime/src/traits/transaction_extension/mod.rs index 58cd0974661a..f8c5dc6a724e 100644 --- a/substrate/primitives/runtime/src/traits/transaction_extension/mod.rs +++ b/substrate/primitives/runtime/src/traits/transaction_extension/mod.rs @@ -19,7 +19,9 @@ use crate::{ scale_info::{MetaType, StaticTypeInfo}, - transaction_validity::{TransactionValidity, TransactionValidityError, ValidTransaction}, + transaction_validity::{ + TransactionSource, TransactionValidity, TransactionValidityError, ValidTransaction, + }, DispatchResult, }; use codec::{Codec, Decode, Encode}; @@ -243,6 +245,7 @@ pub trait TransactionExtension: len: usize, self_implicit: Self::Implicit, inherited_implication: &impl Encode, + source: TransactionSource, ) -> ValidateResult; /// Do any pre-flight stuff for a transaction after validation. @@ -429,6 +432,7 @@ macro_rules! impl_tx_ext_default { _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl $crate::codec::Encode, + _source: $crate::transaction_validity::TransactionSource, ) -> $crate::traits::ValidateResult { Ok((Default::default(), Default::default(), origin)) } @@ -496,6 +500,7 @@ impl TransactionExtension for Tuple { len: usize, self_implicit: Self::Implicit, inherited_implication: &impl Encode, + source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, @@ -521,7 +526,7 @@ impl TransactionExtension for Tuple { // passed into the next items in this pipeline-tuple. &following_implicit_implications, ); - Tuple.validate(origin, call, info, len, item_implicit, &implications)? + Tuple.validate(origin, call, info, len, item_implicit, &implications, source)? }; let valid = valid.combine_with(item_valid); let val = val.push_back(item_val); @@ -616,6 +621,7 @@ impl TransactionExtension for () { _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, (), ::RuntimeOrigin), TransactionValidityError, diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 1314d9d6dd45..d565f65e8d36 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -292,6 +292,7 @@ impl sp_runtime::traits::TransactionExtension for CheckSubstrateCal _len: usize, _self_implicit: Self::Implicit, _inherited_implication: &impl Encode, + _source: TransactionSource, ) -> Result< (ValidTransaction, Self::Val, ::RuntimeOrigin), TransactionValidityError, @@ -1053,7 +1054,7 @@ mod tests { use sp_core::{storage::well_known_keys::HEAP_PAGES, traits::CallContext}; use sp_runtime::{ traits::{DispatchTransaction, Hash as _}, - transaction_validity::{InvalidTransaction, ValidTransaction}, + transaction_validity::{InvalidTransaction, TransactionSource::External, ValidTransaction}, }; use substrate_test_runtime_client::{ prelude::*, runtime::TestAPI, DefaultTestClientBuilderExt, TestClientBuilder, @@ -1211,6 +1212,7 @@ mod tests { &ExtrinsicBuilder::new_call_with_priority(16).build().function, &info, len, + External, ) .unwrap() .0 @@ -1225,6 +1227,7 @@ mod tests { &ExtrinsicBuilder::new_call_do_not_propagate().build().function, &info, len, + External, ) .unwrap() .0 From 95d98e6d612db4e85ba2c71bbf37b5e606e31168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Gil?= Date: Wed, 13 Nov 2024 10:43:40 +0100 Subject: [PATCH 085/166] remove pallet::getter from pallet-staking (#6184) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Part of https://github.com/paritytech/polkadot-sdk/issues/3326 Removes all pallet::getter occurrences from pallet-staking and replaces them with explicit implementations. Adds tests to verify that retrieval of affected entities works as expected so via storage::getter. ## Review Notes 1. Traits added to the `derive` attribute are used in tests (either directly or indirectly). 2. The getters had to be placed in a separate impl block since the other one is annotated with `#[pallet::call]` and that requires `#[pallet::call_index(0)]` annotation on each function in that block. So I thought it's better to separate them. --------- Co-authored-by: Dónal Murray Co-authored-by: Guillaume Thiolliere --- polkadot/runtime/westend/src/lib.rs | 2 +- prdoc/pr_6184.prdoc | 24 + substrate/frame/babe/src/mock.rs | 2 +- substrate/frame/babe/src/tests.rs | 2 +- substrate/frame/beefy/src/mock.rs | 2 +- substrate/frame/beefy/src/tests.rs | 4 +- .../test-staking-e2e/src/lib.rs | 2 +- .../test-staking-e2e/src/mock.rs | 10 +- substrate/frame/grandpa/src/mock.rs | 2 +- substrate/frame/grandpa/src/tests.rs | 2 +- .../test-delegate-stake/src/lib.rs | 18 +- .../test-transfer-stake/src/lib.rs | 12 +- substrate/frame/root-offences/src/lib.rs | 2 +- substrate/frame/root-offences/src/mock.rs | 2 +- substrate/frame/staking/src/benchmarking.rs | 2 +- substrate/frame/staking/src/lib.rs | 4 +- substrate/frame/staking/src/mock.rs | 18 +- substrate/frame/staking/src/pallet/impls.rs | 53 +- substrate/frame/staking/src/pallet/mod.rs | 177 ++++++- substrate/frame/staking/src/testing_utils.rs | 2 +- substrate/frame/staking/src/tests.rs | 480 +++++++++++++++--- 21 files changed, 657 insertions(+), 165 deletions(-) create mode 100644 prdoc/pr_6184.prdoc diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 4c04af111f81..993010cbce66 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -543,7 +543,7 @@ impl Get for MaybeSignedPhase { fn get() -> u32 { // 1 day = 4 eras -> 1 week = 28 eras. We want to disable signed phase once a week to test // the fallback unsigned phase is able to compute elections on Westend. - if Staking::current_era().unwrap_or(1) % 28 == 0 { + if pallet_staking::CurrentEra::::get().unwrap_or(1) % 28 == 0 { 0 } else { SignedPhase::get() diff --git a/prdoc/pr_6184.prdoc b/prdoc/pr_6184.prdoc new file mode 100644 index 000000000000..e05a5884e930 --- /dev/null +++ b/prdoc/pr_6184.prdoc @@ -0,0 +1,24 @@ +title: Remove pallet::getter from pallet-staking +doc: + - audience: Runtime Dev + description: | + This PR removes all pallet::getter occurrences from pallet-staking and replaces them with explicit implementations. + It also adds tests to verify that retrieval of affected entities works as expected so via storage::getter. + +crates: + - name: pallet-babe + bump: patch + - name: pallet-beefy + bump: patch + - name: pallet-election-provider-multi-phase + bump: patch + - name: pallet-grandpa + bump: patch + - name: pallet-nomination-pools + bump: patch + - name: pallet-root-offences + bump: patch + - name: westend-runtime + bump: patch + - name: pallet-staking + bump: patch \ No newline at end of file diff --git a/substrate/frame/babe/src/mock.rs b/substrate/frame/babe/src/mock.rs index c2e24c73a7bd..23857470adc4 100644 --- a/substrate/frame/babe/src/mock.rs +++ b/substrate/frame/babe/src/mock.rs @@ -239,7 +239,7 @@ pub fn start_session(session_index: SessionIndex) { /// Progress to the first block at the given era pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } pub fn make_primary_pre_digest( diff --git a/substrate/frame/babe/src/tests.rs b/substrate/frame/babe/src/tests.rs index eca958160239..5210d9289bcd 100644 --- a/substrate/frame/babe/src/tests.rs +++ b/substrate/frame/babe/src/tests.rs @@ -414,7 +414,7 @@ fn disabled_validators_cannot_author_blocks() { // so we should still be able to author blocks start_era(2); - assert_eq!(Staking::current_era().unwrap(), 2); + assert_eq!(pallet_staking::CurrentEra::::get().unwrap(), 2); // let's disable the validator at index 0 Session::disable_index(0); diff --git a/substrate/frame/beefy/src/mock.rs b/substrate/frame/beefy/src/mock.rs index 2b75c4107414..7ae41c609180 100644 --- a/substrate/frame/beefy/src/mock.rs +++ b/substrate/frame/beefy/src/mock.rs @@ -366,5 +366,5 @@ pub fn start_session(session_index: SessionIndex) { pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } diff --git a/substrate/frame/beefy/src/tests.rs b/substrate/frame/beefy/src/tests.rs index d75237205cac..89645d21f6ba 100644 --- a/substrate/frame/beefy/src/tests.rs +++ b/substrate/frame/beefy/src/tests.rs @@ -313,7 +313,7 @@ fn report_equivocation_current_set_works(mut f: impl ReportEquivocationFn) { let authorities = test_authorities(); ExtBuilder::default().add_authorities(authorities).build_and_execute(|| { - assert_eq!(Staking::current_era(), Some(0)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(0)); assert_eq!(Session::current_index(), 0); start_era(1); @@ -906,7 +906,7 @@ fn report_fork_voting_invalid_context() { let mut era = 1; let block_num = ext.execute_with(|| { - assert_eq!(Staking::current_era(), Some(0)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(0)); assert_eq!(Session::current_index(), 0); start_era(era); diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs index 135149694387..41928905ed95 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs @@ -47,7 +47,7 @@ fn log_current_time() { "block: {:?}, session: {:?}, era: {:?}, EPM phase: {:?} ts: {:?}", System::block_number(), Session::current_index(), - Staking::current_era(), + pallet_staking::CurrentEra::::get(), CurrentPhase::::get(), Now::::get() ); diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index 360f14913fcc..b182ddec77ab 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -49,7 +49,7 @@ use pallet_election_provider_multi_phase::{ unsigned::MinerConfig, Call, CurrentPhase, ElectionCompute, GeometricDepositBase, QueuedSolution, SolutionAccuracyOf, }; -use pallet_staking::StakerStatus; +use pallet_staking::{ActiveEra, CurrentEra, ErasStartSessionIndex, StakerStatus}; use parking_lot::RwLock; use std::sync::Arc; @@ -806,11 +806,11 @@ pub(crate) fn start_active_era( } pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index + ActiveEra::::get().unwrap().index } pub(crate) fn current_era() -> EraIndex { - Staking::current_era().unwrap() + CurrentEra::::get().unwrap() } // Fast forward until EPM signed phase. @@ -862,11 +862,11 @@ pub(crate) fn on_offence_now( >], slash_fraction: &[Perbill], ) { - let now = Staking::active_era().unwrap().index; + let now = ActiveEra::::get().unwrap().index; let _ = Staking::on_offence( offenders, slash_fraction, - Staking::eras_start_session_index(now).unwrap(), + ErasStartSessionIndex::::get(now).unwrap(), ); } diff --git a/substrate/frame/grandpa/src/mock.rs b/substrate/frame/grandpa/src/mock.rs index cf4c29003a71..87369c23948c 100644 --- a/substrate/frame/grandpa/src/mock.rs +++ b/substrate/frame/grandpa/src/mock.rs @@ -297,7 +297,7 @@ pub fn start_session(session_index: SessionIndex) { pub fn start_era(era_index: EraIndex) { start_session((era_index * 3).into()); - assert_eq!(Staking::current_era(), Some(era_index)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(era_index)); } pub fn initialize_block(number: u64, parent_hash: H256) { diff --git a/substrate/frame/grandpa/src/tests.rs b/substrate/frame/grandpa/src/tests.rs index e1e963ce564a..383f77f00de7 100644 --- a/substrate/frame/grandpa/src/tests.rs +++ b/substrate/frame/grandpa/src/tests.rs @@ -319,7 +319,7 @@ fn report_equivocation_current_set_works() { let authorities = test_authorities(); new_test_ext_raw_authorities(authorities).execute_with(|| { - assert_eq!(Staking::current_era(), Some(0)); + assert_eq!(pallet_staking::CurrentEra::::get(), Some(0)); assert_eq!(Session::current_index(), 0); start_era(1); diff --git a/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs b/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs index 7fee2a0bdb23..40025cdbb3cd 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs +++ b/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs @@ -41,7 +41,7 @@ use sp_staking::Agent; fn pool_lifecycle_e2e() { new_test_ext().execute_with(|| { assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -204,7 +204,7 @@ fn pool_lifecycle_e2e() { fn pool_chill_e2e() { new_test_ext().execute_with(|| { assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -330,7 +330,7 @@ fn pool_slash_e2e() { new_test_ext().execute_with(|| { ExistentialDeposit::set(1); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -540,7 +540,7 @@ fn pool_slash_proportional() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -758,7 +758,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -837,7 +837,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -914,7 +914,7 @@ fn pool_migration_e2e() { new_test_ext().execute_with(|| { LegacyAdapter::set(true); assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool with TransferStake strategy. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -1192,7 +1192,7 @@ fn disable_pool_operations_on_non_migrated() { new_test_ext().execute_with(|| { LegacyAdapter::set(true); assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool with TransferStake strategy. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -1369,7 +1369,7 @@ fn pool_no_dangling_delegation() { new_test_ext().execute_with(|| { ExistentialDeposit::set(1); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // pool creator let alice = 10; let bob = 20; diff --git a/substrate/frame/nomination-pools/test-transfer-stake/src/lib.rs b/substrate/frame/nomination-pools/test-transfer-stake/src/lib.rs index 28e978bba0e5..cc39cfee91c8 100644 --- a/substrate/frame/nomination-pools/test-transfer-stake/src/lib.rs +++ b/substrate/frame/nomination-pools/test-transfer-stake/src/lib.rs @@ -34,7 +34,7 @@ use sp_runtime::{bounded_btree_map, traits::Zero}; fn pool_lifecycle_e2e() { new_test_ext().execute_with(|| { assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -286,7 +286,7 @@ fn destroy_pool_with_erroneous_consumer() { fn pool_chill_e2e() { new_test_ext().execute_with(|| { assert_eq!(Balances::minimum_balance(), 5); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 50, 10, 10, 10)); @@ -412,7 +412,7 @@ fn pool_slash_e2e() { new_test_ext().execute_with(|| { ExistentialDeposit::set(1); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -622,7 +622,7 @@ fn pool_slash_proportional() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -759,7 +759,7 @@ fn pool_slash_non_proportional_only_bonded_pool() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -838,7 +838,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { ExistentialDeposit::set(1); BondingDuration::set(28); assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(Staking::current_era(), None); + assert_eq!(CurrentEra::::get(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); diff --git a/substrate/frame/root-offences/src/lib.rs b/substrate/frame/root-offences/src/lib.rs index 6531080b8d10..fd6ffc55e40c 100644 --- a/substrate/frame/root-offences/src/lib.rs +++ b/substrate/frame/root-offences/src/lib.rs @@ -106,7 +106,7 @@ pub mod pallet { fn get_offence_details( offenders: Vec<(T::AccountId, Perbill)>, ) -> Result>, DispatchError> { - let now = Staking::::active_era() + let now = pallet_staking::ActiveEra::::get() .map(|e| e.index) .ok_or(Error::::FailedToGetActiveEra)?; diff --git a/substrate/frame/root-offences/src/mock.rs b/substrate/frame/root-offences/src/mock.rs index af073d7672cf..a27fb36f64a6 100644 --- a/substrate/frame/root-offences/src/mock.rs +++ b/substrate/frame/root-offences/src/mock.rs @@ -296,5 +296,5 @@ pub(crate) fn run_to_block(n: BlockNumber) { } pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index + pallet_staking::ActiveEra::::get().unwrap().index } diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index 96bd3860542f..d842186d5025 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -708,7 +708,7 @@ mod benchmarks { >::insert( current_era, validator.clone(), - >::validators(&validator), + Validators::::get(&validator), ); let caller = whitelisted_caller(); diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index 19d999109d8d..a4a6e71af0df 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -996,7 +996,7 @@ impl Convert for ExposureOf { fn convert(validator: T::AccountId) -> Option>> { - >::active_era() + ActiveEra::::get() .map(|active_era| >::eras_stakers(active_era.index, &validator)) } } @@ -1326,7 +1326,7 @@ impl DisablingStrategy log!( debug, "Won't disable: current_era {:?} > slash_era {:?}", - Pallet::::current_era().unwrap_or_default(), + CurrentEra::::get().unwrap_or_default(), slash_era ); return None diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 4a0209fc5b08..2d3446d2dabc 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -568,11 +568,11 @@ impl ExtBuilder { } pub(crate) fn active_era() -> EraIndex { - Staking::active_era().unwrap().index + pallet_staking::ActiveEra::::get().unwrap().index } pub(crate) fn current_era() -> EraIndex { - Staking::current_era().unwrap() + pallet_staking::CurrentEra::::get().unwrap() } pub(crate) fn bond(who: AccountId, val: Balance) { @@ -663,7 +663,7 @@ pub(crate) fn start_active_era(era_index: EraIndex) { pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { let (payout, _rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), + pallet_staking::ErasTotalStake::::get(active_era()), pallet_balances::TotalIssuance::::get(), duration, ); @@ -673,7 +673,7 @@ pub(crate) fn current_total_payout_for_duration(duration: u64) -> Balance { pub(crate) fn maximum_payout_for_duration(duration: u64) -> Balance { let (payout, rest) = ::EraPayout::era_payout( - Staking::eras_total_stake(active_era()), + pallet_staking::ErasTotalStake::::get(active_era()), pallet_balances::TotalIssuance::::get(), duration, ); @@ -732,11 +732,11 @@ pub(crate) fn on_offence_in_era( } } - if Staking::active_era().unwrap().index == era { + if pallet_staking::ActiveEra::::get().unwrap().index == era { let _ = Staking::on_offence( offenders, slash_fraction, - Staking::eras_start_session_index(era).unwrap(), + pallet_staking::ErasStartSessionIndex::::get(era).unwrap(), ); } else { panic!("cannot slash in era {}", era); @@ -750,7 +750,7 @@ pub(crate) fn on_offence_now( >], slash_fraction: &[Perbill], ) { - let now = Staking::active_era().unwrap().index; + let now = pallet_staking::ActiveEra::::get().unwrap().index; on_offence_in_era(offenders, slash_fraction, now) } @@ -889,10 +889,10 @@ macro_rules! assert_session_era { $session, ); assert_eq!( - Staking::current_era().unwrap(), + CurrentEra::::get().unwrap(), $era, "wrong current era {} != {}", - Staking::current_era().unwrap(), + CurrentEra::::get().unwrap(), $era, ); }; diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index d3423d82769d..972d0f3d47b9 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -193,7 +193,7 @@ impl Pallet { ) -> Result { let mut ledger = Self::ledger(Controller(controller.clone()))?; let (stash, old_total) = (ledger.stash.clone(), ledger.total); - if let Some(current_era) = Self::current_era() { + if let Some(current_era) = CurrentEra::::get() { ledger = ledger.consolidate_unlocked(current_era) } let new_total = ledger.total; @@ -450,9 +450,9 @@ impl Pallet { session_index: SessionIndex, is_genesis: bool, ) -> Option>> { - if let Some(current_era) = Self::current_era() { + if let Some(current_era) = CurrentEra::::get() { // Initial era has been set. - let current_era_start_session_index = Self::eras_start_session_index(current_era) + let current_era_start_session_index = ErasStartSessionIndex::::get(current_era) .unwrap_or_else(|| { frame_support::print("Error: start_session_index must be set for current_era"); 0 @@ -492,12 +492,12 @@ impl Pallet { /// Start a session potentially starting an era. fn start_session(start_session: SessionIndex) { - let next_active_era = Self::active_era().map(|e| e.index + 1).unwrap_or(0); + let next_active_era = ActiveEra::::get().map(|e| e.index + 1).unwrap_or(0); // This is only `Some` when current era has already progressed to the next era, while the // active era is one behind (i.e. in the *last session of the active era*, or *first session // of the new current era*, depending on how you look at it). if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(next_active_era) + ErasStartSessionIndex::::get(next_active_era) { if next_active_era_start_session_index == start_session { Self::start_era(start_session); @@ -517,9 +517,9 @@ impl Pallet { /// End a session potentially ending an era. fn end_session(session_index: SessionIndex) { - if let Some(active_era) = Self::active_era() { + if let Some(active_era) = ActiveEra::::get() { if let Some(next_active_era_start_session_index) = - Self::eras_start_session_index(active_era.index + 1) + ErasStartSessionIndex::::get(active_era.index + 1) { if next_active_era_start_session_index == session_index + 1 { Self::end_era(active_era, session_index); @@ -577,7 +577,7 @@ impl Pallet { let era_duration = (now_as_millis_u64.defensive_saturating_sub(active_era_start)) .saturated_into::(); - let staked = Self::eras_total_stake(&active_era.index); + let staked = ErasTotalStake::::get(&active_era.index); let issuance = asset::total_issuance::(); let (validator_payout, remainder) = @@ -668,7 +668,7 @@ impl Pallet { }; let exposures = Self::collect_exposures(election_result); - if (exposures.len() as u32) < Self::minimum_validator_count().max(1) { + if (exposures.len() as u32) < MinimumValidatorCount::::get().max(1) { // Session will panic if we ever return an empty validator set, thus max(1) ^^. match CurrentEra::::get() { Some(current_era) if current_era > 0 => log!( @@ -677,7 +677,7 @@ impl Pallet { elected, minimum is {})", CurrentEra::::get().unwrap_or(0), exposures.len(), - Self::minimum_validator_count(), + MinimumValidatorCount::::get(), ), None => { // The initial era is allowed to have no exposures. @@ -729,7 +729,7 @@ impl Pallet { // Collect the pref of all winners. for stash in &elected_stashes { - let pref = Self::validators(stash); + let pref = Validators::::get(stash); >::insert(&new_planned_era, stash, pref); } @@ -854,7 +854,7 @@ impl Pallet { /// /// COMPLEXITY: Complexity is `number_of_validator_to_reward x current_elected_len`. pub fn reward_by_ids(validators_points: impl IntoIterator) { - if let Some(active_era) = Self::active_era() { + if let Some(active_era) = ActiveEra::::get() { >::mutate(active_era.index, |era_rewards| { for (validator, points) in validators_points.into_iter() { *era_rewards.individual.entry(validator).or_default() += points; @@ -1196,7 +1196,7 @@ impl ElectionDataProvider for Pallet { fn desired_targets() -> data_provider::Result { Self::register_weight(T::DbWeight::get().reads(1)); - Ok(Self::validator_count()) + Ok(ValidatorCount::::get()) } fn electing_voters(bounds: DataProviderBounds) -> data_provider::Result>> { @@ -1229,10 +1229,10 @@ impl ElectionDataProvider for Pallet { } fn next_election_prediction(now: BlockNumberFor) -> BlockNumberFor { - let current_era = Self::current_era().unwrap_or(0); - let current_session = Self::current_planned_session(); + let current_era = CurrentEra::::get().unwrap_or(0); + let current_session = CurrentPlannedSession::::get(); let current_era_start_session_index = - Self::eras_start_session_index(current_era).unwrap_or(0); + ErasStartSessionIndex::::get(current_era).unwrap_or(0); // Number of session in the current era or the maximum session per era if reached. let era_progress = current_session .saturating_sub(current_era_start_session_index) @@ -1366,7 +1366,7 @@ impl historical::SessionManager Option>)>> { >::new_session(new_index).map(|validators| { - let current_era = Self::current_era() + let current_era = CurrentEra::::get() // Must be some as a new era has been created. .unwrap_or(0); @@ -1384,7 +1384,7 @@ impl historical::SessionManager Option>)>> { >::new_session_genesis(new_index).map( |validators| { - let current_era = Self::current_era() + let current_era = CurrentEra::::get() // Must be some as a new era has been created. .unwrap_or(0); @@ -1449,7 +1449,7 @@ where }; let active_era = { - let active_era = Self::active_era(); + let active_era = ActiveEra::::get(); add_db_reads_writes(1, 0); if active_era.is_none() { // This offence need not be re-submitted. @@ -1457,7 +1457,7 @@ where } active_era.expect("value checked not to be `None`; qed").index }; - let active_era_start_session_index = Self::eras_start_session_index(active_era) + let active_era_start_session_index = ErasStartSessionIndex::::get(active_era) .unwrap_or_else(|| { frame_support::print("Error: start_session_index must be set for current_era"); 0 @@ -1486,7 +1486,7 @@ where let slash_defer_duration = T::SlashDeferDuration::get(); - let invulnerables = Self::invulnerables(); + let invulnerables = Invulnerables::::get(); add_db_reads_writes(1, 0); for (details, slash_fraction) in offenders.iter().zip(slash_fraction) { @@ -1761,7 +1761,7 @@ impl StakingInterface for Pallet { } fn current_era() -> EraIndex { - Self::current_era().unwrap_or(Zero::zero()) + CurrentEra::::get().unwrap_or(Zero::zero()) } fn stake(who: &Self::AccountId) -> Result>, DispatchError> { @@ -1842,7 +1842,8 @@ impl StakingInterface for Pallet { } fn force_unstake(who: Self::AccountId) -> sp_runtime::DispatchResult { - let num_slashing_spans = Self::slashing_spans(&who).map_or(0, |s| s.iter().count() as u32); + let num_slashing_spans = + SlashingSpans::::get(&who).map_or(0, |s| s.iter().count() as u32); Self::force_unstake(RawOrigin::Root.into(), who.clone(), num_slashing_spans) } @@ -2142,7 +2143,7 @@ impl Pallet { /// * For each era exposed validator, check if the exposure total is sane (exposure.total = /// exposure.own + exposure.own). fn check_exposures() -> Result<(), TryRuntimeError> { - let era = Self::active_era().unwrap().index; + let era = ActiveEra::::get().unwrap().index; ErasStakers::::iter_prefix_values(era) .map(|expo| { ensure!( @@ -2170,7 +2171,7 @@ impl Pallet { // Sanity check for the paged exposure of the active era. let mut exposures: BTreeMap>> = BTreeMap::new(); - let era = Self::active_era().unwrap().index; + let era = ActiveEra::::get().unwrap().index; let accumulator_default = PagedExposureMetadata { total: Zero::zero(), own: Zero::zero(), @@ -2232,7 +2233,7 @@ impl Pallet { fn check_nominators() -> Result<(), TryRuntimeError> { // a check per nominator to ensure their entire stake is correctly distributed. Will only // kick-in if the nomination was submitted before the current era. - let era = Self::active_era().unwrap().index; + let era = ActiveEra::::get().unwrap().index; // cache era exposures to avoid too many db reads. let era_exposures = T::SessionInterface::validators() diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index 5210bef853b2..d33b863a521a 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -351,19 +351,16 @@ pub mod pallet { /// The ideal number of active validators. #[pallet::storage] - #[pallet::getter(fn validator_count)] pub type ValidatorCount = StorageValue<_, u32, ValueQuery>; /// Minimum number of staking participants before emergency conditions are imposed. #[pallet::storage] - #[pallet::getter(fn minimum_validator_count)] pub type MinimumValidatorCount = StorageValue<_, u32, ValueQuery>; /// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're /// easy to initialize and the performance hit is minimal (we expect no more than four /// invulnerables) and restricted to testnets. #[pallet::storage] - #[pallet::getter(fn invulnerables)] #[pallet::unbounded] pub type Invulnerables = StorageValue<_, Vec, ValueQuery>; @@ -409,7 +406,6 @@ pub mod pallet { /// /// TWOX-NOTE: SAFE since `AccountId` is a secure hash. #[pallet::storage] - #[pallet::getter(fn validators)] pub type Validators = CountedStorageMap<_, Twox64Concat, T::AccountId, ValidatorPrefs, ValueQuery>; @@ -439,7 +435,6 @@ pub mod pallet { /// /// TWOX-NOTE: SAFE since `AccountId` is a secure hash. #[pallet::storage] - #[pallet::getter(fn nominators)] pub type Nominators = CountedStorageMap<_, Twox64Concat, T::AccountId, Nominations>; @@ -463,7 +458,6 @@ pub mod pallet { /// This is the latest planned era, depending on how the Session pallet queues the validator /// set, it might be active or not. #[pallet::storage] - #[pallet::getter(fn current_era)] pub type CurrentEra = StorageValue<_, EraIndex>; /// The active era information, it holds index and start. @@ -471,7 +465,6 @@ pub mod pallet { /// The active era is the era being currently rewarded. Validator set of this era must be /// equal to [`SessionInterface::validators`]. #[pallet::storage] - #[pallet::getter(fn active_era)] pub type ActiveEra = StorageValue<_, ActiveEraInfo>; /// The session index at which the era start for the last [`Config::HistoryDepth`] eras. @@ -479,7 +472,6 @@ pub mod pallet { /// Note: This tracks the starting session (i.e. session index when era start being active) /// for the eras in `[CurrentEra - HISTORY_DEPTH, CurrentEra]`. #[pallet::storage] - #[pallet::getter(fn eras_start_session_index)] pub type ErasStartSessionIndex = StorageMap<_, Twox64Concat, EraIndex, SessionIndex>; /// Exposure of validator at era. @@ -543,7 +535,6 @@ pub mod pallet { /// Note: Deprecated since v14. Use `EraInfo` instead to work with exposures. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn eras_stakers_clipped)] pub type ErasStakersClipped = StorageDoubleMap< _, Twox64Concat, @@ -580,7 +571,6 @@ pub mod pallet { /// /// It is removed after [`Config::HistoryDepth`] eras. #[pallet::storage] - #[pallet::getter(fn claimed_rewards)] #[pallet::unbounded] pub type ClaimedRewards = StorageDoubleMap< _, @@ -599,7 +589,6 @@ pub mod pallet { /// Is it removed after [`Config::HistoryDepth`] eras. // If prefs hasn't been set or has been removed then 0 commission is returned. #[pallet::storage] - #[pallet::getter(fn eras_validator_prefs)] pub type ErasValidatorPrefs = StorageDoubleMap< _, Twox64Concat, @@ -614,27 +603,23 @@ pub mod pallet { /// /// Eras that haven't finished yet or has been removed doesn't have reward. #[pallet::storage] - #[pallet::getter(fn eras_validator_reward)] pub type ErasValidatorReward = StorageMap<_, Twox64Concat, EraIndex, BalanceOf>; /// Rewards for the last [`Config::HistoryDepth`] eras. /// If reward hasn't been set or has been removed then 0 reward is returned. #[pallet::storage] #[pallet::unbounded] - #[pallet::getter(fn eras_reward_points)] pub type ErasRewardPoints = StorageMap<_, Twox64Concat, EraIndex, EraRewardPoints, ValueQuery>; /// The total amount staked for the last [`Config::HistoryDepth`] eras. /// If total hasn't been set or has been removed then 0 stake is returned. #[pallet::storage] - #[pallet::getter(fn eras_total_stake)] pub type ErasTotalStake = StorageMap<_, Twox64Concat, EraIndex, BalanceOf, ValueQuery>; /// Mode of era forcing. #[pallet::storage] - #[pallet::getter(fn force_era)] pub type ForceEra = StorageValue<_, Forcing, ValueQuery>; /// Maximum staked rewards, i.e. the percentage of the era inflation that @@ -647,13 +632,11 @@ pub mod pallet { /// /// The rest of the slashed value is handled by the `Slash`. #[pallet::storage] - #[pallet::getter(fn slash_reward_fraction)] pub type SlashRewardFraction = StorageValue<_, Perbill, ValueQuery>; /// The amount of currency given to reporters of a slash event which was /// canceled by extraordinary circumstances (e.g. governance). #[pallet::storage] - #[pallet::getter(fn canceled_payout)] pub type CanceledSlashPayout = StorageValue<_, BalanceOf, ValueQuery>; /// All unapplied slashes that are queued for later. @@ -695,7 +678,6 @@ pub mod pallet { /// Slashing spans for stash accounts. #[pallet::storage] - #[pallet::getter(fn slashing_spans)] #[pallet::unbounded] pub type SlashingSpans = StorageMap<_, Twox64Concat, T::AccountId, slashing::SlashingSpans>; @@ -715,7 +697,6 @@ pub mod pallet { /// /// This is basically in sync with the call to [`pallet_session::SessionManager::new_session`]. #[pallet::storage] - #[pallet::getter(fn current_planned_session)] pub type CurrentPlannedSession = StorageValue<_, SessionIndex, ValueQuery>; /// Indices of validators that have offended in the active era. The offenders are disabled for a @@ -950,7 +931,7 @@ pub mod pallet { fn on_finalize(_n: BlockNumberFor) { // Set the start of the first era. - if let Some(mut active_era) = Self::active_era() { + if let Some(mut active_era) = ActiveEra::::get() { if active_era.start.is_none() { let now_as_millis_u64 = T::UnixTime::now().as_millis().saturated_into::(); active_era.start = Some(now_as_millis_u64); @@ -991,6 +972,156 @@ pub mod pallet { } } + impl Pallet { + /// Get the ideal number of active validators. + pub fn validator_count() -> u32 { + ValidatorCount::::get() + } + + /// Get the minimum number of staking participants before emergency conditions are imposed. + pub fn minimum_validator_count() -> u32 { + MinimumValidatorCount::::get() + } + + /// Get the validators that may never be slashed or forcibly kicked out. + pub fn invulnerables() -> Vec { + Invulnerables::::get() + } + + /// Get the preferences of a given validator. + pub fn validators(account_id: EncodeLikeAccountId) -> ValidatorPrefs + where + EncodeLikeAccountId: codec::EncodeLike, + { + Validators::::get(account_id) + } + + /// Get the nomination preferences of a given nominator. + pub fn nominators( + account_id: EncodeLikeAccountId, + ) -> Option> + where + EncodeLikeAccountId: codec::EncodeLike, + { + Nominators::::get(account_id) + } + + /// Get the current era index. + pub fn current_era() -> Option { + CurrentEra::::get() + } + + /// Get the active era information. + pub fn active_era() -> Option { + ActiveEra::::get() + } + + /// Get the session index at which the era starts for the last [`Config::HistoryDepth`] + /// eras. + pub fn eras_start_session_index( + era_index: EncodeLikeEraIndex, + ) -> Option + where + EncodeLikeEraIndex: codec::EncodeLike, + { + ErasStartSessionIndex::::get(era_index) + } + + /// Get the clipped exposure of a given validator at an era. + pub fn eras_stakers_clipped( + era_index: EncodeLikeEraIndex, + account_id: EncodeLikeAccountId, + ) -> Exposure> + where + EncodeLikeEraIndex: codec::EncodeLike, + EncodeLikeAccountId: codec::EncodeLike, + { + ErasStakersClipped::::get(era_index, account_id) + } + + /// Get the paged history of claimed rewards by era for given validator. + pub fn claimed_rewards( + era_index: EncodeLikeEraIndex, + account_id: EncodeLikeAccountId, + ) -> Vec + where + EncodeLikeEraIndex: codec::EncodeLike, + EncodeLikeAccountId: codec::EncodeLike, + { + ClaimedRewards::::get(era_index, account_id) + } + + /// Get the preferences of given validator at given era. + pub fn eras_validator_prefs( + era_index: EncodeLikeEraIndex, + account_id: EncodeLikeAccountId, + ) -> ValidatorPrefs + where + EncodeLikeEraIndex: codec::EncodeLike, + EncodeLikeAccountId: codec::EncodeLike, + { + ErasValidatorPrefs::::get(era_index, account_id) + } + + /// Get the total validator era payout for the last [`Config::HistoryDepth`] eras. + pub fn eras_validator_reward( + era_index: EncodeLikeEraIndex, + ) -> Option> + where + EncodeLikeEraIndex: codec::EncodeLike, + { + ErasValidatorReward::::get(era_index) + } + + /// Get the rewards for the last [`Config::HistoryDepth`] eras. + pub fn eras_reward_points( + era_index: EncodeLikeEraIndex, + ) -> EraRewardPoints + where + EncodeLikeEraIndex: codec::EncodeLike, + { + ErasRewardPoints::::get(era_index) + } + + /// Get the total amount staked for the last [`Config::HistoryDepth`] eras. + pub fn eras_total_stake(era_index: EncodeLikeEraIndex) -> BalanceOf + where + EncodeLikeEraIndex: codec::EncodeLike, + { + ErasTotalStake::::get(era_index) + } + + /// Get the mode of era forcing. + pub fn force_era() -> Forcing { + ForceEra::::get() + } + + /// Get the percentage of the slash that is distributed to reporters. + pub fn slash_reward_fraction() -> Perbill { + SlashRewardFraction::::get() + } + + /// Get the amount of canceled slash payout. + pub fn canceled_payout() -> BalanceOf { + CanceledSlashPayout::::get() + } + + /// Get the slashing spans for given account. + pub fn slashing_spans( + account_id: EncodeLikeAccountId, + ) -> Option + where + EncodeLikeAccountId: codec::EncodeLike, + { + SlashingSpans::::get(account_id) + } + + /// Get the last planned session scheduled by the session pallet. + pub fn current_planned_session() -> SessionIndex { + CurrentPlannedSession::::get() + } + } + #[pallet::call] impl Pallet { /// Take the origin account as a stash and lock up `value` of its balance. `controller` will @@ -1107,7 +1238,7 @@ pub mod pallet { let maybe_withdraw_weight = { if unlocking == T::MaxUnlockingChunks::get() as usize { let real_num_slashing_spans = - Self::slashing_spans(&controller).map_or(0, |s| s.iter().count()); + SlashingSpans::::get(&controller).map_or(0, |s| s.iter().count()); Some(Self::do_withdraw_unbonded(&controller, real_num_slashing_spans as u32)?) } else { None @@ -1147,7 +1278,7 @@ pub mod pallet { ensure!(ledger.active >= min_active_bond, Error::::InsufficientBond); // Note: in case there is no current era it is fine to bond one era more. - let era = Self::current_era() + let era = CurrentEra::::get() .unwrap_or(0) .defensive_saturating_add(T::BondingDuration::get()); if let Some(chunk) = ledger.unlocking.last_mut().filter(|chunk| chunk.era == era) { @@ -1317,7 +1448,7 @@ pub mod pallet { let nominations = Nominations { targets, // Initial nominations are considered submitted at era 0. See `Nominations` doc. - submitted_in: Self::current_era().unwrap_or(0), + submitted_in: CurrentEra::::get().unwrap_or(0), suppressed: false, }; diff --git a/substrate/frame/staking/src/testing_utils.rs b/substrate/frame/staking/src/testing_utils.rs index efd4a40f1ab4..81337710aa90 100644 --- a/substrate/frame/staking/src/testing_utils.rs +++ b/substrate/frame/staking/src/testing_utils.rs @@ -236,5 +236,5 @@ pub fn create_validators_with_nominators_for_era( /// get the current era. pub fn current_era() -> EraIndex { - >::current_era().unwrap_or(0) + CurrentEra::::get().unwrap_or(0) } diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index d1dc6c3db659..ffa317618f1f 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -200,7 +200,7 @@ fn basic_setup_works() { legacy_claimed_rewards: bounded_vec![], } ); - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( Staking::eras_stakers(active_era(), &11), @@ -220,10 +220,10 @@ fn basic_setup_works() { ); // initial total stake = 1125 + 1375 - assert_eq!(Staking::eras_total_stake(active_era()), 2500); + assert_eq!(ErasTotalStake::::get(active_era()), 2500); // The number of validators required. - assert_eq!(Staking::validator_count(), 2); + assert_eq!(ValidatorCount::::get(), 2); // Initial Era and session assert_eq!(active_era(), 0); @@ -233,7 +233,7 @@ fn basic_setup_works() { assert_eq!(asset::stakeable_balance::(&10), 1); // New era is not being forced - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); }); } @@ -336,7 +336,7 @@ fn rewards_should_work() { assert_eq!(asset::total_balance::(&21), init_balance_21); assert_eq!(asset::total_balance::(&101), init_balance_101); assert_eq!( - Staking::eras_reward_points(active_era()), + ErasRewardPoints::::get(active_era()), EraRewardPoints { total: 50 * 3, individual: vec![(11, 100), (21, 50)].into_iter().collect(), @@ -530,8 +530,8 @@ fn less_than_needed_candidates_works() { .validator_count(4) .nominate(false) .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 4); - assert_eq!(Staking::minimum_validator_count(), 1); + assert_eq!(ValidatorCount::::get(), 4); + assert_eq!(MinimumValidatorCount::::get(), 1); assert_eq_uvec!(validator_controllers(), vec![31, 21, 11]); mock::start_active_era(1); @@ -1096,7 +1096,7 @@ fn reward_destination_works() { ); // (era 0, page 0) is claimed - assert_eq!(Staking::claimed_rewards(0, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(0, &11), vec![0]); // Change RewardDestination to Stash >::insert(&11, RewardDestination::Stash); @@ -1127,7 +1127,7 @@ fn reward_destination_works() { ); // (era 1, page 0) is claimed - assert_eq!(Staking::claimed_rewards(1, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(1, &11), vec![0]); // Change RewardDestination to Account >::insert(&11, RewardDestination::Account(11)); @@ -1159,7 +1159,7 @@ fn reward_destination_works() { ); // (era 2, page 0) is claimed - assert_eq!(Staking::claimed_rewards(2, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(2, &11), vec![0]); }); } @@ -1852,7 +1852,7 @@ fn reward_to_stake_works() { .set_stake(21, 2000) .try_state(false) .build_and_execute(|| { - assert_eq!(Staking::validator_count(), 2); + assert_eq!(ValidatorCount::::get(), 2); // Confirm account 10 and 20 are validators assert!(>::contains_key(&11) && >::contains_key(&21)); @@ -2281,7 +2281,7 @@ fn bond_with_duplicate_vote_should_be_ignored_by_election_provider_elected() { #[test] fn new_era_elects_correct_number_of_validators() { ExtBuilder::default().nominate(true).validator_count(1).build_and_execute(|| { - assert_eq!(Staking::validator_count(), 1); + assert_eq!(ValidatorCount::::get(), 1); assert_eq!(validator_controllers().len(), 1); Session::on_initialize(System::block_number()); @@ -2431,11 +2431,11 @@ fn era_is_always_same_length() { let session_per_era = >::get(); mock::start_active_era(1); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session_per_era); + assert_eq!(ErasStartSessionIndex::::get(current_era()).unwrap(), session_per_era); mock::start_active_era(2); assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), + ErasStartSessionIndex::::get(current_era()).unwrap(), session_per_era * 2u32 ); @@ -2444,11 +2444,11 @@ fn era_is_always_same_length() { advance_session(); advance_session(); assert_eq!(current_era(), 3); - assert_eq!(Staking::eras_start_session_index(current_era()).unwrap(), session + 2); + assert_eq!(ErasStartSessionIndex::::get(current_era()).unwrap(), session + 2); mock::start_active_era(4); assert_eq!( - Staking::eras_start_session_index(current_era()).unwrap(), + ErasStartSessionIndex::::get(current_era()).unwrap(), session + 2u32 + session_per_era ); }); @@ -2465,7 +2465,7 @@ fn offence_doesnt_force_new_era() { &[Perbill::from_percent(5)], ); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); }); } @@ -2473,7 +2473,7 @@ fn offence_doesnt_force_new_era() { fn offence_ensures_new_era_without_clobbering() { ExtBuilder::default().build_and_execute(|| { assert_ok!(Staking::force_new_era_always(RuntimeOrigin::root())); - assert_eq!(Staking::force_era(), Forcing::ForceAlways); + assert_eq!(ForceEra::::get(), Forcing::ForceAlways); on_offence_now( &[OffenceDetails { @@ -2483,7 +2483,7 @@ fn offence_ensures_new_era_without_clobbering() { &[Perbill::from_percent(5)], ); - assert_eq!(Staking::force_era(), Forcing::ForceAlways); + assert_eq!(ForceEra::::get(), Forcing::ForceAlways); }); } @@ -2507,7 +2507,7 @@ fn offence_deselects_validator_even_when_slash_is_zero() { &[Perbill::from_percent(0)], ); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); assert!(is_disabled(11)); mock::start_active_era(1); @@ -2557,14 +2557,14 @@ fn validator_is_not_disabled_for_an_offence_in_previous_era() { &[Perbill::from_percent(0)], ); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); assert!(is_disabled(11)); mock::start_active_era(2); // the validator is not disabled in the new era Staking::validate(RuntimeOrigin::signed(11), Default::default()).unwrap(); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); assert!(>::contains_key(11)); assert!(Session::validators().contains(&11)); @@ -2585,7 +2585,7 @@ fn validator_is_not_disabled_for_an_offence_in_previous_era() { assert!(!is_disabled(11)); // and we are not forcing a new era - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); on_offence_in_era( &[OffenceDetails { @@ -2601,7 +2601,7 @@ fn validator_is_not_disabled_for_an_offence_in_previous_era() { assert!(Validators::::iter().any(|(stash, _)| stash == 11)); assert!(!is_disabled(11)); // and we are still not forcing a new era - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); }); } @@ -2733,7 +2733,7 @@ fn dont_slash_if_fraction_is_zero() { // The validator hasn't been slashed. The new era is not forced. assert_eq!(asset::stakeable_balance::(&11), 1000); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); }); } @@ -2754,7 +2754,7 @@ fn only_slash_for_max_in_era() { // The validator has been slashed and has been force-chilled. assert_eq!(asset::stakeable_balance::(&11), 500); - assert_eq!(Staking::force_era(), Forcing::NotForcing); + assert_eq!(ForceEra::::get(), Forcing::NotForcing); on_offence_now( &[OffenceDetails { @@ -3033,7 +3033,7 @@ fn deferred_slashes_are_deferred() { ); // nominations are not removed regardless of the deferring. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!(asset::stakeable_balance::(&11), 1000); assert_eq!(asset::stakeable_balance::(&101), 2000); @@ -3078,7 +3078,7 @@ fn retroactive_deferred_slashes_two_eras_before() { mock::start_active_era(3); - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); System::reset_events(); on_offence_in_era( @@ -3169,7 +3169,7 @@ fn staker_cannot_bail_deferred_slash() { assert_ok!(Staking::chill(RuntimeOrigin::signed(101))); assert_ok!(Staking::unbond(RuntimeOrigin::signed(101), 500)); - assert_eq!(Staking::current_era().unwrap(), 1); + assert_eq!(CurrentEra::::get().unwrap(), 1); assert_eq!(active_era(), 1); assert_eq!( @@ -3191,14 +3191,14 @@ fn staker_cannot_bail_deferred_slash() { mock::start_active_era(2); assert_eq!(asset::stakeable_balance::(&11), 1000); assert_eq!(asset::stakeable_balance::(&101), 2000); - assert_eq!(Staking::current_era().unwrap(), 2); + assert_eq!(CurrentEra::::get().unwrap(), 2); assert_eq!(active_era(), 2); // no slash yet. mock::start_active_era(3); assert_eq!(asset::stakeable_balance::(&11), 1000); assert_eq!(asset::stakeable_balance::(&101), 2000); - assert_eq!(Staking::current_era().unwrap(), 3); + assert_eq!(CurrentEra::::get().unwrap(), 3); assert_eq!(active_era(), 3); // and cannot yet unbond: @@ -3378,7 +3378,7 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid assert_eq!(asset::stakeable_balance::(&101), 2000); // 100 has approval for 11 as of now - assert!(Staking::nominators(101).unwrap().targets.contains(&11)); + assert!(Nominators::::get(101).unwrap().targets.contains(&11)); // 11 and 21 both have the support of 100 let exposure_11 = Staking::eras_stakers(active_era(), &11); @@ -3443,8 +3443,8 @@ fn non_slashable_offence_disables_validator() { mock::start_active_era(1); assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41, 51, 201, 202]); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &21); // offence with no slash associated on_offence_now( @@ -3453,7 +3453,7 @@ fn non_slashable_offence_disables_validator() { ); // it does NOT affect the nominator. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // offence that slashes 25% of the bond on_offence_now( @@ -3462,7 +3462,7 @@ fn non_slashable_offence_disables_validator() { ); // it DOES NOT affect the nominator. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( staking_events_since_last_call(), @@ -3501,10 +3501,10 @@ fn slashing_independent_of_disabling_validator() { mock::start_active_era(1); assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41, 51]); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &21); - let now = Staking::active_era().unwrap().index; + let now = ActiveEra::::get().unwrap().index; // offence with no slash associated on_offence_in_era( @@ -3514,7 +3514,7 @@ fn slashing_independent_of_disabling_validator() { ); // nomination remains untouched. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // offence that slashes 25% of the bond on_offence_in_era( @@ -3524,7 +3524,7 @@ fn slashing_independent_of_disabling_validator() { ); // nomination remains untouched. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); assert_eq!( staking_events_since_last_call(), @@ -3572,9 +3572,9 @@ fn offence_threshold_doesnt_trigger_new_era() { // we have 4 validators and an offending validator threshold of 1/3, // even if the third validator commits an offence a new era should not be forced - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); - let exposure_31 = Staking::eras_stakers(Staking::active_era().unwrap().index, &31); + let exposure_11 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &21); + let exposure_31 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &31); on_offence_now( &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], @@ -3622,8 +3622,8 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41, 51, 201, 202]); assert_eq!(::SessionsPerEra::get(), 3); - let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); - let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_11 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(ActiveEra::::get().unwrap().index, &21); on_offence_now( &[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }], @@ -3631,7 +3631,7 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { ); // nominations are not updated. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); // validator 21 gets disabled since it got slashed assert!(is_disabled(21)); @@ -3648,7 +3648,7 @@ fn disabled_validators_are_kept_disabled_for_whole_era() { ); // nominations are not updated. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); advance_session(); @@ -3713,7 +3713,7 @@ fn claim_reward_at_the_last_era_and_no_double_claim_and_invalid_claim() { let active_era = active_era(); // This is the latest planned era in staking, not the active era - let current_era = Staking::current_era().unwrap(); + let current_era = CurrentEra::::get().unwrap(); // Last kept is 1: assert!(current_era - HistoryDepth::get() == 1); @@ -3777,7 +3777,7 @@ fn zero_slash_keeps_nominators() { assert!(Validators::::iter().any(|(stash, _)| stash == 11)); assert!(is_disabled(11)); // and their nominations are kept. - assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); }); } @@ -3836,8 +3836,8 @@ fn six_session_delay() { assert_eq!(active_era(), init_active_era + 2); // That reward are correct - assert_eq!(Staking::eras_reward_points(init_active_era).total, 1); - assert_eq!(Staking::eras_reward_points(init_active_era + 1).total, 2); + assert_eq!(ErasRewardPoints::::get(init_active_era).total, 1); + assert_eq!(ErasRewardPoints::::get(init_active_era + 1).total, 2); }); } @@ -4082,7 +4082,7 @@ fn test_multi_page_payout_stakers_by_page() { } } - assert_eq!(Staking::claimed_rewards(14, &11), vec![0, 1]); + assert_eq!(ClaimedRewards::::get(14, &11), vec![0, 1]); let last_era = 99; let history_depth = HistoryDepth::get(); @@ -4097,7 +4097,7 @@ fn test_multi_page_payout_stakers_by_page() { // verify we clean up history as we go for era in 0..15 { - assert_eq!(Staking::claimed_rewards(era, &11), Vec::::new()); + assert_eq!(ClaimedRewards::::get(era, &11), Vec::::new()); } // verify only page 0 is marked as claimed @@ -4107,7 +4107,7 @@ fn test_multi_page_payout_stakers_by_page() { first_claimable_reward_era, 0 )); - assert_eq!(Staking::claimed_rewards(first_claimable_reward_era, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(first_claimable_reward_era, &11), vec![0]); // verify page 0 and 1 are marked as claimed assert_ok!(Staking::payout_stakers_by_page( @@ -4116,7 +4116,7 @@ fn test_multi_page_payout_stakers_by_page() { first_claimable_reward_era, 1 )); - assert_eq!(Staking::claimed_rewards(first_claimable_reward_era, &11), vec![0, 1]); + assert_eq!(ClaimedRewards::::get(first_claimable_reward_era, &11), vec![0, 1]); // verify only page 0 is marked as claimed assert_ok!(Staking::payout_stakers_by_page( @@ -4125,7 +4125,7 @@ fn test_multi_page_payout_stakers_by_page() { last_reward_era, 0 )); - assert_eq!(Staking::claimed_rewards(last_reward_era, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(last_reward_era, &11), vec![0]); // verify page 0 and 1 are marked as claimed assert_ok!(Staking::payout_stakers_by_page( @@ -4134,15 +4134,15 @@ fn test_multi_page_payout_stakers_by_page() { last_reward_era, 1 )); - assert_eq!(Staking::claimed_rewards(last_reward_era, &11), vec![0, 1]); + assert_eq!(ClaimedRewards::::get(last_reward_era, &11), vec![0, 1]); // Out of order claims works. assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 69, 0)); - assert_eq!(Staking::claimed_rewards(69, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(69, &11), vec![0]); assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 23, 1)); - assert_eq!(Staking::claimed_rewards(23, &11), vec![1]); + assert_eq!(ClaimedRewards::::get(23, &11), vec![1]); assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, 42, 0)); - assert_eq!(Staking::claimed_rewards(42, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(42, &11), vec![0]); }); } @@ -4293,7 +4293,7 @@ fn test_multi_page_payout_stakers_backward_compatible() { } } - assert_eq!(Staking::claimed_rewards(14, &11), vec![0, 1]); + assert_eq!(ClaimedRewards::::get(14, &11), vec![0, 1]); let last_era = 99; let history_depth = HistoryDepth::get(); @@ -4308,7 +4308,7 @@ fn test_multi_page_payout_stakers_backward_compatible() { // verify we clean up history as we go for era in 0..15 { - assert_eq!(Staking::claimed_rewards(era, &11), Vec::::new()); + assert_eq!(ClaimedRewards::::get(era, &11), Vec::::new()); } // verify only page 0 is marked as claimed @@ -4317,7 +4317,7 @@ fn test_multi_page_payout_stakers_backward_compatible() { 11, first_claimable_reward_era )); - assert_eq!(Staking::claimed_rewards(first_claimable_reward_era, &11), vec![0]); + assert_eq!(ClaimedRewards::::get(first_claimable_reward_era, &11), vec![0]); // verify page 0 and 1 are marked as claimed assert_ok!(Staking::payout_stakers( @@ -4325,7 +4325,7 @@ fn test_multi_page_payout_stakers_backward_compatible() { 11, first_claimable_reward_era, )); - assert_eq!(Staking::claimed_rewards(first_claimable_reward_era, &11), vec![0, 1]); + assert_eq!(ClaimedRewards::::get(first_claimable_reward_era, &11), vec![0, 1]); // change order and verify only page 1 is marked as claimed assert_ok!(Staking::payout_stakers_by_page( @@ -4334,12 +4334,12 @@ fn test_multi_page_payout_stakers_backward_compatible() { last_reward_era, 1 )); - assert_eq!(Staking::claimed_rewards(last_reward_era, &11), vec![1]); + assert_eq!(ClaimedRewards::::get(last_reward_era, &11), vec![1]); // verify page 0 is claimed even when explicit page is not passed assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, last_reward_era,)); - assert_eq!(Staking::claimed_rewards(last_reward_era, &11), vec![1, 0]); + assert_eq!(ClaimedRewards::::get(last_reward_era, &11), vec![1, 0]); // cannot claim any more pages assert_noop!( @@ -4363,10 +4363,10 @@ fn test_multi_page_payout_stakers_backward_compatible() { // Out of order claims works. assert_ok!(Staking::payout_stakers_by_page(RuntimeOrigin::signed(1337), 11, test_era, 2)); - assert_eq!(Staking::claimed_rewards(test_era, &11), vec![2]); + assert_eq!(ClaimedRewards::::get(test_era, &11), vec![2]); assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, test_era)); - assert_eq!(Staking::claimed_rewards(test_era, &11), vec![2, 0]); + assert_eq!(ClaimedRewards::::get(test_era, &11), vec![2, 0]); // cannot claim page 2 again assert_noop!( @@ -4375,10 +4375,10 @@ fn test_multi_page_payout_stakers_backward_compatible() { ); assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, test_era)); - assert_eq!(Staking::claimed_rewards(test_era, &11), vec![2, 0, 1]); + assert_eq!(ClaimedRewards::::get(test_era, &11), vec![2, 0, 1]); assert_ok!(Staking::payout_stakers(RuntimeOrigin::signed(1337), 11, test_era)); - assert_eq!(Staking::claimed_rewards(test_era, &11), vec![2, 0, 1, 3]); + assert_eq!(ClaimedRewards::::get(test_era, &11), vec![2, 0, 1, 3]); }); } @@ -7009,7 +7009,8 @@ mod staking_interface { Error::::IncorrectSlashingSpans ); - let num_slashing_spans = Staking::slashing_spans(&11).map_or(0, |s| s.iter().count()); + let num_slashing_spans = + SlashingSpans::::get(&11).map_or(0, |s| s.iter().count()); assert_ok!(Staking::withdraw_unbonded( RuntimeOrigin::signed(11), num_slashing_spans as u32 @@ -8337,3 +8338,338 @@ mod byzantine_threshold_disabling_strategy { }); } } + +mod getters { + use crate::{ + mock::{self}, + pallet::pallet::{Invulnerables, MinimumValidatorCount, ValidatorCount}, + slashing, + tests::{Staking, Test}, + ActiveEra, ActiveEraInfo, BalanceOf, CanceledSlashPayout, ClaimedRewards, CurrentEra, + CurrentPlannedSession, EraRewardPoints, ErasRewardPoints, ErasStakersClipped, + ErasStartSessionIndex, ErasTotalStake, ErasValidatorPrefs, ErasValidatorReward, ForceEra, + Forcing, Nominations, Nominators, Perbill, SlashRewardFraction, SlashingSpans, + ValidatorPrefs, Validators, + }; + use sp_staking::{EraIndex, Exposure, IndividualExposure, Page, SessionIndex}; + + #[test] + fn get_validator_count_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let v: u32 = 12; + ValidatorCount::::put(v); + + // when + let result = Staking::validator_count(); + + // then + assert_eq!(result, v); + }); + } + + #[test] + fn get_minimum_validator_count_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let v: u32 = 12; + MinimumValidatorCount::::put(v); + + // when + let result = Staking::minimum_validator_count(); + + // then + assert_eq!(result, v); + }); + } + + #[test] + fn get_invulnerables_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let v: Vec = vec![1, 2, 3]; + Invulnerables::::put(v.clone()); + + // when + let result = Staking::invulnerables(); + + // then + assert_eq!(result, v); + }); + } + + #[test] + fn get_validators_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let account_id: mock::AccountId = 1; + let validator_prefs = ValidatorPrefs::default(); + + Validators::::insert(account_id, validator_prefs.clone()); + + // when + let result = Staking::validators(&account_id); + + // then + assert_eq!(result, validator_prefs); + }); + } + + #[test] + fn get_nominators_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let account_id: mock::AccountId = 1; + let nominations: Nominations = Nominations { + targets: Default::default(), + submitted_in: Default::default(), + suppressed: false, + }; + + Nominators::::insert(account_id, nominations.clone()); + + // when + let result = Staking::nominators(account_id); + + // then + assert_eq!(result, Some(nominations)); + }); + } + + #[test] + fn get_current_era_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + CurrentEra::::put(era); + + // when + let result = Staking::current_era(); + + // then + assert_eq!(result, Some(era)); + }); + } + + #[test] + fn get_active_era_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era = ActiveEraInfo { index: 2, start: None }; + ActiveEra::::put(era); + + // when + let result: Option = Staking::active_era(); + + // then + if let Some(era_info) = result { + assert_eq!(era_info.index, 2); + assert_eq!(era_info.start, None); + } else { + panic!("Expected Some(era_info), got None"); + }; + }); + } + + #[test] + fn get_eras_start_session_index_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let session_index: SessionIndex = 14; + ErasStartSessionIndex::::insert(era, session_index); + + // when + let result = Staking::eras_start_session_index(era); + + // then + assert_eq!(result, Some(session_index)); + }); + } + + #[test] + fn get_eras_stakers_clipped_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let account_id: mock::AccountId = 1; + let exposure: Exposure> = Exposure { + total: 1125, + own: 1000, + others: vec![IndividualExposure { who: 101, value: 125 }], + }; + ErasStakersClipped::::insert(era, account_id, exposure.clone()); + + // when + let result = Staking::eras_stakers_clipped(era, &account_id); + + // then + assert_eq!(result, exposure); + }); + } + + #[test] + fn get_claimed_rewards_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let account_id: mock::AccountId = 1; + let rewards = Vec::::new(); + ClaimedRewards::::insert(era, account_id, rewards.clone()); + + // when + let result = Staking::claimed_rewards(era, &account_id); + + // then + assert_eq!(result, rewards); + }); + } + + #[test] + fn get_eras_validator_prefs_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let account_id: mock::AccountId = 1; + let validator_prefs = ValidatorPrefs::default(); + + ErasValidatorPrefs::::insert(era, account_id, validator_prefs.clone()); + + // when + let result = Staking::eras_validator_prefs(era, &account_id); + + // then + assert_eq!(result, validator_prefs); + }); + } + + #[test] + fn get_eras_validator_reward_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let balance_of = BalanceOf::::default(); + + ErasValidatorReward::::insert(era, balance_of); + + // when + let result = Staking::eras_validator_reward(era); + + // then + assert_eq!(result, Some(balance_of)); + }); + } + + #[test] + fn get_eras_reward_points_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let reward_points = EraRewardPoints:: { + total: 1, + individual: vec![(11, 1)].into_iter().collect(), + }; + ErasRewardPoints::::insert(era, reward_points); + + // when + let result = Staking::eras_reward_points(era); + + // then + assert_eq!(result.total, 1); + }); + } + + #[test] + fn get_eras_total_stake_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let era: EraIndex = 12; + let balance_of = BalanceOf::::default(); + + ErasTotalStake::::insert(era, balance_of); + + // when + let result = Staking::eras_total_stake(era); + + // then + assert_eq!(result, balance_of); + }); + } + + #[test] + fn get_force_era_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let forcing = Forcing::NotForcing; + ForceEra::::put(forcing); + + // when + let result = Staking::force_era(); + + // then + assert_eq!(result, forcing); + }); + } + + #[test] + fn get_slash_reward_fraction_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let perbill = Perbill::one(); + SlashRewardFraction::::put(perbill); + + // when + let result = Staking::slash_reward_fraction(); + + // then + assert_eq!(result, perbill); + }); + } + + #[test] + fn get_canceled_payout_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let balance_of = BalanceOf::::default(); + CanceledSlashPayout::::put(balance_of); + + // when + let result = Staking::canceled_payout(); + + // then + assert_eq!(result, balance_of); + }); + } + + #[test] + fn get_slashing_spans_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let account_id: mock::AccountId = 1; + let spans = slashing::SlashingSpans::new(2); + SlashingSpans::::insert(account_id, spans); + + // when + let result: Option = Staking::slashing_spans(&account_id); + + // then + // simple check so as not to add extra macros to slashing::SlashingSpans struct + assert!(result.is_some()); + }); + } + + #[test] + fn get_current_planned_session_returns_value_from_storage() { + sp_io::TestExternalities::default().execute_with(|| { + // given + let session_index = SessionIndex::default(); + CurrentPlannedSession::::put(session_index); + + // when + let result = Staking::current_planned_session(); + + // then + assert_eq!(result, session_index); + }); + } +} From e87bffceeed06734da1b5db3d71fa4666d4a1612 Mon Sep 17 00:00:00 2001 From: Giuseppe Re Date: Wed, 13 Nov 2024 10:59:37 +0100 Subject: [PATCH 086/166] Refactor pallet `society` (#6367) - [x] Removing `without_storage_info` and adding bounds on the stored types for pallet `society` - issue https://github.com/paritytech/polkadot-sdk/issues/6289 - [x] Migrating to benchmarking V2 - https://github.com/paritytech/polkadot-sdk/issues/6202 --------- Co-authored-by: Guillaume Thiolliere Co-authored-by: Muharem --- prdoc/pr_6367.prdoc | 14 + substrate/frame/society/src/benchmarking.rs | 329 ++++++++++++++------ substrate/frame/society/src/lib.rs | 29 +- 3 files changed, 264 insertions(+), 108 deletions(-) create mode 100644 prdoc/pr_6367.prdoc diff --git a/prdoc/pr_6367.prdoc b/prdoc/pr_6367.prdoc new file mode 100644 index 000000000000..fd1e6bb4196d --- /dev/null +++ b/prdoc/pr_6367.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Refactor pallet society + +doc: + - audience: Runtime Dev + description: | + Derives `MaxEncodedLen` implementation for stored types and removes `without_storage_info` attribute. + Migrates benchmarks from v1 to v2 API. + +crates: + - name: pallet-society + bump: minor diff --git a/substrate/frame/society/src/benchmarking.rs b/substrate/frame/society/src/benchmarking.rs index 8c3d2bf32ce7..dc8e3cab775f 100644 --- a/substrate/frame/society/src/benchmarking.rs +++ b/substrate/frame/society/src/benchmarking.rs @@ -21,7 +21,7 @@ use super::*; -use frame_benchmarking::{account, benchmarks_instance_pallet, whitelisted_caller}; +use frame_benchmarking::v2::*; use frame_system::RawOrigin; use alloc::vec; @@ -111,42 +111,57 @@ fn increment_round, I: 'static>() { RoundCount::::put(round_count); } -benchmarks_instance_pallet! { - bid { - let founder = setup_society::()?; +#[instance_benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn bid() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); - }: _(RawOrigin::Signed(caller.clone()), 10u32.into()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 10u32.into()); + let first_bid: Bid> = Bid { who: caller.clone(), kind: BidKind::Deposit(mock_balance_deposit::()), value: 10u32.into(), }; assert_eq!(Bids::::get(), vec![first_bid]); + Ok(()) } - unbid { - let founder = setup_society::()?; + #[benchmark] + fn unbid() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let mut bids = Bids::::get(); Society::::insert_bid(&mut bids, &caller, 10u32.into(), make_bid::(&caller)); Bids::::put(bids); - }: _(RawOrigin::Signed(caller.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); + assert_eq!(Bids::::get(), vec![]); + Ok(()) } - vouch { - let founder = setup_society::()?; + #[benchmark] + fn vouch() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); let vouched: T::AccountId = account("vouched", 0, 0); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let _ = Society::::insert_member(&caller, 1u32.into()); - let vouched_lookup: ::Source = T::Lookup::unlookup(vouched.clone()); - }: _(RawOrigin::Signed(caller.clone()), vouched_lookup, 0u32.into(), 0u32.into()) - verify { + let vouched_lookup: ::Source = + T::Lookup::unlookup(vouched.clone()); + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), vouched_lookup, 0u32.into(), 0u32.into()); + let bids = Bids::::get(); let vouched_bid: Bid> = Bid { who: vouched.clone(), @@ -154,207 +169,328 @@ benchmarks_instance_pallet! { value: 0u32.into(), }; assert_eq!(bids, vec![vouched_bid]); + Ok(()) } - unvouch { - let founder = setup_society::()?; + #[benchmark] + fn unvouch() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); - let vouched: T::AccountId = account("vouched", 0, 0); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let mut bids = Bids::::get(); - Society::::insert_bid(&mut bids, &caller, 10u32.into(), BidKind::Vouch(caller.clone(), 0u32.into())); + Society::::insert_bid( + &mut bids, + &caller, + 10u32.into(), + BidKind::Vouch(caller.clone(), 0u32.into()), + ); Bids::::put(bids); - }: _(RawOrigin::Signed(caller.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); + assert_eq!(Bids::::get(), vec![]); + Ok(()) } - vote { - let founder = setup_society::()?; + #[benchmark] + fn vote() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let _ = Society::::insert_member(&caller, 1u32.into()); let candidate = add_candidate::("candidate", Default::default(), false); - let candidate_lookup: ::Source = T::Lookup::unlookup(candidate.clone()); - }: _(RawOrigin::Signed(caller.clone()), candidate_lookup, true) - verify { + let candidate_lookup: ::Source = + T::Lookup::unlookup(candidate.clone()); + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), candidate_lookup, true); + let maybe_vote: Vote = >::get(candidate.clone(), caller).unwrap(); assert_eq!(maybe_vote.approve, true); + Ok(()) } - defender_vote { - let founder = setup_society::()?; + #[benchmark] + fn defender_vote() -> Result<(), BenchmarkError> { + setup_society::()?; let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let _ = Society::::insert_member(&caller, 1u32.into()); let defender: T::AccountId = account("defender", 0, 0); Defending::::put((defender, caller.clone(), Tally::default())); - }: _(RawOrigin::Signed(caller.clone()), false) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), false); + let round = RoundCount::::get(); let skeptic_vote: Vote = DefenderVotes::::get(round, &caller).unwrap(); assert_eq!(skeptic_vote.approve, false); + Ok(()) } - payout { - let founder = setup_funded_society::()?; + #[benchmark] + fn payout() -> Result<(), BenchmarkError> { + setup_funded_society::()?; // Payee's account already exists and is a member. let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, mock_balance_deposit::()); let _ = Society::::insert_member(&caller, 0u32.into()); // Introduce payout. Society::::bump_payout(&caller, 0u32.into(), 1u32.into()); - }: _(RawOrigin::Signed(caller.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); + let record = Payouts::::get(caller); assert!(record.payouts.is_empty()); + Ok(()) } - waive_repay { - let founder = setup_funded_society::()?; + #[benchmark] + fn waive_repay() -> Result<(), BenchmarkError> { + setup_funded_society::()?; let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); let _ = Society::::insert_member(&caller, 0u32.into()); Society::::bump_payout(&caller, 0u32.into(), 1u32.into()); - }: _(RawOrigin::Signed(caller.clone()), 1u32.into()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), 1u32.into()); + let record = Payouts::::get(caller); assert!(record.payouts.is_empty()); + Ok(()) } - found_society { + #[benchmark] + fn found_society() -> Result<(), BenchmarkError> { let founder: T::AccountId = whitelisted_caller(); let can_found = T::FounderSetOrigin::try_successful_origin().map_err(|_| "No origin")?; - let founder_lookup: ::Source = T::Lookup::unlookup(founder.clone()); - }: _(can_found, founder_lookup, 5, 3, 3, mock_balance_deposit::(), b"benchmarking-society".to_vec()) - verify { + let founder_lookup: ::Source = + T::Lookup::unlookup(founder.clone()); + + #[extrinsic_call] + _( + can_found as T::RuntimeOrigin, + founder_lookup, + 5, + 3, + 3, + mock_balance_deposit::(), + b"benchmarking-society".to_vec(), + ); + assert_eq!(Founder::::get(), Some(founder.clone())); + Ok(()) } - dissolve { + #[benchmark] + fn dissolve() -> Result<(), BenchmarkError> { let founder = setup_society::()?; let members_and_candidates = vec![("m1", "c1"), ("m2", "c2"), ("m3", "c3"), ("m4", "c4")]; let members_count = members_and_candidates.clone().len() as u32; for (m, c) in members_and_candidates { let member: T::AccountId = account(m, 0, 0); let _ = Society::::insert_member(&member, 100u32.into()); - let candidate = add_candidate::(c, Tally { approvals: 1u32.into(), rejections: 1u32.into() }, false); - let candidate_lookup: ::Source = T::Lookup::unlookup(candidate); + let candidate = add_candidate::( + c, + Tally { approvals: 1u32.into(), rejections: 1u32.into() }, + false, + ); + let candidate_lookup: ::Source = + T::Lookup::unlookup(candidate); let _ = Society::::vote(RawOrigin::Signed(member).into(), candidate_lookup, true); } // Leaving only Founder member. - MemberCount::::mutate(|i| { i.saturating_reduce(members_count) }); - }: _(RawOrigin::Signed(founder)) - verify { + MemberCount::::mutate(|i| i.saturating_reduce(members_count)); + + #[extrinsic_call] + _(RawOrigin::Signed(founder)); + assert_eq!(Founder::::get(), None); + Ok(()) } - judge_suspended_member { + #[benchmark] + fn judge_suspended_member() -> Result<(), BenchmarkError> { let founder = setup_society::()?; let caller: T::AccountId = whitelisted_caller(); - let caller_lookup: ::Source = T::Lookup::unlookup(caller.clone()); + let caller_lookup: ::Source = + T::Lookup::unlookup(caller.clone()); let _ = Society::::insert_member(&caller, 0u32.into()); let _ = Society::::suspend_member(&caller); - }: _(RawOrigin::Signed(founder), caller_lookup, false) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(founder), caller_lookup, false); + assert_eq!(SuspendedMembers::::contains_key(&caller), false); + Ok(()) } - set_parameters { + #[benchmark] + fn set_parameters() -> Result<(), BenchmarkError> { let founder = setup_society::()?; let max_members = 10u32; let max_intake = 10u32; let max_strikes = 10u32; let candidate_deposit: BalanceOf = 10u32.into(); let params = GroupParams { max_members, max_intake, max_strikes, candidate_deposit }; - }: _(RawOrigin::Signed(founder), max_members, max_intake, max_strikes, candidate_deposit) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(founder), max_members, max_intake, max_strikes, candidate_deposit); + assert_eq!(Parameters::::get(), Some(params)); + Ok(()) } - punish_skeptic { - let founder = setup_society::()?; + #[benchmark] + fn punish_skeptic() -> Result<(), BenchmarkError> { + setup_society::()?; let candidate = add_candidate::("candidate", Default::default(), false); let skeptic: T::AccountId = account("skeptic", 0, 0); let _ = Society::::insert_member(&skeptic, 0u32.into()); Skeptic::::put(&skeptic); if let Period::Voting { more, .. } = Society::::period() { - frame_system::Pallet::::set_block_number(frame_system::Pallet::::block_number() + more); + frame_system::Pallet::::set_block_number( + frame_system::Pallet::::block_number() + more, + ); } - }: _(RawOrigin::Signed(candidate.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(candidate.clone())); + let candidacy = Candidates::::get(&candidate).unwrap(); assert_eq!(candidacy.skeptic_struck, true); + Ok(()) } - claim_membership { - let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 3u32.into(), rejections: 0u32.into() }, false); + #[benchmark] + fn claim_membership() -> Result<(), BenchmarkError> { + setup_society::()?; + let candidate = add_candidate::( + "candidate", + Tally { approvals: 3u32.into(), rejections: 0u32.into() }, + false, + ); increment_round::(); - }: _(RawOrigin::Signed(candidate.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(candidate.clone())); + assert!(!Candidates::::contains_key(&candidate)); assert!(Members::::contains_key(&candidate)); + Ok(()) } - bestow_membership { + #[benchmark] + fn bestow_membership() -> Result<(), BenchmarkError> { let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 3u32.into(), rejections: 1u32.into() }, false); + let candidate = add_candidate::( + "candidate", + Tally { approvals: 3u32.into(), rejections: 1u32.into() }, + false, + ); increment_round::(); - }: _(RawOrigin::Signed(founder), candidate.clone()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(founder), candidate.clone()); + assert!(!Candidates::::contains_key(&candidate)); assert!(Members::::contains_key(&candidate)); + Ok(()) } - kick_candidate { + #[benchmark] + fn kick_candidate() -> Result<(), BenchmarkError> { let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 1u32.into(), rejections: 1u32.into() }, false); + let candidate = add_candidate::( + "candidate", + Tally { approvals: 1u32.into(), rejections: 1u32.into() }, + false, + ); increment_round::(); - }: _(RawOrigin::Signed(founder), candidate.clone()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(founder), candidate.clone()); + assert!(!Candidates::::contains_key(&candidate)); + Ok(()) } - resign_candidacy { - let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 0u32.into(), rejections: 0u32.into() }, false); - }: _(RawOrigin::Signed(candidate.clone())) - verify { + #[benchmark] + fn resign_candidacy() -> Result<(), BenchmarkError> { + setup_society::()?; + let candidate = add_candidate::( + "candidate", + Tally { approvals: 0u32.into(), rejections: 0u32.into() }, + false, + ); + + #[extrinsic_call] + _(RawOrigin::Signed(candidate.clone())); + assert!(!Candidates::::contains_key(&candidate)); + Ok(()) } - drop_candidate { - let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 0u32.into(), rejections: 3u32.into() }, false); + #[benchmark] + fn drop_candidate() -> Result<(), BenchmarkError> { + setup_society::()?; + let candidate = add_candidate::( + "candidate", + Tally { approvals: 0u32.into(), rejections: 3u32.into() }, + false, + ); let caller: T::AccountId = whitelisted_caller(); let _ = Society::::insert_member(&caller, 0u32.into()); let mut round_count = RoundCount::::get(); round_count = round_count.saturating_add(2u32); RoundCount::::put(round_count); - }: _(RawOrigin::Signed(caller), candidate.clone()) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller), candidate.clone()); + assert!(!Candidates::::contains_key(&candidate)); + Ok(()) } - cleanup_candidacy { - let founder = setup_society::()?; - let candidate = add_candidate::("candidate", Tally { approvals: 0u32.into(), rejections: 0u32.into() }, false); + #[benchmark] + fn cleanup_candidacy() -> Result<(), BenchmarkError> { + setup_society::()?; + let candidate = add_candidate::( + "candidate", + Tally { approvals: 0u32.into(), rejections: 0u32.into() }, + false, + ); let member_one: T::AccountId = account("one", 0, 0); let member_two: T::AccountId = account("two", 0, 0); let _ = Society::::insert_member(&member_one, 0u32.into()); let _ = Society::::insert_member(&member_two, 0u32.into()); - let candidate_lookup: ::Source = T::Lookup::unlookup(candidate.clone()); - let _ = Society::::vote(RawOrigin::Signed(member_one.clone()).into(), candidate_lookup.clone(), true); - let _ = Society::::vote(RawOrigin::Signed(member_two.clone()).into(), candidate_lookup, true); + let candidate_lookup: ::Source = + T::Lookup::unlookup(candidate.clone()); + let _ = Society::::vote( + RawOrigin::Signed(member_one.clone()).into(), + candidate_lookup.clone(), + true, + ); + let _ = Society::::vote( + RawOrigin::Signed(member_two.clone()).into(), + candidate_lookup, + true, + ); Candidates::::remove(&candidate); - }: _(RawOrigin::Signed(member_one), candidate.clone(), 5) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(member_one), candidate.clone(), 5); + assert_eq!(Votes::::get(&candidate, &member_two), None); + Ok(()) } - cleanup_challenge { - let founder = setup_society::()?; + #[benchmark] + fn cleanup_challenge() -> Result<(), BenchmarkError> { + setup_society::()?; ChallengeRoundCount::::put(1u32); let member: T::AccountId = whitelisted_caller(); let _ = Society::::insert_member(&member, 0u32.into()); @@ -364,9 +500,12 @@ benchmarks_instance_pallet! { ChallengeRoundCount::::put(2u32); let mut challenge_round = ChallengeRoundCount::::get(); challenge_round = challenge_round.saturating_sub(1u32); - }: _(RawOrigin::Signed(member.clone()), challenge_round, 1u32) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(member.clone()), challenge_round, 1u32); + assert_eq!(DefenderVotes::::get(challenge_round, &defender), None); + Ok(()) } impl_benchmark_test_suite!( diff --git a/substrate/frame/society/src/lib.rs b/substrate/frame/society/src/lib.rs index 04879cd87091..b893bb6fba7d 100644 --- a/substrate/frame/society/src/lib.rs +++ b/substrate/frame/society/src/lib.rs @@ -297,14 +297,14 @@ type NegativeImbalanceOf = <>::Currency as Currency< >>::NegativeImbalance; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct Vote { approve: bool, weight: u32, } /// A judgement by the suspension judgement origin on a suspended candidate. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum Judgement { /// The suspension judgement origin takes no direct judgment /// and places the candidate back into the bid pool. @@ -316,7 +316,9 @@ pub enum Judgement { } /// Details of a payout given as a per-block linear "trickle". -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, Default, TypeInfo)] +#[derive( + Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, Default, TypeInfo, MaxEncodedLen, +)] pub struct Payout { /// Total value of the payout. value: Balance, @@ -329,7 +331,7 @@ pub struct Payout { } /// Status of a vouching member. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum VouchingStatus { /// Member is currently vouching for a user. Vouching, @@ -341,7 +343,7 @@ pub enum VouchingStatus { pub type StrikeCount = u32; /// A bid for entry into society. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct Bid { /// The bidder/candidate trying to enter society who: AccountId, @@ -361,7 +363,9 @@ pub type Rank = u32; pub type VoteCount = u32; /// Tally of votes. -#[derive(Default, Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive( + Default, Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen, +)] pub struct Tally { /// The approval votes. approvals: VoteCount, @@ -388,7 +392,7 @@ impl Tally { } /// A bid for entry into society. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct Candidacy { /// The index of the round where the candidacy began. round: RoundIndex, @@ -403,7 +407,7 @@ pub struct Candidacy { } /// A vote by a member on a candidate application. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub enum BidKind { /// The given deposit was paid for this bid. Deposit(Balance), @@ -422,7 +426,7 @@ pub type PayoutsFor = BoundedVec<(BlockNumberFor, BalanceOf), >::MaxPayouts>; /// Information concerning a member. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct MemberRecord { rank: Rank, strikes: StrikeCount, @@ -431,7 +435,7 @@ pub struct MemberRecord { } /// Information concerning a member. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, Default)] +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, Default, MaxEncodedLen)] pub struct PayoutRecord { paid: Balance, payouts: PayoutsVec, @@ -443,7 +447,7 @@ pub type PayoutRecordFor = PayoutRecord< >; /// Record for an individual new member who was elevated from a candidate recently. -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct IntakeRecord { who: AccountId, bid: Balance, @@ -453,7 +457,7 @@ pub struct IntakeRecord { pub type IntakeRecordFor = IntakeRecord<::AccountId, BalanceOf>; -#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct GroupParams { max_members: u32, max_intake: u32, @@ -471,7 +475,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] - #[pallet::without_storage_info] pub struct Pallet(_); #[pallet::config] From ac2546b5c2050bee2c669e97505026d37c42d2e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Wed, 13 Nov 2024 10:05:37 +0000 Subject: [PATCH 087/166] frame-benchmarking: Use correct components for pallet instances (#6435) When using multiple instances of the same pallet, each instance was executed with the components of all instances. While actually each instance should only be executed with the components generated for the particular instance. The problem here was that in the runtime only the pallet-name was used to determine if a certain pallet should be benchmarked. When using instances, the pallet name is the same for both of these instances. The solution is to also take the instance name into account. The fix requires to change the `Benchmark` runtime api to also take the `instance`. The node side is written in a backwards compatible way to also support runtimes which do not yet support the `instance` parameter. --------- Co-authored-by: GitHub Action Co-authored-by: clangenb <37865735+clangenb@users.noreply.github.com> Co-authored-by: Adrian Catangiu --- Cargo.lock | 3 + prdoc/pr_6435.prdoc | 16 ++++ substrate/client/db/src/lib.rs | 4 +- substrate/frame/benchmarking/Cargo.toml | 6 ++ .../frame/benchmarking/src/tests_instance.rs | 61 +++++++++++- substrate/frame/benchmarking/src/utils.rs | 3 + substrate/frame/benchmarking/src/v1.rs | 3 +- substrate/frame/referenda/Cargo.toml | 1 - .../benchmarking-cli/src/pallet/command.rs | 92 +++++++++++++------ 9 files changed, 155 insertions(+), 34 deletions(-) create mode 100644 prdoc/pr_6435.prdoc diff --git a/Cargo.lock b/Cargo.lock index e36f252ecb39..f0a133227b32 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6923,15 +6923,18 @@ dependencies = [ "parity-scale-codec", "paste", "rusty-fork", + "sc-client-db", "scale-info", "serde", "sp-api 26.0.0", "sp-application-crypto 30.0.0", "sp-core 28.0.0", + "sp-externalities 0.25.0", "sp-io 30.0.0", "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-runtime-interface 24.0.0", + "sp-state-machine 0.35.0", "sp-storage 19.0.0", "static_assertions", ] diff --git a/prdoc/pr_6435.prdoc b/prdoc/pr_6435.prdoc new file mode 100644 index 000000000000..025c666d9115 --- /dev/null +++ b/prdoc/pr_6435.prdoc @@ -0,0 +1,16 @@ +title: 'frame-benchmarking: Use correct components for pallet instances' +doc: +- audience: Runtime Dev + description: |- + When benchmarking multiple instances of the same pallet, each instance was executed with the components of all instances. While actually each instance should only be executed with the components generated for the particular instance. The problem here was that in the runtime only the pallet-name was used to determine if a certain pallet should be benchmarked. When using instances, the pallet name is the same for both of these instances. The solution is to also take the instance name into account. + + The fix requires to change the `Benchmark` runtime api to also take the `instance`. The node side is written in a backwards compatible way to also support runtimes which do not yet support the `instance` parameter. +crates: +- name: frame-benchmarking + bump: major +- name: frame-benchmarking-cli + bump: major +- name: sc-client-db + bump: none +- name: pallet-referenda + bump: none diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index aaa1398a13bc..cec981c05602 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -1180,7 +1180,7 @@ impl Backend { /// The second argument is the Column that stores the State. /// /// Should only be needed for benchmarking. - #[cfg(any(feature = "runtime-benchmarks"))] + #[cfg(feature = "runtime-benchmarks")] pub fn expose_db(&self) -> (Arc>, sp_database::ColumnId) { (self.storage.db.clone(), columns::STATE) } @@ -1188,7 +1188,7 @@ impl Backend { /// Expose the Storage that is used by this backend. /// /// Should only be needed for benchmarking. - #[cfg(any(feature = "runtime-benchmarks"))] + #[cfg(feature = "runtime-benchmarks")] pub fn expose_storage(&self) -> Arc>> { self.storage.clone() } diff --git a/substrate/frame/benchmarking/Cargo.toml b/substrate/frame/benchmarking/Cargo.toml index 9ea350a1d290..0c74d94b33b8 100644 --- a/substrate/frame/benchmarking/Cargo.toml +++ b/substrate/frame/benchmarking/Cargo.toml @@ -38,6 +38,9 @@ static_assertions = { workspace = true, default-features = true } array-bytes = { workspace = true, default-features = true } rusty-fork = { workspace = true } sp-keystore = { workspace = true, default-features = true } +sc-client-db = { workspace = true } +sp-state-machine = { workspace = true } +sp-externalities = { workspace = true } [features] default = ["std"] @@ -53,14 +56,17 @@ std = [ "sp-api/std", "sp-application-crypto/std", "sp-core/std", + "sp-externalities/std", "sp-io/std", "sp-keystore/std", "sp-runtime-interface/std", "sp-runtime/std", + "sp-state-machine/std", "sp-storage/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", + "sc-client-db/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] diff --git a/substrate/frame/benchmarking/src/tests_instance.rs b/substrate/frame/benchmarking/src/tests_instance.rs index ecffbd1a018f..428f29e2bc16 100644 --- a/substrate/frame/benchmarking/src/tests_instance.rs +++ b/substrate/frame/benchmarking/src/tests_instance.rs @@ -61,6 +61,7 @@ mod pallet_test { #[pallet::weight({0})] pub fn set_value(origin: OriginFor, n: u32) -> DispatchResult { let _sender = ensure_signed(origin)?; + assert!(n >= T::LowerBound::get()); Value::::put(n); Ok(()) } @@ -81,6 +82,7 @@ frame_support::construct_runtime!( { System: frame_system, TestPallet: pallet_test, + TestPallet2: pallet_test::, } ); @@ -117,6 +119,12 @@ impl pallet_test::Config for Test { type UpperBound = ConstU32<100>; } +impl pallet_test::Config for Test { + type RuntimeEvent = RuntimeEvent; + type LowerBound = ConstU32<50>; + type UpperBound = ConstU32<100>; +} + impl pallet_test::OtherConfig for Test { type OtherEvent = RuntimeEvent; } @@ -130,6 +138,7 @@ mod benchmarks { use crate::account; use frame_support::ensure; use frame_system::RawOrigin; + use sp_core::Get; // Additional used internally by the benchmark macro. use super::pallet_test::{Call, Config, Pallet}; @@ -143,7 +152,7 @@ mod benchmarks { } set_value { - let b in 1 .. 1000; + let b in ( >::LowerBound::get() ) .. ( >::UpperBound::get() ); let caller = account::("caller", 0, 0); }: _ (RawOrigin::Signed(caller), b.into()) verify { @@ -173,3 +182,53 @@ mod benchmarks { ) } } + +#[test] +fn ensure_correct_instance_is_selected() { + use crate::utils::Benchmarking; + + crate::define_benchmarks!( + [pallet_test, TestPallet] + [pallet_test, TestPallet2] + ); + + let whitelist = vec![]; + + let mut batches = Vec::::new(); + let config = crate::BenchmarkConfig { + pallet: "pallet_test".bytes().collect::>(), + // We only want that this `instance` is used. + // Otherwise the wrong components are used. + instance: "TestPallet".bytes().collect::>(), + benchmark: "set_value".bytes().collect::>(), + selected_components: TestPallet::benchmarks(false) + .into_iter() + .find_map(|b| { + if b.name == "set_value".as_bytes() { + Some(b.components.into_iter().map(|c| (c.0, c.1)).collect::>()) + } else { + None + } + }) + .unwrap(), + verify: false, + internal_repeats: 1, + }; + let params = (&config, &whitelist); + + let state = sc_client_db::BenchmarkingState::::new( + Default::default(), + None, + false, + false, + ) + .unwrap(); + + let mut overlay = Default::default(); + let mut ext = sp_state_machine::Ext::new(&mut overlay, &state, None); + sp_externalities::set_and_run_with_externalities(&mut ext, || { + add_benchmarks!(params, batches); + Ok::<_, crate::BenchmarkError>(()) + }) + .unwrap(); +} diff --git a/substrate/frame/benchmarking/src/utils.rs b/substrate/frame/benchmarking/src/utils.rs index fb55cee99e81..3a10e43d83b8 100644 --- a/substrate/frame/benchmarking/src/utils.rs +++ b/substrate/frame/benchmarking/src/utils.rs @@ -200,6 +200,8 @@ impl From for BenchmarkError { pub struct BenchmarkConfig { /// The encoded name of the pallet to benchmark. pub pallet: Vec, + /// The encoded name of the pallet instance to benchmark. + pub instance: Vec, /// The encoded name of the benchmark/extrinsic to run. pub benchmark: Vec, /// The selected component values to use when running the benchmark. @@ -229,6 +231,7 @@ pub struct BenchmarkMetadata { sp_api::decl_runtime_apis! { /// Runtime api for benchmarking a FRAME runtime. + #[api_version(2)] pub trait Benchmark { /// Get the benchmark metadata available for this runtime. /// diff --git a/substrate/frame/benchmarking/src/v1.rs b/substrate/frame/benchmarking/src/v1.rs index e73ed1f4382f..64f93b22cf1b 100644 --- a/substrate/frame/benchmarking/src/v1.rs +++ b/substrate/frame/benchmarking/src/v1.rs @@ -1821,12 +1821,13 @@ macro_rules! add_benchmark { let (config, whitelist) = $params; let $crate::BenchmarkConfig { pallet, + instance, benchmark, selected_components, verify, internal_repeats, } = config; - if &pallet[..] == &name_string[..] { + if &pallet[..] == &name_string[..] && &instance[..] == &instance_string[..] { let benchmark_result = <$location>::run_benchmark( &benchmark[..], &selected_components[..], diff --git a/substrate/frame/referenda/Cargo.toml b/substrate/frame/referenda/Cargo.toml index 32dba3436595..e9b4eb04ed51 100644 --- a/substrate/frame/referenda/Cargo.toml +++ b/substrate/frame/referenda/Cargo.toml @@ -57,7 +57,6 @@ std = [ ] runtime-benchmarks = [ "assert_matches", - "frame-benchmarking", "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", diff --git a/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs b/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs index 6f7e79f16384..0c068fc585ba 100644 --- a/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -96,6 +96,7 @@ pub(crate) type PovModesMap = #[derive(Debug, Clone)] struct SelectedBenchmark { pallet: String, + instance: String, extrinsic: String, components: Vec<(BenchmarkParameter, u32, u32)>, pov_modes: Vec<(String, String)>, @@ -152,7 +153,7 @@ fn combine_batches( } /// Explains possible reasons why the metadata for the benchmarking could not be found. -const ERROR_METADATA_NOT_FOUND: &'static str = "Did not find the benchmarking metadata. \ +const ERROR_API_NOT_FOUND: &'static str = "Did not find the benchmarking runtime api. \ This could mean that you either did not build the node correctly with the \ `--features runtime-benchmarks` flag, or the chain spec that you are using was \ not created by a node that was compiled with the flag"; @@ -306,6 +307,33 @@ impl PalletCmd { .with_runtime_cache_size(2) .build(); + let runtime_version: sp_version::RuntimeVersion = Self::exec_state_machine( + StateMachine::new( + state, + &mut Default::default(), + &executor, + "Core_version", + &[], + &mut Self::build_extensions(executor.clone(), state.recorder()), + &runtime_code, + CallContext::Offchain, + ), + "Could not find `Core::version` runtime api.", + )?; + + let benchmark_api_version = runtime_version + .api_version( + &, + sp_runtime::generic::UncheckedExtrinsic<(), (), (), ()>, + >, + > as sp_api::RuntimeApiInfo>::ID, + ) + .ok_or_else(|| ERROR_API_NOT_FOUND)?; + let (list, storage_info): (Vec, Vec) = Self::exec_state_machine( StateMachine::new( @@ -318,7 +346,7 @@ impl PalletCmd { &runtime_code, CallContext::Offchain, ), - ERROR_METADATA_NOT_FOUND, + ERROR_API_NOT_FOUND, )?; // Use the benchmark list and the user input to determine the set of benchmarks to run. @@ -338,7 +366,7 @@ impl PalletCmd { let pov_modes = Self::parse_pov_modes(&benchmarks_to_run)?; let mut failed = Vec::<(String, String)>::new(); - 'outer: for (i, SelectedBenchmark { pallet, extrinsic, components, .. }) in + 'outer: for (i, SelectedBenchmark { pallet, instance, extrinsic, components, .. }) in benchmarks_to_run.clone().into_iter().enumerate() { log::info!( @@ -392,7 +420,31 @@ impl PalletCmd { } all_components }; + for (s, selected_components) in all_components.iter().enumerate() { + let params = |verify: bool, repeats: u32| -> Vec { + if benchmark_api_version >= 2 { + ( + pallet.as_bytes(), + instance.as_bytes(), + extrinsic.as_bytes(), + &selected_components.clone(), + verify, + repeats, + ) + .encode() + } else { + ( + pallet.as_bytes(), + extrinsic.as_bytes(), + &selected_components.clone(), + verify, + repeats, + ) + .encode() + } + }; + // First we run a verification if !self.no_verify { let state = &state_without_tracking; @@ -407,14 +459,7 @@ impl PalletCmd { &mut Default::default(), &executor, "Benchmark_dispatch_benchmark", - &( - pallet.as_bytes(), - extrinsic.as_bytes(), - &selected_components.clone(), - true, // run verification code - 1, // no need to do internal repeats - ) - .encode(), + ¶ms(true, 1), &mut Self::build_extensions(executor.clone(), state.recorder()), &runtime_code, CallContext::Offchain, @@ -447,14 +492,7 @@ impl PalletCmd { &mut Default::default(), &executor, "Benchmark_dispatch_benchmark", - &( - pallet.as_bytes(), - extrinsic.as_bytes(), - &selected_components.clone(), - false, // don't run verification code for final values - self.repeat, - ) - .encode(), + ¶ms(false, self.repeat), &mut Self::build_extensions(executor.clone(), state.recorder()), &runtime_code, CallContext::Offchain, @@ -489,14 +527,7 @@ impl PalletCmd { &mut Default::default(), &executor, "Benchmark_dispatch_benchmark", - &( - pallet.as_bytes(), - extrinsic.as_bytes(), - &selected_components.clone(), - false, // don't run verification code for final values - self.repeat, - ) - .encode(), + ¶ms(false, self.repeat), &mut Self::build_extensions(executor.clone(), state.recorder()), &runtime_code, CallContext::Offchain, @@ -571,6 +602,7 @@ impl PalletCmd { { benchmarks_to_run.push(( item.pallet.clone(), + item.instance.clone(), benchmark.name.clone(), benchmark.components.clone(), benchmark.pov_modes.clone(), @@ -581,13 +613,15 @@ impl PalletCmd { // Convert `Vec` to `String` for better readability. let benchmarks_to_run: Vec<_> = benchmarks_to_run .into_iter() - .map(|(pallet, extrinsic, components, pov_modes)| { - let pallet = String::from_utf8(pallet.clone()).expect("Encoded from String; qed"); + .map(|(pallet, instance, extrinsic, components, pov_modes)| { + let pallet = String::from_utf8(pallet).expect("Encoded from String; qed"); + let instance = String::from_utf8(instance).expect("Encoded from String; qed"); let extrinsic = String::from_utf8(extrinsic.clone()).expect("Encoded from String; qed"); SelectedBenchmark { pallet, + instance, extrinsic, components, pov_modes: pov_modes From a84f2598e1b1d0d0746e3032bd20e0a95a72d9cf Mon Sep 17 00:00:00 2001 From: Kazunobu Ndong <33208377+ndkazu@users.noreply.github.com> Date: Wed, 13 Nov 2024 22:08:09 +0900 Subject: [PATCH 088/166] Get rid of `libp2p` dependency in `sc-authority-discovery` (#5842) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Issue #4859 ## Description This PR removes `libp2p` types in authority-discovery, and replace them with network backend agnostic types from `sc-network-types`. The `sc-network` interface is therefore updated accordingly. --------- Co-authored-by: Bastian Köcher Co-authored-by: command-bot <> Co-authored-by: Dmitry Markin Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> --- Cargo.lock | 3 +- prdoc/pr_5842.prdoc | 18 ++ .../client/authority-discovery/Cargo.toml | 1 - .../client/authority-discovery/src/tests.rs | 2 +- .../client/authority-discovery/src/worker.rs | 6 +- .../src/worker/schema/tests.rs | 14 +- .../authority-discovery/src/worker/tests.rs | 12 +- substrate/client/network/src/behaviour.rs | 10 +- substrate/client/network/src/event.rs | 8 +- .../client/network/src/litep2p/discovery.rs | 2 +- substrate/client/network/src/litep2p/mod.rs | 16 +- .../client/network/src/litep2p/service.rs | 11 +- substrate/client/network/src/service.rs | 10 +- .../client/network/src/service/traits.rs | 9 +- substrate/client/network/src/types.rs | 2 - substrate/client/network/types/Cargo.toml | 2 + substrate/client/network/types/src/kad.rs | 185 ++++++++++++++++++ substrate/client/network/types/src/lib.rs | 2 +- 18 files changed, 258 insertions(+), 55 deletions(-) create mode 100644 prdoc/pr_5842.prdoc create mode 100644 substrate/client/network/types/src/kad.rs diff --git a/Cargo.lock b/Cargo.lock index f0a133227b32..775a7fe99e1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21989,7 +21989,6 @@ dependencies = [ "futures", "futures-timer", "ip_network", - "libp2p", "linked_hash_set", "log", "multihash 0.19.1", @@ -23092,8 +23091,10 @@ name = "sc-network-types" version = "0.10.0" dependencies = [ "bs58", + "bytes", "ed25519-dalek", "libp2p-identity", + "libp2p-kad", "litep2p", "log", "multiaddr 0.18.1", diff --git a/prdoc/pr_5842.prdoc b/prdoc/pr_5842.prdoc new file mode 100644 index 000000000000..0175c7583419 --- /dev/null +++ b/prdoc/pr_5842.prdoc @@ -0,0 +1,18 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Get rid of libp2p dependency in sc-authority-discovery + +doc: + - audience: Node Dev + description: | + Removes `libp2p` types in authority-discovery, and replace them with network backend agnostic types from `sc-network-types`. + The `sc-network` interface is therefore updated accordingly. + +crates: + - name: sc-network + bump: patch + - name: sc-network-types + bump: patch + - name: sc-authority-discovery + bump: patch diff --git a/substrate/client/authority-discovery/Cargo.toml b/substrate/client/authority-discovery/Cargo.toml index 09381ec6b553..fc88d07ef936 100644 --- a/substrate/client/authority-discovery/Cargo.toml +++ b/substrate/client/authority-discovery/Cargo.toml @@ -24,7 +24,6 @@ codec = { workspace = true } futures = { workspace = true } futures-timer = { workspace = true } ip_network = { workspace = true } -libp2p = { features = ["ed25519", "kad"], workspace = true } multihash = { workspace = true } linked_hash_set = { workspace = true } log = { workspace = true, default-features = true } diff --git a/substrate/client/authority-discovery/src/tests.rs b/substrate/client/authority-discovery/src/tests.rs index acfd0e61de01..a73515ee00d2 100644 --- a/substrate/client/authority-discovery/src/tests.rs +++ b/substrate/client/authority-discovery/src/tests.rs @@ -25,7 +25,7 @@ use crate::{ }; use futures::{channel::mpsc::channel, executor::LocalPool, task::LocalSpawn}; -use libp2p::identity::ed25519; +use sc_network_types::ed25519; use std::{collections::HashSet, sync::Arc}; use sc_network::{multiaddr::Protocol, Multiaddr, PeerId}; diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index 9319fbe6321e..ba82910efcdf 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -34,8 +34,8 @@ use futures::{channel::mpsc, future, stream::Fuse, FutureExt, Stream, StreamExt} use addr_cache::AddrCache; use codec::{Decode, Encode}; use ip_network::IpNetwork; -use libp2p::kad::{PeerRecord, Record}; use linked_hash_set::LinkedHashSet; +use sc_network_types::kad::{Key, PeerRecord, Record}; use log::{debug, error, trace}; use prometheus_endpoint::{register, Counter, CounterVec, Gauge, Opts, U64}; @@ -682,7 +682,7 @@ where async fn handle_put_record_requested( &mut self, - record_key: KademliaKey, + record_key: Key, record_value: Vec, publisher: Option, expires: Option, @@ -943,7 +943,7 @@ where authority_id, new_record.creation_time, current_record_info.creation_time, ); self.network.put_record_to( - current_record_info.record.clone(), + current_record_info.record.clone().into(), new_record.peers_with_record.clone(), // If this is empty it means we received the answer from our node local // storage, so we need to update that as well. diff --git a/substrate/client/authority-discovery/src/worker/schema/tests.rs b/substrate/client/authority-discovery/src/worker/schema/tests.rs index 557fa9641f97..1dff1b93e06d 100644 --- a/substrate/client/authority-discovery/src/worker/schema/tests.rs +++ b/substrate/client/authority-discovery/src/worker/schema/tests.rs @@ -26,9 +26,9 @@ mod schema_v2 { use super::*; use codec::Encode; -use libp2p::identity::Keypair; use prost::Message; use sc_network::{Multiaddr, PeerId}; +use sc_network_types::ed25519::Keypair; #[test] fn v2_decodes_v1() { @@ -61,7 +61,7 @@ fn v2_decodes_v1() { #[test] fn v1_decodes_v2() { - let peer_secret = Keypair::generate_ed25519(); + let peer_secret = Keypair::generate(); let peer_public = peer_secret.public(); let peer_id = peer_public.to_peer_id(); let multiaddress: Multiaddr = @@ -73,7 +73,7 @@ fn v1_decodes_v2() { let record_v2 = schema_v2::AuthorityRecord { addresses: vec_addresses.clone() }; let mut vec_record_v2 = vec![]; record_v2.encode(&mut vec_record_v2).unwrap(); - let vec_peer_public = peer_public.encode_protobuf(); + let vec_peer_public = peer_public.to_bytes().to_vec(); let peer_signature_v2 = PeerSignature { public_key: vec_peer_public, signature: vec_peer_signature }; let signed_record_v2 = SignedAuthorityRecord { @@ -97,7 +97,7 @@ fn v1_decodes_v2() { #[test] fn v1_decodes_v3() { - let peer_secret = Keypair::generate_ed25519(); + let peer_secret = Keypair::generate(); let peer_public = peer_secret.public(); let peer_id = peer_public.to_peer_id(); let multiaddress: Multiaddr = @@ -112,7 +112,7 @@ fn v1_decodes_v3() { }; let mut vec_record_v3 = vec![]; record_v3.encode(&mut vec_record_v3).unwrap(); - let vec_peer_public = peer_public.encode_protobuf(); + let vec_peer_public = peer_public.to_bytes().to_vec(); let peer_signature_v3 = PeerSignature { public_key: vec_peer_public, signature: vec_peer_signature }; let signed_record_v3 = SignedAuthorityRecord { @@ -136,7 +136,7 @@ fn v1_decodes_v3() { #[test] fn v3_decodes_v2() { - let peer_secret = Keypair::generate_ed25519(); + let peer_secret = Keypair::generate(); let peer_public = peer_secret.public(); let peer_id = peer_public.to_peer_id(); let multiaddress: Multiaddr = @@ -148,7 +148,7 @@ fn v3_decodes_v2() { let record_v2 = schema_v2::AuthorityRecord { addresses: vec_addresses.clone() }; let mut vec_record_v2 = vec![]; record_v2.encode(&mut vec_record_v2).unwrap(); - let vec_peer_public = peer_public.encode_protobuf(); + let vec_peer_public = peer_public.to_bytes().to_vec(); let peer_signature_v2 = schema_v2::PeerSignature { public_key: vec_peer_public, signature: vec_peer_signature }; let signed_record_v2 = schema_v2::SignedAuthorityRecord { diff --git a/substrate/client/authority-discovery/src/worker/tests.rs b/substrate/client/authority-discovery/src/worker/tests.rs index 8018b5ea492d..6c3a3b56b1cb 100644 --- a/substrate/client/authority-discovery/src/worker/tests.rs +++ b/substrate/client/authority-discovery/src/worker/tests.rs @@ -30,12 +30,14 @@ use futures::{ sink::SinkExt, task::LocalSpawn, }; -use libp2p::{identity::SigningError, kad::record::Key as KademliaKey}; use prometheus_endpoint::prometheus::default_registry; - use sc_client_api::HeaderBackend; -use sc_network::{service::signature::Keypair, Signature}; +use sc_network::{ + service::signature::{Keypair, SigningError}, + PublicKey, Signature, +}; use sc_network_types::{ + kad::Key as KademliaKey, multiaddr::{Multiaddr, Protocol}, PeerId, }; @@ -178,8 +180,8 @@ impl NetworkSigner for TestNetwork { signature: &Vec, message: &Vec, ) -> std::result::Result { - let public_key = libp2p::identity::PublicKey::try_decode_protobuf(&public_key) - .map_err(|error| error.to_string())?; + let public_key = + PublicKey::try_decode_protobuf(&public_key).map_err(|error| error.to_string())?; let peer_id: PeerId = peer_id.into(); let remote: PeerId = public_key.to_peer_id().into(); diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index 5ecbec52d507..dbb72381b660 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -375,18 +375,18 @@ impl From for BehaviourOut { }, DiscoveryOut::Discovered(peer_id) => BehaviourOut::Discovered(peer_id), DiscoveryOut::ValueFound(results, duration) => - BehaviourOut::Dht(DhtEvent::ValueFound(results), Some(duration)), + BehaviourOut::Dht(DhtEvent::ValueFound(results.into()), Some(duration)), DiscoveryOut::ValueNotFound(key, duration) => - BehaviourOut::Dht(DhtEvent::ValueNotFound(key), Some(duration)), + BehaviourOut::Dht(DhtEvent::ValueNotFound(key.into()), Some(duration)), DiscoveryOut::ValuePut(key, duration) => - BehaviourOut::Dht(DhtEvent::ValuePut(key), Some(duration)), + BehaviourOut::Dht(DhtEvent::ValuePut(key.into()), Some(duration)), DiscoveryOut::PutRecordRequest(record_key, record_value, publisher, expires) => BehaviourOut::Dht( - DhtEvent::PutRecordRequest(record_key, record_value, publisher, expires), + DhtEvent::PutRecordRequest(record_key.into(), record_value, publisher, expires), None, ), DiscoveryOut::ValuePutFailed(key, duration) => - BehaviourOut::Dht(DhtEvent::ValuePutFailed(key), Some(duration)), + BehaviourOut::Dht(DhtEvent::ValuePutFailed(key.into()), Some(duration)), DiscoveryOut::RandomKademliaStarted => BehaviourOut::RandomKademliaStarted, } } diff --git a/substrate/client/network/src/event.rs b/substrate/client/network/src/event.rs index 5400d11cb6ac..626cf516a7ec 100644 --- a/substrate/client/network/src/event.rs +++ b/substrate/client/network/src/event.rs @@ -22,12 +22,12 @@ use crate::types::ProtocolName; use bytes::Bytes; -use libp2p::{ - kad::{record::Key, PeerRecord}, - PeerId, -}; use sc_network_common::role::ObservedRole; +use sc_network_types::{ + kad::{Key, PeerRecord}, + PeerId, +}; /// Events generated by DHT as a response to get_value and put_value requests. #[derive(Debug, Clone)] diff --git a/substrate/client/network/src/litep2p/discovery.rs b/substrate/client/network/src/litep2p/discovery.rs index 9043f9420e8d..3a9454e317cc 100644 --- a/substrate/client/network/src/litep2p/discovery.rs +++ b/substrate/client/network/src/litep2p/discovery.rs @@ -27,7 +27,6 @@ use array_bytes::bytes2hex; use futures::{FutureExt, Stream}; use futures_timer::Delay; use ip_network::IpNetwork; -use libp2p::kad::record::Key as KademliaKey; use litep2p::{ protocol::{ libp2p::{ @@ -45,6 +44,7 @@ use litep2p::{ PeerId, ProtocolName, }; use parking_lot::RwLock; +use sc_network_types::kad::Key as KademliaKey; use schnellru::{ByLength, LruMap}; use std::{ diff --git a/substrate/client/network/src/litep2p/mod.rs b/substrate/client/network/src/litep2p/mod.rs index 87b992423674..15501dab688b 100644 --- a/substrate/client/network/src/litep2p/mod.rs +++ b/substrate/client/network/src/litep2p/mod.rs @@ -50,7 +50,6 @@ use crate::{ use codec::Encode; use futures::StreamExt; -use libp2p::kad::{PeerRecord, Record as P2PRecord, RecordKey}; use litep2p::{ config::ConfigBuilder, crypto::ed25519::Keypair, @@ -74,6 +73,7 @@ use litep2p::{ Litep2p, Litep2pEvent, ProtocolName as Litep2pProtocolName, }; use prometheus_endpoint::Registry; +use sc_network_types::kad::{Key as RecordKey, PeerRecord, Record as P2PRecord}; use sc_client_api::BlockBackend; use sc_network_common::{role::Roles, ExHashT}; @@ -711,8 +711,8 @@ impl NetworkBackend for Litep2pNetworkBac self.pending_put_values.insert(query_id, (key, Instant::now())); } NetworkServiceCommand::PutValueTo { record, peers, update_local_storage} => { - let kademlia_key = record.key.to_vec().into(); - let query_id = self.discovery.put_value_to_peers(record, peers, update_local_storage).await; + let kademlia_key = record.key.clone(); + let query_id = self.discovery.put_value_to_peers(record.into(), peers, update_local_storage).await; self.pending_put_values.insert(query_id, (kademlia_key, Instant::now())); } @@ -836,7 +836,7 @@ impl NetworkBackend for Litep2pNetworkBac self.event_streams.send( Event::Dht( DhtEvent::ValueFound( - record + record.into() ) ) ); @@ -864,7 +864,7 @@ impl NetworkBackend for Litep2pNetworkBac ); self.event_streams.send(Event::Dht( - DhtEvent::ValuePut(libp2p::kad::RecordKey::new(&key)) + DhtEvent::ValuePut(key) )); if let Some(ref metrics) = self.metrics { @@ -890,7 +890,7 @@ impl NetworkBackend for Litep2pNetworkBac ); self.event_streams.send(Event::Dht( - DhtEvent::ValuePutFailed(libp2p::kad::RecordKey::new(&key)) + DhtEvent::ValuePutFailed(key) )); if let Some(ref metrics) = self.metrics { @@ -908,7 +908,7 @@ impl NetworkBackend for Litep2pNetworkBac ); self.event_streams.send(Event::Dht( - DhtEvent::ValueNotFound(libp2p::kad::RecordKey::new(&key)) + DhtEvent::ValueNotFound(key) )); if let Some(ref metrics) = self.metrics { @@ -964,7 +964,7 @@ impl NetworkBackend for Litep2pNetworkBac Some(DiscoveryEvent::IncomingRecord { record: Record { key, value, publisher, expires }} ) => { self.event_streams.send(Event::Dht( DhtEvent::PutRecordRequest( - libp2p::kad::RecordKey::new(&key), + key.into(), value, publisher.map(Into::into), expires, diff --git a/substrate/client/network/src/litep2p/service.rs b/substrate/client/network/src/litep2p/service.rs index 693217f5ad94..fa1d47e5a1b7 100644 --- a/substrate/client/network/src/litep2p/service.rs +++ b/substrate/client/network/src/litep2p/service.rs @@ -32,15 +32,15 @@ use crate::{ RequestFailure, Signature, }; -use crate::litep2p::Record; use codec::DecodeAll; use futures::{channel::oneshot, stream::BoxStream}; -use libp2p::{identity::SigningError, kad::record::Key as KademliaKey}; +use libp2p::identity::SigningError; use litep2p::{ addresses::PublicAddresses, crypto::ed25519::Keypair, types::multiaddr::Multiaddr as LiteP2pMultiaddr, }; use parking_lot::RwLock; +use sc_network_types::kad::{Key as KademliaKey, Record}; use sc_network_common::{ role::{ObservedRole, Roles}, @@ -266,12 +266,7 @@ impl NetworkDHTProvider for Litep2pNetworkService { let _ = self.cmd_tx.unbounded_send(NetworkServiceCommand::PutValue { key, value }); } - fn put_record_to( - &self, - record: libp2p::kad::Record, - peers: HashSet, - update_local_storage: bool, - ) { + fn put_record_to(&self, record: Record, peers: HashSet, update_local_storage: bool) { let _ = self.cmd_tx.unbounded_send(NetworkServiceCommand::PutValueTo { record: Record { key: record.key.to_vec().into(), diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 71d0b45aa06d..5e5e4ee28589 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -68,7 +68,6 @@ use libp2p::{ core::{upgrade, ConnectedPoint, Endpoint}, identify::Info as IdentifyInfo, identity::ed25519, - kad::{record::Key as KademliaKey, Record}, multiaddr::{self, Multiaddr}, swarm::{ Config as SwarmConfig, ConnectionError, ConnectionId, DialError, Executor, ListenError, @@ -80,6 +79,7 @@ use log::{debug, error, info, trace, warn}; use metrics::{Histogram, MetricSources, Metrics}; use parking_lot::Mutex; use prometheus_endpoint::Registry; +use sc_network_types::kad::{Key as KademliaKey, Record}; use sc_client_api::BlockBackend; use sc_network_common::{ @@ -1455,17 +1455,17 @@ where fn handle_worker_message(&mut self, msg: ServiceToWorkerMsg) { match msg { ServiceToWorkerMsg::GetValue(key) => - self.network_service.behaviour_mut().get_value(key), + self.network_service.behaviour_mut().get_value(key.into()), ServiceToWorkerMsg::PutValue(key, value) => - self.network_service.behaviour_mut().put_value(key, value), + self.network_service.behaviour_mut().put_value(key.into(), value), ServiceToWorkerMsg::PutRecordTo { record, peers, update_local_storage } => self .network_service .behaviour_mut() - .put_record_to(record, peers, update_local_storage), + .put_record_to(record.into(), peers, update_local_storage), ServiceToWorkerMsg::StoreRecord(key, value, publisher, expires) => self .network_service .behaviour_mut() - .store_record(key, value, publisher, expires), + .store_record(key.into(), value, publisher, expires), ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) => self.network_service.behaviour_mut().add_known_address(peer_id, addr), ServiceToWorkerMsg::EventStream(sender) => self.event_streams.push(sender), diff --git a/substrate/client/network/src/service/traits.rs b/substrate/client/network/src/service/traits.rs index bd4f83c7fd44..f5dd2995acb1 100644 --- a/substrate/client/network/src/service/traits.rs +++ b/substrate/client/network/src/service/traits.rs @@ -32,12 +32,15 @@ use crate::{ }; use futures::{channel::oneshot, Stream}; -use libp2p::kad::Record; use prometheus_endpoint::Registry; use sc_client_api::BlockBackend; use sc_network_common::{role::ObservedRole, ExHashT}; -use sc_network_types::{multiaddr::Multiaddr, PeerId}; +pub use sc_network_types::{ + kad::{Key as KademliaKey, Record}, + multiaddr::Multiaddr, + PeerId, +}; use sp_runtime::traits::Block as BlockT; use std::{ @@ -49,7 +52,7 @@ use std::{ time::{Duration, Instant}, }; -pub use libp2p::{identity::SigningError, kad::record::Key as KademliaKey}; +pub use libp2p::identity::SigningError; /// Supertrait defining the services provided by [`NetworkBackend`] service handle. pub trait NetworkService: diff --git a/substrate/client/network/src/types.rs b/substrate/client/network/src/types.rs index 0652bbcdddec..5289389de381 100644 --- a/substrate/client/network/src/types.rs +++ b/substrate/client/network/src/types.rs @@ -26,8 +26,6 @@ use std::{ sync::Arc, }; -pub use libp2p::{multiaddr, Multiaddr, PeerId}; - /// The protocol name transmitted on the wire. #[derive(Debug, Clone)] pub enum ProtocolName { diff --git a/substrate/client/network/types/Cargo.toml b/substrate/client/network/types/Cargo.toml index 655f104111e4..7438eaeffcd2 100644 --- a/substrate/client/network/types/Cargo.toml +++ b/substrate/client/network/types/Cargo.toml @@ -11,8 +11,10 @@ documentation = "https://docs.rs/sc-network-types" [dependencies] bs58 = { workspace = true, default-features = true } +bytes = { version = "1.4.0", default-features = false } ed25519-dalek = { workspace = true, default-features = true } libp2p-identity = { features = ["ed25519", "peerid", "rand"], workspace = true } +libp2p-kad = { version = "0.44.6", default-features = false } litep2p = { workspace = true } log = { workspace = true, default-features = true } multiaddr = { workspace = true } diff --git a/substrate/client/network/types/src/kad.rs b/substrate/client/network/types/src/kad.rs new file mode 100644 index 000000000000..72028d356dc7 --- /dev/null +++ b/substrate/client/network/types/src/kad.rs @@ -0,0 +1,185 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program 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. + +// This program 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 this program. If not, see . + +use crate::{multihash::Multihash, PeerId}; +use bytes::Bytes; +use libp2p_kad::RecordKey as Libp2pKey; +use litep2p::protocol::libp2p::kademlia::{Record as Litep2pRecord, RecordKey as Litep2pKey}; +use std::{error::Error, fmt, time::Instant}; + +/// The (opaque) key of a record. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Key(Bytes); + +impl Key { + /// Creates a new key from the bytes of the input. + pub fn new>(key: &K) -> Self { + Key(Bytes::copy_from_slice(key.as_ref())) + } + + /// Copies the bytes of the key into a new vector. + pub fn to_vec(&self) -> Vec { + self.0.to_vec() + } +} + +impl AsRef<[u8]> for Key { + fn as_ref(&self) -> &[u8] { + &self.0[..] + } +} + +impl From> for Key { + fn from(v: Vec) -> Key { + Key(Bytes::from(v)) + } +} + +impl From for Key { + fn from(m: Multihash) -> Key { + Key::from(m.to_bytes()) + } +} + +impl From for Key { + fn from(key: Litep2pKey) -> Self { + Self::from(key.to_vec()) + } +} + +impl From for Litep2pKey { + fn from(key: Key) -> Self { + Self::from(key.to_vec()) + } +} + +impl From for Key { + fn from(key: Libp2pKey) -> Self { + Self::from(key.to_vec()) + } +} + +impl From for Libp2pKey { + fn from(key: Key) -> Self { + Self::from(key.to_vec()) + } +} + +/// A record stored in the DHT. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Record { + /// Key of the record. + pub key: Key, + /// Value of the record. + pub value: Vec, + /// The (original) publisher of the record. + pub publisher: Option, + /// The expiration time as measured by a local, monotonic clock. + pub expires: Option, +} + +impl Record { + /// Creates a new record for insertion into the DHT. + pub fn new(key: Key, value: Vec) -> Self { + Record { key, value, publisher: None, expires: None } + } + + /// Checks whether the record is expired w.r.t. the given `Instant`. + pub fn is_expired(&self, now: Instant) -> bool { + self.expires.map_or(false, |t| now >= t) + } +} + +impl From for Record { + fn from(out: libp2p_kad::Record) -> Self { + let vec: Vec = out.key.to_vec(); + let key: Key = vec.into(); + let publisher = out.publisher.map(Into::into); + Record { key, value: out.value, publisher, expires: out.expires } + } +} + +impl From for Litep2pRecord { + fn from(val: Record) -> Self { + let vec: Vec = val.key.to_vec(); + let key: Litep2pKey = vec.into(); + let publisher = val.publisher.map(Into::into); + Litep2pRecord { key, value: val.value, publisher, expires: val.expires } + } +} + +impl From for libp2p_kad::Record { + fn from(a: Record) -> libp2p_kad::Record { + let peer = a.publisher.map(Into::into); + libp2p_kad::Record { + key: a.key.to_vec().into(), + value: a.value, + publisher: peer, + expires: a.expires, + } + } +} + +/// A record either received by the given peer or retrieved from the local +/// record store. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PeerRecord { + /// The peer from whom the record was received. `None` if the record was + /// retrieved from local storage. + pub peer: Option, + pub record: Record, +} + +impl From for PeerRecord { + fn from(out: libp2p_kad::PeerRecord) -> Self { + let peer = out.peer.map(Into::into); + let record = out.record.into(); + PeerRecord { peer, record } + } +} + +/// An error during signing of a message. +#[derive(Debug)] +pub struct SigningError { + msg: String, + source: Option>, +} + +/// An error during encoding of key material. +#[allow(dead_code)] +impl SigningError { + pub(crate) fn new(msg: S) -> Self { + Self { msg: msg.to_string(), source: None } + } + + pub(crate) fn source(self, source: impl Error + Send + Sync + 'static) -> Self { + Self { source: Some(Box::new(source)), ..self } + } +} + +impl fmt::Display for SigningError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Key signing error: {}", self.msg) + } +} + +impl Error for SigningError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + self.source.as_ref().map(|s| &**s as &dyn Error) + } +} diff --git a/substrate/client/network/types/src/lib.rs b/substrate/client/network/types/src/lib.rs index 5684e38ab2e8..093d81533f60 100644 --- a/substrate/client/network/types/src/lib.rs +++ b/substrate/client/network/types/src/lib.rs @@ -17,8 +17,8 @@ // along with this program. If not, see . pub mod ed25519; +pub mod kad; pub mod multiaddr; pub mod multihash; - mod peer_id; pub use peer_id::PeerId; From e617d1d07388b3aad0377d49d0812f6889c9050a Mon Sep 17 00:00:00 2001 From: Stephane Gurgenidze <59443568+sw10pa@users.noreply.github.com> Date: Wed, 13 Nov 2024 14:47:22 +0100 Subject: [PATCH 089/166] backing: improve session buffering for runtime information (#6284) ## Issue [[#3421] backing: improve session buffering for runtime information](https://github.com/paritytech/polkadot-sdk/issues/3421) ## Description In the current implementation of the backing module, certain pieces of information, which remain unchanged throughout a session, are fetched multiple times via runtime API calls. The goal of this task was to introduce a local cache to store such session-stable information and perform the runtime API call only once per session. This PR implements caching specifically for the validators list, node features, executor parameters, minimum backing votes threshold, and validator-to-group mapping, which were previously fetched from the runtime or computed each time `PerRelayParentState` was built. Now, this information is cached and reused within the session. ## TODO * [X] Create a separate struct for per-session caches; * [X] Cache validators list; * [X] Cache node features; * [X] Cache executor parameters; * [X] Cache minimum backing votes threshold; * [X] Cache validator-to-group mapping; * [X] Update tests to reflect these changes; * [X] Add prdoc. ## For the next PR Cache validator groups and any other session-stable data (if present). --- polkadot/node/core/backing/src/error.rs | 3 + polkadot/node/core/backing/src/lib.rs | 269 ++++++++++++++---- polkadot/node/core/backing/src/tests/mod.rs | 189 ++++++------ .../src/tests/prospective_parachains.rs | 143 +++++----- prdoc/pr_6284.prdoc | 22 ++ 5 files changed, 405 insertions(+), 221 deletions(-) create mode 100644 prdoc/pr_6284.prdoc diff --git a/polkadot/node/core/backing/src/error.rs b/polkadot/node/core/backing/src/error.rs index e09d8425f78a..e1852be826f4 100644 --- a/polkadot/node/core/backing/src/error.rs +++ b/polkadot/node/core/backing/src/error.rs @@ -105,6 +105,9 @@ pub enum Error { #[error("Availability store error")] StoreAvailableData(#[source] StoreAvailableDataError), + + #[error("Runtime API returned None for executor params")] + MissingExecutorParams, } /// Utility for eating top level errors and log them. diff --git a/polkadot/node/core/backing/src/lib.rs b/polkadot/node/core/backing/src/lib.rs index 30121418a2fd..250013c6541a 100644 --- a/polkadot/node/core/backing/src/lib.rs +++ b/polkadot/node/core/backing/src/lib.rs @@ -93,12 +93,13 @@ use polkadot_node_subsystem::{ RuntimeApiMessage, RuntimeApiRequest, StatementDistributionMessage, StoreAvailableDataError, }, - overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError, + overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, RuntimeApiError, SpawnedSubsystem, + SubsystemError, }; use polkadot_node_subsystem_util::{ self as util, backing_implicit_view::{FetchError as ImplicitViewFetchError, View as ImplicitView}, - executor_params_at_relay_parent, request_from_runtime, request_session_index_for_child, + request_from_runtime, request_session_executor_params, request_session_index_for_child, request_validator_groups, request_validators, runtime::{ self, fetch_claim_queue, prospective_parachains_mode, request_min_backing_votes, @@ -217,8 +218,10 @@ struct PerRelayParentState { prospective_parachains_mode: ProspectiveParachainsMode, /// The hash of the relay parent on top of which this job is doing it's work. parent: Hash, - /// Session index. - session_index: SessionIndex, + /// The node features. + node_features: NodeFeatures, + /// The executor parameters. + executor_params: Arc, /// The `CoreIndex` assigned to the local validator at this relay parent. assigned_core: Option, /// The candidates that are backed by enough validators in their group, by hash. @@ -292,6 +295,178 @@ impl From<&ActiveLeafState> for ProspectiveParachainsMode { } } +/// A cache for storing data per-session to reduce repeated +/// runtime API calls and avoid redundant computations. +struct PerSessionCache { + /// Cache for storing validators list, retrieved from the runtime. + validators_cache: LruMap>>, + /// Cache for storing node features, retrieved from the runtime. + node_features_cache: LruMap>, + /// Cache for storing executor parameters, retrieved from the runtime. + executor_params_cache: LruMap>, + /// Cache for storing the minimum backing votes threshold, retrieved from the runtime. + minimum_backing_votes_cache: LruMap, + /// Cache for storing validator-to-group mappings, computed from validator groups. + validator_to_group_cache: + LruMap>>>, +} + +impl Default for PerSessionCache { + /// Creates a new `PerSessionCache` with a default capacity. + fn default() -> Self { + Self::new(2) + } +} + +impl PerSessionCache { + /// Creates a new `PerSessionCache` with a given capacity. + fn new(capacity: u32) -> Self { + PerSessionCache { + validators_cache: LruMap::new(ByLength::new(capacity)), + node_features_cache: LruMap::new(ByLength::new(capacity)), + executor_params_cache: LruMap::new(ByLength::new(capacity)), + minimum_backing_votes_cache: LruMap::new(ByLength::new(capacity)), + validator_to_group_cache: LruMap::new(ByLength::new(capacity)), + } + } + + /// Gets validators from the cache or fetches them from the runtime if not present. + async fn validators( + &mut self, + session_index: SessionIndex, + parent: Hash, + sender: &mut impl overseer::SubsystemSender, + ) -> Result>, RuntimeApiError> { + // Try to get the validators list from the cache. + if let Some(validators) = self.validators_cache.get(&session_index) { + return Ok(Arc::clone(validators)); + } + + // Fetch the validators list from the runtime since it was not in the cache. + let validators: Vec = + request_validators(parent, sender).await.await.map_err(|err| { + RuntimeApiError::Execution { runtime_api_name: "Validators", source: Arc::new(err) } + })??; + + // Wrap the validators list in an Arc to avoid a deep copy when storing it in the cache. + let validators = Arc::new(validators); + + // Cache the fetched validators list for future use. + self.validators_cache.insert(session_index, Arc::clone(&validators)); + + Ok(validators) + } + + /// Gets the node features from the cache or fetches it from the runtime if not present. + async fn node_features( + &mut self, + session_index: SessionIndex, + parent: Hash, + sender: &mut impl overseer::SubsystemSender, + ) -> Result, Error> { + // Try to get the node features from the cache. + if let Some(node_features) = self.node_features_cache.get(&session_index) { + return Ok(node_features.clone()); + } + + // Fetch the node features from the runtime since it was not in the cache. + let node_features: Option = + request_node_features(parent, session_index, sender).await?; + + // Cache the fetched node features for future use. + self.node_features_cache.insert(session_index, node_features.clone()); + + Ok(node_features) + } + + /// Gets the executor parameters from the cache or + /// fetches them from the runtime if not present. + async fn executor_params( + &mut self, + session_index: SessionIndex, + parent: Hash, + sender: &mut impl overseer::SubsystemSender, + ) -> Result, RuntimeApiError> { + // Try to get the executor parameters from the cache. + if let Some(executor_params) = self.executor_params_cache.get(&session_index) { + return Ok(Arc::clone(executor_params)); + } + + // Fetch the executor parameters from the runtime since it was not in the cache. + let executor_params = request_session_executor_params(parent, session_index, sender) + .await + .await + .map_err(|err| RuntimeApiError::Execution { + runtime_api_name: "SessionExecutorParams", + source: Arc::new(err), + })?? + .ok_or_else(|| RuntimeApiError::Execution { + runtime_api_name: "SessionExecutorParams", + source: Arc::new(Error::MissingExecutorParams), + })?; + + // Wrap the executor parameters in an Arc to avoid a deep copy when storing it in the cache. + let executor_params = Arc::new(executor_params); + + // Cache the fetched executor parameters for future use. + self.executor_params_cache.insert(session_index, Arc::clone(&executor_params)); + + Ok(executor_params) + } + + /// Gets the minimum backing votes threshold from the + /// cache or fetches it from the runtime if not present. + async fn minimum_backing_votes( + &mut self, + session_index: SessionIndex, + parent: Hash, + sender: &mut impl overseer::SubsystemSender, + ) -> Result { + // Try to get the value from the cache. + if let Some(minimum_backing_votes) = self.minimum_backing_votes_cache.get(&session_index) { + return Ok(*minimum_backing_votes); + } + + // Fetch the value from the runtime since it was not in the cache. + let minimum_backing_votes = request_min_backing_votes(parent, session_index, sender) + .await + .map_err(|err| RuntimeApiError::Execution { + runtime_api_name: "MinimumBackingVotes", + source: Arc::new(err), + })?; + + // Cache the fetched value for future use. + self.minimum_backing_votes_cache.insert(session_index, minimum_backing_votes); + + Ok(minimum_backing_votes) + } + + /// Gets or computes the validator-to-group mapping for a session. + fn validator_to_group( + &mut self, + session_index: SessionIndex, + validators: &[ValidatorId], + validator_groups: &[Vec], + ) -> Arc>> { + let validator_to_group = self + .validator_to_group_cache + .get_or_insert(session_index, || { + let mut vector = vec![None; validators.len()]; + + for (group_idx, validator_group) in validator_groups.iter().enumerate() { + for validator in validator_group { + vector[validator.0 as usize] = Some(GroupIndex(group_idx as u32)); + } + } + + Arc::new(IndexedVec::<_, _>::from(vector)) + }) + .expect("Just inserted"); + + Arc::clone(validator_to_group) + } +} + /// The state of the subsystem. struct State { /// The utility for managing the implicit and explicit views in a consistent way. @@ -322,9 +497,9 @@ struct State { /// This is guaranteed to have an entry for each candidate with a relay parent in the implicit /// or explicit view for which a `Seconded` statement has been successfully imported. per_candidate: HashMap, - /// Cache the per-session Validator->Group mapping. - validator_to_group_cache: - LruMap>>>, + /// A local cache for storing per-session data. This cache helps to + /// reduce repeated calls to the runtime and avoid redundant computations. + per_session_cache: PerSessionCache, /// A clonable sender which is dispatched to background candidate validation tasks to inform /// the main task of the result. background_validation_tx: mpsc::Sender<(Hash, ValidatedCandidateCommand)>, @@ -342,7 +517,7 @@ impl State { per_leaf: HashMap::default(), per_relay_parent: HashMap::default(), per_candidate: HashMap::new(), - validator_to_group_cache: LruMap::new(ByLength::new(2)), + per_session_cache: PerSessionCache::default(), background_validation_tx, keystore, } @@ -670,7 +845,8 @@ struct BackgroundValidationParams { tx_command: mpsc::Sender<(Hash, ValidatedCandidateCommand)>, candidate: CandidateReceipt, relay_parent: Hash, - session_index: SessionIndex, + node_features: NodeFeatures, + executor_params: Arc, persisted_validation_data: PersistedValidationData, pov: PoVData, n_validators: usize, @@ -689,7 +865,8 @@ async fn validate_and_make_available( mut tx_command, candidate, relay_parent, - session_index, + node_features, + executor_params, persisted_validation_data, pov, n_validators, @@ -714,15 +891,6 @@ async fn validate_and_make_available( } }; - let executor_params = match executor_params_at_relay_parent(relay_parent, &mut sender).await { - Ok(ep) => ep, - Err(e) => return Err(Error::UtilError(e)), - }; - - let node_features = request_node_features(relay_parent, session_index, &mut sender) - .await? - .unwrap_or(NodeFeatures::EMPTY); - let pov = match pov { PoVData::Ready(pov) => pov, PoVData::FetchFromValidator { from_validator, candidate_hash, pov_hash } => @@ -758,7 +926,7 @@ async fn validate_and_make_available( validation_code, candidate.clone(), pov.clone(), - executor_params, + executor_params.as_ref().clone(), ) .await? }; @@ -985,7 +1153,7 @@ async fn handle_active_leaves_update( ctx, maybe_new, &state.keystore, - &mut state.validator_to_group_cache, + &mut state.per_session_cache, mode, ) .await?; @@ -1085,17 +1253,13 @@ async fn construct_per_relay_parent_state( ctx: &mut Context, relay_parent: Hash, keystore: &KeystorePtr, - validator_to_group_cache: &mut LruMap< - SessionIndex, - Arc>>, - >, + per_session_cache: &mut PerSessionCache, mode: ProspectiveParachainsMode, ) -> Result, Error> { let parent = relay_parent; - let (session_index, validators, groups, cores) = futures::try_join!( + let (session_index, groups, cores) = futures::try_join!( request_session_index_for_child(parent, ctx.sender()).await, - request_validators(parent, ctx.sender()).await, request_validator_groups(parent, ctx.sender()).await, request_from_runtime(parent, ctx.sender(), |tx| { RuntimeApiRequest::AvailabilityCores(tx) @@ -1106,20 +1270,32 @@ async fn construct_per_relay_parent_state( let session_index = try_runtime_api!(session_index); - let inject_core_index = request_node_features(parent, session_index, ctx.sender()) + let validators = per_session_cache.validators(session_index, parent, ctx.sender()).await; + let validators = try_runtime_api!(validators); + + let node_features = per_session_cache + .node_features(session_index, parent, ctx.sender()) .await? - .unwrap_or(NodeFeatures::EMPTY) + .unwrap_or(NodeFeatures::EMPTY); + + let inject_core_index = node_features .get(FeatureIndex::ElasticScalingMVP as usize) .map(|b| *b) .unwrap_or(false); + let executor_params = + per_session_cache.executor_params(session_index, parent, ctx.sender()).await; + let executor_params = try_runtime_api!(executor_params); + gum::debug!(target: LOG_TARGET, inject_core_index, ?parent, "New state"); - let validators: Vec<_> = try_runtime_api!(validators); let (validator_groups, group_rotation_info) = try_runtime_api!(groups); let cores = try_runtime_api!(cores); - let minimum_backing_votes = - try_runtime_api!(request_min_backing_votes(parent, session_index, ctx.sender()).await); + + let minimum_backing_votes = per_session_cache + .minimum_backing_votes(session_index, parent, ctx.sender()) + .await; + let minimum_backing_votes = try_runtime_api!(minimum_backing_votes); // TODO: https://github.com/paritytech/polkadot-sdk/issues/1940 // Once runtime ver `DISABLED_VALIDATORS_RUNTIME_REQUIREMENT` is released remove this call to @@ -1192,21 +1368,11 @@ async fn construct_per_relay_parent_state( } gum::debug!(target: LOG_TARGET, ?groups, "TableContext"); - let validator_to_group = validator_to_group_cache - .get_or_insert(session_index, || { - let mut vector = vec![None; validators.len()]; - - for (group_idx, validator_group) in validator_groups.iter().enumerate() { - for validator in validator_group { - vector[validator.0 as usize] = Some(GroupIndex(group_idx as u32)); - } - } - - Arc::new(IndexedVec::<_, _>::from(vector)) - }) - .expect("Just inserted"); + let validator_to_group = + per_session_cache.validator_to_group(session_index, &validators, &validator_groups); - let table_context = TableContext { validator, groups, validators, disabled_validators }; + let table_context = + TableContext { validator, groups, validators: validators.to_vec(), disabled_validators }; let table_config = TableConfig { allow_multiple_seconded: match mode { ProspectiveParachainsMode::Enabled { .. } => true, @@ -1217,7 +1383,8 @@ async fn construct_per_relay_parent_state( Ok(Some(PerRelayParentState { prospective_parachains_mode: mode, parent, - session_index, + node_features, + executor_params, assigned_core, backed: HashSet::new(), table: Table::new(table_config), @@ -1229,7 +1396,7 @@ async fn construct_per_relay_parent_state( inject_core_index, n_cores: cores.len() as u32, claim_queue: ClaimQueueSnapshot::from(claim_queue), - validator_to_group: validator_to_group.clone(), + validator_to_group, group_rotation_info, })) } @@ -1895,7 +2062,8 @@ async fn kick_off_validation_work( tx_command: background_validation_tx.clone(), candidate: attesting.candidate, relay_parent: rp_state.parent, - session_index: rp_state.session_index, + node_features: rp_state.node_features.clone(), + executor_params: Arc::clone(&rp_state.executor_params), persisted_validation_data, pov, n_validators: rp_state.table_context.validators.len(), @@ -2049,7 +2217,8 @@ async fn validate_and_second( tx_command: background_validation_tx.clone(), candidate: candidate.clone(), relay_parent: rp_state.parent, - session_index: rp_state.session_index, + node_features: rp_state.node_features.clone(), + executor_params: Arc::clone(&rp_state.executor_params), persisted_validation_data, pov: PoVData::Ready(pov), n_validators: rp_state.table_context.validators.len(), diff --git a/polkadot/node/core/backing/src/tests/mod.rs b/polkadot/node/core/backing/src/tests/mod.rs index 97e25c04282c..5e3d50373870 100644 --- a/polkadot/node/core/backing/src/tests/mod.rs +++ b/polkadot/node/core/backing/src/tests/mod.rs @@ -69,6 +69,14 @@ fn dummy_pvd() -> PersistedValidationData { } } +#[derive(Default)] +struct PerSessionCacheState { + has_cached_validators: bool, + has_cached_node_features: bool, + has_cached_executor_params: bool, + has_cached_minimum_backing_votes: bool, +} + pub(crate) struct TestState { chain_ids: Vec, keystore: KeystorePtr, @@ -85,6 +93,7 @@ pub(crate) struct TestState { minimum_backing_votes: u32, disabled_validators: Vec, node_features: NodeFeatures, + per_session_cache_state: PerSessionCacheState, } impl TestState { @@ -157,6 +166,7 @@ impl Default for TestState { chain_ids, keystore, validators, + per_session_cache_state: PerSessionCacheState::default(), validator_public, validator_groups: (validator_groups, group_rotation_info), validator_to_group, @@ -251,7 +261,7 @@ impl TestCandidateBuilder { } // Tests that the subsystem performs actions that are required on startup. -async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestState) { +async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &mut TestState) { // Start work on some new parent. virtual_overseer .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves(ActiveLeavesUpdate::start_work( @@ -278,16 +288,6 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS } ); - // Check that subsystem job issues a request for a validator set. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.validator_public.clone())).unwrap(); - } - ); - // Check that subsystem job issues a request for the validator groups. assert_matches!( virtual_overseer.recv().await, @@ -308,26 +308,58 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS } ); - // Node features request from runtime: all features are disabled. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) - ) => { - tx.send(Ok(test_state.node_features.clone())).unwrap(); - } - ); + if !test_state.per_session_cache_state.has_cached_validators { + // Check that subsystem job issues a request for a validator set. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) + ) if parent == test_state.relay_parent => { + tx.send(Ok(test_state.validator_public.clone())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_validators = true; + } - // Check if subsystem job issues a request for the minimum backing votes. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::MinimumBackingVotes(session_index, tx), - )) if parent == test_state.relay_parent && session_index == test_state.signing_context.session_index => { - tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); - } - ); + if !test_state.per_session_cache_state.has_cached_node_features { + // Node features request from runtime: all features are disabled. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(_parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) + ) => { + tx.send(Ok(test_state.node_features.clone())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_node_features = true; + } + + if !test_state.per_session_cache_state.has_cached_executor_params { + // Check if subsystem job issues a request for the executor parameters. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(_parent, RuntimeApiRequest::SessionExecutorParams(_session_index, tx)) + ) => { + tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_executor_params = true; + } + + if !test_state.per_session_cache_state.has_cached_minimum_backing_votes { + // Check if subsystem job issues a request for the minimum backing votes. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::MinimumBackingVotes(session_index, tx), + )) if parent == test_state.relay_parent && session_index == test_state.signing_context.session_index => { + tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_minimum_backing_votes = true; + } // Check that subsystem job issues a request for the runtime version. assert_matches!( @@ -382,33 +414,6 @@ async fn assert_validation_requests( tx.send(Ok(Some(validation_code))).unwrap(); } ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::SessionIndexForChild(tx)) - ) => { - tx.send(Ok(1u32.into())).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::SessionExecutorParams(sess_idx, tx)) - ) if sess_idx == 1 => { - tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(sess_idx, tx)) - ) if sess_idx == 1 => { - tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } async fn assert_validate_from_exhaustive( @@ -458,9 +463,9 @@ async fn assert_validate_from_exhaustive( // and in case validation is successful issues a `StatementDistributionMessage`. #[test] fn backing_second_works() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -554,7 +559,7 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { } test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_ab = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd_ab = dummy_pvd(); @@ -772,7 +777,7 @@ fn get_backed_candidate_preserves_order() { .insert(CoreIndex(2), [test_state.chain_ids[1]].into_iter().collect()); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pov_b = PoV { block_data: BlockData(vec![3, 4, 5]) }; @@ -1171,9 +1176,9 @@ fn extract_core_index_from_statement_works() { #[test] fn backing_works_while_validation_ongoing() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_abc = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd_abc = dummy_pvd(); @@ -1366,9 +1371,9 @@ fn backing_works_while_validation_ongoing() { // be a misbehavior. #[test] fn backing_misbehavior_works() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![1, 2, 3]) }; @@ -1552,9 +1557,9 @@ fn backing_misbehavior_works() { // can still second a valid one afterwards. #[test] fn backing_dont_second_invalid() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_block_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -1712,9 +1717,9 @@ fn backing_dont_second_invalid() { // candidate we will not be issuing a `Seconded` statement on it. #[test] fn backing_second_after_first_fails_works() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -1858,9 +1863,9 @@ fn backing_second_after_first_fails_works() { // the work of this subsystem and so it is not fatal to the node. #[test] fn backing_works_after_failed_validation() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -2037,9 +2042,9 @@ fn candidate_backing_reorders_votes() { #[test] fn retry_works() { // sp_tracing::try_init_simple(); - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -2134,7 +2139,7 @@ fn retry_works() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; // Not deterministic which message comes first: - for _ in 0u32..6 { + for _ in 0u32..3 { match virtual_overseer.recv().await { AllMessages::Provisioner(ProvisionerMessage::ProvisionableData( _, @@ -2153,24 +2158,6 @@ fn retry_works() { )) if hash == validation_code_a.hash() => { tx.send(Ok(Some(validation_code_a.clone()))).unwrap(); }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::SessionIndexForChild(tx), - )) => { - tx.send(Ok(1u32.into())).unwrap(); - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::SessionExecutorParams(1, tx), - )) => { - tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::NodeFeatures(1, tx), - )) => { - tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - }, msg => { assert!(false, "Unexpected message: {:?}", msg); }, @@ -2221,10 +2208,10 @@ fn retry_works() { #[test] fn observes_backing_even_if_not_validator() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); let empty_keystore = Arc::new(sc_keystore::LocalKeystore::in_memory()); test_harness(empty_keystore, |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd = dummy_pvd(); @@ -2340,9 +2327,9 @@ fn observes_backing_even_if_not_validator() { // without prospective parachains. #[test] fn cannot_second_multiple_candidates_per_parent() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2478,13 +2465,13 @@ fn new_leaf_view_doesnt_clobber_old() { let relay_parent_2 = Hash::repeat_byte(1); assert_ne!(test_state.relay_parent, relay_parent_2); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; // New leaf that doesn't clobber old. { let old_relay_parent = test_state.relay_parent; test_state.relay_parent = relay_parent_2; - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; test_state.relay_parent = old_relay_parent; } @@ -2537,7 +2524,7 @@ fn disabled_validator_doesnt_distribute_statement_on_receiving_second() { test_state.disabled_validators.push(ValidatorIndex(0)); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2585,7 +2572,7 @@ fn disabled_validator_doesnt_distribute_statement_on_receiving_statement() { test_state.disabled_validators.push(ValidatorIndex(0)); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2647,7 +2634,7 @@ fn validator_ignores_statements_from_disabled_validators() { test_state.disabled_validators.push(ValidatorIndex(2)); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &test_state).await; + test_startup(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); diff --git a/polkadot/node/core/backing/src/tests/prospective_parachains.rs b/polkadot/node/core/backing/src/tests/prospective_parachains.rs index db5409ee4bd5..a05408eff85d 100644 --- a/polkadot/node/core/backing/src/tests/prospective_parachains.rs +++ b/polkadot/node/core/backing/src/tests/prospective_parachains.rs @@ -39,7 +39,7 @@ fn get_parent_hash(hash: Hash) -> Hash { async fn activate_leaf( virtual_overseer: &mut VirtualOverseer, leaf: TestLeaf, - test_state: &TestState, + test_state: &mut TestState, ) { let TestLeaf { activated, min_relay_parents } = leaf; let leaf_hash = activated.hash; @@ -140,16 +140,6 @@ async fn activate_leaf( } ); - // Check that subsystem job issues a request for a validator set. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) - ) if parent == hash => { - tx.send(Ok(test_state.validator_public.clone())).unwrap(); - } - ); - // Check that subsystem job issues a request for the validator groups. assert_matches!( virtual_overseer.recv().await, @@ -172,26 +162,58 @@ async fn activate_leaf( } ); - // Node features request from runtime: all features are disabled. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) - ) if parent == hash => { - tx.send(Ok(Default::default())).unwrap(); - } - ); + if !test_state.per_session_cache_state.has_cached_validators { + // Check that subsystem job issues a request for a validator set. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) + ) if parent == hash => { + tx.send(Ok(test_state.validator_public.clone())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_validators = true; + } - // Check if subsystem job issues a request for the minimum backing votes. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::MinimumBackingVotes(session_index, tx), - )) if parent == hash && session_index == test_state.signing_context.session_index => { - tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); - } - ); + if !test_state.per_session_cache_state.has_cached_node_features { + // Node features request from runtime: all features are disabled. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) + ) if parent == hash => { + tx.send(Ok(Default::default())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_node_features = true; + } + + if !test_state.per_session_cache_state.has_cached_executor_params { + // Check if subsystem job issues a request for the executor parameters. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionExecutorParams(_session_index, tx)) + ) if parent == hash => { + tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_executor_params = true; + } + + if !test_state.per_session_cache_state.has_cached_minimum_backing_votes { + // Check if subsystem job issues a request for the minimum backing votes. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::MinimumBackingVotes(session_index, tx), + )) if parent == hash && session_index == test_state.signing_context.session_index => { + tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_minimum_backing_votes = true; + } // Check that subsystem job issues a request for the runtime version. assert_matches!( @@ -348,7 +370,7 @@ fn make_hypothetical_membership_response( // for all leaves. #[test] fn seconding_sanity_check_allowed_on_all() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate is seconded in a parent of the activated `leaf_a`. const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; @@ -370,8 +392,8 @@ fn seconding_sanity_check_allowed_on_all() { let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; let test_leaf_b = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; - activate_leaf(&mut virtual_overseer, test_leaf_b, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -480,7 +502,7 @@ fn seconding_sanity_check_allowed_on_all() { // for all leaves. #[test] fn seconding_sanity_check_disallowed() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate is seconded in a parent of the activated `leaf_a`. const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; @@ -502,7 +524,7 @@ fn seconding_sanity_check_disallowed() { let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; let test_leaf_b = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -594,8 +616,9 @@ fn seconding_sanity_check_disallowed() { } ); - activate_leaf(&mut virtual_overseer, test_leaf_b, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; let leaf_a_grandparent = get_parent_hash(leaf_a_parent); + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); let candidate = TestCandidateBuilder { para_id, relay_parent: leaf_a_grandparent, @@ -667,7 +690,7 @@ fn seconding_sanity_check_disallowed() { // leaf. #[test] fn seconding_sanity_check_allowed_on_at_least_one_leaf() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate is seconded in a parent of the activated `leaf_a`. const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; @@ -689,8 +712,8 @@ fn seconding_sanity_check_allowed_on_at_least_one_leaf() { let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; let test_leaf_b = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; - activate_leaf(&mut virtual_overseer, test_leaf_b, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -798,7 +821,7 @@ fn seconding_sanity_check_allowed_on_at_least_one_leaf() { // subsystem doesn't change the view. #[test] fn prospective_parachains_reject_candidate() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate is seconded in a parent of the activated `leaf_a`. const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; @@ -811,7 +834,7 @@ fn prospective_parachains_reject_candidate() { let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -961,7 +984,7 @@ fn prospective_parachains_reject_candidate() { // Test that a validator can second multiple candidates per single relay parent. #[test] fn second_multiple_candidates_per_relay_parent() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate `a` is seconded in a parent of the activated `leaf`. const LEAF_BLOCK_NUMBER: BlockNumber = 100; @@ -975,7 +998,7 @@ fn second_multiple_candidates_per_relay_parent() { let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -1083,7 +1106,7 @@ fn second_multiple_candidates_per_relay_parent() { // Test that the candidate reaches quorum successfully. #[test] fn backing_works() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate `a` is seconded in a parent of the activated `leaf`. const LEAF_BLOCK_NUMBER: BlockNumber = 100; @@ -1096,7 +1119,7 @@ fn backing_works() { let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -1225,7 +1248,7 @@ fn backing_works() { // Tests that validators start work on consecutive prospective parachain blocks. #[test] fn concurrent_dependent_candidates() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate `a` is seconded in a grandparent of the activated `leaf`, // candidate `b` -- in parent. @@ -1240,7 +1263,7 @@ fn concurrent_dependent_candidates() { let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let head_data = &[ HeadData(vec![10, 20, 30]), // Before `a`. @@ -1436,32 +1459,12 @@ fn concurrent_dependent_candidates() { break } }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::SessionIndexForChild(tx), - )) => { - tx.send(Ok(1u32.into())).unwrap(); - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::SessionExecutorParams(sess_idx, tx), - )) => { - assert_eq!(sess_idx, 1); - tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); - }, AllMessages::RuntimeApi(RuntimeApiMessage::Request( _parent, RuntimeApiRequest::ValidatorGroups(tx), )) => { tx.send(Ok(test_state.validator_groups.clone())).unwrap(); }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::NodeFeatures(sess_idx, tx), - )) => { - assert_eq!(sess_idx, 1); - tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - }, AllMessages::RuntimeApi(RuntimeApiMessage::Request( _parent, RuntimeApiRequest::AvailabilityCores(tx), @@ -1485,7 +1488,7 @@ fn concurrent_dependent_candidates() { // in a given relay parent. #[test] fn seconding_sanity_check_occupy_same_depth() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { // Candidate `a` is seconded in a parent of the activated `leaf`. const LEAF_BLOCK_NUMBER: BlockNumber = 100; @@ -1502,7 +1505,7 @@ fn seconding_sanity_check_occupy_same_depth() { let min_relay_parents = vec![(para_id_a, min_block_number), (para_id_b, min_block_number)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -1647,7 +1650,7 @@ fn occupied_core_assignment() { let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; let test_leaf_a = TestLeaf { activated, min_relay_parents }; - activate_leaf(&mut virtual_overseer, test_leaf_a, &test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); diff --git a/prdoc/pr_6284.prdoc b/prdoc/pr_6284.prdoc new file mode 100644 index 000000000000..e2d9ebb526d2 --- /dev/null +++ b/prdoc/pr_6284.prdoc @@ -0,0 +1,22 @@ +title: "backing: improve session buffering for runtime information" + +doc: + - audience: Node Dev + description: | + This PR implements caching within the backing module for session-stable information, + reducing redundant runtime API calls. + + Specifically, it introduces a local cache for the: + - validators list; + - node features; + - executor parameters; + - minimum backing votes threshold; + - validator-to-group mapping. + + Previously, this data was fetched or computed repeatedly each time `PerRelayParentState` + was built. With this update, the cached information is fetched once and reused throughout + the session. + +crates: + - name: polkadot-node-core-backing + bump: patch From 6b84431e6c1dcda4b989ec0ca6bb88ab97750cd8 Mon Sep 17 00:00:00 2001 From: Andrei Eres Date: Wed, 13 Nov 2024 19:37:03 +0100 Subject: [PATCH 090/166] Add litep2p network protocol benches (#6455) # Description Add support to run networking protocol benchmarks with litep2p backend. Now we can compare the work of both libp2p and litep2p backends for notifications and request-response protocols. Next step: extract worker initialization from the benchmark loop. ### Example run on local machine image ## Integration Does not affect downstream projects. ## Review Notes https://github.com/paritytech/polkadot-sdk/blob/d4d9502538e8a940b809ecc77843af3cea101e19/substrate/client/network/src/litep2p/service.rs#L510-L520 This method should be implemented to run request benchmarks. --------- Co-authored-by: GitHub Action --- prdoc/pr_6455.prdoc | 8 ++ .../network/benches/notifications_protocol.rs | 114 ++++++++++++----- .../benches/request_response_protocol.rs | 115 +++++++++++------- 3 files changed, 164 insertions(+), 73 deletions(-) create mode 100644 prdoc/pr_6455.prdoc diff --git a/prdoc/pr_6455.prdoc b/prdoc/pr_6455.prdoc new file mode 100644 index 000000000000..9a83048e2fd2 --- /dev/null +++ b/prdoc/pr_6455.prdoc @@ -0,0 +1,8 @@ +title: Add litep2p network protocol benches +doc: +- audience: Node Dev + description: |- + Adds networking protocol benchmarks with litep2p backend +crates: +- name: sc-network + validate: false diff --git a/substrate/client/network/benches/notifications_protocol.rs b/substrate/client/network/benches/notifications_protocol.rs index 7d32c9faeba1..c1e18c7b7f47 100644 --- a/substrate/client/network/benches/notifications_protocol.rs +++ b/substrate/client/network/benches/notifications_protocol.rs @@ -22,15 +22,17 @@ use criterion::{ }; use sc_network::{ config::{ - FullNetworkConfiguration, MultiaddrWithPeerId, NetworkConfiguration, NonDefaultSetConfig, - NonReservedPeerMode, NotificationHandshake, Params, ProtocolId, Role, SetConfig, + FullNetworkConfiguration, MultiaddrWithPeerId, NetworkConfiguration, NonReservedPeerMode, + NotificationHandshake, Params, ProtocolId, Role, SetConfig, }, service::traits::NotificationEvent, - NetworkWorker, NotificationMetrics, NotificationService, Roles, + Litep2pNetworkBackend, NetworkBackend, NetworkWorker, NotificationMetrics, NotificationService, + Roles, }; -use sc_network_common::sync::message::BlockAnnouncesHandshake; +use sc_network_common::{sync::message::BlockAnnouncesHandshake, ExHashT}; use sc_network_types::build_multiaddr; -use sp_runtime::traits::Zero; +use sp_core::H256; +use sp_runtime::traits::{Block as BlockT, Zero}; use std::{ net::{IpAddr, Ipv4Addr, TcpListener}, str::FromStr, @@ -61,12 +63,20 @@ fn get_listen_address() -> sc_network::Multiaddr { build_multiaddr!(Ip4(ip), Tcp(port)) } -pub fn create_network_worker( +fn create_network_worker( listen_addr: sc_network::Multiaddr, -) -> (NetworkWorker, Box) { +) -> (N, Box) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let role = Role::Full; + let mut net_conf = NetworkConfiguration::new_local(); + net_conf.listen_addresses = vec![listen_addr]; + let network_config = FullNetworkConfiguration::::new(&net_conf, None); let genesis_hash = runtime::Hash::zero(); - let (block_announce_config, notification_service) = NonDefaultSetConfig::new( + let (block_announce_config, notification_service) = N::notification_config( "/block-announces/1".into(), vec!["/bench-notifications-protocol/block-announces/1".into()], MAX_SIZE, @@ -82,21 +92,17 @@ pub fn create_network_worker( reserved_nodes: vec![], non_reserved_mode: NonReservedPeerMode::Accept, }, + NotificationMetrics::new(None), + network_config.peer_store_handle(), ); - let mut net_conf = NetworkConfiguration::new_local(); - net_conf.listen_addresses = vec![listen_addr]; - let worker = NetworkWorker::::new(Params::< - runtime::Block, - runtime::Hash, - NetworkWorker<_, _>, - > { + let worker = N::new(Params:: { block_announce_config, role, executor: Box::new(|f| { tokio::spawn(f); }), genesis_hash, - network_config: FullNetworkConfiguration::new(&net_conf, None), + network_config, protocol_id: ProtocolId::from("bench-protocol-name"), fork_id: None, metrics_registry: None, @@ -108,14 +114,21 @@ pub fn create_network_worker( (worker, notification_service) } -async fn run_serially(size: usize, limit: usize) { +async fn run_serially(size: usize, limit: usize) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let listen_address1 = get_listen_address(); let listen_address2 = get_listen_address(); - let (worker1, mut notification_service1) = create_network_worker(listen_address1); - let (worker2, mut notification_service2) = create_network_worker(listen_address2.clone()); - let peer_id2: sc_network::PeerId = (*worker2.local_peer_id()).into(); + let (worker1, mut notification_service1) = create_network_worker::(listen_address1); + let (worker2, mut notification_service2) = + create_network_worker::(listen_address2.clone()); + let peer_id2: sc_network::PeerId = worker2.network_service().local_peer_id().into(); worker1 + .network_service() .add_reserved_peer(MultiaddrWithPeerId { multiaddr: listen_address2, peer_id: peer_id2 }) .unwrap(); @@ -124,6 +137,7 @@ async fn run_serially(size: usize, limit: usize) { let (tx, rx) = async_channel::bounded(10); let network1 = tokio::spawn(async move { + let mut sent_counter = 0; tokio::pin!(network1_run); loop { tokio::select! { @@ -131,17 +145,25 @@ async fn run_serially(size: usize, limit: usize) { event = notification_service1.next_event() => { match event { Some(NotificationEvent::NotificationStreamOpened { .. }) => { + sent_counter += 1; notification_service1 .send_async_notification(&peer_id2, vec![0; size]) .await .unwrap(); }, + Some(NotificationEvent::NotificationStreamClosed { .. }) => { + if sent_counter >= limit { + break; + } + panic!("Unexpected stream closure {:?}", event); + } event => panic!("Unexpected event {:?}", event), }; }, message = rx.recv() => { match message { Ok(Some(_)) => { + sent_counter += 1; notification_service1 .send_async_notification(&peer_id2, vec![0; size]) .await @@ -185,14 +207,21 @@ async fn run_serially(size: usize, limit: usize) { let _ = tokio::join!(network1, network2); } -async fn run_with_backpressure(size: usize, limit: usize) { +async fn run_with_backpressure(size: usize, limit: usize) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let listen_address1 = get_listen_address(); let listen_address2 = get_listen_address(); - let (worker1, mut notification_service1) = create_network_worker(listen_address1); - let (worker2, mut notification_service2) = create_network_worker(listen_address2.clone()); - let peer_id2: sc_network::PeerId = (*worker2.local_peer_id()).into(); + let (worker1, mut notification_service1) = create_network_worker::(listen_address1); + let (worker2, mut notification_service2) = + create_network_worker::(listen_address2.clone()); + let peer_id2: sc_network::PeerId = worker2.network_service().local_peer_id().into(); worker1 + .network_service() .add_reserved_peer(MultiaddrWithPeerId { multiaddr: listen_address2, peer_id: peer_id2 }) .unwrap(); @@ -265,18 +294,47 @@ fn run_benchmark(c: &mut Criterion) { for &(exponent, label) in EXPONENTS.iter() { let size = 2usize.pow(exponent); group.throughput(Throughput::Bytes(NOTIFICATIONS as u64 * size as u64)); + + group.bench_with_input( + BenchmarkId::new("libp2p/serially", label), + &(size, NOTIFICATIONS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| { + run_serially::>(size, limit) + }); + }, + ); + group.bench_with_input( + BenchmarkId::new("litep2p/serially", label), + &(size, NOTIFICATIONS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| { + run_serially::( + size, limit, + ) + }); + }, + ); group.bench_with_input( - BenchmarkId::new("consistently", label), + BenchmarkId::new("libp2p/with_backpressure", label), &(size, NOTIFICATIONS), |b, &(size, limit)| { - b.to_async(&rt).iter(|| run_serially(size, limit)); + b.to_async(&rt).iter(|| { + run_with_backpressure::>( + size, limit, + ) + }); }, ); group.bench_with_input( - BenchmarkId::new("with_backpressure", label), + BenchmarkId::new("litep2p/with_backpressure", label), &(size, NOTIFICATIONS), |b, &(size, limit)| { - b.to_async(&rt).iter(|| run_with_backpressure(size, limit)); + b.to_async(&rt).iter(|| { + run_with_backpressure::( + size, limit, + ) + }); }, ); } diff --git a/substrate/client/network/benches/request_response_protocol.rs b/substrate/client/network/benches/request_response_protocol.rs index 09bf829f5a7e..b428d0d75ac5 100644 --- a/substrate/client/network/benches/request_response_protocol.rs +++ b/substrate/client/network/benches/request_response_protocol.rs @@ -22,16 +22,16 @@ use criterion::{ }; use sc_network::{ config::{ - FullNetworkConfiguration, IncomingRequest, NetworkConfiguration, NonDefaultSetConfig, - NonReservedPeerMode, NotificationHandshake, OutgoingResponse, Params, ProtocolId, Role, - SetConfig, + FullNetworkConfiguration, IncomingRequest, NetworkConfiguration, NonReservedPeerMode, + NotificationHandshake, OutgoingResponse, Params, ProtocolId, Role, SetConfig, }, - IfDisconnected, NetworkBackend, NetworkRequest, NetworkWorker, NotificationMetrics, - NotificationService, Roles, + IfDisconnected, Litep2pNetworkBackend, NetworkBackend, NetworkRequest, NetworkWorker, + NotificationMetrics, NotificationService, Roles, }; -use sc_network_common::sync::message::BlockAnnouncesHandshake; +use sc_network_common::{sync::message::BlockAnnouncesHandshake, ExHashT}; use sc_network_types::build_multiaddr; -use sp_runtime::traits::Zero; +use sp_core::H256; +use sp_runtime::traits::{Block as BlockT, Zero}; use std::{ net::{IpAddr, Ipv4Addr, TcpListener}, str::FromStr, @@ -62,36 +62,38 @@ fn get_listen_address() -> sc_network::Multiaddr { build_multiaddr!(Ip4(ip), Tcp(port)) } -pub fn create_network_worker( +pub fn create_network_worker( listen_addr: sc_network::Multiaddr, -) -> ( - NetworkWorker, - async_channel::Receiver, - Box, -) { +) -> (N, async_channel::Receiver, Box) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let (tx, rx) = async_channel::bounded(10); - let request_response_config = - NetworkWorker::::request_response_config( - "/request-response/1".into(), - vec![], - MAX_SIZE, - MAX_SIZE, - Duration::from_secs(2), - Some(tx), - ); + let request_response_config = N::request_response_config( + "/request-response/1".into(), + vec![], + MAX_SIZE, + MAX_SIZE, + Duration::from_secs(2), + Some(tx), + ); + let role = Role::Full; let mut net_conf = NetworkConfiguration::new_local(); net_conf.listen_addresses = vec![listen_addr]; let mut network_config = FullNetworkConfiguration::new(&net_conf, None); network_config.add_request_response_protocol(request_response_config); - let (block_announce_config, notification_service) = NonDefaultSetConfig::new( + let genesis_hash = runtime::Hash::zero(); + let (block_announce_config, notification_service) = N::notification_config( "/block-announces/1".into(), vec![], 1024, Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( Roles::from(&Role::Full), Zero::zero(), - runtime::Hash::zero(), - runtime::Hash::zero(), + genesis_hash, + genesis_hash, ))), SetConfig { in_peers: 1, @@ -99,14 +101,12 @@ pub fn create_network_worker( reserved_nodes: vec![], non_reserved_mode: NonReservedPeerMode::Accept, }, + NotificationMetrics::new(None), + network_config.peer_store_handle(), ); - let worker = NetworkWorker::::new(Params::< - runtime::Block, - runtime::Hash, - NetworkWorker<_, _>, - > { + let worker = N::new(Params:: { block_announce_config, - role: Role::Full, + role, executor: Box::new(|f| { tokio::spawn(f); }), @@ -123,15 +123,21 @@ pub fn create_network_worker( (worker, rx, notification_service) } -async fn run_serially(size: usize, limit: usize) { +async fn run_serially(size: usize, limit: usize) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let listen_address1 = get_listen_address(); let listen_address2 = get_listen_address(); - let (mut worker1, _rx1, _notification_service1) = create_network_worker(listen_address1); - let service1 = worker1.service().clone(); - let (worker2, rx2, _notification_service2) = create_network_worker(listen_address2.clone()); - let peer_id2 = *worker2.local_peer_id(); + let (worker1, _rx1, _notification_service1) = create_network_worker::(listen_address1); + let service1 = worker1.network_service().clone(); + let (worker2, rx2, _notification_service2) = + create_network_worker::(listen_address2.clone()); + let peer_id2 = worker2.network_service().local_peer_id(); - worker1.add_known_address(peer_id2, listen_address2.into()); + worker1.network_service().add_known_address(peer_id2, listen_address2.into()); let network1_run = worker1.run(); let network2_run = worker2.run(); @@ -188,15 +194,21 @@ async fn run_serially(size: usize, limit: usize) { // The libp2p request-response implementation does not provide any backpressure feedback. // So this benchmark is useless until we implement it for litep2p. #[allow(dead_code)] -async fn run_with_backpressure(size: usize, limit: usize) { +async fn run_with_backpressure(size: usize, limit: usize) +where + B: BlockT + 'static, + H: ExHashT, + N: NetworkBackend, +{ let listen_address1 = get_listen_address(); let listen_address2 = get_listen_address(); - let (mut worker1, _rx1, _notification_service1) = create_network_worker(listen_address1); - let service1 = worker1.service().clone(); - let (worker2, rx2, _notification_service2) = create_network_worker(listen_address2.clone()); - let peer_id2 = *worker2.local_peer_id(); + let (worker1, _rx1, _notification_service1) = create_network_worker::(listen_address1); + let service1 = worker1.network_service().clone(); + let (worker2, rx2, _notification_service2) = + create_network_worker::(listen_address2.clone()); + let peer_id2 = worker2.network_service().local_peer_id(); - worker1.add_known_address(peer_id2, listen_address2.into()); + worker1.network_service().add_known_address(peer_id2, listen_address2.into()); let network1_run = worker1.run(); let network2_run = worker2.run(); @@ -261,10 +273,23 @@ fn run_benchmark(c: &mut Criterion) { let size = 2usize.pow(exponent); group.throughput(Throughput::Bytes(REQUESTS as u64 * size as u64)); group.bench_with_input( - BenchmarkId::new("consistently", label), + BenchmarkId::new("libp2p/serially", label), + &(size, REQUESTS), + |b, &(size, limit)| { + b.to_async(&rt).iter(|| { + run_serially::>(size, limit) + }); + }, + ); + group.bench_with_input( + BenchmarkId::new("litep2p/serially", label), &(size, REQUESTS), |b, &(size, limit)| { - b.to_async(&rt).iter(|| run_serially(size, limit)); + b.to_async(&rt).iter(|| { + run_serially::( + size, limit, + ) + }); }, ); } From bff395f8777dfd85bc0297665c1a68787ed4ea1a Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Wed, 13 Nov 2024 21:24:35 +0100 Subject: [PATCH 091/166] Fixed bridges zombienet tests because of removed NetworkId::Rococo/Westend from xcm::v5 (#6465) Closes: https://github.com/paritytech/polkadot-sdk/issues/6449 --- .../rococo-westend/bridges_rococo_westend.sh | 121 ++++++++++-------- .../js-helpers/wrapped-assets-balance.js | 14 +- bridges/testing/framework/utils/bridges.sh | 4 +- .../roc-reaches-westend.zndsl | 2 +- .../wnd-reaches-rococo.zndsl | 2 +- 5 files changed, 75 insertions(+), 68 deletions(-) diff --git a/bridges/testing/environments/rococo-westend/bridges_rococo_westend.sh b/bridges/testing/environments/rococo-westend/bridges_rococo_westend.sh index e7848fe7163c..321f4d9f26d0 100755 --- a/bridges/testing/environments/rococo-westend/bridges_rococo_westend.sh +++ b/bridges/testing/environments/rococo-westend/bridges_rococo_westend.sh @@ -7,47 +7,52 @@ source "$FRAMEWORK_PATH/utils/bridges.sh" # # Generated by: # -# #[test] -# fn generate_sovereign_accounts() { -# use sp_core::crypto::Ss58Codec; -# use polkadot_parachain_primitives::primitives::Sibling; +##[test] +#fn generate_sovereign_accounts() { +# use polkadot_parachain_primitives::primitives::Sibling; +# use sp_core::crypto::Ss58Codec; +# use staging_xcm_builder::{GlobalConsensusConvertsFor, SiblingParachainConvertsVia}; +# use xcm::latest::{prelude::*, ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH}; +# use xcm_executor::traits::ConvertLocation; # -# parameter_types! { -# pub UniversalLocationAHR: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(1000)); -# pub UniversalLocationAHW: InteriorMultiLocation = X2(GlobalConsensus(Westend), Parachain(1000)); -# } +# const Rococo: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); +# const Westend: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH); +# frame_support::parameter_types! { +# pub UniversalLocationAHR: InteriorLocation = [GlobalConsensus(Rococo), Parachain(1000)].into(); +# pub UniversalLocationAHW: InteriorLocation = [GlobalConsensus(Westend), Parachain(1000)].into(); +# } # -# // SS58=42 -# println!("GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT=\"{}\"", -# frame_support::sp_runtime::AccountId32::new( -# GlobalConsensusConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X1(GlobalConsensus(Rococo)) }).unwrap() -# ).to_ss58check_with_version(42_u16.into()) -# ); -# println!("ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND=\"{}\"", -# frame_support::sp_runtime::AccountId32::new( -# SiblingParachainConvertsVia::::convert_location( -# &MultiLocation { parents: 1, interior: X1(Parachain(1000)) }).unwrap() -# ).to_ss58check_with_version(42_u16.into()) -# ); +# // SS58=42 +# println!("GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT=\"{}\"", +# frame_support::sp_runtime::AccountId32::new( +# GlobalConsensusConvertsFor::::convert_location( +# &Location { parents: 2, interior: GlobalConsensus(Rococo).into() }).unwrap() +# ).to_ss58check_with_version(42_u16.into()) +# ); +# println!("ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND=\"{}\"", +# frame_support::sp_runtime::AccountId32::new( +# SiblingParachainConvertsVia::::convert_location( +# &Location { parents: 1, interior: Parachain(1000).into() }).unwrap() +# ).to_ss58check_with_version(42_u16.into()) +# ); # -# // SS58=42 -# println!("GLOBAL_CONSENSUS_WESTEND_SOVEREIGN_ACCOUNT=\"{}\"", -# frame_support::sp_runtime::AccountId32::new( -# GlobalConsensusConvertsFor::::convert_location( -# &MultiLocation { parents: 2, interior: X1(GlobalConsensus(Westend)) }).unwrap() -# ).to_ss58check_with_version(42_u16.into()) -# ); -# println!("ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO=\"{}\"", -# frame_support::sp_runtime::AccountId32::new( -# SiblingParachainConvertsVia::::convert_location( -# &MultiLocation { parents: 1, interior: X1(Parachain(1000)) }).unwrap() -# ).to_ss58check_with_version(42_u16.into()) -# ); -# } -GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT="5GxRGwT8bU1JeBPTUXc7LEjZMxNrK8MyL2NJnkWFQJTQ4sii" +# // SS58=42 +# println!("GLOBAL_CONSENSUS_WESTEND_SOVEREIGN_ACCOUNT=\"{}\"", +# frame_support::sp_runtime::AccountId32::new( +# GlobalConsensusConvertsFor::::convert_location( +# &Location { parents: 2, interior: GlobalConsensus(Westend).into() }).unwrap() +# ).to_ss58check_with_version(42_u16.into()) +# ); +# println!("ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO=\"{}\"", +# frame_support::sp_runtime::AccountId32::new( +# SiblingParachainConvertsVia::::convert_location( +# &Location { parents: 1, interior: Parachain(1000).into() }).unwrap() +# ).to_ss58check_with_version(42_u16.into()) +# ); +#} +GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT="5HmYPhRNAenHN6xnDLQDLZq71d4BgzPrdJ2sNZo8o1KXi9wr" ASSET_HUB_WESTEND_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_WESTEND="5Eg2fntNprdN3FgH4sfEaaZhYtddZQSQUqvYJ1f2mLtinVhV" -GLOBAL_CONSENSUS_WESTEND_SOVEREIGN_ACCOUNT="5He2Qdztyxxa4GoagY6q1jaiLMmKy1gXS7PdZkhfj8ZG9hk5" +GLOBAL_CONSENSUS_WESTEND_SOVEREIGN_ACCOUNT="5CtHyjQE8fbPaQeBrwaGph6qsSEtnMFBAZcAkxwnEfQkkYAq" ASSET_HUB_ROCOCO_SOVEREIGN_ACCOUNT_AT_BRIDGE_HUB_ROCOCO="5Eg2fntNprdN3FgH4sfEaaZhYtddZQSQUqvYJ1f2mLtinVhV" # Expected sovereign accounts for rewards on BridgeHubs. @@ -115,7 +120,11 @@ ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_ThisChain="5EHnXa ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain="5EHnXaT5Tnt3VGpEvc6jSgYwVToDGxLRMuYoZ8coo6GHyWbR" LANE_ID="00000002" -XCM_VERSION=3 +XCM_VERSION=5 +# 6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e +ROCOCO_GENESIS_HASH=[100,8,222,119,55,197,156,35,136,144,83,58,242,88,150,162,194,6,8,216,179,128,187,1,2,154,203,57,39,129,6,62] +# e143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e +WESTEND_GENESIS_HASH=[225,67,242,56,3,172,80,232,246,248,230,38,149,209,206,158,78,29,104,170,54,193,205,44,253,21,52,2,19,243,66,62] function init_ro_wnd() { local relayer_path=$(ensure_relayer) @@ -270,7 +279,7 @@ case "$1" in "//Alice" \ 1000 \ "ws://127.0.0.1:9910" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": "Westend" }] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }] } }')" \ "$GLOBAL_CONSENSUS_WESTEND_SOVEREIGN_ACCOUNT" \ 10000000000 \ true @@ -289,7 +298,7 @@ case "$1" in "//Alice" \ 1000 \ "ws://127.0.0.1:9910" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1000 } ] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } }')" \ $XCM_VERSION ;; init-bridge-hub-rococo-local) @@ -318,7 +327,7 @@ case "$1" in "//Alice" \ 1013 \ "ws://127.0.0.1:8943" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1002 } ] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1002 } ] } }')" \ $XCM_VERSION ;; init-asset-hub-westend-local) @@ -329,7 +338,7 @@ case "$1" in "//Alice" \ 1000 \ "ws://127.0.0.1:9010" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": "Rococo" }] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }] } }')" \ "$GLOBAL_CONSENSUS_ROCOCO_SOVEREIGN_ACCOUNT" \ 10000000000 \ true @@ -348,7 +357,7 @@ case "$1" in "//Alice" \ 1000 \ "ws://127.0.0.1:9010" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1000 } ] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } }')" \ $XCM_VERSION ;; init-bridge-hub-westend-local) @@ -376,7 +385,7 @@ case "$1" in "//Alice" \ 1002 \ "ws://127.0.0.1:8945" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1013 } ] } }')" \ + "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1013 } ] } }')" \ $XCM_VERSION ;; reserve-transfer-assets-from-asset-hub-rococo-local) @@ -386,9 +395,9 @@ case "$1" in limited_reserve_transfer_assets \ "ws://127.0.0.1:9910" \ "//Alice" \ - "$(jq --null-input '{ "V3": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1000 } ] } } }')" \ - "$(jq --null-input '{ "V3": { "parents": 0, "interior": { "X1": { "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } } } } }')" \ - "$(jq --null-input '{ "V3": [ { "id": { "Concrete": { "parents": 1, "interior": "Here" } }, "fun": { "Fungible": '$amount' } } ] }')" \ + "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \ + "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \ + "$(jq --null-input '{ "V5": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \ 0 \ "Unlimited" ;; @@ -399,9 +408,9 @@ case "$1" in limited_reserve_transfer_assets \ "ws://127.0.0.1:9910" \ "//Alice" \ - "$(jq --null-input '{ "V3": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1000 } ] } } }')" \ - "$(jq --null-input '{ "V3": { "parents": 0, "interior": { "X1": { "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } } } } }')" \ - "$(jq --null-input '{ "V3": [ { "id": { "Concrete": { "parents": 2, "interior": { "X1": { "GlobalConsensus": "Westend" } } } }, "fun": { "Fungible": '$amount' } } ] }')" \ + "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \ + "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \ + "$(jq --null-input '{ "V5": [ { "id": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$WESTEND_GENESIS_HASH' } }] } }, "fun": { "Fungible": '$amount' } } ] }')" \ 0 \ "Unlimited" ;; @@ -412,9 +421,9 @@ case "$1" in limited_reserve_transfer_assets \ "ws://127.0.0.1:9010" \ "//Alice" \ - "$(jq --null-input '{ "V3": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1000 } ] } } }')" \ - "$(jq --null-input '{ "V3": { "parents": 0, "interior": { "X1": { "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } } } } }')" \ - "$(jq --null-input '{ "V3": [ { "id": { "Concrete": { "parents": 1, "interior": "Here" } }, "fun": { "Fungible": '$amount' } } ] }')" \ + "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \ + "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \ + "$(jq --null-input '{ "V5": [ { "id": { "parents": 1, "interior": "Here" }, "fun": { "Fungible": '$amount' } } ] }')" \ 0 \ "Unlimited" ;; @@ -425,9 +434,9 @@ case "$1" in limited_reserve_transfer_assets \ "ws://127.0.0.1:9010" \ "//Alice" \ - "$(jq --null-input '{ "V3": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1000 } ] } } }')" \ - "$(jq --null-input '{ "V3": { "parents": 0, "interior": { "X1": { "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } } } } }')" \ - "$(jq --null-input '{ "V3": [ { "id": { "Concrete": { "parents": 2, "interior": { "X1": { "GlobalConsensus": "Rococo" } } } }, "fun": { "Fungible": '$amount' } } ] }')" \ + "$(jq --null-input '{ "V5": { "parents": 2, "interior": { "X2": [ { "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }, { "Parachain": 1000 } ] } } }')" \ + "$(jq --null-input '{ "V5": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "id": [212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125] } }] } } }')" \ + "$(jq --null-input '{ "V5": [ { "id": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { ByGenesis: '$ROCOCO_GENESIS_HASH' } }] } }, "fun": { "Fungible": '$amount' } } ] }')" \ 0 \ "Unlimited" ;; diff --git a/bridges/testing/framework/js-helpers/wrapped-assets-balance.js b/bridges/testing/framework/js-helpers/wrapped-assets-balance.js index 7b343ed97a88..837b3a3b1dbc 100644 --- a/bridges/testing/framework/js-helpers/wrapped-assets-balance.js +++ b/bridges/testing/framework/js-helpers/wrapped-assets-balance.js @@ -3,17 +3,15 @@ async function run(nodeName, networkInfo, args) { const api = await zombie.connect(wsUri, userDefinedTypes); // TODO: could be replaced with https://github.com/polkadot-js/api/issues/4930 (depends on metadata v15) later - const accountAddress = args[0]; - const expectedForeignAssetBalance = BigInt(args[1]); - const bridgedNetworkName = args[2]; + const accountAddress = args.accountAddress; + const expectedAssetId = args.expectedAssetId; + const expectedAssetBalance = BigInt(args.expectedAssetBalance); + while (true) { - const foreignAssetAccount = await api.query.foreignAssets.account( - { parents: 2, interior: { X1: [{ GlobalConsensus: bridgedNetworkName }] } }, - accountAddress - ); + const foreignAssetAccount = await api.query.foreignAssets.account(expectedAssetId, accountAddress); if (foreignAssetAccount.isSome) { const foreignAssetAccountBalance = foreignAssetAccount.unwrap().balance.toBigInt(); - if (foreignAssetAccountBalance > expectedForeignAssetBalance) { + if (foreignAssetAccountBalance > expectedAssetBalance) { return foreignAssetAccountBalance; } } diff --git a/bridges/testing/framework/utils/bridges.sh b/bridges/testing/framework/utils/bridges.sh index 07d9e4cd50b1..3d7b37b4ffc2 100755 --- a/bridges/testing/framework/utils/bridges.sh +++ b/bridges/testing/framework/utils/bridges.sh @@ -114,7 +114,7 @@ function send_governance_transact() { local dest=$(jq --null-input \ --arg para_id "$para_id" \ - '{ "V3": { "parents": 0, "interior": { "X1": { "Parachain": $para_id } } } }') + '{ "V4": { "parents": 0, "interior": { "X1": [{ "Parachain": $para_id }] } } }') local message=$(jq --null-input \ --argjson hex_encoded_data $hex_encoded_data \ @@ -122,7 +122,7 @@ function send_governance_transact() { --arg require_weight_at_most_proof_size "$require_weight_at_most_proof_size" \ ' { - "V3": [ + "V4": [ { "UnpaidExecution": { "weight_limit": "Unlimited" diff --git a/bridges/testing/tests/0001-asset-transfer/roc-reaches-westend.zndsl b/bridges/testing/tests/0001-asset-transfer/roc-reaches-westend.zndsl index 6e26632fd9f9..b3cafc993e54 100644 --- a/bridges/testing/tests/0001-asset-transfer/roc-reaches-westend.zndsl +++ b/bridges/testing/tests/0001-asset-transfer/roc-reaches-westend.zndsl @@ -6,7 +6,7 @@ Creds: config asset-hub-westend-collator1: run {{ENV_PATH}}/helper.sh with "auto-log reserve-transfer-assets-from-asset-hub-rococo-local 5000000000000" within 120 seconds # check that //Alice received at least 4.8 ROC on Westend AH -asset-hub-westend-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/wrapped-assets-balance.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY,4800000000000,Rococo" within 600 seconds +asset-hub-westend-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/wrapped-assets-balance.js with '{ "accountAddress": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "expectedAssetBalance": 4800000000000, "expectedAssetId": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { "ByGenesis": [100,8,222,119,55,197,156,35,136,144,83,58,242,88,150,162,194,6,8,216,179,128,187,1,2,154,203,57,39,129,6,62] } }] }}}' within 600 seconds # relayer //Ferdie is rewarded for delivering messages from Rococo BH bridge-hub-westend-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/relayer-rewards.js with "5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw,0x00000002,0x6268726F,ThisChain,0" within 300 seconds diff --git a/bridges/testing/tests/0001-asset-transfer/wnd-reaches-rococo.zndsl b/bridges/testing/tests/0001-asset-transfer/wnd-reaches-rococo.zndsl index 5a8d6dabc20e..eacac98982ab 100644 --- a/bridges/testing/tests/0001-asset-transfer/wnd-reaches-rococo.zndsl +++ b/bridges/testing/tests/0001-asset-transfer/wnd-reaches-rococo.zndsl @@ -6,7 +6,7 @@ Creds: config asset-hub-rococo-collator1: run {{ENV_PATH}}/helper.sh with "auto-log reserve-transfer-assets-from-asset-hub-westend-local 5000000000000" within 120 seconds # check that //Alice received at least 4.8 WND on Rococo AH -asset-hub-rococo-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/wrapped-assets-balance.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY,4800000000000,Westend" within 600 seconds +asset-hub-rococo-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/wrapped-assets-balance.js with '{ "accountAddress": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "expectedAssetBalance": 4800000000000, "expectedAssetId": { "parents": 2, "interior": { "X1": [{ "GlobalConsensus": { "ByGenesis": [225,67,242,56,3,172,80,232,246,248,230,38,149,209,206,158,78,29,104,170,54,193,205,44,253,21,52,2,19,243,66,62] } }] }}}' within 600 seconds # relayer //Eve is rewarded for delivering messages from Westend BH bridge-hub-rococo-collator1: js-script {{FRAMEWORK_PATH}}/js-helpers/relayer-rewards.js with "5CiPPseXPECbkjWCa6MnjNokrgYjMqmKndv2rSnekmSK2DjL,0x00000002,0x62687764,ThisChain,0" within 300 seconds From a1af8ed63668fc4a553776e381a12d165e7462f8 Mon Sep 17 00:00:00 2001 From: Guillaume Thiolliere Date: Thu, 14 Nov 2024 11:27:00 +0900 Subject: [PATCH 092/166] Fix staking benchmark (#6463) Found by @ggwpez Fix staking benchmark, error was introduced when migrating to v2: https://github.com/paritytech/polkadot-sdk/pull/6025 --------- Co-authored-by: GitHub Action --- prdoc/pr_6463.prdoc | 8 ++++++++ substrate/frame/staking/src/benchmarking.rs | 20 +++++++++++--------- 2 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 prdoc/pr_6463.prdoc diff --git a/prdoc/pr_6463.prdoc b/prdoc/pr_6463.prdoc new file mode 100644 index 000000000000..9c4787540a49 --- /dev/null +++ b/prdoc/pr_6463.prdoc @@ -0,0 +1,8 @@ +title: Fix staking benchmark +doc: +- audience: Runtime Dev + description: 'Fix staking benchmark, error was introduced when migrating to v2: + https://github.com/paritytech/polkadot-sdk/pull/6025' +crates: +- name: pallet-staking + bump: patch diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index d842186d5025..79d8dd3fbc30 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -975,20 +975,22 @@ mod benchmarks { ) -> Result<(), BenchmarkError> { // number of nominator intention. let n = MaxNominators::::get(); + create_validators_with_nominators_for_era::( + v, + n, + MaxNominationsOf::::get() as usize, + false, + None, + )?; + + let targets; #[block] { - create_validators_with_nominators_for_era::( - v, - n, - MaxNominationsOf::::get() as usize, - false, - None, - )?; + // default bounds are unbounded. + targets = >::get_npos_targets(DataProviderBounds::default()); } - // default bounds are unbounded. - let targets = >::get_npos_targets(DataProviderBounds::default()); assert_eq!(targets.len() as u32, v); Ok(()) From ae4b68b36d6da1dd0d6a78643b634296b3fa8039 Mon Sep 17 00:00:00 2001 From: georgepisaltu <52418509+georgepisaltu@users.noreply.github.com> Date: Thu, 14 Nov 2024 16:10:18 +0200 Subject: [PATCH 093/166] Follow up work on `TransactionExtension` - fix weights and clean up `UncheckedExtrinsic` (#6418) Follow up to https://github.com/paritytech/polkadot-sdk/pull/3685 Partially fixes https://github.com/paritytech/polkadot-sdk/issues/6403 The main PR introduced bare support for the new extension version byte as well as extension weights and benchmarking. This PR: - Removes the redundant extension version byte from the signed v4 extrinsic, previously unused and defaulted to 0. - Adds the extension version byte to the inherited implication passed to `General` transactions. - Whitelists the `pallet_authorship::Author`, `frame_system::Digest` and `pallet_transaction_payment::NextFeeMultiplier` storage items as they are read multiple times by extensions for each transaction, but are hot in memory and currently overestimate the weight. - Whitelists the benchmark caller for `CheckEra` and `CheckGenesis` as the reads are performed for every transaction and overestimate the weight. - Updates the umbrella frame weight template to work with the system extension changes. - Plans on re-running the benchmarks at least for the `frame_system` extensions. --------- Signed-off-by: georgepisaltu Co-authored-by: command-bot <> Co-authored-by: gui --- bridges/bin/runtime-common/src/extensions.rs | 12 +- bridges/modules/relayers/src/extension/mod.rs | 6 + .../storage-weight-reclaim/src/tests.rs | 26 +- polkadot/runtime/common/src/claims.rs | 8 +- prdoc/pr_6418.prdoc | 151 +++ .../frame-umbrella-weight-template.hbs | 2 +- substrate/bin/node/testing/src/bench.rs | 5 +- substrate/bin/node/testing/src/keyring.rs | 5 +- substrate/frame/alliance/src/weights.rs | 420 ++++---- .../frame/asset-conversion/ops/src/weights.rs | 28 +- .../frame/asset-conversion/src/weights.rs | 107 +- substrate/frame/asset-rate/src/weights.rs | 60 +- substrate/frame/assets/src/weights.rs | 362 +++---- substrate/frame/authorship/src/lib.rs | 1 + substrate/frame/bags-list/src/weights.rs | 40 +- .../balances/src/tests/currency_tests.rs | 4 + substrate/frame/balances/src/weights.rs | 152 +-- substrate/frame/beefy-mmr/src/weights.rs | 60 +- substrate/frame/benchmarking/src/weights.rs | 60 +- substrate/frame/bounties/src/weights.rs | 176 ++-- substrate/frame/child-bounties/src/weights.rs | 148 +-- substrate/frame/collective/src/weights.rs | 396 +++---- substrate/frame/contracts/src/weights.rs | 982 +++++++++--------- .../frame/conviction-voting/src/weights.rs | 76 +- .../frame/core-fellowship/src/weights.rs | 120 +-- substrate/frame/democracy/src/weights.rs | 304 +++--- .../src/weights.rs | 152 ++- .../frame/elections-phragmen/src/weights.rs | 224 ++-- .../authorization-tx-extension/src/tests.rs | 13 +- substrate/frame/examples/basic/src/tests.rs | 4 +- .../examples/offchain-worker/src/tests.rs | 2 +- substrate/frame/fast-unstake/src/weights.rs | 104 +- substrate/frame/glutton/src/weights.rs | 132 +-- substrate/frame/identity/src/weights.rs | 848 +++++++++------ substrate/frame/im-online/src/weights.rs | 20 +- substrate/frame/indices/src/weights.rs | 48 +- substrate/frame/lottery/src/weights.rs | 76 +- substrate/frame/membership/src/weights.rs | 108 +- substrate/frame/message-queue/src/weights.rs | 84 +- substrate/frame/migrations/src/weights.rs | 156 +-- substrate/frame/multisig/src/weights.rs | 2 +- .../nft-fractionalization/src/weights.rs | 40 +- substrate/frame/nfts/src/weights.rs | 372 +++---- substrate/frame/nis/src/weights.rs | 144 +-- .../frame/nomination-pools/src/weights.rs | 2 +- substrate/frame/parameters/src/weights.rs | 12 +- substrate/frame/preimage/src/weights.rs | 212 ++-- substrate/frame/proxy/src/weights.rs | 2 +- .../frame/ranked-collective/src/weights.rs | 92 +- substrate/frame/recovery/src/weights.rs | 148 +-- substrate/frame/referenda/src/weights.rs | 248 ++--- substrate/frame/remark/src/weights.rs | 16 +- substrate/frame/revive/src/evm/runtime.rs | 1 + substrate/frame/revive/src/weights.rs | 900 ++++++++-------- substrate/frame/safe-mode/src/weights.rs | 124 +-- substrate/frame/salary/src/weights.rs | 64 +- substrate/frame/scheduler/src/weights.rs | 210 ++-- substrate/frame/session/src/weights.rs | 36 +- substrate/frame/society/src/weights.rs | 172 +-- substrate/frame/staking/src/weights.rs | 2 +- .../frame/state-trie-migration/src/weights.rs | 116 +-- substrate/frame/sudo/src/benchmarking.rs | 2 +- substrate/frame/sudo/src/weights.rs | 64 +- substrate/frame/support/src/dispatch.rs | 12 +- .../support/src/weights/block_weights.rs | 22 +- .../support/src/weights/extrinsic_weights.rs | 22 +- .../system/benchmarking/src/extensions.rs | 26 +- .../system/src/extensions/check_mortality.rs | 2 +- .../src/extensions/check_non_zero_sender.rs | 3 +- .../system/src/extensions/check_nonce.rs | 25 +- .../system/src/extensions/check_weight.rs | 19 +- .../frame/system/src/extensions/weights.rs | 96 +- substrate/frame/system/src/lib.rs | 1 + substrate/frame/system/src/weights.rs | 150 ++- substrate/frame/timestamp/src/weights.rs | 20 +- substrate/frame/tips/src/weights.rs | 128 ++- .../src/benchmarking.rs | 6 +- .../asset-conversion-tx-payment/src/tests.rs | 57 +- .../src/weights.rs | 78 +- .../asset-tx-payment/src/benchmarking.rs | 6 +- .../asset-tx-payment/src/tests.rs | 29 +- .../skip-feeless-payment/src/tests.rs | 12 +- .../transaction-payment/src/benchmarking.rs | 2 +- .../frame/transaction-payment/src/lib.rs | 1 + .../frame/transaction-payment/src/tests.rs | 62 +- .../frame/transaction-payment/src/weights.rs | 42 +- .../frame/transaction-storage/src/weights.rs | 44 +- substrate/frame/treasury/src/weights.rs | 166 ++- substrate/frame/tx-pause/src/weights.rs | 20 +- substrate/frame/uniques/src/weights.rs | 348 +++---- substrate/frame/utility/src/weights.rs | 68 +- .../verify-signature/src/benchmarking.rs | 15 +- substrate/frame/verify-signature/src/tests.rs | 28 +- .../frame/verify-signature/src/weights.rs | 25 +- substrate/frame/vesting/src/weights.rs | 280 +++-- substrate/frame/whitelist/src/weights.rs | 68 +- .../runtime/src/generic/checked_extrinsic.rs | 38 +- .../primitives/runtime/src/generic/mod.rs | 4 +- .../src/generic/unchecked_extrinsic.rs | 38 +- .../dispatch_transaction.rs | 35 +- substrate/test-utils/runtime/src/extrinsic.rs | 2 +- substrate/test-utils/runtime/src/lib.rs | 2 + 102 files changed, 5593 insertions(+), 5072 deletions(-) create mode 100644 prdoc/pr_6418.prdoc diff --git a/bridges/bin/runtime-common/src/extensions.rs b/bridges/bin/runtime-common/src/extensions.rs index 256e975f44c3..44e6b40b7e0c 100644 --- a/bridges/bin/runtime-common/src/extensions.rs +++ b/bridges/bin/runtime-common/src/extensions.rs @@ -615,6 +615,7 @@ mod tests { &(), 0, External, + 0, ), InvalidTransaction::Custom(1) ); @@ -623,7 +624,8 @@ mod tests { 42u64.into(), &MockCall { data: 1 }, &(), - 0 + 0, + 0, ), InvalidTransaction::Custom(1) ); @@ -635,6 +637,7 @@ mod tests { &(), 0, External, + 0, ), InvalidTransaction::Custom(2) ); @@ -643,21 +646,22 @@ mod tests { 42u64.into(), &MockCall { data: 2 }, &(), - 0 + 0, + 0, ), InvalidTransaction::Custom(2) ); assert_eq!( BridgeRejectObsoleteHeadersAndMessages - .validate_only(42u64.into(), &MockCall { data: 3 }, &(), 0, External) + .validate_only(42u64.into(), &MockCall { data: 3 }, &(), 0, External, 0) .unwrap() .0, ValidTransaction { priority: 3, ..Default::default() }, ); assert_eq!( BridgeRejectObsoleteHeadersAndMessages - .validate_and_prepare(42u64.into(), &MockCall { data: 3 }, &(), 0) + .validate_and_prepare(42u64.into(), &MockCall { data: 3 }, &(), 0, 0) .unwrap() .0 .unwrap(), diff --git a/bridges/modules/relayers/src/extension/mod.rs b/bridges/modules/relayers/src/extension/mod.rs index a400aeaee074..34d280d26d6e 100644 --- a/bridges/modules/relayers/src/extension/mod.rs +++ b/bridges/modules/relayers/src/extension/mod.rs @@ -1081,6 +1081,7 @@ mod tests { &DispatchInfo::default(), 0, External, + 0, ) .map(|t| t.0) } @@ -1094,6 +1095,7 @@ mod tests { &DispatchInfo::default(), 0, External, + 0, ) .map(|t| t.0) } @@ -1107,6 +1109,7 @@ mod tests { &DispatchInfo::default(), 0, External, + 0, ) .map(|t| t.0) } @@ -1132,6 +1135,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + 0, ) .map(|(pre, _)| pre) } @@ -1149,6 +1153,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + 0, ) .map(|(pre, _)| pre) } @@ -1166,6 +1171,7 @@ mod tests { &call, &DispatchInfo::default(), 0, + 0, ) .map(|(pre, _)| pre) } diff --git a/cumulus/primitives/storage-weight-reclaim/src/tests.rs b/cumulus/primitives/storage-weight-reclaim/src/tests.rs index c5552b0f0a33..ab83762cc0db 100644 --- a/cumulus/primitives/storage-weight-reclaim/src/tests.rs +++ b/cumulus/primitives/storage-weight-reclaim/src/tests.rs @@ -90,7 +90,7 @@ fn basic_refund() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(0)); @@ -130,7 +130,7 @@ fn underestimating_refund() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(0)); @@ -168,7 +168,7 @@ fn sets_to_node_storage_proof_if_higher() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(1000)); @@ -211,7 +211,7 @@ fn sets_to_node_storage_proof_if_higher() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(175)); @@ -256,7 +256,7 @@ fn does_nothing_without_extension() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, None); @@ -288,7 +288,7 @@ fn negative_refund_is_added_to_weight() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(100)); @@ -321,7 +321,7 @@ fn test_zero_proof_size() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(0)); @@ -354,7 +354,7 @@ fn test_larger_pre_dispatch_proof_size() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(300)); @@ -394,7 +394,7 @@ fn test_incorporates_check_weight_unspent_weight() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(100)); @@ -434,7 +434,7 @@ fn test_incorporates_check_weight_unspent_weight_on_negative() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(100)); @@ -478,7 +478,7 @@ fn test_nothing_relcaimed() { assert_eq!(get_storage_weight().total().proof_size(), 250); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); // Should return `setup_test_externalities` proof recorder value: 100. assert_eq!(pre, Some(0)); @@ -525,7 +525,7 @@ fn test_incorporates_check_weight_unspent_weight_reverse_order() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(100)); @@ -567,7 +567,7 @@ fn test_incorporates_check_weight_unspent_weight_on_negative_reverse_order() { assert_ok!(CheckWeight::::do_prepare(&info, LEN, next_len)); let (pre, _) = StorageWeightReclaim::(PhantomData) - .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN) + .validate_and_prepare(Some(ALICE.clone()).into(), CALL, &info, LEN, 0) .unwrap(); assert_eq!(pre, Some(100)); diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 5383fe41d487..1ee80dd76e2d 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -1078,7 +1078,7 @@ mod tests { }); let di = c.get_dispatch_info(); assert_eq!(di.pays_fee, Pays::No); - let r = p.validate_only(Some(42).into(), &c, &di, 20, External); + let r = p.validate_only(Some(42).into(), &c, &di, 20, External, 0); assert_eq!(r.unwrap().0, ValidTransaction::default()); }); } @@ -1091,13 +1091,13 @@ mod tests { statement: StatementKind::Regular.to_text().to_vec(), }); let di = c.get_dispatch_info(); - let r = p.validate_only(Some(42).into(), &c, &di, 20, External); + let r = p.validate_only(Some(42).into(), &c, &di, 20, External, 0); assert!(r.is_err()); let c = RuntimeCall::Claims(ClaimsCall::attest { statement: StatementKind::Saft.to_text().to_vec(), }); let di = c.get_dispatch_info(); - let r = p.validate_only(Some(69).into(), &c, &di, 20, External); + let r = p.validate_only(Some(69).into(), &c, &di, 20, External, 0); assert!(r.is_err()); }); } @@ -1739,7 +1739,7 @@ mod benchmarking { #[block] { assert!(ext - .test_run(RawOrigin::Signed(account).into(), &call, &info, 0, |_| { + .test_run(RawOrigin::Signed(account).into(), &call, &info, 0, 0, |_| { Ok(Default::default()) }) .unwrap() diff --git a/prdoc/pr_6418.prdoc b/prdoc/pr_6418.prdoc new file mode 100644 index 000000000000..6696b54024b9 --- /dev/null +++ b/prdoc/pr_6418.prdoc @@ -0,0 +1,151 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Follow up work on TransactionExtension - fix weights and clean up UncheckedExtrinsic + +doc: + - audience: Runtime Dev + description: | + This PR removes the redundant extension version byte from the signed v4 extrinsic, previously + unused and defaulted to 0. The extension version byte is also made to be part of the inherited + implication handed to extensions in General transactions. Also, some system extensions + benchmarks were adjusted through whitelisting to not count the reads for frequently read + storage keys. + +crates: + - name: node-testing + bump: patch + - name: pallet-example-offchain-worker + bump: patch + - name: sp-runtime + bump: major + - name: substrate-test-utils + bump: patch + - name: pallet-alliance + bump: patch + - name: pallet-asset-conversion + bump: patch + - name: pallet-asset-conversion-ops + bump: patch + - name: pallet-asset-rate + bump: patch + - name: pallet-assets + bump: patch + - name: pallet-authorship + bump: patch + - name: pallet-bags-list + bump: patch + - name: pallet-balances + bump: patch + - name: pallet-beefy-mmr + bump: patch + - name: frame-benchmarking + bump: patch + - name: pallet-bounties + bump: patch + - name: pallet-broker + bump: patch + - name: pallet-child-bounties + bump: patch + - name: pallet-collective + bump: patch + - name: pallet-contracts + bump: patch + - name: pallet-conviction-voting + bump: patch + - name: pallet-core-fellowship + bump: patch + - name: pallet-democracy + bump: patch + - name: pallet-election-provider-multi-phase + bump: patch + - name: pallet-elections-phragmen + bump: patch + - name: pallet-fast-unstake + bump: patch + - name: pallet-glutton + bump: patch + - name: pallet-identity + bump: patch + - name: pallet-im-online + bump: patch + - name: pallet-indices + bump: patch + - name: pallet-lottery + bump: patch + - name: pallet-membership + bump: patch + - name: pallet-message-queue + bump: patch + - name: pallet-migrations + bump: patch + - name: pallet-multisig + bump: patch + - name: pallet-nft-fractionalization + bump: patch + - name: pallet-nfts + bump: patch + - name: pallet-nis + bump: patch + - name: pallet-nomination-pools + bump: patch + - name: pallet-parameters + bump: patch + - name: pallet-preimage + bump: patch + - name: pallet-proxy + bump: patch + - name: pallet-ranked-collective + bump: patch + - name: pallet-recovery + bump: patch + - name: pallet-referenda + bump: patch + - name: pallet-remark + bump: patch + - name: pallet-revive + bump: patch + - name: pallet-safe-mode + bump: patch + - name: pallet-salary + bump: patch + - name: pallet-scheduler + bump: patch + - name: pallet-session + bump: patch + - name: pallet-society + bump: patch + - name: pallet-staking + bump: patch + - name: pallet-state-trie-migration + bump: patch + - name: pallet-sudo + bump: patch + - name: frame-support + bump: patch + - name: pallet-timestamp + bump: patch + - name: pallet-tips + bump: patch + - name: pallet-asset-conversion-tx-payment + bump: patch + - name: pallet-transaction-payment + bump: patch + - name: pallet-transaction-storage + bump: patch + - name: pallet-treasury + bump: patch + - name: pallet-tx-pause + bump: patch + - name: pallet-uniques + bump: patch + - name: pallet-utility + bump: patch + - name: pallet-verify-signature + bump: patch + - name: pallet-vesting + bump: patch + - name: pallet-whitelist + bump: patch + - name: sp-runtime + bump: major diff --git a/substrate/.maintain/frame-umbrella-weight-template.hbs b/substrate/.maintain/frame-umbrella-weight-template.hbs index 0f26fae1d8f1..b174823b3840 100644 --- a/substrate/.maintain/frame-umbrella-weight-template.hbs +++ b/substrate/.maintain/frame-umbrella-weight-template.hbs @@ -32,7 +32,7 @@ pub trait WeightInfo { /// Weights for `{{pallet}}` using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); -{{#if (eq pallet "frame_system")}} +{{#if (or (eq pallet "frame_system") (eq pallet "frame_system_extensions"))}} impl WeightInfo for SubstrateWeight { {{else}} impl WeightInfo for SubstrateWeight { diff --git a/substrate/bin/node/testing/src/bench.rs b/substrate/bin/node/testing/src/bench.rs index 3812524f0b1f..35f041ef0445 100644 --- a/substrate/bin/node/testing/src/bench.rs +++ b/substrate/bin/node/testing/src/bench.rs @@ -590,7 +590,6 @@ impl BenchKeyring { preamble: Preamble::Signed( sp_runtime::MultiAddress::Id(signed), signature, - 0, tx_ext, ), function: payload.0, @@ -602,8 +601,8 @@ impl BenchKeyring { function: xt.function, } .into(), - ExtrinsicFormat::General(tx_ext) => generic::UncheckedExtrinsic { - preamble: sp_runtime::generic::Preamble::General(0, tx_ext), + ExtrinsicFormat::General(ext_version, tx_ext) => generic::UncheckedExtrinsic { + preamble: sp_runtime::generic::Preamble::General(ext_version, tx_ext), function: xt.function, } .into(), diff --git a/substrate/bin/node/testing/src/keyring.rs b/substrate/bin/node/testing/src/keyring.rs index 20497e85eab9..e5b0299f01a8 100644 --- a/substrate/bin/node/testing/src/keyring.rs +++ b/substrate/bin/node/testing/src/keyring.rs @@ -123,7 +123,6 @@ pub fn sign( preamble: sp_runtime::generic::Preamble::Signed( sp_runtime::MultiAddress::Id(signed), signature, - 0, tx_ext, ), function: payload.0, @@ -135,8 +134,8 @@ pub fn sign( function: xt.function, } .into(), - ExtrinsicFormat::General(tx_ext) => generic::UncheckedExtrinsic { - preamble: sp_runtime::generic::Preamble::General(0, tx_ext), + ExtrinsicFormat::General(ext_version, tx_ext) => generic::UncheckedExtrinsic { + preamble: sp_runtime::generic::Preamble::General(ext_version, tx_ext), function: xt.function, } .into(), diff --git a/substrate/frame/alliance/src/weights.rs b/substrate/frame/alliance/src/weights.rs index 0184ac91107c..dff60ec20cde 100644 --- a/substrate/frame/alliance/src/weights.rs +++ b/substrate/frame/alliance/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_alliance` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -91,16 +91,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `688 + m * (32 ±0) + p * (36 ±0)` + // Measured: `721 + m * (32 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (32 ±0) + p * (36 ±0)` - // Minimum execution time: 31_545_000 picoseconds. - Weight::from_parts(33_432_774, 6676) - // Standard Error: 121 - .saturating_add(Weight::from_parts(232, 0).saturating_mul(b.into())) - // Standard Error: 1_263 - .saturating_add(Weight::from_parts(47_800, 0).saturating_mul(m.into())) - // Standard Error: 1_247 - .saturating_add(Weight::from_parts(188_655, 0).saturating_mul(p.into())) + // Minimum execution time: 36_770_000 picoseconds. + Weight::from_parts(39_685_981, 6676) + // Standard Error: 156 + .saturating_add(Weight::from_parts(588, 0).saturating_mul(b.into())) + // Standard Error: 1_636 + .saturating_add(Weight::from_parts(31_314, 0).saturating_mul(m.into())) + // Standard Error: 1_616 + .saturating_add(Weight::from_parts(158_254, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) @@ -113,12 +113,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `m` is `[5, 100]`. fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1147 + m * (64 ±0)` + // Measured: `1180 + m * (64 ±0)` // Estimated: `6676 + m * (64 ±0)` - // Minimum execution time: 30_462_000 picoseconds. - Weight::from_parts(31_639_466, 6676) - // Standard Error: 980 - .saturating_add(Weight::from_parts(60_075, 0).saturating_mul(m.into())) + // Minimum execution time: 36_851_000 picoseconds. + Weight::from_parts(38_427_277, 6676) + // Standard Error: 1_877 + .saturating_add(Weight::from_parts(50_131, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -137,14 +137,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `674 + m * (96 ±0) + p * (36 ±0)` + // Measured: `707 + m * (96 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 40_765_000 picoseconds. - Weight::from_parts(37_690_472, 6676) - // Standard Error: 1_372 - .saturating_add(Weight::from_parts(69_441, 0).saturating_mul(m.into())) - // Standard Error: 1_338 - .saturating_add(Weight::from_parts(152_833, 0).saturating_mul(p.into())) + // Minimum execution time: 43_572_000 picoseconds. + Weight::from_parts(40_836_679, 6676) + // Standard Error: 1_764 + .saturating_add(Weight::from_parts(59_213, 0).saturating_mul(m.into())) + // Standard Error: 1_720 + .saturating_add(Weight::from_parts(171_689, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -169,16 +169,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1254 + m * (96 ±0) + p * (39 ±0)` + // Measured: `1287 + m * (96 ±0) + p * (39 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (40 ±0)` - // Minimum execution time: 57_367_000 picoseconds. - Weight::from_parts(57_264_486, 6676) - // Standard Error: 141 - .saturating_add(Weight::from_parts(884, 0).saturating_mul(b.into())) - // Standard Error: 1_495 - .saturating_add(Weight::from_parts(57_869, 0).saturating_mul(m.into())) - // Standard Error: 1_458 - .saturating_add(Weight::from_parts(158_784, 0).saturating_mul(p.into())) + // Minimum execution time: 62_758_000 picoseconds. + Weight::from_parts(63_400_227, 6676) + // Standard Error: 233 + .saturating_add(Weight::from_parts(1_156, 0).saturating_mul(b.into())) + // Standard Error: 2_470 + .saturating_add(Weight::from_parts(42_858, 0).saturating_mul(m.into())) + // Standard Error: 2_408 + .saturating_add(Weight::from_parts(185_822, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -200,14 +200,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `675 + m * (96 ±0) + p * (36 ±0)` + // Measured: `708 + m * (96 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 41_253_000 picoseconds. - Weight::from_parts(37_550_833, 6676) - // Standard Error: 1_162 - .saturating_add(Weight::from_parts(77_359, 0).saturating_mul(m.into())) - // Standard Error: 1_148 - .saturating_add(Weight::from_parts(153_523, 0).saturating_mul(p.into())) + // Minimum execution time: 45_287_000 picoseconds. + Weight::from_parts(44_144_056, 6676) + // Standard Error: 1_553 + .saturating_add(Weight::from_parts(50_224, 0).saturating_mul(m.into())) + // Standard Error: 1_534 + .saturating_add(Weight::from_parts(154_551, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -230,16 +230,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `728 + m * (96 ±0) + p * (35 ±0)` + // Measured: `761 + m * (96 ±0) + p * (35 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 42_385_000 picoseconds. - Weight::from_parts(37_222_159, 6676) - // Standard Error: 118 - .saturating_add(Weight::from_parts(1_743, 0).saturating_mul(b.into())) - // Standard Error: 1_268 - .saturating_add(Weight::from_parts(59_743, 0).saturating_mul(m.into())) - // Standard Error: 1_222 - .saturating_add(Weight::from_parts(159_606, 0).saturating_mul(p.into())) + // Minimum execution time: 45_943_000 picoseconds. + Weight::from_parts(43_665_317, 6676) + // Standard Error: 164 + .saturating_add(Weight::from_parts(1_296, 0).saturating_mul(b.into())) + // Standard Error: 1_757 + .saturating_add(Weight::from_parts(35_145, 0).saturating_mul(m.into())) + // Standard Error: 1_694 + .saturating_add(Weight::from_parts(164_507, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -253,14 +253,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `z` is `[0, 100]`. fn init_members(m: u32, z: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `284` + // Measured: `317` // Estimated: `12362` - // Minimum execution time: 31_184_000 picoseconds. - Weight::from_parts(22_860_208, 12362) - // Standard Error: 1_096 - .saturating_add(Weight::from_parts(129_834, 0).saturating_mul(m.into())) - // Standard Error: 1_083 - .saturating_add(Weight::from_parts(97_546, 0).saturating_mul(z.into())) + // Minimum execution time: 34_959_000 picoseconds. + Weight::from_parts(25_620_911, 12362) + // Standard Error: 1_457 + .saturating_add(Weight::from_parts(130_068, 0).saturating_mul(m.into())) + // Standard Error: 1_440 + .saturating_add(Weight::from_parts(113_433, 0).saturating_mul(z.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -281,16 +281,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `z` is `[0, 50]`. fn disband(x: u32, y: u32, z: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + x * (50 ±0) + y * (51 ±0) + z * (251 ±0)` + // Measured: `0 + x * (50 ±0) + y * (51 ±0) + z * (252 ±0)` // Estimated: `12362 + x * (2539 ±0) + y * (2539 ±0) + z * (2603 ±1)` - // Minimum execution time: 359_308_000 picoseconds. - Weight::from_parts(361_696_000, 12362) - // Standard Error: 30_917 - .saturating_add(Weight::from_parts(657_166, 0).saturating_mul(x.into())) - // Standard Error: 30_768 - .saturating_add(Weight::from_parts(670_249, 0).saturating_mul(y.into())) - // Standard Error: 61_480 - .saturating_add(Weight::from_parts(14_340_554, 0).saturating_mul(z.into())) + // Minimum execution time: 384_385_000 picoseconds. + Weight::from_parts(390_301_000, 12362) + // Standard Error: 32_391 + .saturating_add(Weight::from_parts(745_632, 0).saturating_mul(x.into())) + // Standard Error: 32_235 + .saturating_add(Weight::from_parts(758_118, 0).saturating_mul(y.into())) + // Standard Error: 64_412 + .saturating_add(Weight::from_parts(14_822_486, 0).saturating_mul(z.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(x.into()))) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(y.into()))) @@ -307,18 +307,18 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_146_000 picoseconds. - Weight::from_parts(6_540_000, 0) + // Minimum execution time: 6_042_000 picoseconds. + Weight::from_parts(6_385_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Alliance::Announcements` (r:1 w:1) /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) fn announce() -> Weight { // Proof Size summary in bytes: - // Measured: `279` + // Measured: `312` // Estimated: `10187` - // Minimum execution time: 9_008_000 picoseconds. - Weight::from_parts(9_835_000, 10187) + // Minimum execution time: 10_152_000 picoseconds. + Weight::from_parts(10_728_000, 10187) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -326,10 +326,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) fn remove_announcement() -> Weight { // Proof Size summary in bytes: - // Measured: `352` + // Measured: `385` // Estimated: `10187` - // Minimum execution time: 10_308_000 picoseconds. - Weight::from_parts(10_602_000, 10187) + // Minimum execution time: 11_540_000 picoseconds. + Weight::from_parts(12_160_000, 10187) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -343,10 +343,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) fn join_alliance() -> Weight { // Proof Size summary in bytes: - // Measured: `501` + // Measured: `534` // Estimated: `18048` - // Minimum execution time: 40_731_000 picoseconds. - Weight::from_parts(42_453_000, 18048) + // Minimum execution time: 46_932_000 picoseconds. + Weight::from_parts(48_549_000, 18048) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -356,10 +356,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) fn nominate_ally() -> Weight { // Proof Size summary in bytes: - // Measured: `400` + // Measured: `433` // Estimated: `18048` - // Minimum execution time: 24_198_000 picoseconds. - Weight::from_parts(25_258_000, 18048) + // Minimum execution time: 29_716_000 picoseconds. + Weight::from_parts(30_911_000, 18048) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -373,10 +373,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn elevate_ally() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `12362` - // Minimum execution time: 24_509_000 picoseconds. - Weight::from_parts(25_490_000, 12362) + // Minimum execution time: 29_323_000 picoseconds. + Weight::from_parts(30_702_000, 12362) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -392,10 +392,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Alliance::RetiringMembers` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn give_retirement_notice() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `23734` - // Minimum execution time: 30_889_000 picoseconds. - Weight::from_parts(31_930_000, 23734) + // Minimum execution time: 35_317_000 picoseconds. + Weight::from_parts(37_017_000, 23734) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -409,10 +409,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn retire() -> Weight { // Proof Size summary in bytes: - // Measured: `720` + // Measured: `753` // Estimated: `6676` - // Minimum execution time: 38_363_000 picoseconds. - Weight::from_parts(39_428_000, 6676) + // Minimum execution time: 43_741_000 picoseconds. + Weight::from_parts(45_035_000, 6676) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -430,10 +430,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn kick_member() -> Weight { // Proof Size summary in bytes: - // Measured: `774` + // Measured: `807` // Estimated: `18048` - // Minimum execution time: 60_717_000 picoseconds. - Weight::from_parts(61_785_000, 18048) + // Minimum execution time: 61_064_000 picoseconds. + Weight::from_parts(63_267_000, 18048) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -445,14 +445,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `l` is `[0, 255]`. fn add_unscrupulous_items(n: u32, l: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `279` + // Measured: `312` // Estimated: `27187` - // Minimum execution time: 5_393_000 picoseconds. - Weight::from_parts(5_577_000, 27187) - // Standard Error: 3_099 - .saturating_add(Weight::from_parts(1_043_175, 0).saturating_mul(n.into())) - // Standard Error: 1_213 - .saturating_add(Weight::from_parts(71_633, 0).saturating_mul(l.into())) + // Minimum execution time: 5_117_000 picoseconds. + Weight::from_parts(5_371_000, 27187) + // Standard Error: 3_341 + .saturating_add(Weight::from_parts(1_210_414, 0).saturating_mul(n.into())) + // Standard Error: 1_308 + .saturating_add(Weight::from_parts(72_982, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -466,12 +466,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0 + l * (100 ±0) + n * (289 ±0)` // Estimated: `27187` - // Minimum execution time: 5_318_000 picoseconds. - Weight::from_parts(5_581_000, 27187) - // Standard Error: 188_914 - .saturating_add(Weight::from_parts(17_878_267, 0).saturating_mul(n.into())) - // Standard Error: 73_987 - .saturating_add(Weight::from_parts(258_754, 0).saturating_mul(l.into())) + // Minimum execution time: 5_433_000 picoseconds. + Weight::from_parts(5_574_000, 27187) + // Standard Error: 193_236 + .saturating_add(Weight::from_parts(18_613_954, 0).saturating_mul(n.into())) + // Standard Error: 75_679 + .saturating_add(Weight::from_parts(221_928, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -485,10 +485,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn abdicate_fellow_status() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `18048` - // Minimum execution time: 29_423_000 picoseconds. - Weight::from_parts(30_141_000, 18048) + // Minimum execution time: 34_613_000 picoseconds. + Weight::from_parts(35_866_000, 18048) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -511,16 +511,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `688 + m * (32 ±0) + p * (36 ±0)` + // Measured: `721 + m * (32 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (32 ±0) + p * (36 ±0)` - // Minimum execution time: 31_545_000 picoseconds. - Weight::from_parts(33_432_774, 6676) - // Standard Error: 121 - .saturating_add(Weight::from_parts(232, 0).saturating_mul(b.into())) - // Standard Error: 1_263 - .saturating_add(Weight::from_parts(47_800, 0).saturating_mul(m.into())) - // Standard Error: 1_247 - .saturating_add(Weight::from_parts(188_655, 0).saturating_mul(p.into())) + // Minimum execution time: 36_770_000 picoseconds. + Weight::from_parts(39_685_981, 6676) + // Standard Error: 156 + .saturating_add(Weight::from_parts(588, 0).saturating_mul(b.into())) + // Standard Error: 1_636 + .saturating_add(Weight::from_parts(31_314, 0).saturating_mul(m.into())) + // Standard Error: 1_616 + .saturating_add(Weight::from_parts(158_254, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) @@ -533,12 +533,12 @@ impl WeightInfo for () { /// The range of component `m` is `[5, 100]`. fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1147 + m * (64 ±0)` + // Measured: `1180 + m * (64 ±0)` // Estimated: `6676 + m * (64 ±0)` - // Minimum execution time: 30_462_000 picoseconds. - Weight::from_parts(31_639_466, 6676) - // Standard Error: 980 - .saturating_add(Weight::from_parts(60_075, 0).saturating_mul(m.into())) + // Minimum execution time: 36_851_000 picoseconds. + Weight::from_parts(38_427_277, 6676) + // Standard Error: 1_877 + .saturating_add(Weight::from_parts(50_131, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -557,14 +557,14 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `674 + m * (96 ±0) + p * (36 ±0)` + // Measured: `707 + m * (96 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 40_765_000 picoseconds. - Weight::from_parts(37_690_472, 6676) - // Standard Error: 1_372 - .saturating_add(Weight::from_parts(69_441, 0).saturating_mul(m.into())) - // Standard Error: 1_338 - .saturating_add(Weight::from_parts(152_833, 0).saturating_mul(p.into())) + // Minimum execution time: 43_572_000 picoseconds. + Weight::from_parts(40_836_679, 6676) + // Standard Error: 1_764 + .saturating_add(Weight::from_parts(59_213, 0).saturating_mul(m.into())) + // Standard Error: 1_720 + .saturating_add(Weight::from_parts(171_689, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -589,16 +589,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1254 + m * (96 ±0) + p * (39 ±0)` + // Measured: `1287 + m * (96 ±0) + p * (39 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (40 ±0)` - // Minimum execution time: 57_367_000 picoseconds. - Weight::from_parts(57_264_486, 6676) - // Standard Error: 141 - .saturating_add(Weight::from_parts(884, 0).saturating_mul(b.into())) - // Standard Error: 1_495 - .saturating_add(Weight::from_parts(57_869, 0).saturating_mul(m.into())) - // Standard Error: 1_458 - .saturating_add(Weight::from_parts(158_784, 0).saturating_mul(p.into())) + // Minimum execution time: 62_758_000 picoseconds. + Weight::from_parts(63_400_227, 6676) + // Standard Error: 233 + .saturating_add(Weight::from_parts(1_156, 0).saturating_mul(b.into())) + // Standard Error: 2_470 + .saturating_add(Weight::from_parts(42_858, 0).saturating_mul(m.into())) + // Standard Error: 2_408 + .saturating_add(Weight::from_parts(185_822, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -620,14 +620,14 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `675 + m * (96 ±0) + p * (36 ±0)` + // Measured: `708 + m * (96 ±0) + p * (36 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 41_253_000 picoseconds. - Weight::from_parts(37_550_833, 6676) - // Standard Error: 1_162 - .saturating_add(Weight::from_parts(77_359, 0).saturating_mul(m.into())) - // Standard Error: 1_148 - .saturating_add(Weight::from_parts(153_523, 0).saturating_mul(p.into())) + // Minimum execution time: 45_287_000 picoseconds. + Weight::from_parts(44_144_056, 6676) + // Standard Error: 1_553 + .saturating_add(Weight::from_parts(50_224, 0).saturating_mul(m.into())) + // Standard Error: 1_534 + .saturating_add(Weight::from_parts(154_551, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -650,16 +650,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `728 + m * (96 ±0) + p * (35 ±0)` + // Measured: `761 + m * (96 ±0) + p * (35 ±0)` // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` - // Minimum execution time: 42_385_000 picoseconds. - Weight::from_parts(37_222_159, 6676) - // Standard Error: 118 - .saturating_add(Weight::from_parts(1_743, 0).saturating_mul(b.into())) - // Standard Error: 1_268 - .saturating_add(Weight::from_parts(59_743, 0).saturating_mul(m.into())) - // Standard Error: 1_222 - .saturating_add(Weight::from_parts(159_606, 0).saturating_mul(p.into())) + // Minimum execution time: 45_943_000 picoseconds. + Weight::from_parts(43_665_317, 6676) + // Standard Error: 164 + .saturating_add(Weight::from_parts(1_296, 0).saturating_mul(b.into())) + // Standard Error: 1_757 + .saturating_add(Weight::from_parts(35_145, 0).saturating_mul(m.into())) + // Standard Error: 1_694 + .saturating_add(Weight::from_parts(164_507, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) @@ -673,14 +673,14 @@ impl WeightInfo for () { /// The range of component `z` is `[0, 100]`. fn init_members(m: u32, z: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `284` + // Measured: `317` // Estimated: `12362` - // Minimum execution time: 31_184_000 picoseconds. - Weight::from_parts(22_860_208, 12362) - // Standard Error: 1_096 - .saturating_add(Weight::from_parts(129_834, 0).saturating_mul(m.into())) - // Standard Error: 1_083 - .saturating_add(Weight::from_parts(97_546, 0).saturating_mul(z.into())) + // Minimum execution time: 34_959_000 picoseconds. + Weight::from_parts(25_620_911, 12362) + // Standard Error: 1_457 + .saturating_add(Weight::from_parts(130_068, 0).saturating_mul(m.into())) + // Standard Error: 1_440 + .saturating_add(Weight::from_parts(113_433, 0).saturating_mul(z.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -701,16 +701,16 @@ impl WeightInfo for () { /// The range of component `z` is `[0, 50]`. fn disband(x: u32, y: u32, z: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + x * (50 ±0) + y * (51 ±0) + z * (251 ±0)` + // Measured: `0 + x * (50 ±0) + y * (51 ±0) + z * (252 ±0)` // Estimated: `12362 + x * (2539 ±0) + y * (2539 ±0) + z * (2603 ±1)` - // Minimum execution time: 359_308_000 picoseconds. - Weight::from_parts(361_696_000, 12362) - // Standard Error: 30_917 - .saturating_add(Weight::from_parts(657_166, 0).saturating_mul(x.into())) - // Standard Error: 30_768 - .saturating_add(Weight::from_parts(670_249, 0).saturating_mul(y.into())) - // Standard Error: 61_480 - .saturating_add(Weight::from_parts(14_340_554, 0).saturating_mul(z.into())) + // Minimum execution time: 384_385_000 picoseconds. + Weight::from_parts(390_301_000, 12362) + // Standard Error: 32_391 + .saturating_add(Weight::from_parts(745_632, 0).saturating_mul(x.into())) + // Standard Error: 32_235 + .saturating_add(Weight::from_parts(758_118, 0).saturating_mul(y.into())) + // Standard Error: 64_412 + .saturating_add(Weight::from_parts(14_822_486, 0).saturating_mul(z.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(x.into()))) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(y.into()))) @@ -727,18 +727,18 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_146_000 picoseconds. - Weight::from_parts(6_540_000, 0) + // Minimum execution time: 6_042_000 picoseconds. + Weight::from_parts(6_385_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Alliance::Announcements` (r:1 w:1) /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) fn announce() -> Weight { // Proof Size summary in bytes: - // Measured: `279` + // Measured: `312` // Estimated: `10187` - // Minimum execution time: 9_008_000 picoseconds. - Weight::from_parts(9_835_000, 10187) + // Minimum execution time: 10_152_000 picoseconds. + Weight::from_parts(10_728_000, 10187) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -746,10 +746,10 @@ impl WeightInfo for () { /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) fn remove_announcement() -> Weight { // Proof Size summary in bytes: - // Measured: `352` + // Measured: `385` // Estimated: `10187` - // Minimum execution time: 10_308_000 picoseconds. - Weight::from_parts(10_602_000, 10187) + // Minimum execution time: 11_540_000 picoseconds. + Weight::from_parts(12_160_000, 10187) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -763,10 +763,10 @@ impl WeightInfo for () { /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) fn join_alliance() -> Weight { // Proof Size summary in bytes: - // Measured: `501` + // Measured: `534` // Estimated: `18048` - // Minimum execution time: 40_731_000 picoseconds. - Weight::from_parts(42_453_000, 18048) + // Minimum execution time: 46_932_000 picoseconds. + Weight::from_parts(48_549_000, 18048) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -776,10 +776,10 @@ impl WeightInfo for () { /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) fn nominate_ally() -> Weight { // Proof Size summary in bytes: - // Measured: `400` + // Measured: `433` // Estimated: `18048` - // Minimum execution time: 24_198_000 picoseconds. - Weight::from_parts(25_258_000, 18048) + // Minimum execution time: 29_716_000 picoseconds. + Weight::from_parts(30_911_000, 18048) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -793,10 +793,10 @@ impl WeightInfo for () { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn elevate_ally() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `12362` - // Minimum execution time: 24_509_000 picoseconds. - Weight::from_parts(25_490_000, 12362) + // Minimum execution time: 29_323_000 picoseconds. + Weight::from_parts(30_702_000, 12362) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -812,10 +812,10 @@ impl WeightInfo for () { /// Proof: `Alliance::RetiringMembers` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn give_retirement_notice() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `23734` - // Minimum execution time: 30_889_000 picoseconds. - Weight::from_parts(31_930_000, 23734) + // Minimum execution time: 35_317_000 picoseconds. + Weight::from_parts(37_017_000, 23734) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -829,10 +829,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn retire() -> Weight { // Proof Size summary in bytes: - // Measured: `720` + // Measured: `753` // Estimated: `6676` - // Minimum execution time: 38_363_000 picoseconds. - Weight::from_parts(39_428_000, 6676) + // Minimum execution time: 43_741_000 picoseconds. + Weight::from_parts(45_035_000, 6676) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -850,10 +850,10 @@ impl WeightInfo for () { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn kick_member() -> Weight { // Proof Size summary in bytes: - // Measured: `774` + // Measured: `807` // Estimated: `18048` - // Minimum execution time: 60_717_000 picoseconds. - Weight::from_parts(61_785_000, 18048) + // Minimum execution time: 61_064_000 picoseconds. + Weight::from_parts(63_267_000, 18048) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -865,14 +865,14 @@ impl WeightInfo for () { /// The range of component `l` is `[0, 255]`. fn add_unscrupulous_items(n: u32, l: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `279` + // Measured: `312` // Estimated: `27187` - // Minimum execution time: 5_393_000 picoseconds. - Weight::from_parts(5_577_000, 27187) - // Standard Error: 3_099 - .saturating_add(Weight::from_parts(1_043_175, 0).saturating_mul(n.into())) - // Standard Error: 1_213 - .saturating_add(Weight::from_parts(71_633, 0).saturating_mul(l.into())) + // Minimum execution time: 5_117_000 picoseconds. + Weight::from_parts(5_371_000, 27187) + // Standard Error: 3_341 + .saturating_add(Weight::from_parts(1_210_414, 0).saturating_mul(n.into())) + // Standard Error: 1_308 + .saturating_add(Weight::from_parts(72_982, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -886,12 +886,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0 + l * (100 ±0) + n * (289 ±0)` // Estimated: `27187` - // Minimum execution time: 5_318_000 picoseconds. - Weight::from_parts(5_581_000, 27187) - // Standard Error: 188_914 - .saturating_add(Weight::from_parts(17_878_267, 0).saturating_mul(n.into())) - // Standard Error: 73_987 - .saturating_add(Weight::from_parts(258_754, 0).saturating_mul(l.into())) + // Minimum execution time: 5_433_000 picoseconds. + Weight::from_parts(5_574_000, 27187) + // Standard Error: 193_236 + .saturating_add(Weight::from_parts(18_613_954, 0).saturating_mul(n.into())) + // Standard Error: 75_679 + .saturating_add(Weight::from_parts(221_928, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -905,10 +905,10 @@ impl WeightInfo for () { /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn abdicate_fellow_status() -> Weight { // Proof Size summary in bytes: - // Measured: `510` + // Measured: `543` // Estimated: `18048` - // Minimum execution time: 29_423_000 picoseconds. - Weight::from_parts(30_141_000, 18048) + // Minimum execution time: 34_613_000 picoseconds. + Weight::from_parts(35_866_000, 18048) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } diff --git a/substrate/frame/asset-conversion/ops/src/weights.rs b/substrate/frame/asset-conversion/ops/src/weights.rs index 9e7379c50156..65762bed72e2 100644 --- a/substrate/frame/asset-conversion/ops/src/weights.rs +++ b/substrate/frame/asset-conversion/ops/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_asset_conversion_ops` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-13, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_asset_conversion_ops +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_asset_conversion_ops -// --chain=dev +// --output=./substrate/frame/asset-conversion/ops/src/weights.rs // --header=./substrate/HEADER-APACHE2 -// --output=./substrate/frame/asset-conversion-ops/src/weights.rs // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -69,10 +71,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn migrate_to_new_account() -> Weight { // Proof Size summary in bytes: - // Measured: `1762` + // Measured: `1796` // Estimated: `11426` - // Minimum execution time: 223_850_000 picoseconds. - Weight::from_parts(231_676_000, 11426) + // Minimum execution time: 235_181_000 picoseconds. + Weight::from_parts(243_965_000, 11426) .saturating_add(T::DbWeight::get().reads(12_u64)) .saturating_add(T::DbWeight::get().writes(11_u64)) } @@ -94,10 +96,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn migrate_to_new_account() -> Weight { // Proof Size summary in bytes: - // Measured: `1762` + // Measured: `1796` // Estimated: `11426` - // Minimum execution time: 223_850_000 picoseconds. - Weight::from_parts(231_676_000, 11426) + // Minimum execution time: 235_181_000 picoseconds. + Weight::from_parts(243_965_000, 11426) .saturating_add(RocksDbWeight::get().reads(12_u64)) .saturating_add(RocksDbWeight::get().writes(11_u64)) } diff --git a/substrate/frame/asset-conversion/src/weights.rs b/substrate/frame/asset-conversion/src/weights.rs index f6e025520d71..dd7feb08f9f4 100644 --- a/substrate/frame/asset-conversion/src/weights.rs +++ b/substrate/frame/asset-conversion/src/weights.rs @@ -18,24 +18,25 @@ //! Autogenerated weights for `pallet_asset_conversion` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-03-13, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-p5qp1txx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_asset_conversion +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_asset_conversion -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/asset-conversion/src/weights.rs // --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs @@ -71,15 +72,17 @@ impl WeightInfo for SubstrateWeight { /// Proof: `AssetConversion::NextPoolAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PoolAssets::Asset` (r:1 w:1) /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::NextAssetId` (r:1 w:0) + /// Proof: `PoolAssets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PoolAssets::Account` (r:1 w:1) /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `910` + // Measured: `949` // Estimated: `6360` - // Minimum execution time: 95_080_000 picoseconds. - Weight::from_parts(97_241_000, 6360) - .saturating_add(T::DbWeight::get().reads(8_u64)) + // Minimum execution time: 97_276_000 picoseconds. + Weight::from_parts(99_380_000, 6360) + .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } /// Storage: `AssetConversion::Pools` (r:1 w:0) @@ -96,10 +99,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1507` + // Measured: `1546` // Estimated: `11426` - // Minimum execution time: 147_652_000 picoseconds. - Weight::from_parts(153_331_000, 11426) + // Minimum execution time: 153_723_000 picoseconds. + Weight::from_parts(155_774_000, 11426) .saturating_add(T::DbWeight::get().reads(11_u64)) .saturating_add(T::DbWeight::get().writes(10_u64)) } @@ -117,8 +120,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1650` // Estimated: `11426` - // Minimum execution time: 130_738_000 picoseconds. - Weight::from_parts(134_350_000, 11426) + // Minimum execution time: 138_643_000 picoseconds. + Weight::from_parts(140_518_000, 11426) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(8_u64)) } @@ -131,10 +134,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `89 + n * (419 ±0)` // Estimated: `990 + n * (5218 ±0)` - // Minimum execution time: 79_681_000 picoseconds. - Weight::from_parts(81_461_000, 990) - // Standard Error: 320_959 - .saturating_add(Weight::from_parts(11_223_703, 0).saturating_mul(n.into())) + // Minimum execution time: 93_760_000 picoseconds. + Weight::from_parts(6_225_956, 990) + // Standard Error: 70_327 + .saturating_add(Weight::from_parts(45_209_796, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(n.into()))) .saturating_add(Weight::from_parts(0, 5218).saturating_mul(n.into())) @@ -148,10 +151,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `89 + n * (419 ±0)` // Estimated: `990 + n * (5218 ±0)` - // Minimum execution time: 78_988_000 picoseconds. - Weight::from_parts(81_025_000, 990) - // Standard Error: 320_021 - .saturating_add(Weight::from_parts(11_040_712, 0).saturating_mul(n.into())) + // Minimum execution time: 93_972_000 picoseconds. + Weight::from_parts(4_882_727, 990) + // Standard Error: 69_974 + .saturating_add(Weight::from_parts(45_961_057, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(n.into()))) .saturating_add(Weight::from_parts(0, 5218).saturating_mul(n.into())) @@ -171,12 +174,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[0, 3]`. fn touch(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1571` + // Measured: `1610` // Estimated: `6360` - // Minimum execution time: 45_757_000 picoseconds. - Weight::from_parts(48_502_032, 6360) - // Standard Error: 62_850 - .saturating_add(Weight::from_parts(19_450_978, 0).saturating_mul(n.into())) + // Minimum execution time: 56_011_000 picoseconds. + Weight::from_parts(59_515_373, 6360) + // Standard Error: 81_340 + .saturating_add(Weight::from_parts(19_186_821, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(n.into()))) } @@ -194,15 +197,17 @@ impl WeightInfo for () { /// Proof: `AssetConversion::NextPoolAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PoolAssets::Asset` (r:1 w:1) /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::NextAssetId` (r:1 w:0) + /// Proof: `PoolAssets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `PoolAssets::Account` (r:1 w:1) /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) fn create_pool() -> Weight { // Proof Size summary in bytes: - // Measured: `910` + // Measured: `949` // Estimated: `6360` - // Minimum execution time: 95_080_000 picoseconds. - Weight::from_parts(97_241_000, 6360) - .saturating_add(RocksDbWeight::get().reads(8_u64)) + // Minimum execution time: 97_276_000 picoseconds. + Weight::from_parts(99_380_000, 6360) + .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } /// Storage: `AssetConversion::Pools` (r:1 w:0) @@ -219,10 +224,10 @@ impl WeightInfo for () { /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) fn add_liquidity() -> Weight { // Proof Size summary in bytes: - // Measured: `1507` + // Measured: `1546` // Estimated: `11426` - // Minimum execution time: 147_652_000 picoseconds. - Weight::from_parts(153_331_000, 11426) + // Minimum execution time: 153_723_000 picoseconds. + Weight::from_parts(155_774_000, 11426) .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().writes(10_u64)) } @@ -240,8 +245,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1650` // Estimated: `11426` - // Minimum execution time: 130_738_000 picoseconds. - Weight::from_parts(134_350_000, 11426) + // Minimum execution time: 138_643_000 picoseconds. + Weight::from_parts(140_518_000, 11426) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(8_u64)) } @@ -254,10 +259,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `89 + n * (419 ±0)` // Estimated: `990 + n * (5218 ±0)` - // Minimum execution time: 79_681_000 picoseconds. - Weight::from_parts(81_461_000, 990) - // Standard Error: 320_959 - .saturating_add(Weight::from_parts(11_223_703, 0).saturating_mul(n.into())) + // Minimum execution time: 93_760_000 picoseconds. + Weight::from_parts(6_225_956, 990) + // Standard Error: 70_327 + .saturating_add(Weight::from_parts(45_209_796, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(n.into()))) .saturating_add(Weight::from_parts(0, 5218).saturating_mul(n.into())) @@ -271,10 +276,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `89 + n * (419 ±0)` // Estimated: `990 + n * (5218 ±0)` - // Minimum execution time: 78_988_000 picoseconds. - Weight::from_parts(81_025_000, 990) - // Standard Error: 320_021 - .saturating_add(Weight::from_parts(11_040_712, 0).saturating_mul(n.into())) + // Minimum execution time: 93_972_000 picoseconds. + Weight::from_parts(4_882_727, 990) + // Standard Error: 69_974 + .saturating_add(Weight::from_parts(45_961_057, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(n.into()))) .saturating_add(Weight::from_parts(0, 5218).saturating_mul(n.into())) @@ -294,12 +299,12 @@ impl WeightInfo for () { /// The range of component `n` is `[0, 3]`. fn touch(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1571` + // Measured: `1610` // Estimated: `6360` - // Minimum execution time: 45_757_000 picoseconds. - Weight::from_parts(48_502_032, 6360) - // Standard Error: 62_850 - .saturating_add(Weight::from_parts(19_450_978, 0).saturating_mul(n.into())) + // Minimum execution time: 56_011_000 picoseconds. + Weight::from_parts(59_515_373, 6360) + // Standard Error: 81_340 + .saturating_add(Weight::from_parts(19_186_821, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes((2_u64).saturating_mul(n.into()))) } diff --git a/substrate/frame/asset-rate/src/weights.rs b/substrate/frame/asset-rate/src/weights.rs index fb577b618b33..c1991dc4ebb2 100644 --- a/substrate/frame/asset-rate/src/weights.rs +++ b/substrate/frame/asset-rate/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_asset_rate` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -60,35 +60,35 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: // Measured: `76` - // Estimated: `3501` - // Minimum execution time: 9_816_000 picoseconds. - Weight::from_parts(10_076_000, 3501) + // Estimated: `3502` + // Minimum execution time: 10_361_000 picoseconds. + Weight::from_parts(10_757_000, 3502) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn update() -> Weight { // Proof Size summary in bytes: - // Measured: `137` - // Estimated: `3501` - // Minimum execution time: 10_164_000 picoseconds. - Weight::from_parts(10_598_000, 3501) + // Measured: `134` + // Estimated: `3502` + // Minimum execution time: 11_193_000 picoseconds. + Weight::from_parts(11_625_000, 3502) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn remove() -> Weight { // Proof Size summary in bytes: - // Measured: `137` - // Estimated: `3501` - // Minimum execution time: 10_837_000 picoseconds. - Weight::from_parts(11_050_000, 3501) + // Measured: `134` + // Estimated: `3502` + // Minimum execution time: 11_941_000 picoseconds. + Weight::from_parts(12_440_000, 3502) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -97,35 +97,35 @@ impl WeightInfo for SubstrateWeight { // For backwards compatibility and tests. impl WeightInfo for () { /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: // Measured: `76` - // Estimated: `3501` - // Minimum execution time: 9_816_000 picoseconds. - Weight::from_parts(10_076_000, 3501) + // Estimated: `3502` + // Minimum execution time: 10_361_000 picoseconds. + Weight::from_parts(10_757_000, 3502) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn update() -> Weight { // Proof Size summary in bytes: - // Measured: `137` - // Estimated: `3501` - // Minimum execution time: 10_164_000 picoseconds. - Weight::from_parts(10_598_000, 3501) + // Measured: `134` + // Estimated: `3502` + // Minimum execution time: 11_193_000 picoseconds. + Weight::from_parts(11_625_000, 3502) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) fn remove() -> Weight { // Proof Size summary in bytes: - // Measured: `137` - // Estimated: `3501` - // Minimum execution time: 10_837_000 picoseconds. - Weight::from_parts(11_050_000, 3501) + // Measured: `134` + // Estimated: `3502` + // Minimum execution time: 11_941_000 picoseconds. + Weight::from_parts(12_440_000, 3502) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/assets/src/weights.rs b/substrate/frame/assets/src/weights.rs index 57f7e951b73c..09997bc9d719 100644 --- a/substrate/frame/assets/src/weights.rs +++ b/substrate/frame/assets/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_assets` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -91,26 +91,30 @@ pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3675` - // Minimum execution time: 26_165_000 picoseconds. - Weight::from_parts(26_838_000, 3675) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Minimum execution time: 33_908_000 picoseconds. + Weight::from_parts(37_126_000, 3675) + .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn force_create() -> Weight { // Proof Size summary in bytes: // Measured: `153` // Estimated: `3675` - // Minimum execution time: 11_152_000 picoseconds. - Weight::from_parts(11_624_000, 3675) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Minimum execution time: 13_105_000 picoseconds. + Weight::from_parts(13_348_000, 3675) + .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Assets::Asset` (r:1 w:1) @@ -119,8 +123,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_961_000 picoseconds. - Weight::from_parts(12_408_000, 3675) + // Minimum execution time: 17_478_000 picoseconds. + Weight::from_parts(17_964_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -133,12 +137,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `c` is `[0, 1000]`. fn destroy_accounts(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + c * (208 ±0)` + // Measured: `71 + c * (208 ±0)` // Estimated: `3675 + c * (2609 ±0)` - // Minimum execution time: 15_815_000 picoseconds. - Weight::from_parts(16_370_000, 3675) - // Standard Error: 7_448 - .saturating_add(Weight::from_parts(13_217_179, 0).saturating_mul(c.into())) + // Minimum execution time: 20_846_000 picoseconds. + Weight::from_parts(21_195_000, 3675) + // Standard Error: 13_008 + .saturating_add(Weight::from_parts(15_076_064, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -154,10 +158,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `522 + a * (86 ±0)` // Estimated: `3675 + a * (2623 ±0)` - // Minimum execution time: 16_791_000 picoseconds. - Weight::from_parts(17_066_000, 3675) - // Standard Error: 7_163 - .saturating_add(Weight::from_parts(14_436_592, 0).saturating_mul(a.into())) + // Minimum execution time: 21_340_000 picoseconds. + Weight::from_parts(21_916_000, 3675) + // Standard Error: 8_545 + .saturating_add(Weight::from_parts(15_868_375, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -172,8 +176,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 12_769_000 picoseconds. - Weight::from_parts(13_097_000, 3675) + // Minimum execution time: 18_110_000 picoseconds. + Weight::from_parts(18_512_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -185,8 +189,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 22_539_000 picoseconds. - Weight::from_parts(23_273_000, 3675) + // Minimum execution time: 27_639_000 picoseconds. + Weight::from_parts(28_680_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -198,8 +202,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 30_885_000 picoseconds. - Weight::from_parts(31_800_000, 3675) + // Minimum execution time: 36_011_000 picoseconds. + Weight::from_parts(37_095_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -213,8 +217,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 43_618_000 picoseconds. - Weight::from_parts(44_794_000, 6208) + // Minimum execution time: 48_531_000 picoseconds. + Weight::from_parts(50_508_000, 6208) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -228,8 +232,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 39_174_000 picoseconds. - Weight::from_parts(40_059_000, 6208) + // Minimum execution time: 44_754_000 picoseconds. + Weight::from_parts(45_999_000, 6208) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -243,8 +247,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 43_963_000 picoseconds. - Weight::from_parts(44_995_000, 6208) + // Minimum execution time: 48_407_000 picoseconds. + Weight::from_parts(49_737_000, 6208) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -256,8 +260,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_853_000 picoseconds. - Weight::from_parts(16_414_000, 3675) + // Minimum execution time: 21_827_000 picoseconds. + Weight::from_parts(22_616_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -269,8 +273,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_925_000 picoseconds. - Weight::from_parts(16_449_000, 3675) + // Minimum execution time: 21_579_000 picoseconds. + Weight::from_parts(22_406_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -280,8 +284,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_629_000 picoseconds. - Weight::from_parts(12_138_000, 3675) + // Minimum execution time: 16_754_000 picoseconds. + Weight::from_parts(17_556_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -291,8 +295,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_653_000 picoseconds. - Weight::from_parts(12_058_000, 3675) + // Minimum execution time: 16_602_000 picoseconds. + Weight::from_parts(17_551_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -304,8 +308,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 13_292_000 picoseconds. - Weight::from_parts(13_686_000, 3675) + // Minimum execution time: 18_231_000 picoseconds. + Weight::from_parts(18_899_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -315,8 +319,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 11_805_000 picoseconds. - Weight::from_parts(12_060_000, 3675) + // Minimum execution time: 16_396_000 picoseconds. + Weight::from_parts(16_937_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -326,16 +330,12 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) /// The range of component `n` is `[0, 50]`. /// The range of component `s` is `[0, 50]`. - fn set_metadata(n: u32, s: u32, ) -> Weight { + fn set_metadata(_n: u32, _s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 26_289_000 picoseconds. - Weight::from_parts(27_543_545, 3675) - // Standard Error: 939 - .saturating_add(Weight::from_parts(4_967, 0).saturating_mul(n.into())) - // Standard Error: 939 - .saturating_add(Weight::from_parts(3_698, 0).saturating_mul(s.into())) + // Minimum execution time: 31_604_000 picoseconds. + Weight::from_parts(33_443_707, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -347,8 +347,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `515` // Estimated: `3675` - // Minimum execution time: 27_560_000 picoseconds. - Weight::from_parts(28_541_000, 3675) + // Minimum execution time: 32_152_000 picoseconds. + Weight::from_parts(32_893_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -362,12 +362,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `190` // Estimated: `3675` - // Minimum execution time: 12_378_000 picoseconds. - Weight::from_parts(13_057_891, 3675) - // Standard Error: 474 - .saturating_add(Weight::from_parts(1_831, 0).saturating_mul(n.into())) - // Standard Error: 474 - .saturating_add(Weight::from_parts(2_387, 0).saturating_mul(s.into())) + // Minimum execution time: 13_637_000 picoseconds. + Weight::from_parts(14_385_881, 3675) + // Standard Error: 375 + .saturating_add(Weight::from_parts(1_821, 0).saturating_mul(n.into())) + // Standard Error: 375 + .saturating_add(Weight::from_parts(147, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -379,8 +379,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `515` // Estimated: `3675` - // Minimum execution time: 27_134_000 picoseconds. - Weight::from_parts(28_333_000, 3675) + // Minimum execution time: 31_587_000 picoseconds. + Weight::from_parts(32_438_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -390,8 +390,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 11_524_000 picoseconds. - Weight::from_parts(11_934_000, 3675) + // Minimum execution time: 16_006_000 picoseconds. + Weight::from_parts(16_623_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -403,8 +403,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 30_206_000 picoseconds. - Weight::from_parts(31_624_000, 3675) + // Minimum execution time: 36_026_000 picoseconds. + Weight::from_parts(37_023_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -420,8 +420,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `668` // Estimated: `6208` - // Minimum execution time: 64_074_000 picoseconds. - Weight::from_parts(66_145_000, 6208) + // Minimum execution time: 68_731_000 picoseconds. + Weight::from_parts(70_171_000, 6208) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -433,8 +433,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `555` // Estimated: `3675` - // Minimum execution time: 32_790_000 picoseconds. - Weight::from_parts(33_634_000, 3675) + // Minimum execution time: 38_039_000 picoseconds. + Weight::from_parts(39_018_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -446,8 +446,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `555` // Estimated: `3675` - // Minimum execution time: 33_150_000 picoseconds. - Weight::from_parts(34_440_000, 3675) + // Minimum execution time: 38_056_000 picoseconds. + Weight::from_parts(39_228_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -457,8 +457,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 12_365_000 picoseconds. - Weight::from_parts(12_870_000, 3675) + // Minimum execution time: 16_653_000 picoseconds. + Weight::from_parts(17_240_000, 3675) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -472,8 +472,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `453` // Estimated: `3675` - // Minimum execution time: 32_308_000 picoseconds. - Weight::from_parts(33_080_000, 3675) + // Minimum execution time: 37_938_000 picoseconds. + Weight::from_parts(38_960_000, 3675) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -485,8 +485,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 29_870_000 picoseconds. - Weight::from_parts(30_562_000, 3675) + // Minimum execution time: 35_210_000 picoseconds. + Weight::from_parts(36_222_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -500,8 +500,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `579` // Estimated: `3675` - // Minimum execution time: 31_980_000 picoseconds. - Weight::from_parts(33_747_000, 3675) + // Minimum execution time: 36_787_000 picoseconds. + Weight::from_parts(38_229_000, 3675) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -513,8 +513,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `510` // Estimated: `3675` - // Minimum execution time: 29_599_000 picoseconds. - Weight::from_parts(30_919_000, 3675) + // Minimum execution time: 34_185_000 picoseconds. + Weight::from_parts(35_456_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -526,20 +526,25 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_741_000 picoseconds. - Weight::from_parts(16_558_000, 3675) + // Minimum execution time: 21_482_000 picoseconds. + Weight::from_parts(22_135_000, 3675) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `3593` - // Minimum execution time: 46_573_000 picoseconds. - Weight::from_parts(47_385_000, 3593) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Measured: `498` + // Estimated: `6208` + // Minimum execution time: 58_108_000 picoseconds. + Weight::from_parts(59_959_000, 6208) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) } } @@ -547,26 +552,30 @@ impl WeightInfo for SubstrateWeight { impl WeightInfo for () { /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3675` - // Minimum execution time: 26_165_000 picoseconds. - Weight::from_parts(26_838_000, 3675) - .saturating_add(RocksDbWeight::get().reads(2_u64)) + // Minimum execution time: 33_908_000 picoseconds. + Weight::from_parts(37_126_000, 3675) + .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn force_create() -> Weight { // Proof Size summary in bytes: // Measured: `153` // Estimated: `3675` - // Minimum execution time: 11_152_000 picoseconds. - Weight::from_parts(11_624_000, 3675) - .saturating_add(RocksDbWeight::get().reads(1_u64)) + // Minimum execution time: 13_105_000 picoseconds. + Weight::from_parts(13_348_000, 3675) + .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Assets::Asset` (r:1 w:1) @@ -575,8 +584,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_961_000 picoseconds. - Weight::from_parts(12_408_000, 3675) + // Minimum execution time: 17_478_000 picoseconds. + Weight::from_parts(17_964_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -589,12 +598,12 @@ impl WeightInfo for () { /// The range of component `c` is `[0, 1000]`. fn destroy_accounts(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `0 + c * (208 ±0)` + // Measured: `71 + c * (208 ±0)` // Estimated: `3675 + c * (2609 ±0)` - // Minimum execution time: 15_815_000 picoseconds. - Weight::from_parts(16_370_000, 3675) - // Standard Error: 7_448 - .saturating_add(Weight::from_parts(13_217_179, 0).saturating_mul(c.into())) + // Minimum execution time: 20_846_000 picoseconds. + Weight::from_parts(21_195_000, 3675) + // Standard Error: 13_008 + .saturating_add(Weight::from_parts(15_076_064, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((2_u64).saturating_mul(c.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -610,10 +619,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `522 + a * (86 ±0)` // Estimated: `3675 + a * (2623 ±0)` - // Minimum execution time: 16_791_000 picoseconds. - Weight::from_parts(17_066_000, 3675) - // Standard Error: 7_163 - .saturating_add(Weight::from_parts(14_436_592, 0).saturating_mul(a.into())) + // Minimum execution time: 21_340_000 picoseconds. + Weight::from_parts(21_916_000, 3675) + // Standard Error: 8_545 + .saturating_add(Weight::from_parts(15_868_375, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(a.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -628,8 +637,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 12_769_000 picoseconds. - Weight::from_parts(13_097_000, 3675) + // Minimum execution time: 18_110_000 picoseconds. + Weight::from_parts(18_512_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -641,8 +650,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 22_539_000 picoseconds. - Weight::from_parts(23_273_000, 3675) + // Minimum execution time: 27_639_000 picoseconds. + Weight::from_parts(28_680_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -654,8 +663,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 30_885_000 picoseconds. - Weight::from_parts(31_800_000, 3675) + // Minimum execution time: 36_011_000 picoseconds. + Weight::from_parts(37_095_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -669,8 +678,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 43_618_000 picoseconds. - Weight::from_parts(44_794_000, 6208) + // Minimum execution time: 48_531_000 picoseconds. + Weight::from_parts(50_508_000, 6208) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -684,8 +693,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 39_174_000 picoseconds. - Weight::from_parts(40_059_000, 6208) + // Minimum execution time: 44_754_000 picoseconds. + Weight::from_parts(45_999_000, 6208) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -699,8 +708,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `498` // Estimated: `6208` - // Minimum execution time: 43_963_000 picoseconds. - Weight::from_parts(44_995_000, 6208) + // Minimum execution time: 48_407_000 picoseconds. + Weight::from_parts(49_737_000, 6208) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -712,8 +721,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_853_000 picoseconds. - Weight::from_parts(16_414_000, 3675) + // Minimum execution time: 21_827_000 picoseconds. + Weight::from_parts(22_616_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -725,8 +734,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_925_000 picoseconds. - Weight::from_parts(16_449_000, 3675) + // Minimum execution time: 21_579_000 picoseconds. + Weight::from_parts(22_406_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -736,8 +745,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_629_000 picoseconds. - Weight::from_parts(12_138_000, 3675) + // Minimum execution time: 16_754_000 picoseconds. + Weight::from_parts(17_556_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -747,8 +756,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 11_653_000 picoseconds. - Weight::from_parts(12_058_000, 3675) + // Minimum execution time: 16_602_000 picoseconds. + Weight::from_parts(17_551_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -760,8 +769,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 13_292_000 picoseconds. - Weight::from_parts(13_686_000, 3675) + // Minimum execution time: 18_231_000 picoseconds. + Weight::from_parts(18_899_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -771,8 +780,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 11_805_000 picoseconds. - Weight::from_parts(12_060_000, 3675) + // Minimum execution time: 16_396_000 picoseconds. + Weight::from_parts(16_937_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -782,16 +791,12 @@ impl WeightInfo for () { /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) /// The range of component `n` is `[0, 50]`. /// The range of component `s` is `[0, 50]`. - fn set_metadata(n: u32, s: u32, ) -> Weight { + fn set_metadata(_n: u32, _s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 26_289_000 picoseconds. - Weight::from_parts(27_543_545, 3675) - // Standard Error: 939 - .saturating_add(Weight::from_parts(4_967, 0).saturating_mul(n.into())) - // Standard Error: 939 - .saturating_add(Weight::from_parts(3_698, 0).saturating_mul(s.into())) + // Minimum execution time: 31_604_000 picoseconds. + Weight::from_parts(33_443_707, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -803,8 +808,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `515` // Estimated: `3675` - // Minimum execution time: 27_560_000 picoseconds. - Weight::from_parts(28_541_000, 3675) + // Minimum execution time: 32_152_000 picoseconds. + Weight::from_parts(32_893_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -818,12 +823,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `190` // Estimated: `3675` - // Minimum execution time: 12_378_000 picoseconds. - Weight::from_parts(13_057_891, 3675) - // Standard Error: 474 - .saturating_add(Weight::from_parts(1_831, 0).saturating_mul(n.into())) - // Standard Error: 474 - .saturating_add(Weight::from_parts(2_387, 0).saturating_mul(s.into())) + // Minimum execution time: 13_637_000 picoseconds. + Weight::from_parts(14_385_881, 3675) + // Standard Error: 375 + .saturating_add(Weight::from_parts(1_821, 0).saturating_mul(n.into())) + // Standard Error: 375 + .saturating_add(Weight::from_parts(147, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -835,8 +840,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `515` // Estimated: `3675` - // Minimum execution time: 27_134_000 picoseconds. - Weight::from_parts(28_333_000, 3675) + // Minimum execution time: 31_587_000 picoseconds. + Weight::from_parts(32_438_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -846,8 +851,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 11_524_000 picoseconds. - Weight::from_parts(11_934_000, 3675) + // Minimum execution time: 16_006_000 picoseconds. + Weight::from_parts(16_623_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -859,8 +864,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `385` // Estimated: `3675` - // Minimum execution time: 30_206_000 picoseconds. - Weight::from_parts(31_624_000, 3675) + // Minimum execution time: 36_026_000 picoseconds. + Weight::from_parts(37_023_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -876,8 +881,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `668` // Estimated: `6208` - // Minimum execution time: 64_074_000 picoseconds. - Weight::from_parts(66_145_000, 6208) + // Minimum execution time: 68_731_000 picoseconds. + Weight::from_parts(70_171_000, 6208) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -889,8 +894,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `555` // Estimated: `3675` - // Minimum execution time: 32_790_000 picoseconds. - Weight::from_parts(33_634_000, 3675) + // Minimum execution time: 38_039_000 picoseconds. + Weight::from_parts(39_018_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -902,8 +907,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `555` // Estimated: `3675` - // Minimum execution time: 33_150_000 picoseconds. - Weight::from_parts(34_440_000, 3675) + // Minimum execution time: 38_056_000 picoseconds. + Weight::from_parts(39_228_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -913,8 +918,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 12_365_000 picoseconds. - Weight::from_parts(12_870_000, 3675) + // Minimum execution time: 16_653_000 picoseconds. + Weight::from_parts(17_240_000, 3675) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -928,8 +933,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `453` // Estimated: `3675` - // Minimum execution time: 32_308_000 picoseconds. - Weight::from_parts(33_080_000, 3675) + // Minimum execution time: 37_938_000 picoseconds. + Weight::from_parts(38_960_000, 3675) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -941,8 +946,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3675` - // Minimum execution time: 29_870_000 picoseconds. - Weight::from_parts(30_562_000, 3675) + // Minimum execution time: 35_210_000 picoseconds. + Weight::from_parts(36_222_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -956,8 +961,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `579` // Estimated: `3675` - // Minimum execution time: 31_980_000 picoseconds. - Weight::from_parts(33_747_000, 3675) + // Minimum execution time: 36_787_000 picoseconds. + Weight::from_parts(38_229_000, 3675) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -969,8 +974,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `510` // Estimated: `3675` - // Minimum execution time: 29_599_000 picoseconds. - Weight::from_parts(30_919_000, 3675) + // Minimum execution time: 34_185_000 picoseconds. + Weight::from_parts(35_456_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -982,19 +987,24 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `459` // Estimated: `3675` - // Minimum execution time: 15_741_000 picoseconds. - Weight::from_parts(16_558_000, 3675) + // Minimum execution time: 21_482_000 picoseconds. + Weight::from_parts(22_135_000, 3675) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `3593` - // Minimum execution time: 46_573_000 picoseconds. - Weight::from_parts(47_385_000, 3593) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) + // Measured: `498` + // Estimated: `6208` + // Minimum execution time: 58_108_000 picoseconds. + Weight::from_parts(59_959_000, 6208) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) } } diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index 1de2262a2014..5c969a3480d4 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -67,6 +67,7 @@ pub mod pallet { } #[pallet::storage] + #[pallet::whitelist_storage] /// Author of current block. pub(super) type Author = StorageValue<_, T::AccountId, OptionQuery>; } diff --git a/substrate/frame/bags-list/src/weights.rs b/substrate/frame/bags-list/src/weights.rs index 8a5424881e97..52218277a795 100644 --- a/substrate/frame/bags-list/src/weights.rs +++ b/substrate/frame/bags-list/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_bags_list` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -69,10 +69,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn rebag_non_terminal() -> Weight { // Proof Size summary in bytes: - // Measured: `1719` + // Measured: `1785` // Estimated: `11506` - // Minimum execution time: 60_062_000 picoseconds. - Weight::from_parts(62_341_000, 11506) + // Minimum execution time: 69_033_000 picoseconds. + Weight::from_parts(71_551_000, 11506) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -86,10 +86,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn rebag_terminal() -> Weight { // Proof Size summary in bytes: - // Measured: `1613` + // Measured: `1679` // Estimated: `8877` - // Minimum execution time: 57_585_000 picoseconds. - Weight::from_parts(59_480_000, 8877) + // Minimum execution time: 66_157_000 picoseconds. + Weight::from_parts(69_215_000, 8877) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -105,10 +105,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn put_in_front_of() -> Weight { // Proof Size summary in bytes: - // Measured: `1925` + // Measured: `1991` // Estimated: `11506` - // Minimum execution time: 69_552_000 picoseconds. - Weight::from_parts(71_211_000, 11506) + // Minimum execution time: 79_581_000 picoseconds. + Weight::from_parts(81_999_000, 11506) .saturating_add(T::DbWeight::get().reads(10_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -126,10 +126,10 @@ impl WeightInfo for () { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn rebag_non_terminal() -> Weight { // Proof Size summary in bytes: - // Measured: `1719` + // Measured: `1785` // Estimated: `11506` - // Minimum execution time: 60_062_000 picoseconds. - Weight::from_parts(62_341_000, 11506) + // Minimum execution time: 69_033_000 picoseconds. + Weight::from_parts(71_551_000, 11506) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -143,10 +143,10 @@ impl WeightInfo for () { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn rebag_terminal() -> Weight { // Proof Size summary in bytes: - // Measured: `1613` + // Measured: `1679` // Estimated: `8877` - // Minimum execution time: 57_585_000 picoseconds. - Weight::from_parts(59_480_000, 8877) + // Minimum execution time: 66_157_000 picoseconds. + Weight::from_parts(69_215_000, 8877) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -162,10 +162,10 @@ impl WeightInfo for () { /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) fn put_in_front_of() -> Weight { // Proof Size summary in bytes: - // Measured: `1925` + // Measured: `1991` // Estimated: `11506` - // Minimum execution time: 69_552_000 picoseconds. - Weight::from_parts(71_211_000, 11506) + // Minimum execution time: 79_581_000 picoseconds. + Weight::from_parts(81_999_000, 11506) .saturating_add(RocksDbWeight::get().reads(10_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } diff --git a/substrate/frame/balances/src/tests/currency_tests.rs b/substrate/frame/balances/src/tests/currency_tests.rs index 7fcc49d50aa5..5ad818e5bfa2 100644 --- a/substrate/frame/balances/src/tests/currency_tests.rs +++ b/substrate/frame/balances/src/tests/currency_tests.rs @@ -265,6 +265,7 @@ fn lock_should_work_reserve() { CALL, &info_from_weight(Weight::from_parts(1, 0)), 1, + 0, ) .is_err()); assert!(ChargeTransactionPayment::::validate_and_prepare( @@ -273,6 +274,7 @@ fn lock_should_work_reserve() { CALL, &info_from_weight(Weight::from_parts(1, 0)), 1, + 0, ) .is_err()); }); @@ -296,6 +298,7 @@ fn lock_should_work_tx_fee() { CALL, &info_from_weight(Weight::from_parts(1, 0)), 1, + 0, ) .is_err()); assert!(ChargeTransactionPayment::::validate_and_prepare( @@ -304,6 +307,7 @@ fn lock_should_work_tx_fee() { CALL, &info_from_weight(Weight::from_parts(1, 0)), 1, + 0, ) .is_err()); }); diff --git a/substrate/frame/balances/src/weights.rs b/substrate/frame/balances/src/weights.rs index 55decef273f6..0c7a1354cda0 100644 --- a/substrate/frame/balances/src/weights.rs +++ b/substrate/frame/balances/src/weights.rs @@ -17,27 +17,29 @@ //! Autogenerated weights for `pallet_balances` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 42.0.0 -//! DATE: 2024-09-04, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `8f4ffe8f7785`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `None`, DB CACHE: `1024` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// frame-omni-bencher -// v1 +// ./target/production/substrate-node // benchmark // pallet -// --extrinsic=* -// --runtime=target/release/wbuild/kitchensink-runtime/kitchensink_runtime.wasm -// --pallet=pallet_balances -// --header=/__w/polkadot-sdk/polkadot-sdk/substrate/HEADER-APACHE2 -// --output=/__w/polkadot-sdk/polkadot-sdk/substrate/frame/balances/src/weights.rs -// --wasm-execution=compiled +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --wasm-execution=compiled // --heap-pages=4096 -// --template=substrate/.maintain/frame-weight-template.hbs +// --output=./substrate/frame/balances/src/weights.rs +// --header=./substrate/HEADER-APACHE2 +// --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -69,10 +71,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_allow_death() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 75_624_000 picoseconds. - Weight::from_parts(77_290_000, 3593) + // Minimum execution time: 50_023_000 picoseconds. + Weight::from_parts(51_105_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -80,10 +82,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_keep_alive() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 60_398_000 picoseconds. - Weight::from_parts(61_290_000, 3593) + // Minimum execution time: 39_923_000 picoseconds. + Weight::from_parts(40_655_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -91,10 +93,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_creating() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 18_963_000 picoseconds. - Weight::from_parts(19_802_000, 3593) + // Minimum execution time: 15_062_000 picoseconds. + Weight::from_parts(15_772_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -102,10 +104,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_killing() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 30_517_000 picoseconds. - Weight::from_parts(31_293_000, 3593) + // Minimum execution time: 21_797_000 picoseconds. + Weight::from_parts(22_287_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -113,10 +115,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `155` // Estimated: `6196` - // Minimum execution time: 77_017_000 picoseconds. - Weight::from_parts(78_184_000, 6196) + // Minimum execution time: 51_425_000 picoseconds. + Weight::from_parts(52_600_000, 6196) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -124,10 +126,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 75_600_000 picoseconds. - Weight::from_parts(76_817_000, 3593) + // Minimum execution time: 49_399_000 picoseconds. + Weight::from_parts(51_205_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -135,10 +137,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_unreserve() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 24_503_000 picoseconds. - Weight::from_parts(25_026_000, 3593) + // Minimum execution time: 18_119_000 picoseconds. + Weight::from_parts(18_749_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -149,10 +151,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 24_077_000 picoseconds. - Weight::from_parts(24_339_000, 990) - // Standard Error: 18_669 - .saturating_add(Weight::from_parts(21_570_294, 0).saturating_mul(u.into())) + // Minimum execution time: 16_783_000 picoseconds. + Weight::from_parts(17_076_000, 990) + // Standard Error: 15_126 + .saturating_add(Weight::from_parts(14_834_157, 0).saturating_mul(u.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) @@ -161,22 +163,22 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_070_000 picoseconds. - Weight::from_parts(8_727_000, 0) + // Minimum execution time: 6_048_000 picoseconds. + Weight::from_parts(6_346_000, 0) } fn burn_allow_death() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 46_978_000 picoseconds. - Weight::from_parts(47_917_000, 0) + // Minimum execution time: 30_215_000 picoseconds. + Weight::from_parts(30_848_000, 0) } fn burn_keep_alive() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 31_141_000 picoseconds. - Weight::from_parts(31_917_000, 0) + // Minimum execution time: 20_813_000 picoseconds. + Weight::from_parts(21_553_000, 0) } } @@ -186,10 +188,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_allow_death() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 75_624_000 picoseconds. - Weight::from_parts(77_290_000, 3593) + // Minimum execution time: 50_023_000 picoseconds. + Weight::from_parts(51_105_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -197,10 +199,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_keep_alive() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 60_398_000 picoseconds. - Weight::from_parts(61_290_000, 3593) + // Minimum execution time: 39_923_000 picoseconds. + Weight::from_parts(40_655_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -208,10 +210,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_creating() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 18_963_000 picoseconds. - Weight::from_parts(19_802_000, 3593) + // Minimum execution time: 15_062_000 picoseconds. + Weight::from_parts(15_772_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -219,10 +221,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_set_balance_killing() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 30_517_000 picoseconds. - Weight::from_parts(31_293_000, 3593) + // Minimum execution time: 21_797_000 picoseconds. + Weight::from_parts(22_287_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -230,10 +232,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `155` // Estimated: `6196` - // Minimum execution time: 77_017_000 picoseconds. - Weight::from_parts(78_184_000, 6196) + // Minimum execution time: 51_425_000 picoseconds. + Weight::from_parts(52_600_000, 6196) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -241,10 +243,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer_all() -> Weight { // Proof Size summary in bytes: - // Measured: `0` + // Measured: `52` // Estimated: `3593` - // Minimum execution time: 75_600_000 picoseconds. - Weight::from_parts(76_817_000, 3593) + // Minimum execution time: 49_399_000 picoseconds. + Weight::from_parts(51_205_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -252,10 +254,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn force_unreserve() -> Weight { // Proof Size summary in bytes: - // Measured: `52` + // Measured: `174` // Estimated: `3593` - // Minimum execution time: 24_503_000 picoseconds. - Weight::from_parts(25_026_000, 3593) + // Minimum execution time: 18_119_000 picoseconds. + Weight::from_parts(18_749_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -266,10 +268,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0 + u * (135 ±0)` // Estimated: `990 + u * (2603 ±0)` - // Minimum execution time: 24_077_000 picoseconds. - Weight::from_parts(24_339_000, 990) - // Standard Error: 18_669 - .saturating_add(Weight::from_parts(21_570_294, 0).saturating_mul(u.into())) + // Minimum execution time: 16_783_000 picoseconds. + Weight::from_parts(17_076_000, 990) + // Standard Error: 15_126 + .saturating_add(Weight::from_parts(14_834_157, 0).saturating_mul(u.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(u.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(u.into()))) .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) @@ -278,21 +280,21 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_070_000 picoseconds. - Weight::from_parts(8_727_000, 0) + // Minimum execution time: 6_048_000 picoseconds. + Weight::from_parts(6_346_000, 0) } fn burn_allow_death() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 46_978_000 picoseconds. - Weight::from_parts(47_917_000, 0) + // Minimum execution time: 30_215_000 picoseconds. + Weight::from_parts(30_848_000, 0) } fn burn_keep_alive() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 31_141_000 picoseconds. - Weight::from_parts(31_917_000, 0) + // Minimum execution time: 20_813_000 picoseconds. + Weight::from_parts(21_553_000, 0) } } diff --git a/substrate/frame/beefy-mmr/src/weights.rs b/substrate/frame/beefy-mmr/src/weights.rs index c292f25400cc..dcfdb560ee94 100644 --- a/substrate/frame/beefy-mmr/src/weights.rs +++ b/substrate/frame/beefy-mmr/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_beefy_mmr` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-08-13, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-696hpswk-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_beefy_mmr +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_beefy_mmr -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/beefy-mmr/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -61,20 +63,20 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn extract_validation_context() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 7_461_000 picoseconds. - Weight::from_parts(7_669_000, 3509) + // Minimum execution time: 6_687_000 picoseconds. + Weight::from_parts(6_939_000, 3509) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Mmr::Nodes` (r:1 w:0) /// Proof: `Mmr::Nodes` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) fn read_peak() -> Weight { // Proof Size summary in bytes: - // Measured: `333` + // Measured: `386` // Estimated: `3505` - // Minimum execution time: 6_137_000 picoseconds. - Weight::from_parts(6_423_000, 3505) + // Minimum execution time: 10_409_000 picoseconds. + Weight::from_parts(10_795_000, 3505) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Mmr::RootHash` (r:1 w:0) @@ -84,12 +86,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[2, 512]`. fn n_items_proof_is_non_canonical(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `325` + // Measured: `378` // Estimated: `1517` - // Minimum execution time: 10_687_000 picoseconds. - Weight::from_parts(14_851_626, 1517) - // Standard Error: 1_455 - .saturating_add(Weight::from_parts(961_703, 0).saturating_mul(n.into())) + // Minimum execution time: 15_459_000 picoseconds. + Weight::from_parts(21_963_366, 1517) + // Standard Error: 1_528 + .saturating_add(Weight::from_parts(984_907, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) } } @@ -100,20 +102,20 @@ impl WeightInfo for () { /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn extract_validation_context() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 7_461_000 picoseconds. - Weight::from_parts(7_669_000, 3509) + // Minimum execution time: 6_687_000 picoseconds. + Weight::from_parts(6_939_000, 3509) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Mmr::Nodes` (r:1 w:0) /// Proof: `Mmr::Nodes` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) fn read_peak() -> Weight { // Proof Size summary in bytes: - // Measured: `333` + // Measured: `386` // Estimated: `3505` - // Minimum execution time: 6_137_000 picoseconds. - Weight::from_parts(6_423_000, 3505) + // Minimum execution time: 10_409_000 picoseconds. + Weight::from_parts(10_795_000, 3505) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Mmr::RootHash` (r:1 w:0) @@ -123,12 +125,12 @@ impl WeightInfo for () { /// The range of component `n` is `[2, 512]`. fn n_items_proof_is_non_canonical(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `325` + // Measured: `378` // Estimated: `1517` - // Minimum execution time: 10_687_000 picoseconds. - Weight::from_parts(14_851_626, 1517) - // Standard Error: 1_455 - .saturating_add(Weight::from_parts(961_703, 0).saturating_mul(n.into())) + // Minimum execution time: 15_459_000 picoseconds. + Weight::from_parts(21_963_366, 1517) + // Standard Error: 1_528 + .saturating_add(Weight::from_parts(984_907, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) } } diff --git a/substrate/frame/benchmarking/src/weights.rs b/substrate/frame/benchmarking/src/weights.rs index ea9ef6eb5c6d..e3c4df0bf72a 100644 --- a/substrate/frame/benchmarking/src/weights.rs +++ b/substrate/frame/benchmarking/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `frame_benchmarking` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -67,49 +67,49 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 132_000 picoseconds. - Weight::from_parts(160_546, 0) + // Minimum execution time: 157_000 picoseconds. + Weight::from_parts(207_660, 0) } /// The range of component `i` is `[0, 1000000]`. fn subtraction(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 133_000 picoseconds. - Weight::from_parts(171_395, 0) + // Minimum execution time: 162_000 picoseconds. + Weight::from_parts(211_047, 0) } /// The range of component `i` is `[0, 1000000]`. fn multiplication(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 126_000 picoseconds. - Weight::from_parts(166_417, 0) + // Minimum execution time: 158_000 picoseconds. + Weight::from_parts(221_118, 0) } /// The range of component `i` is `[0, 1000000]`. fn division(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 131_000 picoseconds. - Weight::from_parts(166_348, 0) + // Minimum execution time: 160_000 picoseconds. + Weight::from_parts(211_723, 0) } fn hashing() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 26_583_601_000 picoseconds. - Weight::from_parts(26_795_212_000, 0) + // Minimum execution time: 24_426_716_000 picoseconds. + Weight::from_parts(24_453_973_000, 0) } /// The range of component `i` is `[0, 100]`. fn sr25519_verification(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 158_000 picoseconds. - Weight::from_parts(5_277_102, 0) - // Standard Error: 6_279 - .saturating_add(Weight::from_parts(40_610_511, 0).saturating_mul(i.into())) + // Minimum execution time: 210_000 picoseconds. + Weight::from_parts(3_898_542, 0) + // Standard Error: 9_136 + .saturating_add(Weight::from_parts(40_574_115, 0).saturating_mul(i.into())) } } @@ -120,48 +120,48 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 132_000 picoseconds. - Weight::from_parts(160_546, 0) + // Minimum execution time: 157_000 picoseconds. + Weight::from_parts(207_660, 0) } /// The range of component `i` is `[0, 1000000]`. fn subtraction(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 133_000 picoseconds. - Weight::from_parts(171_395, 0) + // Minimum execution time: 162_000 picoseconds. + Weight::from_parts(211_047, 0) } /// The range of component `i` is `[0, 1000000]`. fn multiplication(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 126_000 picoseconds. - Weight::from_parts(166_417, 0) + // Minimum execution time: 158_000 picoseconds. + Weight::from_parts(221_118, 0) } /// The range of component `i` is `[0, 1000000]`. fn division(_i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 131_000 picoseconds. - Weight::from_parts(166_348, 0) + // Minimum execution time: 160_000 picoseconds. + Weight::from_parts(211_723, 0) } fn hashing() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 26_583_601_000 picoseconds. - Weight::from_parts(26_795_212_000, 0) + // Minimum execution time: 24_426_716_000 picoseconds. + Weight::from_parts(24_453_973_000, 0) } /// The range of component `i` is `[0, 100]`. fn sr25519_verification(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 158_000 picoseconds. - Weight::from_parts(5_277_102, 0) - // Standard Error: 6_279 - .saturating_add(Weight::from_parts(40_610_511, 0).saturating_mul(i.into())) + // Minimum execution time: 210_000 picoseconds. + Weight::from_parts(3_898_542, 0) + // Standard Error: 9_136 + .saturating_add(Weight::from_parts(40_574_115, 0).saturating_mul(i.into())) } } diff --git a/substrate/frame/bounties/src/weights.rs b/substrate/frame/bounties/src/weights.rs index 7230fa4a6a77..1df6d3143edb 100644 --- a/substrate/frame/bounties/src/weights.rs +++ b/substrate/frame/bounties/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_bounties` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-10-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-augrssgt-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_bounties +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_bounties -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/bounties/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -77,12 +79,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `d` is `[0, 300]`. fn propose_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `343` + // Measured: `342` // Estimated: `3593` - // Minimum execution time: 31_284_000 picoseconds. - Weight::from_parts(33_484_932, 3593) - // Standard Error: 299 - .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(d.into())) + // Minimum execution time: 27_112_000 picoseconds. + Weight::from_parts(28_480_264, 3593) + // Standard Error: 167 + .saturating_add(Weight::from_parts(755, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -94,8 +96,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `434` // Estimated: `3642` - // Minimum execution time: 17_656_000 picoseconds. - Weight::from_parts(18_501_000, 3642) + // Minimum execution time: 14_400_000 picoseconds. + Weight::from_parts(14_955_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -105,8 +107,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `454` // Estimated: `3642` - // Minimum execution time: 15_416_000 picoseconds. - Weight::from_parts(16_463_000, 3642) + // Minimum execution time: 17_380_000 picoseconds. + Weight::from_parts(18_234_000, 3642) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -116,10 +118,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn approve_bounty_with_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `454` + // Measured: `434` // Estimated: `3642` - // Minimum execution time: 21_802_000 picoseconds. - Weight::from_parts(22_884_000, 3642) + // Minimum execution time: 19_733_000 picoseconds. + Weight::from_parts(21_051_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -131,8 +133,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `630` // Estimated: `3642` - // Minimum execution time: 45_843_000 picoseconds. - Weight::from_parts(47_558_000, 3642) + // Minimum execution time: 44_620_000 picoseconds. + Weight::from_parts(45_529_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -144,8 +146,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `626` // Estimated: `3642` - // Minimum execution time: 35_720_000 picoseconds. - Weight::from_parts(37_034_000, 3642) + // Minimum execution time: 34_825_000 picoseconds. + Weight::from_parts(36_092_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -157,8 +159,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `638` // Estimated: `3642` - // Minimum execution time: 23_318_000 picoseconds. - Weight::from_parts(24_491_000, 3642) + // Minimum execution time: 22_985_000 picoseconds. + Weight::from_parts(23_657_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -170,14 +172,18 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `Bounties::BountyDescriptions` (r:0 w:1) /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn claim_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `1069` + // Measured: `1036` // Estimated: `8799` - // Minimum execution time: 127_643_000 picoseconds. - Weight::from_parts(130_844_000, 8799) + // Minimum execution time: 119_682_000 picoseconds. + Weight::from_parts(122_515_000, 8799) .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) + .saturating_add(T::DbWeight::get().writes(8_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -189,29 +195,31 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_proposed() -> Weight { // Proof Size summary in bytes: - // Measured: `683` + // Measured: `682` // Estimated: `3642` - // Minimum execution time: 49_963_000 picoseconds. - Weight::from_parts(51_484_000, 3642) + // Minimum execution time: 47_430_000 picoseconds. + Weight::from_parts(48_592_000, 3642) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:0) + /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Bounties::BountyDescriptions` (r:0 w:1) /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn close_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `985` + // Measured: `952` // Estimated: `6196` - // Minimum execution time: 89_310_000 picoseconds. - Weight::from_parts(92_223_000, 6196) + // Minimum execution time: 85_520_000 picoseconds. + Weight::from_parts(87_644_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) + .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -219,8 +227,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `490` // Estimated: `3642` - // Minimum execution time: 16_630_000 picoseconds. - Weight::from_parts(17_171_000, 3642) + // Minimum execution time: 18_145_000 picoseconds. + Weight::from_parts(18_727_000, 3642) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -233,12 +241,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `b` is `[0, 100]`. fn spend_funds(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `205 + b * (297 ±0)` + // Measured: `71 + b * (298 ±0)` // Estimated: `1887 + b * (5206 ±0)` - // Minimum execution time: 4_334_000 picoseconds. - Weight::from_parts(1_256_424, 1887) - // Standard Error: 42_406 - .saturating_add(Weight::from_parts(36_979_844, 0).saturating_mul(b.into())) + // Minimum execution time: 3_649_000 picoseconds. + Weight::from_parts(3_727_000, 1887) + // Standard Error: 8_881 + .saturating_add(Weight::from_parts(35_199_034, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -260,12 +268,12 @@ impl WeightInfo for () { /// The range of component `d` is `[0, 300]`. fn propose_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `343` + // Measured: `342` // Estimated: `3593` - // Minimum execution time: 31_284_000 picoseconds. - Weight::from_parts(33_484_932, 3593) - // Standard Error: 299 - .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(d.into())) + // Minimum execution time: 27_112_000 picoseconds. + Weight::from_parts(28_480_264, 3593) + // Standard Error: 167 + .saturating_add(Weight::from_parts(755, 0).saturating_mul(d.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -277,8 +285,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `434` // Estimated: `3642` - // Minimum execution time: 17_656_000 picoseconds. - Weight::from_parts(18_501_000, 3642) + // Minimum execution time: 14_400_000 picoseconds. + Weight::from_parts(14_955_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -288,8 +296,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `454` // Estimated: `3642` - // Minimum execution time: 15_416_000 picoseconds. - Weight::from_parts(16_463_000, 3642) + // Minimum execution time: 17_380_000 picoseconds. + Weight::from_parts(18_234_000, 3642) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -299,10 +307,10 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn approve_bounty_with_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `454` + // Measured: `434` // Estimated: `3642` - // Minimum execution time: 21_802_000 picoseconds. - Weight::from_parts(22_884_000, 3642) + // Minimum execution time: 19_733_000 picoseconds. + Weight::from_parts(21_051_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -314,8 +322,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `630` // Estimated: `3642` - // Minimum execution time: 45_843_000 picoseconds. - Weight::from_parts(47_558_000, 3642) + // Minimum execution time: 44_620_000 picoseconds. + Weight::from_parts(45_529_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -327,8 +335,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `626` // Estimated: `3642` - // Minimum execution time: 35_720_000 picoseconds. - Weight::from_parts(37_034_000, 3642) + // Minimum execution time: 34_825_000 picoseconds. + Weight::from_parts(36_092_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -340,8 +348,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `638` // Estimated: `3642` - // Minimum execution time: 23_318_000 picoseconds. - Weight::from_parts(24_491_000, 3642) + // Minimum execution time: 22_985_000 picoseconds. + Weight::from_parts(23_657_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -353,14 +361,18 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `Bounties::BountyDescriptions` (r:0 w:1) /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn claim_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `1069` + // Measured: `1036` // Estimated: `8799` - // Minimum execution time: 127_643_000 picoseconds. - Weight::from_parts(130_844_000, 8799) + // Minimum execution time: 119_682_000 picoseconds. + Weight::from_parts(122_515_000, 8799) .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(6_u64)) + .saturating_add(RocksDbWeight::get().writes(8_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -372,29 +384,31 @@ impl WeightInfo for () { /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) fn close_bounty_proposed() -> Weight { // Proof Size summary in bytes: - // Measured: `683` + // Measured: `682` // Estimated: `3642` - // Minimum execution time: 49_963_000 picoseconds. - Weight::from_parts(51_484_000, 3642) + // Minimum execution time: 47_430_000 picoseconds. + Weight::from_parts(48_592_000, 3642) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:0) + /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Bounties::BountyDescriptions` (r:0 w:1) /// Proof: `Bounties::BountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:0 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) fn close_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `985` + // Measured: `952` // Estimated: `6196` - // Minimum execution time: 89_310_000 picoseconds. - Weight::from_parts(92_223_000, 6196) + // Minimum execution time: 85_520_000 picoseconds. + Weight::from_parts(87_644_000, 6196) .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) + .saturating_add(RocksDbWeight::get().writes(6_u64)) } /// Storage: `Bounties::Bounties` (r:1 w:1) /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) @@ -402,8 +416,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `490` // Estimated: `3642` - // Minimum execution time: 16_630_000 picoseconds. - Weight::from_parts(17_171_000, 3642) + // Minimum execution time: 18_145_000 picoseconds. + Weight::from_parts(18_727_000, 3642) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -416,12 +430,12 @@ impl WeightInfo for () { /// The range of component `b` is `[0, 100]`. fn spend_funds(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `205 + b * (297 ±0)` + // Measured: `71 + b * (298 ±0)` // Estimated: `1887 + b * (5206 ±0)` - // Minimum execution time: 4_334_000 picoseconds. - Weight::from_parts(1_256_424, 1887) - // Standard Error: 42_406 - .saturating_add(Weight::from_parts(36_979_844, 0).saturating_mul(b.into())) + // Minimum execution time: 3_649_000 picoseconds. + Weight::from_parts(3_727_000, 1887) + // Standard Error: 8_881 + .saturating_add(Weight::from_parts(35_199_034, 0).saturating_mul(b.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(b.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) diff --git a/substrate/frame/child-bounties/src/weights.rs b/substrate/frame/child-bounties/src/weights.rs index 1c0583d58e02..61bb5bca7a78 100644 --- a/substrate/frame/child-bounties/src/weights.rs +++ b/substrate/frame/child-bounties/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_child_bounties` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -70,19 +70,21 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyCount` (r:1 w:1) - /// Proof: `ChildBounties::ChildBountyCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:1 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ChildBounties` (r:0 w:1) /// Proof: `ChildBounties::ChildBounties` (`max_values`: None, `max_size`: Some(145), added: 2620, mode: `MaxEncodedLen`) /// The range of component `d` is `[0, 300]`. - fn add_child_bounty(_d: u32, ) -> Weight { + fn add_child_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `745` + // Measured: `812` // Estimated: `6196` - // Minimum execution time: 65_654_000 picoseconds. - Weight::from_parts(68_255_084, 6196) + // Minimum execution time: 71_601_000 picoseconds. + Weight::from_parts(74_162_244, 6196) + // Standard Error: 328 + .saturating_add(Weight::from_parts(1_528, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -94,10 +96,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn propose_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `799` + // Measured: `842` // Estimated: `3642` - // Minimum execution time: 18_534_000 picoseconds. - Weight::from_parts(19_332_000, 3642) + // Minimum execution time: 24_835_000 picoseconds. + Weight::from_parts(26_049_000, 3642) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -109,10 +111,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn accept_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `945` + // Measured: `1048` // Estimated: `3642` - // Minimum execution time: 33_212_000 picoseconds. - Weight::from_parts(35_407_000, 3642) + // Minimum execution time: 40_409_000 picoseconds. + Weight::from_parts(41_432_000, 3642) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -124,10 +126,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn unassign_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `945` + // Measured: `1048` // Estimated: `3642` - // Minimum execution time: 35_510_000 picoseconds. - Weight::from_parts(36_345_000, 3642) + // Minimum execution time: 49_747_000 picoseconds. + Weight::from_parts(51_222_000, 3642) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -137,10 +139,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ChildBounties` (`max_values`: None, `max_size`: Some(145), added: 2620, mode: `MaxEncodedLen`) fn award_child_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `842` + // Measured: `908` // Estimated: `3642` - // Minimum execution time: 19_085_000 picoseconds. - Weight::from_parts(20_094_000, 3642) + // Minimum execution time: 26_462_000 picoseconds. + Weight::from_parts(27_166_000, 3642) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -150,14 +152,14 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn claim_child_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `682` + // Measured: `752` // Estimated: `8799` - // Minimum execution time: 110_529_000 picoseconds. - Weight::from_parts(112_660_000, 8799) + // Minimum execution time: 110_207_000 picoseconds. + Weight::from_parts(111_918_000, 8799) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -171,14 +173,14 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn close_child_bounty_added() -> Weight { // Proof Size summary in bytes: - // Measured: `1045` + // Measured: `1122` // Estimated: `6196` - // Minimum execution time: 76_363_000 picoseconds. - Weight::from_parts(77_799_000, 6196) + // Minimum execution time: 78_217_000 picoseconds. + Weight::from_parts(79_799_000, 6196) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -192,14 +194,14 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn close_child_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `1232` + // Measured: `1343` // Estimated: `8799` - // Minimum execution time: 89_977_000 picoseconds. - Weight::from_parts(92_978_000, 8799) + // Minimum execution time: 93_624_000 picoseconds. + Weight::from_parts(96_697_000, 8799) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -213,19 +215,21 @@ impl WeightInfo for () { /// Proof: `Bounties::Bounties` (`max_values`: None, `max_size`: Some(177), added: 2652, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyCount` (r:1 w:1) - /// Proof: `ChildBounties::ChildBountyCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ParentTotalChildBounties` (r:1 w:1) + /// Proof: `ChildBounties::ParentTotalChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ChildBounties` (r:0 w:1) /// Proof: `ChildBounties::ChildBounties` (`max_values`: None, `max_size`: Some(145), added: 2620, mode: `MaxEncodedLen`) /// The range of component `d` is `[0, 300]`. - fn add_child_bounty(_d: u32, ) -> Weight { + fn add_child_bounty(d: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `745` + // Measured: `812` // Estimated: `6196` - // Minimum execution time: 65_654_000 picoseconds. - Weight::from_parts(68_255_084, 6196) + // Minimum execution time: 71_601_000 picoseconds. + Weight::from_parts(74_162_244, 6196) + // Standard Error: 328 + .saturating_add(Weight::from_parts(1_528, 0).saturating_mul(d.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -237,10 +241,10 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) fn propose_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `799` + // Measured: `842` // Estimated: `3642` - // Minimum execution time: 18_534_000 picoseconds. - Weight::from_parts(19_332_000, 3642) + // Minimum execution time: 24_835_000 picoseconds. + Weight::from_parts(26_049_000, 3642) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -252,10 +256,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn accept_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `945` + // Measured: `1048` // Estimated: `3642` - // Minimum execution time: 33_212_000 picoseconds. - Weight::from_parts(35_407_000, 3642) + // Minimum execution time: 40_409_000 picoseconds. + Weight::from_parts(41_432_000, 3642) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -267,10 +271,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn unassign_curator() -> Weight { // Proof Size summary in bytes: - // Measured: `945` + // Measured: `1048` // Estimated: `3642` - // Minimum execution time: 35_510_000 picoseconds. - Weight::from_parts(36_345_000, 3642) + // Minimum execution time: 49_747_000 picoseconds. + Weight::from_parts(51_222_000, 3642) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -280,10 +284,10 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ChildBounties` (`max_values`: None, `max_size`: Some(145), added: 2620, mode: `MaxEncodedLen`) fn award_child_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `842` + // Measured: `908` // Estimated: `3642` - // Minimum execution time: 19_085_000 picoseconds. - Weight::from_parts(20_094_000, 3642) + // Minimum execution time: 26_462_000 picoseconds. + Weight::from_parts(27_166_000, 3642) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -293,14 +297,14 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn claim_child_bounty() -> Weight { // Proof Size summary in bytes: - // Measured: `682` + // Measured: `752` // Estimated: `8799` - // Minimum execution time: 110_529_000 picoseconds. - Weight::from_parts(112_660_000, 8799) + // Minimum execution time: 110_207_000 picoseconds. + Weight::from_parts(111_918_000, 8799) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -314,14 +318,14 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:2 w:2) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn close_child_bounty_added() -> Weight { // Proof Size summary in bytes: - // Measured: `1045` + // Measured: `1122` // Estimated: `6196` - // Minimum execution time: 76_363_000 picoseconds. - Weight::from_parts(77_799_000, 6196) + // Minimum execution time: 78_217_000 picoseconds. + Weight::from_parts(79_799_000, 6196) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -335,14 +339,14 @@ impl WeightInfo for () { /// Proof: `ChildBounties::ChildrenCuratorFees` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) /// Storage: `ChildBounties::ParentChildBounties` (r:1 w:1) /// Proof: `ChildBounties::ParentChildBounties` (`max_values`: None, `max_size`: Some(16), added: 2491, mode: `MaxEncodedLen`) - /// Storage: `ChildBounties::ChildBountyDescriptions` (r:0 w:1) - /// Proof: `ChildBounties::ChildBountyDescriptions` (`max_values`: None, `max_size`: Some(314), added: 2789, mode: `MaxEncodedLen`) + /// Storage: `ChildBounties::ChildBountyDescriptionsV1` (r:0 w:1) + /// Proof: `ChildBounties::ChildBountyDescriptionsV1` (`max_values`: None, `max_size`: Some(326), added: 2801, mode: `MaxEncodedLen`) fn close_child_bounty_active() -> Weight { // Proof Size summary in bytes: - // Measured: `1232` + // Measured: `1343` // Estimated: `8799` - // Minimum execution time: 89_977_000 picoseconds. - Weight::from_parts(92_978_000, 8799) + // Minimum execution time: 93_624_000 picoseconds. + Weight::from_parts(96_697_000, 8799) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } diff --git a/substrate/frame/collective/src/weights.rs b/substrate/frame/collective/src/weights.rs index 1a7485b4ab7b..4d47d2fe9ead 100644 --- a/substrate/frame/collective/src/weights.rs +++ b/substrate/frame/collective/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_collective` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-09-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-svzsllib-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_collective +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_collective -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/collective/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -80,13 +82,13 @@ impl WeightInfo for SubstrateWeight { fn set_members(m: u32, _n: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + m * (3232 ±0) + p * (3190 ±0)` - // Estimated: `15894 + m * (1967 ±23) + p * (4332 ±23)` - // Minimum execution time: 16_699_000 picoseconds. - Weight::from_parts(17_015_000, 15894) - // Standard Error: 63_844 - .saturating_add(Weight::from_parts(4_593_256, 0).saturating_mul(m.into())) - // Standard Error: 63_844 - .saturating_add(Weight::from_parts(8_935_845, 0).saturating_mul(p.into())) + // Estimated: `15927 + m * (1967 ±24) + p * (4332 ±24)` + // Minimum execution time: 16_292_000 picoseconds. + Weight::from_parts(16_707_000, 15927) + // Standard Error: 65_976 + .saturating_add(Weight::from_parts(4_766_715, 0).saturating_mul(m.into())) + // Standard Error: 65_976 + .saturating_add(Weight::from_parts(9_280_562, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -104,14 +106,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `m` is `[1, 100]`. fn execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `380 + m * (32 ±0)` + // Measured: `413 + m * (32 ±0)` // Estimated: `3997 + m * (32 ±0)` - // Minimum execution time: 22_010_000 picoseconds. - Weight::from_parts(21_392_812, 3997) - // Standard Error: 34 - .saturating_add(Weight::from_parts(1_533, 0).saturating_mul(b.into())) - // Standard Error: 354 - .saturating_add(Weight::from_parts(15_866, 0).saturating_mul(m.into())) + // Minimum execution time: 24_281_000 picoseconds. + Weight::from_parts(23_568_200, 3997) + // Standard Error: 47 + .saturating_add(Weight::from_parts(1_681, 0).saturating_mul(b.into())) + // Standard Error: 492 + .saturating_add(Weight::from_parts(15_851, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } @@ -127,14 +129,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `m` is `[1, 100]`. fn propose_execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `380 + m * (32 ±0)` + // Measured: `413 + m * (32 ±0)` // Estimated: `3997 + m * (32 ±0)` - // Minimum execution time: 24_250_000 picoseconds. - Weight::from_parts(23_545_893, 3997) - // Standard Error: 40 - .saturating_add(Weight::from_parts(1_646, 0).saturating_mul(b.into())) - // Standard Error: 421 - .saturating_add(Weight::from_parts(26_248, 0).saturating_mul(m.into())) + // Minimum execution time: 26_424_000 picoseconds. + Weight::from_parts(26_130_784, 3997) + // Standard Error: 56 + .saturating_add(Weight::from_parts(1_577, 0).saturating_mul(b.into())) + // Standard Error: 585 + .saturating_add(Weight::from_parts(20_984, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } @@ -145,7 +147,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Council::Proposals` (r:1 w:1) /// Proof: `Council::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Council::ProposalCount` (r:1 w:1) /// Proof: `Council::ProposalCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Council::Voting` (r:0 w:1) @@ -157,16 +159,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `618 + m * (32 ±0) + p * (36 ±0)` - // Estimated: `3991 + m * (33 ±0) + p * (36 ±0)` - // Minimum execution time: 46_538_000 picoseconds. - Weight::from_parts(63_900_448, 3991) - // Standard Error: 350 - .saturating_add(Weight::from_parts(2_827, 0).saturating_mul(b.into())) - // Standard Error: 3_658 - .saturating_add(Weight::from_parts(53_340, 0).saturating_mul(m.into())) - // Standard Error: 3_611 - .saturating_add(Weight::from_parts(213_719, 0).saturating_mul(p.into())) + // Measured: `651 + m * (32 ±0) + p * (36 ±0)` + // Estimated: `4024 + m * (33 ±0) + p * (36 ±0)` + // Minimum execution time: 47_547_000 picoseconds. + Weight::from_parts(65_808_006, 4024) + // Standard Error: 330 + .saturating_add(Weight::from_parts(4_211, 0).saturating_mul(b.into())) + // Standard Error: 3_443 + .saturating_add(Weight::from_parts(43_705, 0).saturating_mul(m.into())) + // Standard Error: 3_399 + .saturating_add(Weight::from_parts(235_928, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) .saturating_add(Weight::from_parts(0, 33).saturating_mul(m.into())) @@ -179,12 +181,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `m` is `[5, 100]`. fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1011 + m * (64 ±0)` - // Estimated: `4475 + m * (64 ±0)` - // Minimum execution time: 28_413_000 picoseconds. - Weight::from_parts(28_981_832, 4475) - // Standard Error: 665 - .saturating_add(Weight::from_parts(43_005, 0).saturating_mul(m.into())) + // Measured: `1044 + m * (64 ±0)` + // Estimated: `4508 + m * (64 ±0)` + // Minimum execution time: 32_388_000 picoseconds. + Weight::from_parts(34_955_946, 4508) + // Standard Error: 2_253 + .saturating_add(Weight::from_parts(34_184, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -201,14 +203,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `600 + m * (64 ±0) + p * (36 ±0)` - // Estimated: `4042 + m * (65 ±0) + p * (36 ±0)` - // Minimum execution time: 27_725_000 picoseconds. - Weight::from_parts(30_174_093, 4042) - // Standard Error: 1_458 - .saturating_add(Weight::from_parts(41_100, 0).saturating_mul(m.into())) - // Standard Error: 1_422 - .saturating_add(Weight::from_parts(177_303, 0).saturating_mul(p.into())) + // Measured: `633 + m * (64 ±0) + p * (36 ±0)` + // Estimated: `4075 + m * (65 ±0) + p * (36 ±0)` + // Minimum execution time: 29_663_000 picoseconds. + Weight::from_parts(33_355_561, 4075) + // Standard Error: 2_045 + .saturating_add(Weight::from_parts(28_190, 0).saturating_mul(m.into())) + // Standard Error: 1_994 + .saturating_add(Weight::from_parts(185_801, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 65).saturating_mul(m.into())) @@ -231,16 +233,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1047 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` - // Estimated: `4360 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` - // Minimum execution time: 48_882_000 picoseconds. - Weight::from_parts(51_938_773, 4360) - // Standard Error: 208 - .saturating_add(Weight::from_parts(3_559, 0).saturating_mul(b.into())) - // Standard Error: 2_201 - .saturating_add(Weight::from_parts(38_678, 0).saturating_mul(m.into())) - // Standard Error: 2_145 - .saturating_add(Weight::from_parts(214_061, 0).saturating_mul(p.into())) + // Measured: `1080 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `4393 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 46_764_000 picoseconds. + Weight::from_parts(49_084_241, 4393) + // Standard Error: 284 + .saturating_add(Weight::from_parts(3_771, 0).saturating_mul(b.into())) + // Standard Error: 3_003 + .saturating_add(Weight::from_parts(33_189, 0).saturating_mul(m.into())) + // Standard Error: 2_927 + .saturating_add(Weight::from_parts(245_387, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) @@ -261,14 +263,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `620 + m * (64 ±0) + p * (36 ±0)` - // Estimated: `4062 + m * (65 ±0) + p * (36 ±0)` - // Minimum execution time: 30_613_000 picoseconds. - Weight::from_parts(36_174_190, 4062) - // Standard Error: 1_899 - .saturating_add(Weight::from_parts(46_781, 0).saturating_mul(m.into())) - // Standard Error: 1_851 - .saturating_add(Weight::from_parts(185_875, 0).saturating_mul(p.into())) + // Measured: `653 + m * (64 ±0) + p * (36 ±0)` + // Estimated: `4095 + m * (65 ±0) + p * (36 ±0)` + // Minimum execution time: 32_188_000 picoseconds. + Weight::from_parts(35_015_624, 4095) + // Standard Error: 2_283 + .saturating_add(Weight::from_parts(39_633, 0).saturating_mul(m.into())) + // Standard Error: 2_226 + .saturating_add(Weight::from_parts(191_898, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 65).saturating_mul(m.into())) @@ -293,16 +295,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1067 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` - // Estimated: `4380 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` - // Minimum execution time: 51_253_000 picoseconds. - Weight::from_parts(56_399_941, 4380) - // Standard Error: 218 - .saturating_add(Weight::from_parts(2_920, 0).saturating_mul(b.into())) - // Standard Error: 2_310 - .saturating_add(Weight::from_parts(30_473, 0).saturating_mul(m.into())) - // Standard Error: 2_252 - .saturating_add(Weight::from_parts(208_468, 0).saturating_mul(p.into())) + // Measured: `1100 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `4413 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 49_281_000 picoseconds. + Weight::from_parts(53_838_013, 4413) + // Standard Error: 317 + .saturating_add(Weight::from_parts(4_011, 0).saturating_mul(b.into())) + // Standard Error: 3_353 + .saturating_add(Weight::from_parts(19_609, 0).saturating_mul(m.into())) + // Standard Error: 3_269 + .saturating_add(Weight::from_parts(236_964, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) @@ -318,12 +320,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn disapprove_proposal(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `392 + p * (32 ±0)` - // Estimated: `1877 + p * (32 ±0)` - // Minimum execution time: 14_646_000 picoseconds. - Weight::from_parts(17_305_497, 1877) - // Standard Error: 1_331 - .saturating_add(Weight::from_parts(156_038, 0).saturating_mul(p.into())) + // Measured: `425 + p * (32 ±0)` + // Estimated: `1910 + p * (32 ±0)` + // Minimum execution time: 14_767_000 picoseconds. + Weight::from_parts(16_823_844, 1910) + // Standard Error: 1_424 + .saturating_add(Weight::from_parts(170_583, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(p.into())) @@ -335,7 +337,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Council::Proposals` (r:1 w:1) /// Proof: `Council::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Council::Voting` (r:0 w:1) @@ -344,19 +346,19 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[1, 100]`. fn kill(d: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1863 + d * (212 ±0) + p * (41 ±0)` - // Estimated: `5172 + d * (1901 ±14) + p * (43 ±0)` - // Minimum execution time: 22_164_000 picoseconds. - Weight::from_parts(24_932_256, 5172) - // Standard Error: 404_014 - .saturating_add(Weight::from_parts(33_833_807, 0).saturating_mul(d.into())) - // Standard Error: 6_256 - .saturating_add(Weight::from_parts(281_910, 0).saturating_mul(p.into())) + // Measured: `1896 + d * (212 ±0) + p * (41 ±0)` + // Estimated: `5205 + d * (1910 ±14) + p * (43 ±0)` + // Minimum execution time: 24_956_000 picoseconds. + Weight::from_parts(25_382_488, 5205) + // Standard Error: 374_961 + .saturating_add(Weight::from_parts(31_856_043, 0).saturating_mul(d.into())) + // Standard Error: 5_806 + .saturating_add(Weight::from_parts(288_259, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(d.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(d.into()))) - .saturating_add(Weight::from_parts(0, 1901).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(0, 1910).saturating_mul(d.into())) .saturating_add(Weight::from_parts(0, 43).saturating_mul(p.into())) } /// Storage: `Council::ProposalOf` (r:1 w:0) @@ -366,13 +368,13 @@ impl WeightInfo for SubstrateWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn release_proposal_cost() -> Weight { // Proof Size summary in bytes: - // Measured: `1964` - // Estimated: `5429` - // Minimum execution time: 69_220_000 picoseconds. - Weight::from_parts(70_215_000, 5429) + // Measured: `1997` + // Estimated: `5462` + // Minimum execution time: 67_153_000 picoseconds. + Weight::from_parts(70_174_000, 5462) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -394,13 +396,13 @@ impl WeightInfo for () { fn set_members(m: u32, _n: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + m * (3232 ±0) + p * (3190 ±0)` - // Estimated: `15894 + m * (1967 ±23) + p * (4332 ±23)` - // Minimum execution time: 16_699_000 picoseconds. - Weight::from_parts(17_015_000, 15894) - // Standard Error: 63_844 - .saturating_add(Weight::from_parts(4_593_256, 0).saturating_mul(m.into())) - // Standard Error: 63_844 - .saturating_add(Weight::from_parts(8_935_845, 0).saturating_mul(p.into())) + // Estimated: `15927 + m * (1967 ±24) + p * (4332 ±24)` + // Minimum execution time: 16_292_000 picoseconds. + Weight::from_parts(16_707_000, 15927) + // Standard Error: 65_976 + .saturating_add(Weight::from_parts(4_766_715, 0).saturating_mul(m.into())) + // Standard Error: 65_976 + .saturating_add(Weight::from_parts(9_280_562, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(p.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -418,14 +420,14 @@ impl WeightInfo for () { /// The range of component `m` is `[1, 100]`. fn execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `380 + m * (32 ±0)` + // Measured: `413 + m * (32 ±0)` // Estimated: `3997 + m * (32 ±0)` - // Minimum execution time: 22_010_000 picoseconds. - Weight::from_parts(21_392_812, 3997) - // Standard Error: 34 - .saturating_add(Weight::from_parts(1_533, 0).saturating_mul(b.into())) - // Standard Error: 354 - .saturating_add(Weight::from_parts(15_866, 0).saturating_mul(m.into())) + // Minimum execution time: 24_281_000 picoseconds. + Weight::from_parts(23_568_200, 3997) + // Standard Error: 47 + .saturating_add(Weight::from_parts(1_681, 0).saturating_mul(b.into())) + // Standard Error: 492 + .saturating_add(Weight::from_parts(15_851, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } @@ -441,14 +443,14 @@ impl WeightInfo for () { /// The range of component `m` is `[1, 100]`. fn propose_execute(b: u32, m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `380 + m * (32 ±0)` + // Measured: `413 + m * (32 ±0)` // Estimated: `3997 + m * (32 ±0)` - // Minimum execution time: 24_250_000 picoseconds. - Weight::from_parts(23_545_893, 3997) - // Standard Error: 40 - .saturating_add(Weight::from_parts(1_646, 0).saturating_mul(b.into())) - // Standard Error: 421 - .saturating_add(Weight::from_parts(26_248, 0).saturating_mul(m.into())) + // Minimum execution time: 26_424_000 picoseconds. + Weight::from_parts(26_130_784, 3997) + // Standard Error: 56 + .saturating_add(Weight::from_parts(1_577, 0).saturating_mul(b.into())) + // Standard Error: 585 + .saturating_add(Weight::from_parts(20_984, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) } @@ -459,7 +461,7 @@ impl WeightInfo for () { /// Storage: `Council::Proposals` (r:1 w:1) /// Proof: `Council::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Council::ProposalCount` (r:1 w:1) /// Proof: `Council::ProposalCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Council::Voting` (r:0 w:1) @@ -471,16 +473,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `618 + m * (32 ±0) + p * (36 ±0)` - // Estimated: `3991 + m * (33 ±0) + p * (36 ±0)` - // Minimum execution time: 46_538_000 picoseconds. - Weight::from_parts(63_900_448, 3991) - // Standard Error: 350 - .saturating_add(Weight::from_parts(2_827, 0).saturating_mul(b.into())) - // Standard Error: 3_658 - .saturating_add(Weight::from_parts(53_340, 0).saturating_mul(m.into())) - // Standard Error: 3_611 - .saturating_add(Weight::from_parts(213_719, 0).saturating_mul(p.into())) + // Measured: `651 + m * (32 ±0) + p * (36 ±0)` + // Estimated: `4024 + m * (33 ±0) + p * (36 ±0)` + // Minimum execution time: 47_547_000 picoseconds. + Weight::from_parts(65_808_006, 4024) + // Standard Error: 330 + .saturating_add(Weight::from_parts(4_211, 0).saturating_mul(b.into())) + // Standard Error: 3_443 + .saturating_add(Weight::from_parts(43_705, 0).saturating_mul(m.into())) + // Standard Error: 3_399 + .saturating_add(Weight::from_parts(235_928, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) .saturating_add(Weight::from_parts(0, 33).saturating_mul(m.into())) @@ -493,12 +495,12 @@ impl WeightInfo for () { /// The range of component `m` is `[5, 100]`. fn vote(m: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1011 + m * (64 ±0)` - // Estimated: `4475 + m * (64 ±0)` - // Minimum execution time: 28_413_000 picoseconds. - Weight::from_parts(28_981_832, 4475) - // Standard Error: 665 - .saturating_add(Weight::from_parts(43_005, 0).saturating_mul(m.into())) + // Measured: `1044 + m * (64 ±0)` + // Estimated: `4508 + m * (64 ±0)` + // Minimum execution time: 32_388_000 picoseconds. + Weight::from_parts(34_955_946, 4508) + // Standard Error: 2_253 + .saturating_add(Weight::from_parts(34_184, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -515,14 +517,14 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_early_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `600 + m * (64 ±0) + p * (36 ±0)` - // Estimated: `4042 + m * (65 ±0) + p * (36 ±0)` - // Minimum execution time: 27_725_000 picoseconds. - Weight::from_parts(30_174_093, 4042) - // Standard Error: 1_458 - .saturating_add(Weight::from_parts(41_100, 0).saturating_mul(m.into())) - // Standard Error: 1_422 - .saturating_add(Weight::from_parts(177_303, 0).saturating_mul(p.into())) + // Measured: `633 + m * (64 ±0) + p * (36 ±0)` + // Estimated: `4075 + m * (65 ±0) + p * (36 ±0)` + // Minimum execution time: 29_663_000 picoseconds. + Weight::from_parts(33_355_561, 4075) + // Standard Error: 2_045 + .saturating_add(Weight::from_parts(28_190, 0).saturating_mul(m.into())) + // Standard Error: 1_994 + .saturating_add(Weight::from_parts(185_801, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 65).saturating_mul(m.into())) @@ -545,16 +547,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1047 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` - // Estimated: `4360 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` - // Minimum execution time: 48_882_000 picoseconds. - Weight::from_parts(51_938_773, 4360) - // Standard Error: 208 - .saturating_add(Weight::from_parts(3_559, 0).saturating_mul(b.into())) - // Standard Error: 2_201 - .saturating_add(Weight::from_parts(38_678, 0).saturating_mul(m.into())) - // Standard Error: 2_145 - .saturating_add(Weight::from_parts(214_061, 0).saturating_mul(p.into())) + // Measured: `1080 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `4393 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 46_764_000 picoseconds. + Weight::from_parts(49_084_241, 4393) + // Standard Error: 284 + .saturating_add(Weight::from_parts(3_771, 0).saturating_mul(b.into())) + // Standard Error: 3_003 + .saturating_add(Weight::from_parts(33_189, 0).saturating_mul(m.into())) + // Standard Error: 2_927 + .saturating_add(Weight::from_parts(245_387, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) @@ -575,14 +577,14 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_disapproved(m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `620 + m * (64 ±0) + p * (36 ±0)` - // Estimated: `4062 + m * (65 ±0) + p * (36 ±0)` - // Minimum execution time: 30_613_000 picoseconds. - Weight::from_parts(36_174_190, 4062) - // Standard Error: 1_899 - .saturating_add(Weight::from_parts(46_781, 0).saturating_mul(m.into())) - // Standard Error: 1_851 - .saturating_add(Weight::from_parts(185_875, 0).saturating_mul(p.into())) + // Measured: `653 + m * (64 ±0) + p * (36 ±0)` + // Estimated: `4095 + m * (65 ±0) + p * (36 ±0)` + // Minimum execution time: 32_188_000 picoseconds. + Weight::from_parts(35_015_624, 4095) + // Standard Error: 2_283 + .saturating_add(Weight::from_parts(39_633, 0).saturating_mul(m.into())) + // Standard Error: 2_226 + .saturating_add(Weight::from_parts(191_898, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 65).saturating_mul(m.into())) @@ -607,16 +609,16 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1067 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` - // Estimated: `4380 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` - // Minimum execution time: 51_253_000 picoseconds. - Weight::from_parts(56_399_941, 4380) - // Standard Error: 218 - .saturating_add(Weight::from_parts(2_920, 0).saturating_mul(b.into())) - // Standard Error: 2_310 - .saturating_add(Weight::from_parts(30_473, 0).saturating_mul(m.into())) - // Standard Error: 2_252 - .saturating_add(Weight::from_parts(208_468, 0).saturating_mul(p.into())) + // Measured: `1100 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `4413 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 49_281_000 picoseconds. + Weight::from_parts(53_838_013, 4413) + // Standard Error: 317 + .saturating_add(Weight::from_parts(4_011, 0).saturating_mul(b.into())) + // Standard Error: 3_353 + .saturating_add(Weight::from_parts(19_609, 0).saturating_mul(m.into())) + // Standard Error: 3_269 + .saturating_add(Weight::from_parts(236_964, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) @@ -632,12 +634,12 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn disapprove_proposal(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `392 + p * (32 ±0)` - // Estimated: `1877 + p * (32 ±0)` - // Minimum execution time: 14_646_000 picoseconds. - Weight::from_parts(17_305_497, 1877) - // Standard Error: 1_331 - .saturating_add(Weight::from_parts(156_038, 0).saturating_mul(p.into())) + // Measured: `425 + p * (32 ±0)` + // Estimated: `1910 + p * (32 ±0)` + // Minimum execution time: 14_767_000 picoseconds. + Weight::from_parts(16_823_844, 1910) + // Standard Error: 1_424 + .saturating_add(Weight::from_parts(170_583, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(p.into())) @@ -649,7 +651,7 @@ impl WeightInfo for () { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Council::Proposals` (r:1 w:1) /// Proof: `Council::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `Council::Voting` (r:0 w:1) @@ -658,19 +660,19 @@ impl WeightInfo for () { /// The range of component `p` is `[1, 100]`. fn kill(d: u32, p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1863 + d * (212 ±0) + p * (41 ±0)` - // Estimated: `5172 + d * (1901 ±14) + p * (43 ±0)` - // Minimum execution time: 22_164_000 picoseconds. - Weight::from_parts(24_932_256, 5172) - // Standard Error: 404_014 - .saturating_add(Weight::from_parts(33_833_807, 0).saturating_mul(d.into())) - // Standard Error: 6_256 - .saturating_add(Weight::from_parts(281_910, 0).saturating_mul(p.into())) + // Measured: `1896 + d * (212 ±0) + p * (41 ±0)` + // Estimated: `5205 + d * (1910 ±14) + p * (43 ±0)` + // Minimum execution time: 24_956_000 picoseconds. + Weight::from_parts(25_382_488, 5205) + // Standard Error: 374_961 + .saturating_add(Weight::from_parts(31_856_043, 0).saturating_mul(d.into())) + // Standard Error: 5_806 + .saturating_add(Weight::from_parts(288_259, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((2_u64).saturating_mul(d.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(d.into()))) - .saturating_add(Weight::from_parts(0, 1901).saturating_mul(d.into())) + .saturating_add(Weight::from_parts(0, 1910).saturating_mul(d.into())) .saturating_add(Weight::from_parts(0, 43).saturating_mul(p.into())) } /// Storage: `Council::ProposalOf` (r:1 w:0) @@ -680,13 +682,13 @@ impl WeightInfo for () { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(337), added: 2812, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn release_proposal_cost() -> Weight { // Proof Size summary in bytes: - // Measured: `1964` - // Estimated: `5429` - // Minimum execution time: 69_220_000 picoseconds. - Weight::from_parts(70_215_000, 5429) + // Measured: `1997` + // Estimated: `5462` + // Minimum execution time: 67_153_000 picoseconds. + Weight::from_parts(70_174_000, 5462) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } diff --git a/substrate/frame/contracts/src/weights.rs b/substrate/frame/contracts/src/weights.rs index 25b36fc404fe..f6c56468e5de 100644 --- a/substrate/frame/contracts/src/weights.rs +++ b/substrate/frame/contracts/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_contracts` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-07-17, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-yaoqqom-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_contracts +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_contracts -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/contracts/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -141,8 +143,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 1_915_000 picoseconds. - Weight::from_parts(1_986_000, 1627) + // Minimum execution time: 2_809_000 picoseconds. + Weight::from_parts(2_956_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -152,10 +154,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `452 + k * (69 ±0)` // Estimated: `442 + k * (70 ±0)` - // Minimum execution time: 11_103_000 picoseconds. - Weight::from_parts(11_326_000, 442) - // Standard Error: 2_291 - .saturating_add(Weight::from_parts(1_196_329, 0).saturating_mul(k.into())) + // Minimum execution time: 17_559_000 picoseconds. + Weight::from_parts(17_850_000, 442) + // Standard Error: 2_722 + .saturating_add(Weight::from_parts(1_376_892, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -169,10 +171,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 7_783_000 picoseconds. - Weight::from_parts(4_462_075, 6149) + // Minimum execution time: 8_830_000 picoseconds. + Weight::from_parts(6_649_003, 6149) // Standard Error: 5 - .saturating_add(Weight::from_parts(1_634, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_676, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -185,8 +187,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 15_971_000 picoseconds. - Weight::from_parts(16_730_000, 6450) + // Minimum execution time: 21_927_000 picoseconds. + Weight::from_parts(22_655_000, 6450) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -199,10 +201,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 3_149_000 picoseconds. - Weight::from_parts(3_264_000, 3635) - // Standard Error: 559 - .saturating_add(Weight::from_parts(1_111_209, 0).saturating_mul(k.into())) + // Minimum execution time: 4_465_000 picoseconds. + Weight::from_parts(4_774_000, 3635) + // Standard Error: 867 + .saturating_add(Weight::from_parts(1_071_462, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -221,10 +223,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 15_072_000 picoseconds. - Weight::from_parts(15_721_891, 6263) + // Minimum execution time: 21_627_000 picoseconds. + Weight::from_parts(21_491_424, 6263) // Standard Error: 2 - .saturating_add(Weight::from_parts(428, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(480, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -235,8 +237,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `440` // Estimated: `6380` - // Minimum execution time: 12_047_000 picoseconds. - Weight::from_parts(12_500_000, 6380) + // Minimum execution time: 17_262_000 picoseconds. + Weight::from_parts(17_785_000, 6380) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -245,13 +247,13 @@ impl WeightInfo for SubstrateWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) fn v14_migration_step() -> Weight { // Proof Size summary in bytes: // Measured: `352` // Estimated: `6292` - // Minimum execution time: 47_488_000 picoseconds. - Weight::from_parts(48_482_000, 6292) + // Minimum execution time: 52_303_000 picoseconds. + Weight::from_parts(53_902_000, 6292) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -263,8 +265,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `594` // Estimated: `6534` - // Minimum execution time: 52_801_000 picoseconds. - Weight::from_parts(54_230_000, 6534) + // Minimum execution time: 58_585_000 picoseconds. + Weight::from_parts(60_478_000, 6534) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -274,8 +276,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `409` // Estimated: `6349` - // Minimum execution time: 11_618_000 picoseconds. - Weight::from_parts(12_068_000, 6349) + // Minimum execution time: 16_673_000 picoseconds. + Weight::from_parts(17_325_000, 6349) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -285,8 +287,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_131_000 picoseconds. - Weight::from_parts(2_255_000, 1627) + // Minimum execution time: 3_073_000 picoseconds. + Weight::from_parts(3_262_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -298,8 +300,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 10_773_000 picoseconds. - Weight::from_parts(11_118_000, 3631) + // Minimum execution time: 11_687_000 picoseconds. + Weight::from_parts(12_178_000, 3631) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -309,8 +311,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_371_000 picoseconds. - Weight::from_parts(4_624_000, 3607) + // Minimum execution time: 4_553_000 picoseconds. + Weight::from_parts(4_826_000, 3607) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -321,8 +323,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 5_612_000 picoseconds. - Weight::from_parts(5_838_000, 3632) + // Minimum execution time: 6_794_000 picoseconds. + Weight::from_parts(6_959_000, 3632) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -333,8 +335,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 5_487_000 picoseconds. - Weight::from_parts(5_693_000, 3607) + // Minimum execution time: 6_120_000 picoseconds. + Weight::from_parts(6_420_000, 3607) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -354,11 +356,11 @@ impl WeightInfo for SubstrateWeight { fn call_with_code_per_byte(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `800 + c * (1 ±0)` - // Estimated: `4266 + c * (1 ±0)` - // Minimum execution time: 247_545_000 picoseconds. - Weight::from_parts(268_016_699, 4266) - // Standard Error: 4 - .saturating_add(Weight::from_parts(700, 0).saturating_mul(c.into())) + // Estimated: `4268 + c * (1 ±0)` + // Minimum execution time: 266_424_000 picoseconds. + Weight::from_parts(283_325_502, 4268) + // Standard Error: 12 + .saturating_add(Weight::from_parts(950, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -368,7 +370,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:2 w:2) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::Nonce` (r:1 w:1) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) @@ -385,15 +387,15 @@ impl WeightInfo for SubstrateWeight { fn instantiate_with_code(c: u32, i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `323` - // Estimated: `6262` - // Minimum execution time: 4_396_772_000 picoseconds. - Weight::from_parts(235_107_907, 6262) - // Standard Error: 185 - .saturating_add(Weight::from_parts(53_843, 0).saturating_mul(c.into())) - // Standard Error: 22 - .saturating_add(Weight::from_parts(2_143, 0).saturating_mul(i.into())) - // Standard Error: 22 - .saturating_add(Weight::from_parts(2_210, 0).saturating_mul(s.into())) + // Estimated: `6267` + // Minimum execution time: 4_371_315_000 picoseconds. + Weight::from_parts(4_739_462_000, 6267) + // Standard Error: 329 + .saturating_add(Weight::from_parts(38_518, 0).saturating_mul(c.into())) + // Standard Error: 39 + .saturating_add(Weight::from_parts(605, 0).saturating_mul(i.into())) + // Standard Error: 39 + .saturating_add(Weight::from_parts(561, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -412,19 +414,19 @@ impl WeightInfo for SubstrateWeight { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// The range of component `i` is `[0, 1048576]`. /// The range of component `s` is `[0, 1048576]`. fn instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `560` - // Estimated: `4017` - // Minimum execution time: 2_240_868_000 picoseconds. - Weight::from_parts(2_273_668_000, 4017) - // Standard Error: 32 - .saturating_add(Weight::from_parts(934, 0).saturating_mul(i.into())) - // Standard Error: 32 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + // Estimated: `4016` + // Minimum execution time: 2_304_531_000 picoseconds. + Weight::from_parts(2_352_810_000, 4016) + // Standard Error: 35 + .saturating_add(Weight::from_parts(1_004, 0).saturating_mul(i.into())) + // Standard Error: 35 + .saturating_add(Weight::from_parts(936, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -444,8 +446,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `826` // Estimated: `4291` - // Minimum execution time: 165_067_000 picoseconds. - Weight::from_parts(168_582_000, 4291) + // Minimum execution time: 183_658_000 picoseconds. + Weight::from_parts(189_507_000, 4291) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -454,7 +456,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) /// The range of component `c` is `[0, 125952]`. @@ -462,10 +464,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 229_454_000 picoseconds. - Weight::from_parts(251_495_551, 3607) - // Standard Error: 71 - .saturating_add(Weight::from_parts(51_428, 0).saturating_mul(c.into())) + // Minimum execution time: 253_006_000 picoseconds. + Weight::from_parts(269_271_744, 3607) + // Standard Error: 79 + .saturating_add(Weight::from_parts(49_970, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -474,7 +476,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) /// The range of component `c` is `[0, 125952]`. @@ -482,10 +484,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 240_390_000 picoseconds. - Weight::from_parts(273_854_266, 3607) - // Standard Error: 243 - .saturating_add(Weight::from_parts(51_836, 0).saturating_mul(c.into())) + // Minimum execution time: 247_567_000 picoseconds. + Weight::from_parts(271_875_922, 3607) + // Standard Error: 78 + .saturating_add(Weight::from_parts(50_117, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -494,15 +496,15 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) fn remove_code() -> Weight { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 39_374_000 picoseconds. - Weight::from_parts(40_247_000, 3780) + // Minimum execution time: 48_151_000 picoseconds. + Weight::from_parts(49_407_000, 3780) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -516,8 +518,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 24_473_000 picoseconds. - Weight::from_parts(25_890_000, 6492) + // Minimum execution time: 30_173_000 picoseconds. + Weight::from_parts(30_941_000, 6492) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -526,17 +528,17 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_528_000 picoseconds. - Weight::from_parts(9_301_010, 0) - // Standard Error: 98 - .saturating_add(Weight::from_parts(53_173, 0).saturating_mul(r.into())) + // Minimum execution time: 8_350_000 picoseconds. + Weight::from_parts(9_238_867, 0) + // Standard Error: 139 + .saturating_add(Weight::from_parts(52_355, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 643_000 picoseconds. - Weight::from_parts(678_000, 0) + // Minimum execution time: 757_000 picoseconds. + Weight::from_parts(827_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -544,8 +546,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `354` // Estimated: `3819` - // Minimum execution time: 6_107_000 picoseconds. - Weight::from_parts(6_235_000, 3819) + // Minimum execution time: 12_202_000 picoseconds. + Weight::from_parts(12_708_000, 3819) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) @@ -554,109 +556,106 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `3912` - // Minimum execution time: 7_316_000 picoseconds. - Weight::from_parts(7_653_000, 3912) + // Minimum execution time: 13_492_000 picoseconds. + Weight::from_parts(13_845_000, 3912) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 721_000 picoseconds. - Weight::from_parts(764_000, 0) + // Minimum execution time: 798_000 picoseconds. + Weight::from_parts(856_000, 0) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 369_000 picoseconds. - Weight::from_parts(417_000, 0) + // Minimum execution time: 364_000 picoseconds. + Weight::from_parts(414_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 318_000 picoseconds. - Weight::from_parts(349_000, 0) + // Minimum execution time: 355_000 picoseconds. + Weight::from_parts(396_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 590_000 picoseconds. - Weight::from_parts(628_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(719_000, 0) } fn seal_gas_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 660_000 picoseconds. - Weight::from_parts(730_000, 0) + // Minimum execution time: 770_000 picoseconds. + Weight::from_parts(827_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 4_361_000 picoseconds. - Weight::from_parts(4_577_000, 0) + // Minimum execution time: 5_839_000 picoseconds. + Weight::from_parts(6_174_000, 0) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 560_000 picoseconds. - Weight::from_parts(603_000, 0) + // Minimum execution time: 681_000 picoseconds. + Weight::from_parts(757_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 561_000 picoseconds. - Weight::from_parts(610_000, 0) + // Minimum execution time: 696_000 picoseconds. + Weight::from_parts(730_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 557_000 picoseconds. - Weight::from_parts(583_000, 0) + // Minimum execution time: 654_000 picoseconds. + Weight::from_parts(713_000, 0) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 550_000 picoseconds. - Weight::from_parts(602_000, 0) + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(752_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) fn seal_weight_to_fee() -> Weight { // Proof Size summary in bytes: - // Measured: `67` - // Estimated: `1552` - // Minimum execution time: 4_065_000 picoseconds. - Weight::from_parts(4_291_000, 1552) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_562_000 picoseconds. + Weight::from_parts(1_749_000, 0) } /// The range of component `n` is `[0, 1048572]`. fn seal_input(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 487_000 picoseconds. - Weight::from_parts(517_000, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(301, 0).saturating_mul(n.into())) + // Minimum execution time: 483_000 picoseconds. + Weight::from_parts(536_000, 0) + // Standard Error: 4 + .saturating_add(Weight::from_parts(329, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048572]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 318_000 picoseconds. - Weight::from_parts(372_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(411, 0).saturating_mul(n.into())) + // Minimum execution time: 372_000 picoseconds. + Weight::from_parts(384_000, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(433, 0).saturating_mul(n.into())) } /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -669,10 +668,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319 + n * (78 ±0)` // Estimated: `3784 + n * (2553 ±0)` - // Minimum execution time: 13_251_000 picoseconds. - Weight::from_parts(15_257_892, 3784) - // Standard Error: 7_089 - .saturating_add(Weight::from_parts(3_443_907, 0).saturating_mul(n.into())) + // Minimum execution time: 19_308_000 picoseconds. + Weight::from_parts(20_544_934, 3784) + // Standard Error: 9_422 + .saturating_add(Weight::from_parts(4_431_910, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -685,8 +684,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1561` - // Minimum execution time: 3_434_000 picoseconds. - Weight::from_parts(3_605_000, 1561) + // Minimum execution time: 4_503_000 picoseconds. + Weight::from_parts(4_743_000, 1561) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `System::EventTopics` (r:4 w:4) @@ -697,12 +696,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `990 + t * (2475 ±0)` - // Minimum execution time: 3_668_000 picoseconds. - Weight::from_parts(3_999_591, 990) - // Standard Error: 5_767 - .saturating_add(Weight::from_parts(2_011_090, 0).saturating_mul(t.into())) + // Minimum execution time: 3_838_000 picoseconds. + Weight::from_parts(4_110_930, 990) + // Standard Error: 6_782 + .saturating_add(Weight::from_parts(2_241_357, 0).saturating_mul(t.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(12, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(20, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(t.into()))) .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) @@ -712,10 +711,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 443_000 picoseconds. - Weight::from_parts(472_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(1_207, 0).saturating_mul(i.into())) + // Minimum execution time: 506_000 picoseconds. + Weight::from_parts(526_000, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(1_223, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -723,8 +722,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16618` // Estimated: `16618` - // Minimum execution time: 13_752_000 picoseconds. - Weight::from_parts(14_356_000, 16618) + // Minimum execution time: 16_531_000 picoseconds. + Weight::from_parts(16_947_000, 16618) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -733,8 +732,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `26628` // Estimated: `26628` - // Minimum execution time: 43_444_000 picoseconds. - Weight::from_parts(45_087_000, 26628) + // Minimum execution time: 57_673_000 picoseconds. + Weight::from_parts(63_131_000, 26628) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -743,8 +742,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16618` // Estimated: `16618` - // Minimum execution time: 15_616_000 picoseconds. - Weight::from_parts(16_010_000, 16618) + // Minimum execution time: 18_388_000 picoseconds. + Weight::from_parts(18_882_000, 16618) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -754,8 +753,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `26628` // Estimated: `26628` - // Minimum execution time: 47_020_000 picoseconds. - Weight::from_parts(50_152_000, 26628) + // Minimum execution time: 62_048_000 picoseconds. + Weight::from_parts(71_685_000, 26628) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -767,12 +766,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `250 + o * (1 ±0)` // Estimated: `249 + o * (1 ±0)` - // Minimum execution time: 8_824_000 picoseconds. - Weight::from_parts(8_915_233, 249) - // Standard Error: 1 - .saturating_add(Weight::from_parts(255, 0).saturating_mul(n.into())) - // Standard Error: 1 - .saturating_add(Weight::from_parts(39, 0).saturating_mul(o.into())) + // Minimum execution time: 11_886_000 picoseconds. + Weight::from_parts(11_100_121, 249) + // Standard Error: 2 + .saturating_add(Weight::from_parts(258, 0).saturating_mul(n.into())) + // Standard Error: 2 + .saturating_add(Weight::from_parts(91, 0).saturating_mul(o.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -784,10 +783,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_133_000 picoseconds. - Weight::from_parts(7_912_778, 248) + // Minimum execution time: 9_576_000 picoseconds. + Weight::from_parts(10_418_109, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(88, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(115, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -799,10 +798,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_746_000 picoseconds. - Weight::from_parts(7_647_236, 248) + // Minimum execution time: 8_903_000 picoseconds. + Weight::from_parts(10_108_260, 248) // Standard Error: 2 - .saturating_add(Weight::from_parts(603, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(626, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -813,10 +812,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_247_000 picoseconds. - Weight::from_parts(6_952_661, 248) + // Minimum execution time: 8_216_000 picoseconds. + Weight::from_parts(9_267_036, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(77, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(103, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -827,10 +826,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_428_000 picoseconds. - Weight::from_parts(8_384_015, 248) + // Minimum execution time: 9_713_000 picoseconds. + Weight::from_parts(10_998_797, 248) // Standard Error: 2 - .saturating_add(Weight::from_parts(625, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(639, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -839,36 +838,36 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_478_000 picoseconds. - Weight::from_parts(1_533_000, 0) + // Minimum execution time: 1_521_000 picoseconds. + Weight::from_parts(1_612_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_485_000 picoseconds. - Weight::from_parts(2_728_000, 0) + // Minimum execution time: 2_866_000 picoseconds. + Weight::from_parts(3_150_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_195_000 picoseconds. - Weight::from_parts(3_811_000, 0) + // Minimum execution time: 3_200_000 picoseconds. + Weight::from_parts(3_373_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_902_000 picoseconds. - Weight::from_parts(4_118_000, 0) + // Minimum execution time: 4_138_000 picoseconds. + Weight::from_parts(4_488_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_571_000 picoseconds. - Weight::from_parts(1_662_000, 0) + // Minimum execution time: 1_594_000 picoseconds. + Weight::from_parts(1_799_000, 0) } /// The range of component `n` is `[0, 16384]`. /// The range of component `o` is `[0, 16384]`. @@ -876,57 +875,57 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_250_000 picoseconds. - Weight::from_parts(2_465_568, 0) + // Minimum execution time: 5_811_000 picoseconds. + Weight::from_parts(2_851_992, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(201, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(208, 0).saturating_mul(n.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(223, 0).saturating_mul(o.into())) + .saturating_add(Weight::from_parts(222, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_012_000 picoseconds. - Weight::from_parts(2_288_004, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(239, 0).saturating_mul(n.into())) + // Minimum execution time: 2_335_000 picoseconds. + Weight::from_parts(2_661_318, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(234, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_906_000 picoseconds. - Weight::from_parts(2_121_040, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(225, 0).saturating_mul(n.into())) + // Minimum execution time: 2_189_000 picoseconds. + Weight::from_parts(2_487_605, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(220, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_736_000 picoseconds. - Weight::from_parts(1_954_728, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(111, 0).saturating_mul(n.into())) + // Minimum execution time: 1_831_000 picoseconds. + Weight::from_parts(2_071_548, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(134, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_872_000 picoseconds. - Weight::from_parts(8_125_644, 0) + // Minimum execution time: 8_106_000 picoseconds. + Weight::from_parts(8_556_699, 0) } fn seal_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 8_489_000 picoseconds. - Weight::from_parts(8_791_000, 0) + // Minimum execution time: 10_433_000 picoseconds. + Weight::from_parts(10_873_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -942,12 +941,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `620 + t * (280 ±0)` // Estimated: `4085 + t * (2182 ±0)` - // Minimum execution time: 122_759_000 picoseconds. - Weight::from_parts(120_016_020, 4085) - // Standard Error: 173_118 - .saturating_add(Weight::from_parts(42_848_338, 0).saturating_mul(t.into())) + // Minimum execution time: 140_018_000 picoseconds. + Weight::from_parts(142_816_362, 4085) + // Standard Error: 187_348 + .saturating_add(Weight::from_parts(42_978_763, 0).saturating_mul(t.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(3, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -962,8 +961,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 111_566_000 picoseconds. - Weight::from_parts(115_083_000, 3895) + // Minimum execution time: 130_708_000 picoseconds. + Weight::from_parts(134_865_000, 3895) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) @@ -982,12 +981,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `676` // Estimated: `4132` - // Minimum execution time: 1_871_402_000 picoseconds. - Weight::from_parts(1_890_038_000, 4132) - // Standard Error: 24 - .saturating_add(Weight::from_parts(581, 0).saturating_mul(i.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(915, 0).saturating_mul(s.into())) + // Minimum execution time: 1_891_181_000 picoseconds. + Weight::from_parts(1_901_270_000, 4132) + // Standard Error: 26 + .saturating_add(Weight::from_parts(617, 0).saturating_mul(i.into())) + // Standard Error: 26 + .saturating_add(Weight::from_parts(983, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -996,64 +995,64 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 966_000 picoseconds. - Weight::from_parts(9_599_151, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_336, 0).saturating_mul(n.into())) + // Minimum execution time: 979_000 picoseconds. + Weight::from_parts(12_708_667, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_416_000 picoseconds. - Weight::from_parts(10_964_255, 0) + // Minimum execution time: 1_402_000 picoseconds. + Weight::from_parts(12_527_035, 0) // Standard Error: 1 - .saturating_add(Weight::from_parts(3_593, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_526, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 821_000 picoseconds. - Weight::from_parts(6_579_283, 0) + // Minimum execution time: 787_000 picoseconds. + Weight::from_parts(8_175_079, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_466, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_460, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 773_000 picoseconds. - Weight::from_parts(10_990_209, 0) + // Minimum execution time: 807_000 picoseconds. + Weight::from_parts(6_418_831, 0) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_457, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_468, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 125697]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 43_195_000 picoseconds. - Weight::from_parts(41_864_855, 0) - // Standard Error: 9 - .saturating_add(Weight::from_parts(5_154, 0).saturating_mul(n.into())) + // Minimum execution time: 49_651_000 picoseconds. + Weight::from_parts(48_834_618, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(5_221, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_747_000 picoseconds. - Weight::from_parts(49_219_000, 0) + // Minimum execution time: 48_222_000 picoseconds. + Weight::from_parts(49_638_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_854_000 picoseconds. - Weight::from_parts(12_962_000, 0) + // Minimum execution time: 12_739_000 picoseconds. + Weight::from_parts(12_958_000, 0) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) @@ -1063,8 +1062,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 17_868_000 picoseconds. - Weight::from_parts(18_486_000, 3895) + // Minimum execution time: 25_663_000 picoseconds. + Weight::from_parts(26_249_000, 3895) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -1074,8 +1073,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3820` - // Minimum execution time: 8_393_000 picoseconds. - Weight::from_parts(8_640_000, 3820) + // Minimum execution time: 14_726_000 picoseconds. + Weight::from_parts(15_392_000, 3820) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -1085,8 +1084,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3558` - // Minimum execution time: 7_489_000 picoseconds. - Weight::from_parts(7_815_000, 3558) + // Minimum execution time: 13_779_000 picoseconds. + Weight::from_parts(14_168_000, 3558) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -1094,15 +1093,15 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 299_000 picoseconds. - Weight::from_parts(339_000, 0) + // Minimum execution time: 359_000 picoseconds. + Weight::from_parts(402_000, 0) } fn seal_account_reentrance_count() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 324_000 picoseconds. - Weight::from_parts(380_000, 0) + // Minimum execution time: 339_000 picoseconds. + Weight::from_parts(389_000, 0) } /// Storage: `Contracts::Nonce` (r:1 w:0) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -1110,8 +1109,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `219` // Estimated: `1704` - // Minimum execution time: 2_768_000 picoseconds. - Weight::from_parts(3_025_000, 1704) + // Minimum execution time: 4_079_000 picoseconds. + Weight::from_parts(4_355_000, 1704) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// The range of component `r` is `[0, 5000]`. @@ -1119,10 +1118,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 766_000 picoseconds. - Weight::from_parts(722_169, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(7_191, 0).saturating_mul(r.into())) + // Minimum execution time: 836_000 picoseconds. + Weight::from_parts(591_552, 0) + // Standard Error: 17 + .saturating_add(Weight::from_parts(7_522, 0).saturating_mul(r.into())) } } @@ -1134,8 +1133,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 1_915_000 picoseconds. - Weight::from_parts(1_986_000, 1627) + // Minimum execution time: 2_809_000 picoseconds. + Weight::from_parts(2_956_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1145,10 +1144,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `452 + k * (69 ±0)` // Estimated: `442 + k * (70 ±0)` - // Minimum execution time: 11_103_000 picoseconds. - Weight::from_parts(11_326_000, 442) - // Standard Error: 2_291 - .saturating_add(Weight::from_parts(1_196_329, 0).saturating_mul(k.into())) + // Minimum execution time: 17_559_000 picoseconds. + Weight::from_parts(17_850_000, 442) + // Standard Error: 2_722 + .saturating_add(Weight::from_parts(1_376_892, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -1162,10 +1161,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 7_783_000 picoseconds. - Weight::from_parts(4_462_075, 6149) + // Minimum execution time: 8_830_000 picoseconds. + Weight::from_parts(6_649_003, 6149) // Standard Error: 5 - .saturating_add(Weight::from_parts(1_634, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_676, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1178,8 +1177,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 15_971_000 picoseconds. - Weight::from_parts(16_730_000, 6450) + // Minimum execution time: 21_927_000 picoseconds. + Weight::from_parts(22_655_000, 6450) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1192,10 +1191,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 3_149_000 picoseconds. - Weight::from_parts(3_264_000, 3635) - // Standard Error: 559 - .saturating_add(Weight::from_parts(1_111_209, 0).saturating_mul(k.into())) + // Minimum execution time: 4_465_000 picoseconds. + Weight::from_parts(4_774_000, 3635) + // Standard Error: 867 + .saturating_add(Weight::from_parts(1_071_462, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -1214,10 +1213,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 15_072_000 picoseconds. - Weight::from_parts(15_721_891, 6263) + // Minimum execution time: 21_627_000 picoseconds. + Weight::from_parts(21_491_424, 6263) // Standard Error: 2 - .saturating_add(Weight::from_parts(428, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(480, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1228,8 +1227,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `440` // Estimated: `6380` - // Minimum execution time: 12_047_000 picoseconds. - Weight::from_parts(12_500_000, 6380) + // Minimum execution time: 17_262_000 picoseconds. + Weight::from_parts(17_785_000, 6380) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1238,13 +1237,13 @@ impl WeightInfo for () { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) fn v14_migration_step() -> Weight { // Proof Size summary in bytes: // Measured: `352` // Estimated: `6292` - // Minimum execution time: 47_488_000 picoseconds. - Weight::from_parts(48_482_000, 6292) + // Minimum execution time: 52_303_000 picoseconds. + Weight::from_parts(53_902_000, 6292) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1256,8 +1255,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `594` // Estimated: `6534` - // Minimum execution time: 52_801_000 picoseconds. - Weight::from_parts(54_230_000, 6534) + // Minimum execution time: 58_585_000 picoseconds. + Weight::from_parts(60_478_000, 6534) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1267,8 +1266,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `409` // Estimated: `6349` - // Minimum execution time: 11_618_000 picoseconds. - Weight::from_parts(12_068_000, 6349) + // Minimum execution time: 16_673_000 picoseconds. + Weight::from_parts(17_325_000, 6349) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1278,8 +1277,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_131_000 picoseconds. - Weight::from_parts(2_255_000, 1627) + // Minimum execution time: 3_073_000 picoseconds. + Weight::from_parts(3_262_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1291,8 +1290,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 10_773_000 picoseconds. - Weight::from_parts(11_118_000, 3631) + // Minimum execution time: 11_687_000 picoseconds. + Weight::from_parts(12_178_000, 3631) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1302,8 +1301,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_371_000 picoseconds. - Weight::from_parts(4_624_000, 3607) + // Minimum execution time: 4_553_000 picoseconds. + Weight::from_parts(4_826_000, 3607) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -1314,8 +1313,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 5_612_000 picoseconds. - Weight::from_parts(5_838_000, 3632) + // Minimum execution time: 6_794_000 picoseconds. + Weight::from_parts(6_959_000, 3632) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -1326,8 +1325,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 5_487_000 picoseconds. - Weight::from_parts(5_693_000, 3607) + // Minimum execution time: 6_120_000 picoseconds. + Weight::from_parts(6_420_000, 3607) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1347,11 +1346,11 @@ impl WeightInfo for () { fn call_with_code_per_byte(c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `800 + c * (1 ±0)` - // Estimated: `4266 + c * (1 ±0)` - // Minimum execution time: 247_545_000 picoseconds. - Weight::from_parts(268_016_699, 4266) - // Standard Error: 4 - .saturating_add(Weight::from_parts(700, 0).saturating_mul(c.into())) + // Estimated: `4268 + c * (1 ±0)` + // Minimum execution time: 266_424_000 picoseconds. + Weight::from_parts(283_325_502, 4268) + // Standard Error: 12 + .saturating_add(Weight::from_parts(950, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1361,7 +1360,7 @@ impl WeightInfo for () { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:2 w:2) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::Nonce` (r:1 w:1) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) @@ -1378,15 +1377,15 @@ impl WeightInfo for () { fn instantiate_with_code(c: u32, i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `323` - // Estimated: `6262` - // Minimum execution time: 4_396_772_000 picoseconds. - Weight::from_parts(235_107_907, 6262) - // Standard Error: 185 - .saturating_add(Weight::from_parts(53_843, 0).saturating_mul(c.into())) - // Standard Error: 22 - .saturating_add(Weight::from_parts(2_143, 0).saturating_mul(i.into())) - // Standard Error: 22 - .saturating_add(Weight::from_parts(2_210, 0).saturating_mul(s.into())) + // Estimated: `6267` + // Minimum execution time: 4_371_315_000 picoseconds. + Weight::from_parts(4_739_462_000, 6267) + // Standard Error: 329 + .saturating_add(Weight::from_parts(38_518, 0).saturating_mul(c.into())) + // Standard Error: 39 + .saturating_add(Weight::from_parts(605, 0).saturating_mul(i.into())) + // Standard Error: 39 + .saturating_add(Weight::from_parts(561, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -1405,19 +1404,19 @@ impl WeightInfo for () { /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// The range of component `i` is `[0, 1048576]`. /// The range of component `s` is `[0, 1048576]`. fn instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `560` - // Estimated: `4017` - // Minimum execution time: 2_240_868_000 picoseconds. - Weight::from_parts(2_273_668_000, 4017) - // Standard Error: 32 - .saturating_add(Weight::from_parts(934, 0).saturating_mul(i.into())) - // Standard Error: 32 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + // Estimated: `4016` + // Minimum execution time: 2_304_531_000 picoseconds. + Weight::from_parts(2_352_810_000, 4016) + // Standard Error: 35 + .saturating_add(Weight::from_parts(1_004, 0).saturating_mul(i.into())) + // Standard Error: 35 + .saturating_add(Weight::from_parts(936, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -1437,8 +1436,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `826` // Estimated: `4291` - // Minimum execution time: 165_067_000 picoseconds. - Weight::from_parts(168_582_000, 4291) + // Minimum execution time: 183_658_000 picoseconds. + Weight::from_parts(189_507_000, 4291) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1447,7 +1446,7 @@ impl WeightInfo for () { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) /// The range of component `c` is `[0, 125952]`. @@ -1455,10 +1454,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 229_454_000 picoseconds. - Weight::from_parts(251_495_551, 3607) - // Standard Error: 71 - .saturating_add(Weight::from_parts(51_428, 0).saturating_mul(c.into())) + // Minimum execution time: 253_006_000 picoseconds. + Weight::from_parts(269_271_744, 3607) + // Standard Error: 79 + .saturating_add(Weight::from_parts(49_970, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1467,7 +1466,7 @@ impl WeightInfo for () { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) /// The range of component `c` is `[0, 125952]`. @@ -1475,10 +1474,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 240_390_000 picoseconds. - Weight::from_parts(273_854_266, 3607) - // Standard Error: 243 - .saturating_add(Weight::from_parts(51_836, 0).saturating_mul(c.into())) + // Minimum execution time: 247_567_000 picoseconds. + Weight::from_parts(271_875_922, 3607) + // Standard Error: 78 + .saturating_add(Weight::from_parts(50_117, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1487,15 +1486,15 @@ impl WeightInfo for () { /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `Measured`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `Measured`) /// Storage: `Contracts::PristineCode` (r:0 w:1) /// Proof: `Contracts::PristineCode` (`max_values`: None, `max_size`: Some(125988), added: 128463, mode: `Measured`) fn remove_code() -> Weight { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 39_374_000 picoseconds. - Weight::from_parts(40_247_000, 3780) + // Minimum execution time: 48_151_000 picoseconds. + Weight::from_parts(49_407_000, 3780) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1509,8 +1508,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 24_473_000 picoseconds. - Weight::from_parts(25_890_000, 6492) + // Minimum execution time: 30_173_000 picoseconds. + Weight::from_parts(30_941_000, 6492) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1519,17 +1518,17 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_528_000 picoseconds. - Weight::from_parts(9_301_010, 0) - // Standard Error: 98 - .saturating_add(Weight::from_parts(53_173, 0).saturating_mul(r.into())) + // Minimum execution time: 8_350_000 picoseconds. + Weight::from_parts(9_238_867, 0) + // Standard Error: 139 + .saturating_add(Weight::from_parts(52_355, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 643_000 picoseconds. - Weight::from_parts(678_000, 0) + // Minimum execution time: 757_000 picoseconds. + Weight::from_parts(827_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -1537,8 +1536,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `354` // Estimated: `3819` - // Minimum execution time: 6_107_000 picoseconds. - Weight::from_parts(6_235_000, 3819) + // Minimum execution time: 12_202_000 picoseconds. + Weight::from_parts(12_708_000, 3819) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) @@ -1547,109 +1546,106 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `3912` - // Minimum execution time: 7_316_000 picoseconds. - Weight::from_parts(7_653_000, 3912) + // Minimum execution time: 13_492_000 picoseconds. + Weight::from_parts(13_845_000, 3912) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 721_000 picoseconds. - Weight::from_parts(764_000, 0) + // Minimum execution time: 798_000 picoseconds. + Weight::from_parts(856_000, 0) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 369_000 picoseconds. - Weight::from_parts(417_000, 0) + // Minimum execution time: 364_000 picoseconds. + Weight::from_parts(414_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 318_000 picoseconds. - Weight::from_parts(349_000, 0) + // Minimum execution time: 355_000 picoseconds. + Weight::from_parts(396_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 590_000 picoseconds. - Weight::from_parts(628_000, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(719_000, 0) } fn seal_gas_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 660_000 picoseconds. - Weight::from_parts(730_000, 0) + // Minimum execution time: 770_000 picoseconds. + Weight::from_parts(827_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 4_361_000 picoseconds. - Weight::from_parts(4_577_000, 0) + // Minimum execution time: 5_839_000 picoseconds. + Weight::from_parts(6_174_000, 0) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 560_000 picoseconds. - Weight::from_parts(603_000, 0) + // Minimum execution time: 681_000 picoseconds. + Weight::from_parts(757_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 561_000 picoseconds. - Weight::from_parts(610_000, 0) + // Minimum execution time: 696_000 picoseconds. + Weight::from_parts(730_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 557_000 picoseconds. - Weight::from_parts(583_000, 0) + // Minimum execution time: 654_000 picoseconds. + Weight::from_parts(713_000, 0) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 550_000 picoseconds. - Weight::from_parts(602_000, 0) + // Minimum execution time: 707_000 picoseconds. + Weight::from_parts(752_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) fn seal_weight_to_fee() -> Weight { // Proof Size summary in bytes: - // Measured: `67` - // Estimated: `1552` - // Minimum execution time: 4_065_000 picoseconds. - Weight::from_parts(4_291_000, 1552) - .saturating_add(RocksDbWeight::get().reads(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_562_000 picoseconds. + Weight::from_parts(1_749_000, 0) } /// The range of component `n` is `[0, 1048572]`. fn seal_input(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 487_000 picoseconds. - Weight::from_parts(517_000, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(301, 0).saturating_mul(n.into())) + // Minimum execution time: 483_000 picoseconds. + Weight::from_parts(536_000, 0) + // Standard Error: 4 + .saturating_add(Weight::from_parts(329, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048572]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 318_000 picoseconds. - Weight::from_parts(372_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(411, 0).saturating_mul(n.into())) + // Minimum execution time: 372_000 picoseconds. + Weight::from_parts(384_000, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(433, 0).saturating_mul(n.into())) } /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -1662,10 +1658,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319 + n * (78 ±0)` // Estimated: `3784 + n * (2553 ±0)` - // Minimum execution time: 13_251_000 picoseconds. - Weight::from_parts(15_257_892, 3784) - // Standard Error: 7_089 - .saturating_add(Weight::from_parts(3_443_907, 0).saturating_mul(n.into())) + // Minimum execution time: 19_308_000 picoseconds. + Weight::from_parts(20_544_934, 3784) + // Standard Error: 9_422 + .saturating_add(Weight::from_parts(4_431_910, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -1678,8 +1674,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1561` - // Minimum execution time: 3_434_000 picoseconds. - Weight::from_parts(3_605_000, 1561) + // Minimum execution time: 4_503_000 picoseconds. + Weight::from_parts(4_743_000, 1561) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `System::EventTopics` (r:4 w:4) @@ -1690,12 +1686,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `990 + t * (2475 ±0)` - // Minimum execution time: 3_668_000 picoseconds. - Weight::from_parts(3_999_591, 990) - // Standard Error: 5_767 - .saturating_add(Weight::from_parts(2_011_090, 0).saturating_mul(t.into())) + // Minimum execution time: 3_838_000 picoseconds. + Weight::from_parts(4_110_930, 990) + // Standard Error: 6_782 + .saturating_add(Weight::from_parts(2_241_357, 0).saturating_mul(t.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(12, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(20, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(t.into()))) .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) @@ -1705,10 +1701,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 443_000 picoseconds. - Weight::from_parts(472_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(1_207, 0).saturating_mul(i.into())) + // Minimum execution time: 506_000 picoseconds. + Weight::from_parts(526_000, 0) + // Standard Error: 11 + .saturating_add(Weight::from_parts(1_223, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -1716,8 +1712,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16618` // Estimated: `16618` - // Minimum execution time: 13_752_000 picoseconds. - Weight::from_parts(14_356_000, 16618) + // Minimum execution time: 16_531_000 picoseconds. + Weight::from_parts(16_947_000, 16618) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1726,8 +1722,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `26628` // Estimated: `26628` - // Minimum execution time: 43_444_000 picoseconds. - Weight::from_parts(45_087_000, 26628) + // Minimum execution time: 57_673_000 picoseconds. + Weight::from_parts(63_131_000, 26628) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1736,8 +1732,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16618` // Estimated: `16618` - // Minimum execution time: 15_616_000 picoseconds. - Weight::from_parts(16_010_000, 16618) + // Minimum execution time: 18_388_000 picoseconds. + Weight::from_parts(18_882_000, 16618) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1747,8 +1743,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `26628` // Estimated: `26628` - // Minimum execution time: 47_020_000 picoseconds. - Weight::from_parts(50_152_000, 26628) + // Minimum execution time: 62_048_000 picoseconds. + Weight::from_parts(71_685_000, 26628) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1760,12 +1756,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `250 + o * (1 ±0)` // Estimated: `249 + o * (1 ±0)` - // Minimum execution time: 8_824_000 picoseconds. - Weight::from_parts(8_915_233, 249) - // Standard Error: 1 - .saturating_add(Weight::from_parts(255, 0).saturating_mul(n.into())) - // Standard Error: 1 - .saturating_add(Weight::from_parts(39, 0).saturating_mul(o.into())) + // Minimum execution time: 11_886_000 picoseconds. + Weight::from_parts(11_100_121, 249) + // Standard Error: 2 + .saturating_add(Weight::from_parts(258, 0).saturating_mul(n.into())) + // Standard Error: 2 + .saturating_add(Weight::from_parts(91, 0).saturating_mul(o.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -1777,10 +1773,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_133_000 picoseconds. - Weight::from_parts(7_912_778, 248) + // Minimum execution time: 9_576_000 picoseconds. + Weight::from_parts(10_418_109, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(88, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(115, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1792,10 +1788,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_746_000 picoseconds. - Weight::from_parts(7_647_236, 248) + // Minimum execution time: 8_903_000 picoseconds. + Weight::from_parts(10_108_260, 248) // Standard Error: 2 - .saturating_add(Weight::from_parts(603, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(626, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1806,10 +1802,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_247_000 picoseconds. - Weight::from_parts(6_952_661, 248) + // Minimum execution time: 8_216_000 picoseconds. + Weight::from_parts(9_267_036, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(77, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(103, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1820,10 +1816,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_428_000 picoseconds. - Weight::from_parts(8_384_015, 248) + // Minimum execution time: 9_713_000 picoseconds. + Weight::from_parts(10_998_797, 248) // Standard Error: 2 - .saturating_add(Weight::from_parts(625, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(639, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1832,36 +1828,36 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_478_000 picoseconds. - Weight::from_parts(1_533_000, 0) + // Minimum execution time: 1_521_000 picoseconds. + Weight::from_parts(1_612_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_485_000 picoseconds. - Weight::from_parts(2_728_000, 0) + // Minimum execution time: 2_866_000 picoseconds. + Weight::from_parts(3_150_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_195_000 picoseconds. - Weight::from_parts(3_811_000, 0) + // Minimum execution time: 3_200_000 picoseconds. + Weight::from_parts(3_373_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_902_000 picoseconds. - Weight::from_parts(4_118_000, 0) + // Minimum execution time: 4_138_000 picoseconds. + Weight::from_parts(4_488_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_571_000 picoseconds. - Weight::from_parts(1_662_000, 0) + // Minimum execution time: 1_594_000 picoseconds. + Weight::from_parts(1_799_000, 0) } /// The range of component `n` is `[0, 16384]`. /// The range of component `o` is `[0, 16384]`. @@ -1869,57 +1865,57 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_250_000 picoseconds. - Weight::from_parts(2_465_568, 0) + // Minimum execution time: 5_811_000 picoseconds. + Weight::from_parts(2_851_992, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(201, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(208, 0).saturating_mul(n.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(223, 0).saturating_mul(o.into())) + .saturating_add(Weight::from_parts(222, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_012_000 picoseconds. - Weight::from_parts(2_288_004, 0) - // Standard Error: 3 - .saturating_add(Weight::from_parts(239, 0).saturating_mul(n.into())) + // Minimum execution time: 2_335_000 picoseconds. + Weight::from_parts(2_661_318, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(234, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_906_000 picoseconds. - Weight::from_parts(2_121_040, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(225, 0).saturating_mul(n.into())) + // Minimum execution time: 2_189_000 picoseconds. + Weight::from_parts(2_487_605, 0) + // Standard Error: 1 + .saturating_add(Weight::from_parts(220, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_736_000 picoseconds. - Weight::from_parts(1_954_728, 0) - // Standard Error: 0 - .saturating_add(Weight::from_parts(111, 0).saturating_mul(n.into())) + // Minimum execution time: 1_831_000 picoseconds. + Weight::from_parts(2_071_548, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(134, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 16384]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_872_000 picoseconds. - Weight::from_parts(8_125_644, 0) + // Minimum execution time: 8_106_000 picoseconds. + Weight::from_parts(8_556_699, 0) } fn seal_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 8_489_000 picoseconds. - Weight::from_parts(8_791_000, 0) + // Minimum execution time: 10_433_000 picoseconds. + Weight::from_parts(10_873_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -1935,12 +1931,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `620 + t * (280 ±0)` // Estimated: `4085 + t * (2182 ±0)` - // Minimum execution time: 122_759_000 picoseconds. - Weight::from_parts(120_016_020, 4085) - // Standard Error: 173_118 - .saturating_add(Weight::from_parts(42_848_338, 0).saturating_mul(t.into())) + // Minimum execution time: 140_018_000 picoseconds. + Weight::from_parts(142_816_362, 4085) + // Standard Error: 187_348 + .saturating_add(Weight::from_parts(42_978_763, 0).saturating_mul(t.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(3, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -1955,8 +1951,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 111_566_000 picoseconds. - Weight::from_parts(115_083_000, 3895) + // Minimum execution time: 130_708_000 picoseconds. + Weight::from_parts(134_865_000, 3895) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) @@ -1975,12 +1971,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `676` // Estimated: `4132` - // Minimum execution time: 1_871_402_000 picoseconds. - Weight::from_parts(1_890_038_000, 4132) - // Standard Error: 24 - .saturating_add(Weight::from_parts(581, 0).saturating_mul(i.into())) - // Standard Error: 24 - .saturating_add(Weight::from_parts(915, 0).saturating_mul(s.into())) + // Minimum execution time: 1_891_181_000 picoseconds. + Weight::from_parts(1_901_270_000, 4132) + // Standard Error: 26 + .saturating_add(Weight::from_parts(617, 0).saturating_mul(i.into())) + // Standard Error: 26 + .saturating_add(Weight::from_parts(983, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1989,64 +1985,64 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 966_000 picoseconds. - Weight::from_parts(9_599_151, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_336, 0).saturating_mul(n.into())) + // Minimum execution time: 979_000 picoseconds. + Weight::from_parts(12_708_667, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_416_000 picoseconds. - Weight::from_parts(10_964_255, 0) + // Minimum execution time: 1_402_000 picoseconds. + Weight::from_parts(12_527_035, 0) // Standard Error: 1 - .saturating_add(Weight::from_parts(3_593, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_526, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 821_000 picoseconds. - Weight::from_parts(6_579_283, 0) + // Minimum execution time: 787_000 picoseconds. + Weight::from_parts(8_175_079, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_466, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_460, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 773_000 picoseconds. - Weight::from_parts(10_990_209, 0) + // Minimum execution time: 807_000 picoseconds. + Weight::from_parts(6_418_831, 0) // Standard Error: 1 - .saturating_add(Weight::from_parts(1_457, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_468, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 125697]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 43_195_000 picoseconds. - Weight::from_parts(41_864_855, 0) - // Standard Error: 9 - .saturating_add(Weight::from_parts(5_154, 0).saturating_mul(n.into())) + // Minimum execution time: 49_651_000 picoseconds. + Weight::from_parts(48_834_618, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(5_221, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_747_000 picoseconds. - Weight::from_parts(49_219_000, 0) + // Minimum execution time: 48_222_000 picoseconds. + Weight::from_parts(49_638_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_854_000 picoseconds. - Weight::from_parts(12_962_000, 0) + // Minimum execution time: 12_739_000 picoseconds. + Weight::from_parts(12_958_000, 0) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) @@ -2056,8 +2052,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 17_868_000 picoseconds. - Weight::from_parts(18_486_000, 3895) + // Minimum execution time: 25_663_000 picoseconds. + Weight::from_parts(26_249_000, 3895) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -2067,8 +2063,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3820` - // Minimum execution time: 8_393_000 picoseconds. - Weight::from_parts(8_640_000, 3820) + // Minimum execution time: 14_726_000 picoseconds. + Weight::from_parts(15_392_000, 3820) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -2078,8 +2074,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3558` - // Minimum execution time: 7_489_000 picoseconds. - Weight::from_parts(7_815_000, 3558) + // Minimum execution time: 13_779_000 picoseconds. + Weight::from_parts(14_168_000, 3558) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -2087,15 +2083,15 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 299_000 picoseconds. - Weight::from_parts(339_000, 0) + // Minimum execution time: 359_000 picoseconds. + Weight::from_parts(402_000, 0) } fn seal_account_reentrance_count() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 324_000 picoseconds. - Weight::from_parts(380_000, 0) + // Minimum execution time: 339_000 picoseconds. + Weight::from_parts(389_000, 0) } /// Storage: `Contracts::Nonce` (r:1 w:0) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -2103,8 +2099,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `219` // Estimated: `1704` - // Minimum execution time: 2_768_000 picoseconds. - Weight::from_parts(3_025_000, 1704) + // Minimum execution time: 4_079_000 picoseconds. + Weight::from_parts(4_355_000, 1704) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// The range of component `r` is `[0, 5000]`. @@ -2112,9 +2108,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 766_000 picoseconds. - Weight::from_parts(722_169, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(7_191, 0).saturating_mul(r.into())) + // Minimum execution time: 836_000 picoseconds. + Weight::from_parts(591_552, 0) + // Standard Error: 17 + .saturating_add(Weight::from_parts(7_522, 0).saturating_mul(r.into())) } } diff --git a/substrate/frame/conviction-voting/src/weights.rs b/substrate/frame/conviction-voting/src/weights.rs index d8f3ffcb3be6..1abcd83e7d5c 100644 --- a/substrate/frame/conviction-voting/src/weights.rs +++ b/substrate/frame/conviction-voting/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_conviction_voting` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -81,8 +81,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `13141` // Estimated: `219984` - // Minimum execution time: 114_422_000 picoseconds. - Weight::from_parts(118_642_000, 219984) + // Minimum execution time: 135_295_000 picoseconds. + Weight::from_parts(142_897_000, 219984) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -104,8 +104,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `20283` // Estimated: `219984` - // Minimum execution time: 290_934_000 picoseconds. - Weight::from_parts(303_286_000, 219984) + // Minimum execution time: 324_485_000 picoseconds. + Weight::from_parts(337_467_000, 219984) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -121,8 +121,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `20035` // Estimated: `219984` - // Minimum execution time: 277_464_000 picoseconds. - Weight::from_parts(284_288_000, 219984) + // Minimum execution time: 302_574_000 picoseconds. + Weight::from_parts(315_016_000, 219984) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -134,8 +134,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `12742` // Estimated: `30706` - // Minimum execution time: 54_538_000 picoseconds. - Weight::from_parts(55_758_000, 30706) + // Minimum execution time: 65_548_000 picoseconds. + Weight::from_parts(71_499_000, 30706) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -158,10 +158,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `306 + r * (1628 ±0)` // Estimated: `109992 + r * (109992 ±0)` - // Minimum execution time: 47_243_000 picoseconds. - Weight::from_parts(50_023_534, 109992) - // Standard Error: 228_993 - .saturating_add(Weight::from_parts(43_173_465, 0).saturating_mul(r.into())) + // Minimum execution time: 61_383_000 picoseconds. + Weight::from_parts(70_695_789, 109992) + // Standard Error: 457_836 + .saturating_add(Weight::from_parts(44_163_910, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -181,10 +181,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `472 + r * (1377 ±0)` // Estimated: `109992 + r * (109992 ±0)` - // Minimum execution time: 23_529_000 picoseconds. - Weight::from_parts(25_071_526, 109992) - // Standard Error: 138_190 - .saturating_add(Weight::from_parts(40_350_973, 0).saturating_mul(r.into())) + // Minimum execution time: 33_466_000 picoseconds. + Weight::from_parts(39_261_420, 109992) + // Standard Error: 358_545 + .saturating_add(Weight::from_parts(43_197_579, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -203,8 +203,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `11800` // Estimated: `30706` - // Minimum execution time: 69_473_000 picoseconds. - Weight::from_parts(71_519_000, 30706) + // Minimum execution time: 87_030_000 picoseconds. + Weight::from_parts(91_851_000, 30706) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -230,8 +230,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `13141` // Estimated: `219984` - // Minimum execution time: 114_422_000 picoseconds. - Weight::from_parts(118_642_000, 219984) + // Minimum execution time: 135_295_000 picoseconds. + Weight::from_parts(142_897_000, 219984) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -253,8 +253,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `20283` // Estimated: `219984` - // Minimum execution time: 290_934_000 picoseconds. - Weight::from_parts(303_286_000, 219984) + // Minimum execution time: 324_485_000 picoseconds. + Weight::from_parts(337_467_000, 219984) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -270,8 +270,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `20035` // Estimated: `219984` - // Minimum execution time: 277_464_000 picoseconds. - Weight::from_parts(284_288_000, 219984) + // Minimum execution time: 302_574_000 picoseconds. + Weight::from_parts(315_016_000, 219984) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -283,8 +283,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `12742` // Estimated: `30706` - // Minimum execution time: 54_538_000 picoseconds. - Weight::from_parts(55_758_000, 30706) + // Minimum execution time: 65_548_000 picoseconds. + Weight::from_parts(71_499_000, 30706) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -307,10 +307,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `306 + r * (1628 ±0)` // Estimated: `109992 + r * (109992 ±0)` - // Minimum execution time: 47_243_000 picoseconds. - Weight::from_parts(50_023_534, 109992) - // Standard Error: 228_993 - .saturating_add(Weight::from_parts(43_173_465, 0).saturating_mul(r.into())) + // Minimum execution time: 61_383_000 picoseconds. + Weight::from_parts(70_695_789, 109992) + // Standard Error: 457_836 + .saturating_add(Weight::from_parts(44_163_910, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -330,10 +330,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `472 + r * (1377 ±0)` // Estimated: `109992 + r * (109992 ±0)` - // Minimum execution time: 23_529_000 picoseconds. - Weight::from_parts(25_071_526, 109992) - // Standard Error: 138_190 - .saturating_add(Weight::from_parts(40_350_973, 0).saturating_mul(r.into())) + // Minimum execution time: 33_466_000 picoseconds. + Weight::from_parts(39_261_420, 109992) + // Standard Error: 358_545 + .saturating_add(Weight::from_parts(43_197_579, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -352,8 +352,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `11800` // Estimated: `30706` - // Minimum execution time: 69_473_000 picoseconds. - Weight::from_parts(71_519_000, 30706) + // Minimum execution time: 87_030_000 picoseconds. + Weight::from_parts(91_851_000, 30706) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } diff --git a/substrate/frame/core-fellowship/src/weights.rs b/substrate/frame/core-fellowship/src/weights.rs index 5e64600b662b..9bca8cb56094 100644 --- a/substrate/frame/core-fellowship/src/weights.rs +++ b/substrate/frame/core-fellowship/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_core_fellowship` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-x5tnzzy-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_core_fellowship +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_core_fellowship -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/core-fellowship/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -72,8 +74,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_772_000 picoseconds. - Weight::from_parts(6_000_000, 0) + // Minimum execution time: 6_652_000 picoseconds. + Weight::from_parts(7_082_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `CoreFellowship::Params` (r:1 w:1) @@ -82,8 +84,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `399` // Estimated: `1853` - // Minimum execution time: 10_050_000 picoseconds. - Weight::from_parts(10_244_000, 1853) + // Minimum execution time: 12_485_000 picoseconds. + Weight::from_parts(12_784_000, 1853) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -105,8 +107,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `17278` // Estimated: `19894` - // Minimum execution time: 54_433_000 picoseconds. - Weight::from_parts(55_650_000, 19894) + // Minimum execution time: 61_243_000 picoseconds. + Weight::from_parts(63_033_000, 19894) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -128,8 +130,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `17388` // Estimated: `19894` - // Minimum execution time: 57_634_000 picoseconds. - Weight::from_parts(58_816_000, 19894) + // Minimum execution time: 65_063_000 picoseconds. + Weight::from_parts(67_047_000, 19894) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -141,8 +143,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `388` // Estimated: `3514` - // Minimum execution time: 14_527_000 picoseconds. - Weight::from_parts(14_948_000, 3514) + // Minimum execution time: 21_924_000 picoseconds. + Weight::from_parts(22_691_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -160,8 +162,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `146` // Estimated: `3514` - // Minimum execution time: 22_137_000 picoseconds. - Weight::from_parts(22_925_000, 3514) + // Minimum execution time: 24_720_000 picoseconds. + Weight::from_parts(25_580_000, 3514) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -183,8 +185,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16931` // Estimated: `19894` - // Minimum execution time: 51_837_000 picoseconds. - Weight::from_parts(52_810_000, 19894) + // Minimum execution time: 58_481_000 picoseconds. + Weight::from_parts(59_510_000, 19894) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -205,10 +207,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16844` // Estimated: `19894 + r * (2489 ±0)` - // Minimum execution time: 45_065_000 picoseconds. - Weight::from_parts(34_090_392, 19894) - // Standard Error: 18_620 - .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + // Minimum execution time: 53_570_000 picoseconds. + Weight::from_parts(42_220_685, 19894) + // Standard Error: 18_061 + .saturating_add(Weight::from_parts(13_858_309, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -225,8 +227,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3514` - // Minimum execution time: 14_321_000 picoseconds. - Weight::from_parts(14_747_000, 3514) + // Minimum execution time: 17_492_000 picoseconds. + Weight::from_parts(18_324_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -238,8 +240,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `313` // Estimated: `3514` - // Minimum execution time: 13_525_000 picoseconds. - Weight::from_parts(13_843_000, 3514) + // Minimum execution time: 16_534_000 picoseconds. + Weight::from_parts(17_046_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -253,8 +255,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16843` // Estimated: `19894` - // Minimum execution time: 34_719_000 picoseconds. - Weight::from_parts(35_162_000, 19894) + // Minimum execution time: 42_264_000 picoseconds. + Weight::from_parts(43_281_000, 19894) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -266,8 +268,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `79` // Estimated: `19894` - // Minimum execution time: 23_477_000 picoseconds. - Weight::from_parts(23_897_000, 19894) + // Minimum execution time: 25_461_000 picoseconds. + Weight::from_parts(26_014_000, 19894) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -281,8 +283,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_772_000 picoseconds. - Weight::from_parts(6_000_000, 0) + // Minimum execution time: 6_652_000 picoseconds. + Weight::from_parts(7_082_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `CoreFellowship::Params` (r:1 w:1) @@ -291,8 +293,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `399` // Estimated: `1853` - // Minimum execution time: 10_050_000 picoseconds. - Weight::from_parts(10_244_000, 1853) + // Minimum execution time: 12_485_000 picoseconds. + Weight::from_parts(12_784_000, 1853) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -314,8 +316,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `17278` // Estimated: `19894` - // Minimum execution time: 54_433_000 picoseconds. - Weight::from_parts(55_650_000, 19894) + // Minimum execution time: 61_243_000 picoseconds. + Weight::from_parts(63_033_000, 19894) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -337,8 +339,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `17388` // Estimated: `19894` - // Minimum execution time: 57_634_000 picoseconds. - Weight::from_parts(58_816_000, 19894) + // Minimum execution time: 65_063_000 picoseconds. + Weight::from_parts(67_047_000, 19894) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -350,8 +352,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `388` // Estimated: `3514` - // Minimum execution time: 14_527_000 picoseconds. - Weight::from_parts(14_948_000, 3514) + // Minimum execution time: 21_924_000 picoseconds. + Weight::from_parts(22_691_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -369,8 +371,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `146` // Estimated: `3514` - // Minimum execution time: 22_137_000 picoseconds. - Weight::from_parts(22_925_000, 3514) + // Minimum execution time: 24_720_000 picoseconds. + Weight::from_parts(25_580_000, 3514) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -392,8 +394,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16931` // Estimated: `19894` - // Minimum execution time: 51_837_000 picoseconds. - Weight::from_parts(52_810_000, 19894) + // Minimum execution time: 58_481_000 picoseconds. + Weight::from_parts(59_510_000, 19894) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -414,10 +416,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16844` // Estimated: `19894 + r * (2489 ±0)` - // Minimum execution time: 45_065_000 picoseconds. - Weight::from_parts(34_090_392, 19894) - // Standard Error: 18_620 - .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + // Minimum execution time: 53_570_000 picoseconds. + Weight::from_parts(42_220_685, 19894) + // Standard Error: 18_061 + .saturating_add(Weight::from_parts(13_858_309, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -434,8 +436,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3514` - // Minimum execution time: 14_321_000 picoseconds. - Weight::from_parts(14_747_000, 3514) + // Minimum execution time: 17_492_000 picoseconds. + Weight::from_parts(18_324_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -447,8 +449,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `313` // Estimated: `3514` - // Minimum execution time: 13_525_000 picoseconds. - Weight::from_parts(13_843_000, 3514) + // Minimum execution time: 16_534_000 picoseconds. + Weight::from_parts(17_046_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -462,8 +464,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16843` // Estimated: `19894` - // Minimum execution time: 34_719_000 picoseconds. - Weight::from_parts(35_162_000, 19894) + // Minimum execution time: 42_264_000 picoseconds. + Weight::from_parts(43_281_000, 19894) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -475,8 +477,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `79` // Estimated: `19894` - // Minimum execution time: 23_477_000 picoseconds. - Weight::from_parts(23_897_000, 19894) + // Minimum execution time: 25_461_000 picoseconds. + Weight::from_parts(26_014_000, 19894) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/democracy/src/weights.rs b/substrate/frame/democracy/src/weights.rs index 6eb82c631a2a..0a2200a78b5d 100644 --- a/substrate/frame/democracy/src/weights.rs +++ b/substrate/frame/democracy/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_democracy` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -96,8 +96,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4834` // Estimated: `18187` - // Minimum execution time: 42_266_000 picoseconds. - Weight::from_parts(43_382_000, 18187) + // Minimum execution time: 48_991_000 picoseconds. + Weight::from_parts(50_476_000, 18187) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -107,8 +107,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3589` // Estimated: `6695` - // Minimum execution time: 37_765_000 picoseconds. - Weight::from_parts(38_679_000, 6695) + // Minimum execution time: 43_129_000 picoseconds. + Weight::from_parts(45_076_000, 6695) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -124,8 +124,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3503` // Estimated: `7260` - // Minimum execution time: 56_200_000 picoseconds. - Weight::from_parts(57_320_000, 7260) + // Minimum execution time: 63_761_000 picoseconds. + Weight::from_parts(65_424_000, 7260) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -141,8 +141,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3525` // Estimated: `7260` - // Minimum execution time: 58_633_000 picoseconds. - Weight::from_parts(60_809_000, 7260) + // Minimum execution time: 66_543_000 picoseconds. + Weight::from_parts(69_537_000, 7260) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -156,8 +156,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `399` // Estimated: `3666` - // Minimum execution time: 23_908_000 picoseconds. - Weight::from_parts(24_659_000, 3666) + // Minimum execution time: 28_934_000 picoseconds. + Weight::from_parts(29_982_000, 3666) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -179,8 +179,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `5943` // Estimated: `18187` - // Minimum execution time: 100_268_000 picoseconds. - Weight::from_parts(101_309_000, 18187) + // Minimum execution time: 108_004_000 picoseconds. + Weight::from_parts(110_779_000, 18187) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -192,8 +192,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3449` // Estimated: `6703` - // Minimum execution time: 12_143_000 picoseconds. - Weight::from_parts(12_843_000, 6703) + // Minimum execution time: 17_630_000 picoseconds. + Weight::from_parts(18_419_000, 6703) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -203,8 +203,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_792_000 picoseconds. - Weight::from_parts(2_922_000, 0) + // Minimum execution time: 2_572_000 picoseconds. + Weight::from_parts(2_810_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) @@ -213,8 +213,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_792_000 picoseconds. - Weight::from_parts(2_953_000, 0) + // Minimum execution time: 2_628_000 picoseconds. + Weight::from_parts(2_724_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) @@ -229,8 +229,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 23_948_000 picoseconds. - Weight::from_parts(24_773_000, 3518) + // Minimum execution time: 24_624_000 picoseconds. + Weight::from_parts(25_518_000, 3518) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -244,8 +244,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3552` // Estimated: `6703` - // Minimum execution time: 27_233_000 picoseconds. - Weight::from_parts(28_327_000, 6703) + // Minimum execution time: 31_786_000 picoseconds. + Weight::from_parts(32_786_000, 6703) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -261,8 +261,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `5854` // Estimated: `18187` - // Minimum execution time: 82_141_000 picoseconds. - Weight::from_parts(83_511_000, 18187) + // Minimum execution time: 87_352_000 picoseconds. + Weight::from_parts(89_670_000, 18187) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -274,8 +274,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `304` // Estimated: `3518` - // Minimum execution time: 16_650_000 picoseconds. - Weight::from_parts(17_140_000, 3518) + // Minimum execution time: 17_561_000 picoseconds. + Weight::from_parts(18_345_000, 3518) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -290,10 +290,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `1489 + r * (2676 ±0)` - // Minimum execution time: 5_308_000 picoseconds. - Weight::from_parts(6_320_667, 1489) - // Standard Error: 6_714 - .saturating_add(Weight::from_parts(3_307_440, 0).saturating_mul(r.into())) + // Minimum execution time: 6_801_000 picoseconds. + Weight::from_parts(8_524_132, 1489) + // Standard Error: 10_028 + .saturating_add(Weight::from_parts(4_073_619, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -316,10 +316,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `18187 + r * (2676 ±0)` - // Minimum execution time: 8_287_000 picoseconds. - Weight::from_parts(7_834_729, 18187) - // Standard Error: 7_499 - .saturating_add(Weight::from_parts(3_333_021, 0).saturating_mul(r.into())) + // Minimum execution time: 10_160_000 picoseconds. + Weight::from_parts(11_472_067, 18187) + // Standard Error: 10_730 + .saturating_add(Weight::from_parts(4_104_654, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -338,10 +338,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `863 + r * (108 ±0)` // Estimated: `19800 + r * (2676 ±0)` - // Minimum execution time: 40_681_000 picoseconds. - Weight::from_parts(46_603_677, 19800) - // Standard Error: 7_453 - .saturating_add(Weight::from_parts(4_269_926, 0).saturating_mul(r.into())) + // Minimum execution time: 49_741_000 picoseconds. + Weight::from_parts(53_544_421, 19800) + // Standard Error: 11_984 + .saturating_add(Weight::from_parts(5_123_946, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -357,10 +357,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `526 + r * (108 ±0)` // Estimated: `13530 + r * (2676 ±0)` - // Minimum execution time: 18_176_000 picoseconds. - Weight::from_parts(19_473_041, 13530) - // Standard Error: 6_046 - .saturating_add(Weight::from_parts(4_259_914, 0).saturating_mul(r.into())) + // Minimum execution time: 24_977_000 picoseconds. + Weight::from_parts(22_449_729, 13530) + // Standard Error: 10_846 + .saturating_add(Weight::from_parts(5_058_209, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -373,8 +373,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_828_000 picoseconds. - Weight::from_parts(2_979_000, 0) + // Minimum execution time: 2_700_000 picoseconds. + Weight::from_parts(3_028_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) @@ -390,10 +390,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `596` // Estimated: `7260` - // Minimum execution time: 24_256_000 picoseconds. - Weight::from_parts(35_489_844, 7260) - // Standard Error: 2_809 - .saturating_add(Weight::from_parts(82_542, 0).saturating_mul(r.into())) + // Minimum execution time: 31_183_000 picoseconds. + Weight::from_parts(43_105_470, 7260) + // Standard Error: 3_096 + .saturating_add(Weight::from_parts(98_571, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -410,10 +410,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `597 + r * (22 ±0)` // Estimated: `7260` - // Minimum execution time: 32_306_000 picoseconds. - Weight::from_parts(35_288_926, 7260) - // Standard Error: 1_742 - .saturating_add(Weight::from_parts(118_566, 0).saturating_mul(r.into())) + // Minimum execution time: 39_672_000 picoseconds. + Weight::from_parts(44_120_387, 7260) + // Standard Error: 1_890 + .saturating_add(Weight::from_parts(130_089, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -426,10 +426,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 15_269_000 picoseconds. - Weight::from_parts(18_595_547, 7260) - // Standard Error: 1_952 - .saturating_add(Weight::from_parts(122_967, 0).saturating_mul(r.into())) + // Minimum execution time: 21_396_000 picoseconds. + Weight::from_parts(26_151_983, 7260) + // Standard Error: 2_052 + .saturating_add(Weight::from_parts(131_709, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -442,10 +442,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 15_213_000 picoseconds. - Weight::from_parts(18_870_570, 7260) - // Standard Error: 1_802 - .saturating_add(Weight::from_parts(124_205, 0).saturating_mul(r.into())) + // Minimum execution time: 21_425_000 picoseconds. + Weight::from_parts(26_335_367, 7260) + // Standard Error: 2_170 + .saturating_add(Weight::from_parts(130_502, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -459,10 +459,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_external_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `456` + // Measured: `351` // Estimated: `3556` - // Minimum execution time: 17_827_000 picoseconds. - Weight::from_parts(18_255_000, 3556) + // Minimum execution time: 19_765_000 picoseconds. + Weight::from_parts(20_266_000, 3556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -474,8 +474,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 14_205_000 picoseconds. - Weight::from_parts(14_631_000, 3518) + // Minimum execution time: 16_560_000 picoseconds. + Weight::from_parts(17_277_000, 3518) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -489,10 +489,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_proposal_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `4988` + // Measured: `4883` // Estimated: `18187` - // Minimum execution time: 40_868_000 picoseconds. - Weight::from_parts(41_688_000, 18187) + // Minimum execution time: 47_711_000 picoseconds. + Weight::from_parts(48_669_000, 18187) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -504,8 +504,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4855` // Estimated: `18187` - // Minimum execution time: 36_573_000 picoseconds. - Weight::from_parts(37_017_000, 18187) + // Minimum execution time: 43_809_000 picoseconds. + Weight::from_parts(45_698_000, 18187) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -517,10 +517,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_referendum_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 13_741_000 picoseconds. - Weight::from_parts(14_337_000, 3556) + // Minimum execution time: 14_736_000 picoseconds. + Weight::from_parts(15_191_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -532,8 +532,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `335` // Estimated: `3666` - // Minimum execution time: 16_358_000 picoseconds. - Weight::from_parts(17_157_000, 3666) + // Minimum execution time: 22_803_000 picoseconds. + Weight::from_parts(23_732_000, 3666) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -553,8 +553,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4834` // Estimated: `18187` - // Minimum execution time: 42_266_000 picoseconds. - Weight::from_parts(43_382_000, 18187) + // Minimum execution time: 48_991_000 picoseconds. + Weight::from_parts(50_476_000, 18187) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -564,8 +564,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3589` // Estimated: `6695` - // Minimum execution time: 37_765_000 picoseconds. - Weight::from_parts(38_679_000, 6695) + // Minimum execution time: 43_129_000 picoseconds. + Weight::from_parts(45_076_000, 6695) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -581,8 +581,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3503` // Estimated: `7260` - // Minimum execution time: 56_200_000 picoseconds. - Weight::from_parts(57_320_000, 7260) + // Minimum execution time: 63_761_000 picoseconds. + Weight::from_parts(65_424_000, 7260) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -598,8 +598,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3525` // Estimated: `7260` - // Minimum execution time: 58_633_000 picoseconds. - Weight::from_parts(60_809_000, 7260) + // Minimum execution time: 66_543_000 picoseconds. + Weight::from_parts(69_537_000, 7260) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -613,8 +613,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `399` // Estimated: `3666` - // Minimum execution time: 23_908_000 picoseconds. - Weight::from_parts(24_659_000, 3666) + // Minimum execution time: 28_934_000 picoseconds. + Weight::from_parts(29_982_000, 3666) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -636,8 +636,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `5943` // Estimated: `18187` - // Minimum execution time: 100_268_000 picoseconds. - Weight::from_parts(101_309_000, 18187) + // Minimum execution time: 108_004_000 picoseconds. + Weight::from_parts(110_779_000, 18187) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -649,8 +649,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3449` // Estimated: `6703` - // Minimum execution time: 12_143_000 picoseconds. - Weight::from_parts(12_843_000, 6703) + // Minimum execution time: 17_630_000 picoseconds. + Weight::from_parts(18_419_000, 6703) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -660,8 +660,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_792_000 picoseconds. - Weight::from_parts(2_922_000, 0) + // Minimum execution time: 2_572_000 picoseconds. + Weight::from_parts(2_810_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) @@ -670,8 +670,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_792_000 picoseconds. - Weight::from_parts(2_953_000, 0) + // Minimum execution time: 2_628_000 picoseconds. + Weight::from_parts(2_724_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) @@ -686,8 +686,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 23_948_000 picoseconds. - Weight::from_parts(24_773_000, 3518) + // Minimum execution time: 24_624_000 picoseconds. + Weight::from_parts(25_518_000, 3518) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -701,8 +701,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3552` // Estimated: `6703` - // Minimum execution time: 27_233_000 picoseconds. - Weight::from_parts(28_327_000, 6703) + // Minimum execution time: 31_786_000 picoseconds. + Weight::from_parts(32_786_000, 6703) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -718,8 +718,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `5854` // Estimated: `18187` - // Minimum execution time: 82_141_000 picoseconds. - Weight::from_parts(83_511_000, 18187) + // Minimum execution time: 87_352_000 picoseconds. + Weight::from_parts(89_670_000, 18187) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -731,8 +731,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `304` // Estimated: `3518` - // Minimum execution time: 16_650_000 picoseconds. - Weight::from_parts(17_140_000, 3518) + // Minimum execution time: 17_561_000 picoseconds. + Weight::from_parts(18_345_000, 3518) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -747,10 +747,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `1489 + r * (2676 ±0)` - // Minimum execution time: 5_308_000 picoseconds. - Weight::from_parts(6_320_667, 1489) - // Standard Error: 6_714 - .saturating_add(Weight::from_parts(3_307_440, 0).saturating_mul(r.into())) + // Minimum execution time: 6_801_000 picoseconds. + Weight::from_parts(8_524_132, 1489) + // Standard Error: 10_028 + .saturating_add(Weight::from_parts(4_073_619, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -773,10 +773,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `18187 + r * (2676 ±0)` - // Minimum execution time: 8_287_000 picoseconds. - Weight::from_parts(7_834_729, 18187) - // Standard Error: 7_499 - .saturating_add(Weight::from_parts(3_333_021, 0).saturating_mul(r.into())) + // Minimum execution time: 10_160_000 picoseconds. + Weight::from_parts(11_472_067, 18187) + // Standard Error: 10_730 + .saturating_add(Weight::from_parts(4_104_654, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -795,10 +795,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `863 + r * (108 ±0)` // Estimated: `19800 + r * (2676 ±0)` - // Minimum execution time: 40_681_000 picoseconds. - Weight::from_parts(46_603_677, 19800) - // Standard Error: 7_453 - .saturating_add(Weight::from_parts(4_269_926, 0).saturating_mul(r.into())) + // Minimum execution time: 49_741_000 picoseconds. + Weight::from_parts(53_544_421, 19800) + // Standard Error: 11_984 + .saturating_add(Weight::from_parts(5_123_946, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -814,10 +814,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `526 + r * (108 ±0)` // Estimated: `13530 + r * (2676 ±0)` - // Minimum execution time: 18_176_000 picoseconds. - Weight::from_parts(19_473_041, 13530) - // Standard Error: 6_046 - .saturating_add(Weight::from_parts(4_259_914, 0).saturating_mul(r.into())) + // Minimum execution time: 24_977_000 picoseconds. + Weight::from_parts(22_449_729, 13530) + // Standard Error: 10_846 + .saturating_add(Weight::from_parts(5_058_209, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -830,8 +830,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_828_000 picoseconds. - Weight::from_parts(2_979_000, 0) + // Minimum execution time: 2_700_000 picoseconds. + Weight::from_parts(3_028_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) @@ -847,10 +847,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `596` // Estimated: `7260` - // Minimum execution time: 24_256_000 picoseconds. - Weight::from_parts(35_489_844, 7260) - // Standard Error: 2_809 - .saturating_add(Weight::from_parts(82_542, 0).saturating_mul(r.into())) + // Minimum execution time: 31_183_000 picoseconds. + Weight::from_parts(43_105_470, 7260) + // Standard Error: 3_096 + .saturating_add(Weight::from_parts(98_571, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -867,10 +867,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `597 + r * (22 ±0)` // Estimated: `7260` - // Minimum execution time: 32_306_000 picoseconds. - Weight::from_parts(35_288_926, 7260) - // Standard Error: 1_742 - .saturating_add(Weight::from_parts(118_566, 0).saturating_mul(r.into())) + // Minimum execution time: 39_672_000 picoseconds. + Weight::from_parts(44_120_387, 7260) + // Standard Error: 1_890 + .saturating_add(Weight::from_parts(130_089, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -883,10 +883,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 15_269_000 picoseconds. - Weight::from_parts(18_595_547, 7260) - // Standard Error: 1_952 - .saturating_add(Weight::from_parts(122_967, 0).saturating_mul(r.into())) + // Minimum execution time: 21_396_000 picoseconds. + Weight::from_parts(26_151_983, 7260) + // Standard Error: 2_052 + .saturating_add(Weight::from_parts(131_709, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -899,10 +899,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 15_213_000 picoseconds. - Weight::from_parts(18_870_570, 7260) - // Standard Error: 1_802 - .saturating_add(Weight::from_parts(124_205, 0).saturating_mul(r.into())) + // Minimum execution time: 21_425_000 picoseconds. + Weight::from_parts(26_335_367, 7260) + // Standard Error: 2_170 + .saturating_add(Weight::from_parts(130_502, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -916,10 +916,10 @@ impl WeightInfo for () { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_external_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `456` + // Measured: `351` // Estimated: `3556` - // Minimum execution time: 17_827_000 picoseconds. - Weight::from_parts(18_255_000, 3556) + // Minimum execution time: 19_765_000 picoseconds. + Weight::from_parts(20_266_000, 3556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -931,8 +931,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 14_205_000 picoseconds. - Weight::from_parts(14_631_000, 3518) + // Minimum execution time: 16_560_000 picoseconds. + Weight::from_parts(17_277_000, 3518) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -946,10 +946,10 @@ impl WeightInfo for () { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_proposal_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `4988` + // Measured: `4883` // Estimated: `18187` - // Minimum execution time: 40_868_000 picoseconds. - Weight::from_parts(41_688_000, 18187) + // Minimum execution time: 47_711_000 picoseconds. + Weight::from_parts(48_669_000, 18187) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -961,8 +961,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4855` // Estimated: `18187` - // Minimum execution time: 36_573_000 picoseconds. - Weight::from_parts(37_017_000, 18187) + // Minimum execution time: 43_809_000 picoseconds. + Weight::from_parts(45_698_000, 18187) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -974,10 +974,10 @@ impl WeightInfo for () { /// Proof: `Democracy::MetadataOf` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn set_referendum_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 13_741_000 picoseconds. - Weight::from_parts(14_337_000, 3556) + // Minimum execution time: 14_736_000 picoseconds. + Weight::from_parts(15_191_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -989,8 +989,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `335` // Estimated: `3666` - // Minimum execution time: 16_358_000 picoseconds. - Weight::from_parts(17_157_000, 3666) + // Minimum execution time: 22_803_000 picoseconds. + Weight::from_parts(23_732_000, 3666) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/election-provider-multi-phase/src/weights.rs b/substrate/frame/election-provider-multi-phase/src/weights.rs index 1398ed047784..2569e46e351e 100644 --- a/substrate/frame/election-provider-multi-phase/src/weights.rs +++ b/substrate/frame/election-provider-multi-phase/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_election_provider_multi_phase` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -84,10 +84,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ElectionProviderMultiPhase::CurrentPhase` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn on_initialize_nothing() -> Weight { // Proof Size summary in bytes: - // Measured: `1061` + // Measured: `1094` // Estimated: `3481` - // Minimum execution time: 19_436_000 picoseconds. - Weight::from_parts(20_138_000, 3481) + // Minimum execution time: 27_022_000 picoseconds. + Weight::from_parts(27_654_000, 3481) .saturating_add(T::DbWeight::get().reads(8_u64)) } /// Storage: `ElectionProviderMultiPhase::Round` (r:1 w:0) @@ -98,8 +98,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `148` // Estimated: `1633` - // Minimum execution time: 8_356_000 picoseconds. - Weight::from_parts(8_708_000, 1633) + // Minimum execution time: 9_613_000 picoseconds. + Weight::from_parts(9_845_000, 1633) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -111,8 +111,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `148` // Estimated: `1633` - // Minimum execution time: 9_088_000 picoseconds. - Weight::from_parts(9_382_000, 1633) + // Minimum execution time: 10_404_000 picoseconds. + Weight::from_parts(10_847_000, 1633) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -124,8 +124,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 25_899_000 picoseconds. - Weight::from_parts(26_456_000, 3593) + // Minimum execution time: 26_673_000 picoseconds. + Weight::from_parts(27_349_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -135,8 +135,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 17_671_000 picoseconds. - Weight::from_parts(18_131_000, 3593) + // Minimum execution time: 19_544_000 picoseconds. + Weight::from_parts(19_818_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -152,10 +152,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 251_900_000 picoseconds. - Weight::from_parts(257_174_000, 0) - // Standard Error: 1_606 - .saturating_add(Weight::from_parts(250_961, 0).saturating_mul(v.into())) + // Minimum execution time: 485_154_000 picoseconds. + Weight::from_parts(498_991_000, 0) + // Standard Error: 3_249 + .saturating_add(Weight::from_parts(337_425, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `ElectionProviderMultiPhase::SignedSubmissionIndices` (r:1 w:1) @@ -182,12 +182,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `371 + a * (768 ±0) + d * (48 ±0)` // Estimated: `3923 + a * (768 ±0) + d * (49 ±0)` - // Minimum execution time: 331_717_000 picoseconds. - Weight::from_parts(29_922_189, 3923) - // Standard Error: 9_972 - .saturating_add(Weight::from_parts(570_967, 0).saturating_mul(a.into())) - // Standard Error: 14_948 - .saturating_add(Weight::from_parts(159_043, 0).saturating_mul(d.into())) + // Minimum execution time: 352_979_000 picoseconds. + Weight::from_parts(383_783_000, 3923) + // Standard Error: 6_259 + .saturating_add(Weight::from_parts(426_032, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(8_u64)) .saturating_add(Weight::from_parts(0, 768).saturating_mul(a.into())) @@ -203,17 +201,15 @@ impl WeightInfo for SubstrateWeight { /// Proof: `ElectionProviderMultiPhase::SignedSubmissionIndices` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `ElectionProviderMultiPhase::SignedSubmissionNextIndex` (r:1 w:1) /// Proof: `ElectionProviderMultiPhase::SignedSubmissionNextIndex` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `ElectionProviderMultiPhase::SignedSubmissionsMap` (r:0 w:1) /// Proof: `ElectionProviderMultiPhase::SignedSubmissionsMap` (`max_values`: None, `max_size`: None, mode: `Measured`) fn submit() -> Weight { // Proof Size summary in bytes: - // Measured: `927` - // Estimated: `2412` - // Minimum execution time: 44_129_000 picoseconds. - Weight::from_parts(46_420_000, 2412) - .saturating_add(T::DbWeight::get().reads(6_u64)) + // Measured: `860` + // Estimated: `2345` + // Minimum execution time: 50_191_000 picoseconds. + Weight::from_parts(51_531_000, 2345) + .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `ElectionProviderMultiPhase::CurrentPhase` (r:1 w:0) @@ -238,12 +234,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `253 + t * (32 ±0) + v * (553 ±0)` // Estimated: `1738 + t * (32 ±0) + v * (553 ±0)` - // Minimum execution time: 5_585_830_000 picoseconds. - Weight::from_parts(5_662_741_000, 1738) - // Standard Error: 17_454 - .saturating_add(Weight::from_parts(352_514, 0).saturating_mul(v.into())) - // Standard Error: 51_723 - .saturating_add(Weight::from_parts(4_182_087, 0).saturating_mul(a.into())) + // Minimum execution time: 5_946_406_000 picoseconds. + Weight::from_parts(6_087_882_000, 1738) + // Standard Error: 20_145 + .saturating_add(Weight::from_parts(348_338, 0).saturating_mul(v.into())) + // Standard Error: 59_699 + .saturating_add(Weight::from_parts(4_596_494, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(t.into())) @@ -265,12 +261,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `228 + t * (32 ±0) + v * (553 ±0)` // Estimated: `1713 + t * (32 ±0) + v * (553 ±0)` - // Minimum execution time: 4_902_422_000 picoseconds. - Weight::from_parts(5_001_852_000, 1713) + // Minimum execution time: 5_004_146_000 picoseconds. + Weight::from_parts(5_166_030_000, 1713) // Standard Error: 15_536 - .saturating_add(Weight::from_parts(354_309, 0).saturating_mul(v.into())) - // Standard Error: 46_041 - .saturating_add(Weight::from_parts(3_090_094, 0).saturating_mul(a.into())) + .saturating_add(Weight::from_parts(306_715, 0).saturating_mul(v.into())) + // Standard Error: 46_039 + .saturating_add(Weight::from_parts(3_418_885, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(t.into())) .saturating_add(Weight::from_parts(0, 553).saturating_mul(v.into())) @@ -297,10 +293,10 @@ impl WeightInfo for () { /// Proof: `ElectionProviderMultiPhase::CurrentPhase` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn on_initialize_nothing() -> Weight { // Proof Size summary in bytes: - // Measured: `1061` + // Measured: `1094` // Estimated: `3481` - // Minimum execution time: 19_436_000 picoseconds. - Weight::from_parts(20_138_000, 3481) + // Minimum execution time: 27_022_000 picoseconds. + Weight::from_parts(27_654_000, 3481) .saturating_add(RocksDbWeight::get().reads(8_u64)) } /// Storage: `ElectionProviderMultiPhase::Round` (r:1 w:0) @@ -311,8 +307,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `148` // Estimated: `1633` - // Minimum execution time: 8_356_000 picoseconds. - Weight::from_parts(8_708_000, 1633) + // Minimum execution time: 9_613_000 picoseconds. + Weight::from_parts(9_845_000, 1633) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -324,8 +320,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `148` // Estimated: `1633` - // Minimum execution time: 9_088_000 picoseconds. - Weight::from_parts(9_382_000, 1633) + // Minimum execution time: 10_404_000 picoseconds. + Weight::from_parts(10_847_000, 1633) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -337,8 +333,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 25_899_000 picoseconds. - Weight::from_parts(26_456_000, 3593) + // Minimum execution time: 26_673_000 picoseconds. + Weight::from_parts(27_349_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -348,8 +344,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `174` // Estimated: `3593` - // Minimum execution time: 17_671_000 picoseconds. - Weight::from_parts(18_131_000, 3593) + // Minimum execution time: 19_544_000 picoseconds. + Weight::from_parts(19_818_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -365,10 +361,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 251_900_000 picoseconds. - Weight::from_parts(257_174_000, 0) - // Standard Error: 1_606 - .saturating_add(Weight::from_parts(250_961, 0).saturating_mul(v.into())) + // Minimum execution time: 485_154_000 picoseconds. + Weight::from_parts(498_991_000, 0) + // Standard Error: 3_249 + .saturating_add(Weight::from_parts(337_425, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `ElectionProviderMultiPhase::SignedSubmissionIndices` (r:1 w:1) @@ -395,12 +391,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `371 + a * (768 ±0) + d * (48 ±0)` // Estimated: `3923 + a * (768 ±0) + d * (49 ±0)` - // Minimum execution time: 331_717_000 picoseconds. - Weight::from_parts(29_922_189, 3923) - // Standard Error: 9_972 - .saturating_add(Weight::from_parts(570_967, 0).saturating_mul(a.into())) - // Standard Error: 14_948 - .saturating_add(Weight::from_parts(159_043, 0).saturating_mul(d.into())) + // Minimum execution time: 352_979_000 picoseconds. + Weight::from_parts(383_783_000, 3923) + // Standard Error: 6_259 + .saturating_add(Weight::from_parts(426_032, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(8_u64)) .saturating_add(Weight::from_parts(0, 768).saturating_mul(a.into())) @@ -416,17 +410,15 @@ impl WeightInfo for () { /// Proof: `ElectionProviderMultiPhase::SignedSubmissionIndices` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `ElectionProviderMultiPhase::SignedSubmissionNextIndex` (r:1 w:1) /// Proof: `ElectionProviderMultiPhase::SignedSubmissionNextIndex` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `ElectionProviderMultiPhase::SignedSubmissionsMap` (r:0 w:1) /// Proof: `ElectionProviderMultiPhase::SignedSubmissionsMap` (`max_values`: None, `max_size`: None, mode: `Measured`) fn submit() -> Weight { // Proof Size summary in bytes: - // Measured: `927` - // Estimated: `2412` - // Minimum execution time: 44_129_000 picoseconds. - Weight::from_parts(46_420_000, 2412) - .saturating_add(RocksDbWeight::get().reads(6_u64)) + // Measured: `860` + // Estimated: `2345` + // Minimum execution time: 50_191_000 picoseconds. + Weight::from_parts(51_531_000, 2345) + .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `ElectionProviderMultiPhase::CurrentPhase` (r:1 w:0) @@ -451,12 +443,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `253 + t * (32 ±0) + v * (553 ±0)` // Estimated: `1738 + t * (32 ±0) + v * (553 ±0)` - // Minimum execution time: 5_585_830_000 picoseconds. - Weight::from_parts(5_662_741_000, 1738) - // Standard Error: 17_454 - .saturating_add(Weight::from_parts(352_514, 0).saturating_mul(v.into())) - // Standard Error: 51_723 - .saturating_add(Weight::from_parts(4_182_087, 0).saturating_mul(a.into())) + // Minimum execution time: 5_946_406_000 picoseconds. + Weight::from_parts(6_087_882_000, 1738) + // Standard Error: 20_145 + .saturating_add(Weight::from_parts(348_338, 0).saturating_mul(v.into())) + // Standard Error: 59_699 + .saturating_add(Weight::from_parts(4_596_494, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(t.into())) @@ -478,12 +470,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `228 + t * (32 ±0) + v * (553 ±0)` // Estimated: `1713 + t * (32 ±0) + v * (553 ±0)` - // Minimum execution time: 4_902_422_000 picoseconds. - Weight::from_parts(5_001_852_000, 1713) + // Minimum execution time: 5_004_146_000 picoseconds. + Weight::from_parts(5_166_030_000, 1713) // Standard Error: 15_536 - .saturating_add(Weight::from_parts(354_309, 0).saturating_mul(v.into())) - // Standard Error: 46_041 - .saturating_add(Weight::from_parts(3_090_094, 0).saturating_mul(a.into())) + .saturating_add(Weight::from_parts(306_715, 0).saturating_mul(v.into())) + // Standard Error: 46_039 + .saturating_add(Weight::from_parts(3_418_885, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(t.into())) .saturating_add(Weight::from_parts(0, 553).saturating_mul(v.into())) diff --git a/substrate/frame/elections-phragmen/src/weights.rs b/substrate/frame/elections-phragmen/src/weights.rs index fb2e10f9f066..f71106a47978 100644 --- a/substrate/frame/elections-phragmen/src/weights.rs +++ b/substrate/frame/elections-phragmen/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_elections_phragmen` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -83,12 +83,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `v` is `[1, 16]`. fn vote_equal(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `403 + v * (80 ±0)` + // Measured: `436 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 30_160_000 picoseconds. - Weight::from_parts(31_473_640, 4764) - // Standard Error: 3_581 - .saturating_add(Weight::from_parts(135_663, 0).saturating_mul(v.into())) + // Minimum execution time: 39_685_000 picoseconds. + Weight::from_parts(40_878_043, 4764) + // Standard Error: 3_272 + .saturating_add(Weight::from_parts(168_519, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -108,12 +108,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `v` is `[2, 16]`. fn vote_more(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `371 + v * (80 ±0)` + // Measured: `404 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 41_429_000 picoseconds. - Weight::from_parts(42_684_714, 4764) - // Standard Error: 4_828 - .saturating_add(Weight::from_parts(173_254, 0).saturating_mul(v.into())) + // Minimum execution time: 51_703_000 picoseconds. + Weight::from_parts(53_305_901, 4764) + // Standard Error: 5_269 + .saturating_add(Weight::from_parts(167_784, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -133,12 +133,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `v` is `[2, 16]`. fn vote_less(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `403 + v * (80 ±0)` + // Measured: `436 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 41_013_000 picoseconds. - Weight::from_parts(42_555_632, 4764) - // Standard Error: 4_627 - .saturating_add(Weight::from_parts(162_225, 0).saturating_mul(v.into())) + // Minimum execution time: 51_554_000 picoseconds. + Weight::from_parts(53_523_254, 4764) + // Standard Error: 5_642 + .saturating_add(Weight::from_parts(156_053, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -151,10 +151,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) fn remove_voter() -> Weight { // Proof Size summary in bytes: - // Measured: `925` + // Measured: `958` // Estimated: `4764` - // Minimum execution time: 43_431_000 picoseconds. - Weight::from_parts(44_500_000, 4764) + // Minimum execution time: 51_835_000 picoseconds. + Weight::from_parts(56_349_000, 4764) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -167,12 +167,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `c` is `[1, 64]`. fn submit_candidacy(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1570 + c * (48 ±0)` - // Estimated: `3055 + c * (48 ±0)` - // Minimum execution time: 34_520_000 picoseconds. - Weight::from_parts(35_911_881, 3055) - // Standard Error: 1_885 - .saturating_add(Weight::from_parts(123_837, 0).saturating_mul(c.into())) + // Measured: `1603 + c * (48 ±0)` + // Estimated: `3088 + c * (48 ±0)` + // Minimum execution time: 40_974_000 picoseconds. + Weight::from_parts(42_358_018, 3088) + // Standard Error: 1_472 + .saturating_add(Weight::from_parts(85_881, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 48).saturating_mul(c.into())) @@ -182,12 +182,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `c` is `[1, 64]`. fn renounce_candidacy_candidate(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `285 + c * (48 ±0)` - // Estimated: `1770 + c * (48 ±0)` - // Minimum execution time: 28_020_000 picoseconds. - Weight::from_parts(29_227_248, 1770) - // Standard Error: 1_202 - .saturating_add(Weight::from_parts(83_328, 0).saturating_mul(c.into())) + // Measured: `318 + c * (48 ±0)` + // Estimated: `1803 + c * (48 ±0)` + // Minimum execution time: 33_286_000 picoseconds. + Weight::from_parts(34_809_065, 1803) + // Standard Error: 1_507 + .saturating_add(Weight::from_parts(67_115, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 48).saturating_mul(c.into())) @@ -204,10 +204,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn renounce_candidacy_members() -> Weight { // Proof Size summary in bytes: - // Measured: `1933` - // Estimated: `3418` - // Minimum execution time: 42_489_000 picoseconds. - Weight::from_parts(43_710_000, 3418) + // Measured: `1999` + // Estimated: `3484` + // Minimum execution time: 49_223_000 picoseconds. + Weight::from_parts(50_790_000, 3484) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -215,10 +215,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Elections::RunnersUp` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn renounce_candidacy_runners_up() -> Weight { // Proof Size summary in bytes: - // Measured: `880` - // Estimated: `2365` - // Minimum execution time: 29_228_000 picoseconds. - Weight::from_parts(30_343_000, 2365) + // Measured: `913` + // Estimated: `2398` + // Minimum execution time: 36_995_000 picoseconds. + Weight::from_parts(37_552_000, 2398) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -245,10 +245,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn remove_member_with_replacement() -> Weight { // Proof Size summary in bytes: - // Measured: `1933` + // Measured: `1999` // Estimated: `3593` - // Minimum execution time: 46_909_000 picoseconds. - Weight::from_parts(47_907_000, 3593) + // Minimum execution time: 54_506_000 picoseconds. + Weight::from_parts(55_765_000, 3593) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -271,13 +271,13 @@ impl WeightInfo for SubstrateWeight { fn clean_defunct_voters(v: u32, d: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + d * (818 ±0) + v * (57 ±0)` - // Estimated: `24906 + d * (3774 ±0) + v * (24 ±0)` - // Minimum execution time: 5_175_000 picoseconds. - Weight::from_parts(5_797_000, 24906) - // Standard Error: 10_951 - .saturating_add(Weight::from_parts(39_675, 0).saturating_mul(v.into())) - // Standard Error: 23_850 - .saturating_add(Weight::from_parts(53_959_224, 0).saturating_mul(d.into())) + // Estimated: `24939 + d * (3774 ±1) + v * (24 ±0)` + // Minimum execution time: 7_043_000 picoseconds. + Weight::from_parts(7_628_000, 24939) + // Standard Error: 17_891 + .saturating_add(Weight::from_parts(357_049, 0).saturating_mul(v.into())) + // Standard Error: 38_964 + .saturating_add(Weight::from_parts(61_698_254, 0).saturating_mul(d.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().reads((4_u64).saturating_mul(d.into()))) .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(d.into()))) @@ -308,13 +308,13 @@ impl WeightInfo for SubstrateWeight { fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + e * (28 ±0) + v * (606 ±0)` - // Estimated: `178920 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` - // Minimum execution time: 1_136_994_000 picoseconds. - Weight::from_parts(1_142_143_000, 178920) - // Standard Error: 595_387 - .saturating_add(Weight::from_parts(19_373_386, 0).saturating_mul(v.into())) - // Standard Error: 38_201 - .saturating_add(Weight::from_parts(797_696, 0).saturating_mul(e.into())) + // Estimated: `179052 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` + // Minimum execution time: 1_343_974_000 picoseconds. + Weight::from_parts(1_352_233_000, 179052) + // Standard Error: 597_762 + .saturating_add(Weight::from_parts(20_404_086, 0).saturating_mul(v.into())) + // Standard Error: 38_353 + .saturating_add(Weight::from_parts(793_851, 0).saturating_mul(e.into())) .saturating_add(T::DbWeight::get().reads(21_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(v.into()))) @@ -343,12 +343,12 @@ impl WeightInfo for () { /// The range of component `v` is `[1, 16]`. fn vote_equal(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `403 + v * (80 ±0)` + // Measured: `436 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 30_160_000 picoseconds. - Weight::from_parts(31_473_640, 4764) - // Standard Error: 3_581 - .saturating_add(Weight::from_parts(135_663, 0).saturating_mul(v.into())) + // Minimum execution time: 39_685_000 picoseconds. + Weight::from_parts(40_878_043, 4764) + // Standard Error: 3_272 + .saturating_add(Weight::from_parts(168_519, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -368,12 +368,12 @@ impl WeightInfo for () { /// The range of component `v` is `[2, 16]`. fn vote_more(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `371 + v * (80 ±0)` + // Measured: `404 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 41_429_000 picoseconds. - Weight::from_parts(42_684_714, 4764) - // Standard Error: 4_828 - .saturating_add(Weight::from_parts(173_254, 0).saturating_mul(v.into())) + // Minimum execution time: 51_703_000 picoseconds. + Weight::from_parts(53_305_901, 4764) + // Standard Error: 5_269 + .saturating_add(Weight::from_parts(167_784, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -393,12 +393,12 @@ impl WeightInfo for () { /// The range of component `v` is `[2, 16]`. fn vote_less(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `403 + v * (80 ±0)` + // Measured: `436 + v * (80 ±0)` // Estimated: `4764 + v * (80 ±0)` - // Minimum execution time: 41_013_000 picoseconds. - Weight::from_parts(42_555_632, 4764) - // Standard Error: 4_627 - .saturating_add(Weight::from_parts(162_225, 0).saturating_mul(v.into())) + // Minimum execution time: 51_554_000 picoseconds. + Weight::from_parts(53_523_254, 4764) + // Standard Error: 5_642 + .saturating_add(Weight::from_parts(156_053, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 80).saturating_mul(v.into())) @@ -411,10 +411,10 @@ impl WeightInfo for () { /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) fn remove_voter() -> Weight { // Proof Size summary in bytes: - // Measured: `925` + // Measured: `958` // Estimated: `4764` - // Minimum execution time: 43_431_000 picoseconds. - Weight::from_parts(44_500_000, 4764) + // Minimum execution time: 51_835_000 picoseconds. + Weight::from_parts(56_349_000, 4764) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -427,12 +427,12 @@ impl WeightInfo for () { /// The range of component `c` is `[1, 64]`. fn submit_candidacy(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1570 + c * (48 ±0)` - // Estimated: `3055 + c * (48 ±0)` - // Minimum execution time: 34_520_000 picoseconds. - Weight::from_parts(35_911_881, 3055) - // Standard Error: 1_885 - .saturating_add(Weight::from_parts(123_837, 0).saturating_mul(c.into())) + // Measured: `1603 + c * (48 ±0)` + // Estimated: `3088 + c * (48 ±0)` + // Minimum execution time: 40_974_000 picoseconds. + Weight::from_parts(42_358_018, 3088) + // Standard Error: 1_472 + .saturating_add(Weight::from_parts(85_881, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 48).saturating_mul(c.into())) @@ -442,12 +442,12 @@ impl WeightInfo for () { /// The range of component `c` is `[1, 64]`. fn renounce_candidacy_candidate(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `285 + c * (48 ±0)` - // Estimated: `1770 + c * (48 ±0)` - // Minimum execution time: 28_020_000 picoseconds. - Weight::from_parts(29_227_248, 1770) - // Standard Error: 1_202 - .saturating_add(Weight::from_parts(83_328, 0).saturating_mul(c.into())) + // Measured: `318 + c * (48 ±0)` + // Estimated: `1803 + c * (48 ±0)` + // Minimum execution time: 33_286_000 picoseconds. + Weight::from_parts(34_809_065, 1803) + // Standard Error: 1_507 + .saturating_add(Weight::from_parts(67_115, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 48).saturating_mul(c.into())) @@ -464,10 +464,10 @@ impl WeightInfo for () { /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn renounce_candidacy_members() -> Weight { // Proof Size summary in bytes: - // Measured: `1933` - // Estimated: `3418` - // Minimum execution time: 42_489_000 picoseconds. - Weight::from_parts(43_710_000, 3418) + // Measured: `1999` + // Estimated: `3484` + // Minimum execution time: 49_223_000 picoseconds. + Weight::from_parts(50_790_000, 3484) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -475,10 +475,10 @@ impl WeightInfo for () { /// Proof: `Elections::RunnersUp` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn renounce_candidacy_runners_up() -> Weight { // Proof Size summary in bytes: - // Measured: `880` - // Estimated: `2365` - // Minimum execution time: 29_228_000 picoseconds. - Weight::from_parts(30_343_000, 2365) + // Measured: `913` + // Estimated: `2398` + // Minimum execution time: 36_995_000 picoseconds. + Weight::from_parts(37_552_000, 2398) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -505,10 +505,10 @@ impl WeightInfo for () { /// Proof: `Council::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn remove_member_with_replacement() -> Weight { // Proof Size summary in bytes: - // Measured: `1933` + // Measured: `1999` // Estimated: `3593` - // Minimum execution time: 46_909_000 picoseconds. - Weight::from_parts(47_907_000, 3593) + // Minimum execution time: 54_506_000 picoseconds. + Weight::from_parts(55_765_000, 3593) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -531,13 +531,13 @@ impl WeightInfo for () { fn clean_defunct_voters(v: u32, d: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + d * (818 ±0) + v * (57 ±0)` - // Estimated: `24906 + d * (3774 ±0) + v * (24 ±0)` - // Minimum execution time: 5_175_000 picoseconds. - Weight::from_parts(5_797_000, 24906) - // Standard Error: 10_951 - .saturating_add(Weight::from_parts(39_675, 0).saturating_mul(v.into())) - // Standard Error: 23_850 - .saturating_add(Weight::from_parts(53_959_224, 0).saturating_mul(d.into())) + // Estimated: `24939 + d * (3774 ±1) + v * (24 ±0)` + // Minimum execution time: 7_043_000 picoseconds. + Weight::from_parts(7_628_000, 24939) + // Standard Error: 17_891 + .saturating_add(Weight::from_parts(357_049, 0).saturating_mul(v.into())) + // Standard Error: 38_964 + .saturating_add(Weight::from_parts(61_698_254, 0).saturating_mul(d.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().reads((4_u64).saturating_mul(d.into()))) .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(d.into()))) @@ -568,13 +568,13 @@ impl WeightInfo for () { fn election_phragmen(c: u32, v: u32, e: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + e * (28 ±0) + v * (606 ±0)` - // Estimated: `178920 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` - // Minimum execution time: 1_136_994_000 picoseconds. - Weight::from_parts(1_142_143_000, 178920) - // Standard Error: 595_387 - .saturating_add(Weight::from_parts(19_373_386, 0).saturating_mul(v.into())) - // Standard Error: 38_201 - .saturating_add(Weight::from_parts(797_696, 0).saturating_mul(e.into())) + // Estimated: `179052 + c * (2135 ±7) + e * (12 ±0) + v * (2653 ±6)` + // Minimum execution time: 1_343_974_000 picoseconds. + Weight::from_parts(1_352_233_000, 179052) + // Standard Error: 597_762 + .saturating_add(Weight::from_parts(20_404_086, 0).saturating_mul(v.into())) + // Standard Error: 38_353 + .saturating_add(Weight::from_parts(793_851, 0).saturating_mul(e.into())) .saturating_add(RocksDbWeight::get().reads(21_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(v.into()))) diff --git a/substrate/frame/examples/authorization-tx-extension/src/tests.rs b/substrate/frame/examples/authorization-tx-extension/src/tests.rs index 7ede549a2f13..8ca35c099556 100644 --- a/substrate/frame/examples/authorization-tx-extension/src/tests.rs +++ b/substrate/frame/examples/authorization-tx-extension/src/tests.rs @@ -26,6 +26,7 @@ use frame_support::{ use pallet_verify_signature::VerifySignature; use sp_keyring::AccountKeyring; use sp_runtime::{ + generic::ExtensionVersion, traits::{Applyable, Checkable, IdentityLookup, TransactionExtension}, MultiSignature, MultiSigner, }; @@ -40,6 +41,7 @@ fn create_asset_works() { // Simple call to create asset with Id `42`. let create_asset_call = RuntimeCall::Assets(pallet_assets::Call::create_asset { asset_id: 42 }); + let ext_version: ExtensionVersion = 0; // Create extension that will be used for dispatch. let initial_nonce = 23; let tx_ext = ( @@ -52,7 +54,7 @@ fn create_asset_works() { // Create the transaction signature, to be used in the top level `VerifyMultiSignature` // extension. let tx_sign = MultiSignature::Sr25519( - (&create_asset_call, &tx_ext, tx_ext.implicit().unwrap()) + (&(ext_version, &create_asset_call), &tx_ext, tx_ext.implicit().unwrap()) .using_encoded(|e| alice_keyring.sign(&sp_io::hashing::blake2_256(e))), ); // Add the signature to the extension. @@ -106,6 +108,7 @@ fn create_coowned_asset_works() { // Simple call to create asset with Id `42`. let create_asset_call = RuntimeCall::Assets(pallet_assets::Call::create_asset { asset_id: 42 }); + let ext_version: ExtensionVersion = 0; // Create the inner transaction extension, to be signed by our coowners, Alice and Bob. let inner_ext: InnerTxExtension = ( frame_system::CheckGenesis::::new(), @@ -113,7 +116,8 @@ fn create_coowned_asset_works() { frame_system::CheckEra::::from(sp_runtime::generic::Era::immortal()), ); // Create the payload Alice and Bob need to sign. - let inner_payload = (&create_asset_call, &inner_ext, inner_ext.implicit().unwrap()); + let inner_payload = + (&(ext_version, &create_asset_call), &inner_ext, inner_ext.implicit().unwrap()); // Create Alice's signature. let alice_inner_sig = MultiSignature::Sr25519( inner_payload.using_encoded(|e| alice_keyring.sign(&sp_io::hashing::blake2_256(e))), @@ -138,7 +142,7 @@ fn create_coowned_asset_works() { // Create Charlie's transaction signature, to be used in the top level // `VerifyMultiSignature` extension. let tx_sign = MultiSignature::Sr25519( - (&create_asset_call, &tx_ext, tx_ext.implicit().unwrap()) + (&(ext_version, &create_asset_call), &tx_ext, tx_ext.implicit().unwrap()) .using_encoded(|e| charlie_keyring.sign(&sp_io::hashing::blake2_256(e))), ); // Add the signature to the extension. @@ -192,6 +196,7 @@ fn inner_authorization_works() { // Simple call to create asset with Id `42`. let create_asset_call = RuntimeCall::Assets(pallet_assets::Call::create_asset { asset_id: 42 }); + let ext_version: ExtensionVersion = 0; // Create the inner transaction extension, to be signed by our coowners, Alice and Bob. They // are going to sign this transaction as a mortal one. let inner_ext: InnerTxExtension = ( @@ -227,7 +232,7 @@ fn inner_authorization_works() { // Create Charlie's transaction signature, to be used in the top level // `VerifyMultiSignature` extension. let tx_sign = MultiSignature::Sr25519( - (&create_asset_call, &tx_ext, tx_ext.implicit().unwrap()) + (&(ext_version, &create_asset_call), &tx_ext, tx_ext.implicit().unwrap()) .using_encoded(|e| charlie_keyring.sign(&sp_io::hashing::blake2_256(e))), ); // Add the signature to the extension that Charlie signed. diff --git a/substrate/frame/examples/basic/src/tests.rs b/substrate/frame/examples/basic/src/tests.rs index 8008f9264c7b..5ec253ebecf4 100644 --- a/substrate/frame/examples/basic/src/tests.rs +++ b/substrate/frame/examples/basic/src/tests.rs @@ -147,7 +147,7 @@ fn signed_ext_watch_dummy_works() { assert_eq!( WatchDummy::(PhantomData) - .validate_only(Some(1).into(), &call, &info, 150, External) + .validate_only(Some(1).into(), &call, &info, 150, External, 0) .unwrap() .0 .priority, @@ -155,7 +155,7 @@ fn signed_ext_watch_dummy_works() { ); assert_eq!( WatchDummy::(PhantomData) - .validate_only(Some(1).into(), &call, &info, 250, External) + .validate_only(Some(1).into(), &call, &info, 250, External, 0) .unwrap_err(), InvalidTransaction::ExhaustsResources.into(), ); diff --git a/substrate/frame/examples/offchain-worker/src/tests.rs b/substrate/frame/examples/offchain-worker/src/tests.rs index 755beb8b82ec..df5cf02594f6 100644 --- a/substrate/frame/examples/offchain-worker/src/tests.rs +++ b/substrate/frame/examples/offchain-worker/src/tests.rs @@ -240,7 +240,7 @@ fn should_submit_signed_transaction_on_chain() { let tx = pool_state.write().transactions.pop().unwrap(); assert!(pool_state.read().transactions.is_empty()); let tx = Extrinsic::decode(&mut &*tx).unwrap(); - assert!(matches!(tx.preamble, sp_runtime::generic::Preamble::Signed(0, (), 0, (),))); + assert!(matches!(tx.preamble, sp_runtime::generic::Preamble::Signed(0, (), (),))); assert_eq!(tx.function, RuntimeCall::Example(crate::Call::submit_price { price: 15523 })); }); } diff --git a/substrate/frame/fast-unstake/src/weights.rs b/substrate/frame/fast-unstake/src/weights.rs index dc875e93229e..efa2a67ae35d 100644 --- a/substrate/frame/fast-unstake/src/weights.rs +++ b/substrate/frame/fast-unstake/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_fast_unstake` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -79,6 +79,8 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:64 w:64) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Storage: `Staking::VirtualStakers` (r:64 w:64) + /// Proof: `Staking::VirtualStakers` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:64 w:64) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:64 w:0) @@ -94,16 +96,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `b` is `[1, 64]`. fn on_idle_unstake(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1475 + b * (452 ±0)` + // Measured: `1575 + b * (452 ±0)` // Estimated: `7253 + b * (3774 ±0)` - // Minimum execution time: 84_536_000 picoseconds. - Weight::from_parts(41_949_894, 7253) - // Standard Error: 28_494 - .saturating_add(Weight::from_parts(52_945_820, 0).saturating_mul(b.into())) + // Minimum execution time: 99_430_000 picoseconds. + Weight::from_parts(47_845_798, 7253) + // Standard Error: 35_454 + .saturating_add(Weight::from_parts(61_016_013, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().reads((8_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().reads((9_u64).saturating_mul(b.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) - .saturating_add(T::DbWeight::get().writes((5_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes((6_u64).saturating_mul(b.into()))) .saturating_add(Weight::from_parts(0, 3774).saturating_mul(b.into())) } /// Storage: `FastUnstake::ErasToCheckPerBlock` (r:1 w:0) @@ -126,14 +128,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `b` is `[1, 64]`. fn on_idle_check(v: u32, b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1879 + b * (55 ±0) + v * (10055 ±0)` + // Measured: `1912 + b * (55 ±0) + v * (10055 ±0)` // Estimated: `7253 + b * (56 ±0) + v * (12531 ±0)` - // Minimum execution time: 1_745_807_000 picoseconds. - Weight::from_parts(1_757_648_000, 7253) - // Standard Error: 12_994_693 - .saturating_add(Weight::from_parts(416_410_247, 0).saturating_mul(v.into())) - // Standard Error: 51_993_247 - .saturating_add(Weight::from_parts(1_654_551_441, 0).saturating_mul(b.into())) + // Minimum execution time: 1_839_591_000 picoseconds. + Weight::from_parts(1_849_618_000, 7253) + // Standard Error: 13_246_289 + .saturating_add(Weight::from_parts(424_466_486, 0).saturating_mul(v.into())) + // Standard Error: 52_999_911 + .saturating_add(Weight::from_parts(1_664_762_641, 0).saturating_mul(b.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(v.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -164,6 +166,8 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Staking::VirtualStakers` (r:1 w:0) + /// Proof: `Staking::VirtualStakers` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:1 w:1) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) @@ -172,11 +176,11 @@ impl WeightInfo for SubstrateWeight { /// Proof: `FastUnstake::CounterForQueue` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn register_fast_unstake() -> Weight { // Proof Size summary in bytes: - // Measured: `1955` + // Measured: `2020` // Estimated: `7253` - // Minimum execution time: 136_437_000 picoseconds. - Weight::from_parts(138_827_000, 7253) - .saturating_add(T::DbWeight::get().reads(15_u64)) + // Minimum execution time: 151_529_000 picoseconds. + Weight::from_parts(155_498_000, 7253) + .saturating_add(T::DbWeight::get().reads(16_u64)) .saturating_add(T::DbWeight::get().writes(9_u64)) } /// Storage: `FastUnstake::ErasToCheckPerBlock` (r:1 w:0) @@ -193,10 +197,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `FastUnstake::CounterForQueue` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn deregister() -> Weight { // Proof Size summary in bytes: - // Measured: `1350` + // Measured: `1383` // Estimated: `7253` - // Minimum execution time: 45_337_000 picoseconds. - Weight::from_parts(47_359_000, 7253) + // Minimum execution time: 55_859_000 picoseconds. + Weight::from_parts(56_949_000, 7253) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -206,8 +210,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_258_000 picoseconds. - Weight::from_parts(2_406_000, 0) + // Minimum execution time: 2_226_000 picoseconds. + Weight::from_parts(2_356_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } } @@ -232,6 +236,8 @@ impl WeightInfo for () { /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:64 w:64) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Storage: `Staking::VirtualStakers` (r:64 w:64) + /// Proof: `Staking::VirtualStakers` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:64 w:64) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:64 w:0) @@ -247,16 +253,16 @@ impl WeightInfo for () { /// The range of component `b` is `[1, 64]`. fn on_idle_unstake(b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1475 + b * (452 ±0)` + // Measured: `1575 + b * (452 ±0)` // Estimated: `7253 + b * (3774 ±0)` - // Minimum execution time: 84_536_000 picoseconds. - Weight::from_parts(41_949_894, 7253) - // Standard Error: 28_494 - .saturating_add(Weight::from_parts(52_945_820, 0).saturating_mul(b.into())) + // Minimum execution time: 99_430_000 picoseconds. + Weight::from_parts(47_845_798, 7253) + // Standard Error: 35_454 + .saturating_add(Weight::from_parts(61_016_013, 0).saturating_mul(b.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) - .saturating_add(RocksDbWeight::get().reads((8_u64).saturating_mul(b.into()))) + .saturating_add(RocksDbWeight::get().reads((9_u64).saturating_mul(b.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) - .saturating_add(RocksDbWeight::get().writes((5_u64).saturating_mul(b.into()))) + .saturating_add(RocksDbWeight::get().writes((6_u64).saturating_mul(b.into()))) .saturating_add(Weight::from_parts(0, 3774).saturating_mul(b.into())) } /// Storage: `FastUnstake::ErasToCheckPerBlock` (r:1 w:0) @@ -279,14 +285,14 @@ impl WeightInfo for () { /// The range of component `b` is `[1, 64]`. fn on_idle_check(v: u32, b: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1879 + b * (55 ±0) + v * (10055 ±0)` + // Measured: `1912 + b * (55 ±0) + v * (10055 ±0)` // Estimated: `7253 + b * (56 ±0) + v * (12531 ±0)` - // Minimum execution time: 1_745_807_000 picoseconds. - Weight::from_parts(1_757_648_000, 7253) - // Standard Error: 12_994_693 - .saturating_add(Weight::from_parts(416_410_247, 0).saturating_mul(v.into())) - // Standard Error: 51_993_247 - .saturating_add(Weight::from_parts(1_654_551_441, 0).saturating_mul(b.into())) + // Minimum execution time: 1_839_591_000 picoseconds. + Weight::from_parts(1_849_618_000, 7253) + // Standard Error: 13_246_289 + .saturating_add(Weight::from_parts(424_466_486, 0).saturating_mul(v.into())) + // Standard Error: 52_999_911 + .saturating_add(Weight::from_parts(1_664_762_641, 0).saturating_mul(b.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(v.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -317,6 +323,8 @@ impl WeightInfo for () { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Staking::VirtualStakers` (r:1 w:0) + /// Proof: `Staking::VirtualStakers` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:1 w:1) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) @@ -325,11 +333,11 @@ impl WeightInfo for () { /// Proof: `FastUnstake::CounterForQueue` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn register_fast_unstake() -> Weight { // Proof Size summary in bytes: - // Measured: `1955` + // Measured: `2020` // Estimated: `7253` - // Minimum execution time: 136_437_000 picoseconds. - Weight::from_parts(138_827_000, 7253) - .saturating_add(RocksDbWeight::get().reads(15_u64)) + // Minimum execution time: 151_529_000 picoseconds. + Weight::from_parts(155_498_000, 7253) + .saturating_add(RocksDbWeight::get().reads(16_u64)) .saturating_add(RocksDbWeight::get().writes(9_u64)) } /// Storage: `FastUnstake::ErasToCheckPerBlock` (r:1 w:0) @@ -346,10 +354,10 @@ impl WeightInfo for () { /// Proof: `FastUnstake::CounterForQueue` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn deregister() -> Weight { // Proof Size summary in bytes: - // Measured: `1350` + // Measured: `1383` // Estimated: `7253` - // Minimum execution time: 45_337_000 picoseconds. - Weight::from_parts(47_359_000, 7253) + // Minimum execution time: 55_859_000 picoseconds. + Weight::from_parts(56_949_000, 7253) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -359,8 +367,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_258_000 picoseconds. - Weight::from_parts(2_406_000, 0) + // Minimum execution time: 2_226_000 picoseconds. + Weight::from_parts(2_356_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/glutton/src/weights.rs b/substrate/frame/glutton/src/weights.rs index d9e6ebd9d8a9..825ab922408f 100644 --- a/substrate/frame/glutton/src/weights.rs +++ b/substrate/frame/glutton/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_glutton` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -72,12 +72,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[0, 1000]`. fn initialize_pallet_grow(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `86` + // Measured: `113` // Estimated: `1489` - // Minimum execution time: 8_453_000 picoseconds. - Weight::from_parts(5_470_386, 1489) - // Standard Error: 4_723 - .saturating_add(Weight::from_parts(10_418_732, 0).saturating_mul(n.into())) + // Minimum execution time: 9_697_000 picoseconds. + Weight::from_parts(9_901_000, 1489) + // Standard Error: 4_104 + .saturating_add(Weight::from_parts(10_452_607, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -89,12 +89,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[0, 1000]`. fn initialize_pallet_shrink(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `119` + // Measured: `146` // Estimated: `1489` - // Minimum execution time: 8_646_000 picoseconds. - Weight::from_parts(7_948_965, 1489) - // Standard Error: 2_154 - .saturating_add(Weight::from_parts(1_197_352, 0).saturating_mul(n.into())) + // Minimum execution time: 9_630_000 picoseconds. + Weight::from_parts(9_800_000, 1489) + // Standard Error: 1_222 + .saturating_add(Weight::from_parts(1_172_845, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -104,22 +104,22 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 643_000 picoseconds. - Weight::from_parts(4_035_744, 0) - // Standard Error: 14 - .saturating_add(Weight::from_parts(105_406, 0).saturating_mul(i.into())) + // Minimum execution time: 666_000 picoseconds. + Weight::from_parts(1_717_806, 0) + // Standard Error: 8 + .saturating_add(Weight::from_parts(106_571, 0).saturating_mul(i.into())) } /// Storage: `Glutton::TrashData` (r:5000 w:0) /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) /// The range of component `i` is `[0, 5000]`. fn waste_proof_size_some(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `119114 + i * (1022 ±0)` + // Measured: `119141 + i * (1022 ±0)` // Estimated: `990 + i * (3016 ±0)` - // Minimum execution time: 228_000 picoseconds. - Weight::from_parts(62_060_711, 990) - // Standard Error: 5_638 - .saturating_add(Weight::from_parts(5_970_065, 0).saturating_mul(i.into())) + // Minimum execution time: 408_000 picoseconds. + Weight::from_parts(389_107_502, 990) + // Standard Error: 8_027 + .saturating_add(Weight::from_parts(7_091_830, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(Weight::from_parts(0, 3016).saturating_mul(i.into())) } @@ -131,10 +131,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) fn on_idle_high_proof_waste() -> Weight { // Proof Size summary in bytes: - // Measured: `1900497` + // Measured: `1900524` // Estimated: `5239782` - // Minimum execution time: 57_557_511_000 picoseconds. - Weight::from_parts(57_644_868_000, 5239782) + // Minimum execution time: 58_810_751_000 picoseconds. + Weight::from_parts(59_238_169_000, 5239782) .saturating_add(T::DbWeight::get().reads(1739_u64)) } /// Storage: `Glutton::Storage` (r:1 w:0) @@ -145,10 +145,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) fn on_idle_low_proof_waste() -> Weight { // Proof Size summary in bytes: - // Measured: `9547` + // Measured: `9574` // Estimated: `16070` - // Minimum execution time: 101_362_469_000 picoseconds. - Weight::from_parts(101_583_065_000, 16070) + // Minimum execution time: 100_387_946_000 picoseconds. + Weight::from_parts(100_470_819_000, 16070) .saturating_add(T::DbWeight::get().reads(7_u64)) } /// Storage: `Glutton::Storage` (r:1 w:0) @@ -157,10 +157,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) fn empty_on_idle() -> Weight { // Proof Size summary in bytes: - // Measured: `86` + // Measured: `113` // Estimated: `1493` - // Minimum execution time: 5_118_000 picoseconds. - Weight::from_parts(5_320_000, 1493) + // Minimum execution time: 6_587_000 picoseconds. + Weight::from_parts(6_835_000, 1493) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Glutton::Compute` (r:0 w:1) @@ -169,8 +169,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_925_000 picoseconds. - Weight::from_parts(6_193_000, 0) + // Minimum execution time: 5_238_000 picoseconds. + Weight::from_parts(5_466_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Glutton::Storage` (r:0 w:1) @@ -179,8 +179,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_912_000 picoseconds. - Weight::from_parts(6_170_000, 0) + // Minimum execution time: 5_136_000 picoseconds. + Weight::from_parts(5_437_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } } @@ -194,12 +194,12 @@ impl WeightInfo for () { /// The range of component `n` is `[0, 1000]`. fn initialize_pallet_grow(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `86` + // Measured: `113` // Estimated: `1489` - // Minimum execution time: 8_453_000 picoseconds. - Weight::from_parts(5_470_386, 1489) - // Standard Error: 4_723 - .saturating_add(Weight::from_parts(10_418_732, 0).saturating_mul(n.into())) + // Minimum execution time: 9_697_000 picoseconds. + Weight::from_parts(9_901_000, 1489) + // Standard Error: 4_104 + .saturating_add(Weight::from_parts(10_452_607, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -211,12 +211,12 @@ impl WeightInfo for () { /// The range of component `n` is `[0, 1000]`. fn initialize_pallet_shrink(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `119` + // Measured: `146` // Estimated: `1489` - // Minimum execution time: 8_646_000 picoseconds. - Weight::from_parts(7_948_965, 1489) - // Standard Error: 2_154 - .saturating_add(Weight::from_parts(1_197_352, 0).saturating_mul(n.into())) + // Minimum execution time: 9_630_000 picoseconds. + Weight::from_parts(9_800_000, 1489) + // Standard Error: 1_222 + .saturating_add(Weight::from_parts(1_172_845, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -226,22 +226,22 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 643_000 picoseconds. - Weight::from_parts(4_035_744, 0) - // Standard Error: 14 - .saturating_add(Weight::from_parts(105_406, 0).saturating_mul(i.into())) + // Minimum execution time: 666_000 picoseconds. + Weight::from_parts(1_717_806, 0) + // Standard Error: 8 + .saturating_add(Weight::from_parts(106_571, 0).saturating_mul(i.into())) } /// Storage: `Glutton::TrashData` (r:5000 w:0) /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) /// The range of component `i` is `[0, 5000]`. fn waste_proof_size_some(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `119114 + i * (1022 ±0)` + // Measured: `119141 + i * (1022 ±0)` // Estimated: `990 + i * (3016 ±0)` - // Minimum execution time: 228_000 picoseconds. - Weight::from_parts(62_060_711, 990) - // Standard Error: 5_638 - .saturating_add(Weight::from_parts(5_970_065, 0).saturating_mul(i.into())) + // Minimum execution time: 408_000 picoseconds. + Weight::from_parts(389_107_502, 990) + // Standard Error: 8_027 + .saturating_add(Weight::from_parts(7_091_830, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(Weight::from_parts(0, 3016).saturating_mul(i.into())) } @@ -253,10 +253,10 @@ impl WeightInfo for () { /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) fn on_idle_high_proof_waste() -> Weight { // Proof Size summary in bytes: - // Measured: `1900497` + // Measured: `1900524` // Estimated: `5239782` - // Minimum execution time: 57_557_511_000 picoseconds. - Weight::from_parts(57_644_868_000, 5239782) + // Minimum execution time: 58_810_751_000 picoseconds. + Weight::from_parts(59_238_169_000, 5239782) .saturating_add(RocksDbWeight::get().reads(1739_u64)) } /// Storage: `Glutton::Storage` (r:1 w:0) @@ -267,10 +267,10 @@ impl WeightInfo for () { /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) fn on_idle_low_proof_waste() -> Weight { // Proof Size summary in bytes: - // Measured: `9547` + // Measured: `9574` // Estimated: `16070` - // Minimum execution time: 101_362_469_000 picoseconds. - Weight::from_parts(101_583_065_000, 16070) + // Minimum execution time: 100_387_946_000 picoseconds. + Weight::from_parts(100_470_819_000, 16070) .saturating_add(RocksDbWeight::get().reads(7_u64)) } /// Storage: `Glutton::Storage` (r:1 w:0) @@ -279,10 +279,10 @@ impl WeightInfo for () { /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) fn empty_on_idle() -> Weight { // Proof Size summary in bytes: - // Measured: `86` + // Measured: `113` // Estimated: `1493` - // Minimum execution time: 5_118_000 picoseconds. - Weight::from_parts(5_320_000, 1493) + // Minimum execution time: 6_587_000 picoseconds. + Weight::from_parts(6_835_000, 1493) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Glutton::Compute` (r:0 w:1) @@ -291,8 +291,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_925_000 picoseconds. - Weight::from_parts(6_193_000, 0) + // Minimum execution time: 5_238_000 picoseconds. + Weight::from_parts(5_466_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Glutton::Storage` (r:0 w:1) @@ -301,8 +301,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_912_000 picoseconds. - Weight::from_parts(6_170_000, 0) + // Minimum execution time: 5_136_000 picoseconds. + Weight::from_parts(5_437_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/identity/src/weights.rs b/substrate/frame/identity/src/weights.rs index a74cca9dc8ec..f1ede9213280 100644 --- a/substrate/frame/identity/src/weights.rs +++ b/substrate/frame/identity/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_identity` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -69,13 +69,13 @@ pub trait WeightInfo { fn quit_sub(s: u32, ) -> Weight; fn add_username_authority() -> Weight; fn remove_username_authority() -> Weight; - fn set_username_for(p: u32) -> Weight; + fn set_username_for(p: u32, ) -> Weight; fn accept_username() -> Weight; - fn remove_expired_approval(p: u32) -> Weight; + fn remove_expired_approval(p: u32, ) -> Weight; fn set_primary_username() -> Weight; fn unbind_username() -> Weight; fn remove_username() -> Weight; - fn kill_username(p: u32) -> Weight; + fn kill_username(p: u32, ) -> Weight; fn migration_v2_authority_step() -> Weight; fn migration_v2_username_step() -> Weight; fn migration_v2_identity_step() -> Weight; @@ -94,29 +94,29 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `32 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 8_696_000 picoseconds. - Weight::from_parts(9_620_793, 2626) - // Standard Error: 1_909 - .saturating_add(Weight::from_parts(94_977, 0).saturating_mul(r.into())) + // Minimum execution time: 9_510_000 picoseconds. + Weight::from_parts(10_180_808, 2626) + // Standard Error: 1_519 + .saturating_add(Weight::from_parts(97_439, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn set_identity(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6978 + r * (5 ±0)` - // Estimated: `11037` - // Minimum execution time: 110_950_000 picoseconds. - Weight::from_parts(112_705_139, 11037) - // Standard Error: 6_475 - .saturating_add(Weight::from_parts(212_737, 0).saturating_mul(r.into())) + // Measured: `6977 + r * (5 ±0)` + // Estimated: `11003` + // Minimum execution time: 121_544_000 picoseconds. + Weight::from_parts(123_405_465, 11003) + // Standard Error: 10_028 + .saturating_add(Weight::from_parts(280_726, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:100 w:100) @@ -125,11 +125,11 @@ impl WeightInfo for SubstrateWeight { fn set_subs_new(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `101` - // Estimated: `11037 + s * (2589 ±0)` - // Minimum execution time: 9_440_000 picoseconds. - Weight::from_parts(23_266_871, 11037) - // Standard Error: 10_640 - .saturating_add(Weight::from_parts(3_663_971, 0).saturating_mul(s.into())) + // Estimated: `11003 + s * (2589 ±0)` + // Minimum execution time: 13_867_000 picoseconds. + Weight::from_parts(26_900_535, 11003) + // Standard Error: 5_334 + .saturating_add(Weight::from_parts(3_798_050, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(s.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -137,7 +137,7 @@ impl WeightInfo for SubstrateWeight { .saturating_add(Weight::from_parts(0, 2589).saturating_mul(s.into())) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) @@ -146,11 +146,11 @@ impl WeightInfo for SubstrateWeight { fn set_subs_old(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `194 + p * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 9_588_000 picoseconds. - Weight::from_parts(22_403_362, 11037) - // Standard Error: 3_359 - .saturating_add(Weight::from_parts(1_557_280, 0).saturating_mul(p.into())) + // Estimated: `11003` + // Minimum execution time: 13_911_000 picoseconds. + Weight::from_parts(31_349_327, 11003) + // Standard Error: 4_045 + .saturating_add(Weight::from_parts(1_503_129, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) @@ -158,21 +158,21 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. /// The range of component `s` is `[0, 100]`. fn clear_identity(r: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7070 + r * (5 ±0) + s * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 55_387_000 picoseconds. - Weight::from_parts(52_575_769, 11037) - // Standard Error: 17_705 - .saturating_add(Weight::from_parts(268_160, 0).saturating_mul(r.into())) - // Standard Error: 3_454 - .saturating_add(Weight::from_parts(1_576_194, 0).saturating_mul(s.into())) + // Measured: `7069 + r * (5 ±0) + s * (32 ±0)` + // Estimated: `11003` + // Minimum execution time: 61_520_000 picoseconds. + Weight::from_parts(63_655_763, 11003) + // Standard Error: 12_100 + .saturating_add(Weight::from_parts(174_203, 0).saturating_mul(r.into())) + // Standard Error: 2_361 + .saturating_add(Weight::from_parts(1_480_283, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -180,30 +180,30 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Identity::Registrars` (r:1 w:0) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn request_judgement(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6968 + r * (57 ±0)` - // Estimated: `11037` - // Minimum execution time: 78_243_000 picoseconds. - Weight::from_parts(80_404_226, 11037) - // Standard Error: 5_153 - .saturating_add(Weight::from_parts(149_799, 0).saturating_mul(r.into())) + // Measured: `6967 + r * (57 ±0)` + // Estimated: `11003` + // Minimum execution time: 85_411_000 picoseconds. + Weight::from_parts(87_137_905, 11003) + // Standard Error: 5_469 + .saturating_add(Weight::from_parts(189_201, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn cancel_request(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6999` - // Estimated: `11037` - // Minimum execution time: 73_360_000 picoseconds. - Weight::from_parts(76_216_374, 11037) - // Standard Error: 15_603 - .saturating_add(Weight::from_parts(189_080, 0).saturating_mul(r.into())) + // Measured: `6998` + // Estimated: `11003` + // Minimum execution time: 83_034_000 picoseconds. + Weight::from_parts(84_688_145, 11003) + // Standard Error: 4_493 + .saturating_add(Weight::from_parts(126_412, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -214,10 +214,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_287_000 picoseconds. - Weight::from_parts(6_721_854, 2626) - // Standard Error: 1_488 - .saturating_add(Weight::from_parts(96_288, 0).saturating_mul(r.into())) + // Minimum execution time: 6_984_000 picoseconds. + Weight::from_parts(7_653_398, 2626) + // Standard Error: 1_328 + .saturating_add(Weight::from_parts(83_290, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -228,10 +228,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_441_000 picoseconds. - Weight::from_parts(6_864_863, 2626) - // Standard Error: 1_403 - .saturating_add(Weight::from_parts(85_123, 0).saturating_mul(r.into())) + // Minimum execution time: 10_608_000 picoseconds. + Weight::from_parts(11_047_553, 2626) + // Standard Error: 1_253 + .saturating_add(Weight::from_parts(76_665, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -242,33 +242,33 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_249_000 picoseconds. - Weight::from_parts(6_658_251, 2626) - // Standard Error: 1_443 - .saturating_add(Weight::from_parts(92_586, 0).saturating_mul(r.into())) + // Minimum execution time: 10_291_000 picoseconds. + Weight::from_parts(10_787_424, 2626) + // Standard Error: 1_267 + .saturating_add(Weight::from_parts(88_833, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::Registrars` (r:1 w:0) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. fn provide_judgement(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7046 + r * (57 ±0)` - // Estimated: `11037` - // Minimum execution time: 97_969_000 picoseconds. - Weight::from_parts(101_366_385, 11037) - // Standard Error: 19_594 - .saturating_add(Weight::from_parts(103_251, 0).saturating_mul(r.into())) + // Measured: `7045 + r * (57 ±0)` + // Estimated: `11003` + // Minimum execution time: 105_178_000 picoseconds. + Weight::from_parts(107_276_823, 11003) + // Standard Error: 7_063 + .saturating_add(Weight::from_parts(149_499, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) @@ -277,20 +277,20 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 100]`. fn kill_identity(r: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7277 + r * (5 ±0) + s * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 73_785_000 picoseconds. - Weight::from_parts(73_606_063, 11037) - // Standard Error: 26_433 - .saturating_add(Weight::from_parts(230_018, 0).saturating_mul(r.into())) - // Standard Error: 5_157 - .saturating_add(Weight::from_parts(1_483_326, 0).saturating_mul(s.into())) + // Measured: `7276 + r * (5 ±0) + s * (32 ±0)` + // Estimated: `11003` + // Minimum execution time: 76_175_000 picoseconds. + Weight::from_parts(77_692_045, 11003) + // Standard Error: 14_176 + .saturating_add(Weight::from_parts(201_431, 0).saturating_mul(r.into())) + // Standard Error: 2_766 + .saturating_add(Weight::from_parts(1_499_834, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) @@ -299,32 +299,32 @@ impl WeightInfo for SubstrateWeight { fn add_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `475 + s * (36 ±0)` - // Estimated: `11037` - // Minimum execution time: 27_304_000 picoseconds. - Weight::from_parts(31_677_329, 11037) - // Standard Error: 1_388 - .saturating_add(Weight::from_parts(102_193, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 29_756_000 picoseconds. + Weight::from_parts(38_457_195, 11003) + // Standard Error: 2_153 + .saturating_add(Weight::from_parts(114_749, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 100]`. fn rename_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `591 + s * (3 ±0)` - // Estimated: `11037` - // Minimum execution time: 12_925_000 picoseconds. - Weight::from_parts(14_756_477, 11037) - // Standard Error: 646 - .saturating_add(Weight::from_parts(36_734, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 21_627_000 picoseconds. + Weight::from_parts(24_786_470, 11003) + // Standard Error: 837 + .saturating_add(Weight::from_parts(63_553, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) @@ -333,11 +333,11 @@ impl WeightInfo for SubstrateWeight { fn remove_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `638 + s * (35 ±0)` - // Estimated: `11037` - // Minimum execution time: 30_475_000 picoseconds. - Weight::from_parts(33_821_774, 11037) - // Standard Error: 1_012 - .saturating_add(Weight::from_parts(87_704, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 37_768_000 picoseconds. + Weight::from_parts(41_759_997, 11003) + // Standard Error: 1_157 + .saturating_add(Weight::from_parts(97_679, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -352,116 +352,225 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `704 + s * (37 ±0)` // Estimated: `6723` - // Minimum execution time: 22_841_000 picoseconds. - Weight::from_parts(25_781_412, 6723) - // Standard Error: 1_145 - .saturating_add(Weight::from_parts(84_692, 0).saturating_mul(s.into())) + // Minimum execution time: 29_539_000 picoseconds. + Weight::from_parts(31_966_337, 6723) + // Standard Error: 1_076 + .saturating_add(Weight::from_parts(94_311, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:0 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:0 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn add_username_authority() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_983_000 picoseconds. - Weight::from_parts(7_388_000, 0) + // Minimum execution time: 6_783_000 picoseconds. + Weight::from_parts(7_098_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:1 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn remove_username_authority() -> Weight { // Proof Size summary in bytes: - // Measured: `80` + // Measured: `79` // Estimated: `3517` - // Minimum execution time: 9_717_000 picoseconds. - Weight::from_parts(10_322_000, 3517) + // Minimum execution time: 10_772_000 picoseconds. + Weight::from_parts(11_136_000, 3517) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:1 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Identity::AccountOfUsername` (r:1 w:1) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) /// Storage: `Identity::PendingUsernames` (r:1 w:0) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) - fn set_username_for(_p: u32) -> Weight { + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn set_username_for(_p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `80` - // Estimated: `11037` - // Minimum execution time: 70_714_000 picoseconds. - Weight::from_parts(74_990_000, 11037) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Measured: `181` + // Estimated: `3593` + // Minimum execution time: 68_832_000 picoseconds. + Weight::from_parts(91_310_781, 3593) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) } /// Storage: `Identity::PendingUsernames` (r:1 w:1) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) - /// Storage: `Identity::AccountOfUsername` (r:0 w:1) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:0 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) fn accept_username() -> Weight { // Proof Size summary in bytes: - // Measured: `115` - // Estimated: `11037` - // Minimum execution time: 21_996_000 picoseconds. - Weight::from_parts(22_611_000, 11037) + // Measured: `116` + // Estimated: `3567` + // Minimum execution time: 21_196_000 picoseconds. + Weight::from_parts(21_755_000, 3567) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `Identity::PendingUsernames` (r:1 w:1) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - fn remove_expired_approval(_p: u32) -> Weight { + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn remove_expired_approval(_p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `115` - // Estimated: `3550` - // Minimum execution time: 16_880_000 picoseconds. - Weight::from_parts(28_371_000, 3550) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Measured: `309` + // Estimated: `3593` + // Minimum execution time: 19_371_000 picoseconds. + Weight::from_parts(62_390_200, 3593) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } - /// Storage: `Identity::AccountOfUsername` (r:1 w:0) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:0 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn set_primary_username() -> Weight { // Proof Size summary in bytes: - // Measured: `257` - // Estimated: `11037` - // Minimum execution time: 16_771_000 picoseconds. - Weight::from_parts(17_333_000, 11037) - .saturating_add(T::DbWeight::get().reads(2_u64)) + // Measured: `172` + // Estimated: `3563` + // Minimum execution time: 13_890_000 picoseconds. + Weight::from_parts(14_307_000, 3563) + .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UsernameInfoOf` (r:1 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn unbind_username() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `236` + // Estimated: `3563` + // Minimum execution time: 22_126_000 picoseconds. + Weight::from_parts(23_177_000, 3563) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn remove_username() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `297` + // Estimated: `3563` + // Minimum execution time: 27_513_000 picoseconds. + Weight::from_parts(28_389_000, 3563) + .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) } - fn kill_username(_p: u32) -> Weight { - Weight::zero() + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn kill_username(_p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `470` + // Estimated: `3593` + // Minimum execution time: 25_125_000 picoseconds. + Weight::from_parts(55_315_063, 3593) + .saturating_add(T::DbWeight::get().reads(5_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) } + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:2 w:0) + /// Storage: `Identity::AuthorityOf` (r:0 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn migration_v2_authority_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `147` + // Estimated: `6087` + // Minimum execution time: 9_218_000 picoseconds. + Weight::from_parts(9_560_000, 6087) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:2 w:0) + /// Storage: `Identity::UsernameInfoOf` (r:0 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) fn migration_v2_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `159` + // Estimated: `6099` + // Minimum execution time: 9_090_000 picoseconds. + Weight::from_parts(9_456_000, 6099) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: `Identity::IdentityOf` (r:2 w:1) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:0 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn migration_v2_identity_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `7062` + // Estimated: `21016` + // Minimum execution time: 64_909_000 picoseconds. + Weight::from_parts(65_805_000, 21016) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } + /// Storage: `Identity::PendingUsernames` (r:2 w:1) + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) fn migration_v2_pending_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `201` + // Estimated: `6144` + // Minimum execution time: 8_518_000 picoseconds. + Weight::from_parts(8_933_000, 6144) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: `Identity::AuthorityOf` (r:2 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:1 w:1) fn migration_v2_cleanup_authority_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `288` + // Estimated: `6044` + // Minimum execution time: 16_108_000 picoseconds. + Weight::from_parts(16_597_000, 6044) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UsernameInfoOf` (r:2 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:1 w:1) fn migration_v2_cleanup_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `290` + // Estimated: `6136` + // Minimum execution time: 11_336_000 picoseconds. + Weight::from_parts(11_938_000, 6136) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } } @@ -474,29 +583,29 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `32 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 8_696_000 picoseconds. - Weight::from_parts(9_620_793, 2626) - // Standard Error: 1_909 - .saturating_add(Weight::from_parts(94_977, 0).saturating_mul(r.into())) + // Minimum execution time: 9_510_000 picoseconds. + Weight::from_parts(10_180_808, 2626) + // Standard Error: 1_519 + .saturating_add(Weight::from_parts(97_439, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn set_identity(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6978 + r * (5 ±0)` - // Estimated: `11037` - // Minimum execution time: 110_950_000 picoseconds. - Weight::from_parts(112_705_139, 11037) - // Standard Error: 6_475 - .saturating_add(Weight::from_parts(212_737, 0).saturating_mul(r.into())) + // Measured: `6977 + r * (5 ±0)` + // Estimated: `11003` + // Minimum execution time: 121_544_000 picoseconds. + Weight::from_parts(123_405_465, 11003) + // Standard Error: 10_028 + .saturating_add(Weight::from_parts(280_726, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:100 w:100) @@ -505,11 +614,11 @@ impl WeightInfo for () { fn set_subs_new(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `101` - // Estimated: `11037 + s * (2589 ±0)` - // Minimum execution time: 9_440_000 picoseconds. - Weight::from_parts(23_266_871, 11037) - // Standard Error: 10_640 - .saturating_add(Weight::from_parts(3_663_971, 0).saturating_mul(s.into())) + // Estimated: `11003 + s * (2589 ±0)` + // Minimum execution time: 13_867_000 picoseconds. + Weight::from_parts(26_900_535, 11003) + // Standard Error: 5_334 + .saturating_add(Weight::from_parts(3_798_050, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(s.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -517,7 +626,7 @@ impl WeightInfo for () { .saturating_add(Weight::from_parts(0, 2589).saturating_mul(s.into())) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) @@ -526,11 +635,11 @@ impl WeightInfo for () { fn set_subs_old(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `194 + p * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 9_588_000 picoseconds. - Weight::from_parts(22_403_362, 11037) - // Standard Error: 3_359 - .saturating_add(Weight::from_parts(1_557_280, 0).saturating_mul(p.into())) + // Estimated: `11003` + // Minimum execution time: 13_911_000 picoseconds. + Weight::from_parts(31_349_327, 11003) + // Standard Error: 4_045 + .saturating_add(Weight::from_parts(1_503_129, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(p.into()))) @@ -538,21 +647,21 @@ impl WeightInfo for () { /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. /// The range of component `s` is `[0, 100]`. fn clear_identity(r: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7070 + r * (5 ±0) + s * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 55_387_000 picoseconds. - Weight::from_parts(52_575_769, 11037) - // Standard Error: 17_705 - .saturating_add(Weight::from_parts(268_160, 0).saturating_mul(r.into())) - // Standard Error: 3_454 - .saturating_add(Weight::from_parts(1_576_194, 0).saturating_mul(s.into())) + // Measured: `7069 + r * (5 ±0) + s * (32 ±0)` + // Estimated: `11003` + // Minimum execution time: 61_520_000 picoseconds. + Weight::from_parts(63_655_763, 11003) + // Standard Error: 12_100 + .saturating_add(Weight::from_parts(174_203, 0).saturating_mul(r.into())) + // Standard Error: 2_361 + .saturating_add(Weight::from_parts(1_480_283, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -560,30 +669,30 @@ impl WeightInfo for () { /// Storage: `Identity::Registrars` (r:1 w:0) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn request_judgement(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6968 + r * (57 ±0)` - // Estimated: `11037` - // Minimum execution time: 78_243_000 picoseconds. - Weight::from_parts(80_404_226, 11037) - // Standard Error: 5_153 - .saturating_add(Weight::from_parts(149_799, 0).saturating_mul(r.into())) + // Measured: `6967 + r * (57 ±0)` + // Estimated: `11003` + // Minimum execution time: 85_411_000 picoseconds. + Weight::from_parts(87_137_905, 11003) + // Standard Error: 5_469 + .saturating_add(Weight::from_parts(189_201, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 20]`. fn cancel_request(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `6999` - // Estimated: `11037` - // Minimum execution time: 73_360_000 picoseconds. - Weight::from_parts(76_216_374, 11037) - // Standard Error: 15_603 - .saturating_add(Weight::from_parts(189_080, 0).saturating_mul(r.into())) + // Measured: `6998` + // Estimated: `11003` + // Minimum execution time: 83_034_000 picoseconds. + Weight::from_parts(84_688_145, 11003) + // Standard Error: 4_493 + .saturating_add(Weight::from_parts(126_412, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -594,10 +703,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_287_000 picoseconds. - Weight::from_parts(6_721_854, 2626) - // Standard Error: 1_488 - .saturating_add(Weight::from_parts(96_288, 0).saturating_mul(r.into())) + // Minimum execution time: 6_984_000 picoseconds. + Weight::from_parts(7_653_398, 2626) + // Standard Error: 1_328 + .saturating_add(Weight::from_parts(83_290, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -608,10 +717,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_441_000 picoseconds. - Weight::from_parts(6_864_863, 2626) - // Standard Error: 1_403 - .saturating_add(Weight::from_parts(85_123, 0).saturating_mul(r.into())) + // Minimum execution time: 10_608_000 picoseconds. + Weight::from_parts(11_047_553, 2626) + // Standard Error: 1_253 + .saturating_add(Weight::from_parts(76_665, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -622,33 +731,33 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `89 + r * (57 ±0)` // Estimated: `2626` - // Minimum execution time: 6_249_000 picoseconds. - Weight::from_parts(6_658_251, 2626) - // Standard Error: 1_443 - .saturating_add(Weight::from_parts(92_586, 0).saturating_mul(r.into())) + // Minimum execution time: 10_291_000 picoseconds. + Weight::from_parts(10_787_424, 2626) + // Standard Error: 1_267 + .saturating_add(Weight::from_parts(88_833, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::Registrars` (r:1 w:0) /// Proof: `Identity::Registrars` (`max_values`: Some(1), `max_size`: Some(1141), added: 1636, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// The range of component `r` is `[1, 19]`. fn provide_judgement(r: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7046 + r * (57 ±0)` - // Estimated: `11037` - // Minimum execution time: 97_969_000 picoseconds. - Weight::from_parts(101_366_385, 11037) - // Standard Error: 19_594 - .saturating_add(Weight::from_parts(103_251, 0).saturating_mul(r.into())) + // Measured: `7045 + r * (57 ±0)` + // Estimated: `11003` + // Minimum execution time: 105_178_000 picoseconds. + Weight::from_parts(107_276_823, 11003) + // Standard Error: 7_063 + .saturating_add(Weight::from_parts(149_499, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::SubsOf` (r:1 w:1) /// Proof: `Identity::SubsOf` (`max_values`: None, `max_size`: Some(3258), added: 5733, mode: `MaxEncodedLen`) /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:0 w:100) @@ -657,20 +766,20 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 100]`. fn kill_identity(r: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `7277 + r * (5 ±0) + s * (32 ±0)` - // Estimated: `11037` - // Minimum execution time: 73_785_000 picoseconds. - Weight::from_parts(73_606_063, 11037) - // Standard Error: 26_433 - .saturating_add(Weight::from_parts(230_018, 0).saturating_mul(r.into())) - // Standard Error: 5_157 - .saturating_add(Weight::from_parts(1_483_326, 0).saturating_mul(s.into())) + // Measured: `7276 + r * (5 ±0) + s * (32 ±0)` + // Estimated: `11003` + // Minimum execution time: 76_175_000 picoseconds. + Weight::from_parts(77_692_045, 11003) + // Standard Error: 14_176 + .saturating_add(Weight::from_parts(201_431, 0).saturating_mul(r.into())) + // Standard Error: 2_766 + .saturating_add(Weight::from_parts(1_499_834, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(s.into()))) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) @@ -679,32 +788,32 @@ impl WeightInfo for () { fn add_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `475 + s * (36 ±0)` - // Estimated: `11037` - // Minimum execution time: 27_304_000 picoseconds. - Weight::from_parts(31_677_329, 11037) - // Standard Error: 1_388 - .saturating_add(Weight::from_parts(102_193, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 29_756_000 picoseconds. + Weight::from_parts(38_457_195, 11003) + // Standard Error: 2_153 + .saturating_add(Weight::from_parts(114_749, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// The range of component `s` is `[1, 100]`. fn rename_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `591 + s * (3 ±0)` - // Estimated: `11037` - // Minimum execution time: 12_925_000 picoseconds. - Weight::from_parts(14_756_477, 11037) - // Standard Error: 646 - .saturating_add(Weight::from_parts(36_734, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 21_627_000 picoseconds. + Weight::from_parts(24_786_470, 11003) + // Standard Error: 837 + .saturating_add(Weight::from_parts(63_553, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Identity::IdentityOf` (r:1 w:0) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) /// Storage: `Identity::SuperOf` (r:1 w:1) /// Proof: `Identity::SuperOf` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) /// Storage: `Identity::SubsOf` (r:1 w:1) @@ -713,11 +822,11 @@ impl WeightInfo for () { fn remove_sub(s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `638 + s * (35 ±0)` - // Estimated: `11037` - // Minimum execution time: 30_475_000 picoseconds. - Weight::from_parts(33_821_774, 11037) - // Standard Error: 1_012 - .saturating_add(Weight::from_parts(87_704, 0).saturating_mul(s.into())) + // Estimated: `11003` + // Minimum execution time: 37_768_000 picoseconds. + Weight::from_parts(41_759_997, 11003) + // Standard Error: 1_157 + .saturating_add(Weight::from_parts(97_679, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -732,115 +841,224 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `704 + s * (37 ±0)` // Estimated: `6723` - // Minimum execution time: 22_841_000 picoseconds. - Weight::from_parts(25_781_412, 6723) - // Standard Error: 1_145 - .saturating_add(Weight::from_parts(84_692, 0).saturating_mul(s.into())) + // Minimum execution time: 29_539_000 picoseconds. + Weight::from_parts(31_966_337, 6723) + // Standard Error: 1_076 + .saturating_add(Weight::from_parts(94_311, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:0 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:0 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn add_username_authority() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_983_000 picoseconds. - Weight::from_parts(7_388_000, 0) + // Minimum execution time: 6_783_000 picoseconds. + Weight::from_parts(7_098_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:1 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn remove_username_authority() -> Weight { // Proof Size summary in bytes: - // Measured: `80` + // Measured: `79` // Estimated: `3517` - // Minimum execution time: 9_717_000 picoseconds. - Weight::from_parts(10_322_000, 3517) + // Minimum execution time: 10_772_000 picoseconds. + Weight::from_parts(11_136_000, 3517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: `Identity::UsernameAuthorities` (r:1 w:1) - /// Proof: `Identity::UsernameAuthorities` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) - /// Storage: `Identity::AccountOfUsername` (r:1 w:1) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) /// Storage: `Identity::PendingUsernames` (r:1 w:0) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) - fn set_username_for(_p: u32) -> Weight { + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn set_username_for(_p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `80` - // Estimated: `11037` - // Minimum execution time: 70_714_000 picoseconds. - Weight::from_parts(74_990_000, 11037) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Measured: `181` + // Estimated: `3593` + // Minimum execution time: 68_832_000 picoseconds. + Weight::from_parts(91_310_781, 3593) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) } /// Storage: `Identity::PendingUsernames` (r:1 w:1) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) - /// Storage: `Identity::AccountOfUsername` (r:0 w:1) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:0 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) fn accept_username() -> Weight { // Proof Size summary in bytes: - // Measured: `115` - // Estimated: `11037` - // Minimum execution time: 21_996_000 picoseconds. - Weight::from_parts(22_611_000, 11037) + // Measured: `116` + // Estimated: `3567` + // Minimum execution time: 21_196_000 picoseconds. + Weight::from_parts(21_755_000, 3567) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `Identity::PendingUsernames` (r:1 w:1) - /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(85), added: 2560, mode: `MaxEncodedLen`) - fn remove_expired_approval(_p: u32) -> Weight { + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn remove_expired_approval(_p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `115` - // Estimated: `3550` - // Minimum execution time: 16_880_000 picoseconds. - Weight::from_parts(28_371_000, 3550) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) + // Measured: `309` + // Estimated: `3593` + // Minimum execution time: 19_371_000 picoseconds. + Weight::from_parts(62_390_200, 3593) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } - /// Storage: `Identity::AccountOfUsername` (r:1 w:0) - /// Proof: `Identity::AccountOfUsername` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) - /// Storage: `Identity::IdentityOf` (r:1 w:1) - /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7572), added: 10047, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:0 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn set_primary_username() -> Weight { // Proof Size summary in bytes: - // Measured: `257` - // Estimated: `11037` - // Minimum execution time: 16_771_000 picoseconds. - Weight::from_parts(17_333_000, 11037) - .saturating_add(RocksDbWeight::get().reads(2_u64)) + // Measured: `172` + // Estimated: `3563` + // Minimum execution time: 13_890_000 picoseconds. + Weight::from_parts(14_307_000, 3563) + .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UsernameInfoOf` (r:1 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) fn unbind_username() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `236` + // Estimated: `3563` + // Minimum execution time: 22_126_000 picoseconds. + Weight::from_parts(23_177_000, 3563) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn remove_username() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `297` + // Estimated: `3563` + // Minimum execution time: 27_513_000 picoseconds. + Weight::from_parts(28_389_000, 3563) + .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } - fn kill_username(_p: u32) -> Weight { - Weight::zero() + /// Storage: `Identity::UsernameInfoOf` (r:1 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:1 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Identity::UnbindingUsernames` (r:1 w:1) + /// Proof: `Identity::UnbindingUsernames` (`max_values`: None, `max_size`: Some(53), added: 2528, mode: `MaxEncodedLen`) + /// Storage: `Identity::AuthorityOf` (r:1 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 1]`. + fn kill_username(_p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `470` + // Estimated: `3593` + // Minimum execution time: 25_125_000 picoseconds. + Weight::from_parts(55_315_063, 3593) + .saturating_add(RocksDbWeight::get().reads(5_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) } + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:2 w:0) + /// Storage: `Identity::AuthorityOf` (r:0 w:1) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn migration_v2_authority_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `147` + // Estimated: `6087` + // Minimum execution time: 9_218_000 picoseconds. + Weight::from_parts(9_560_000, 6087) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:2 w:0) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:2 w:0) + /// Storage: `Identity::UsernameInfoOf` (r:0 w:1) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) fn migration_v2_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `159` + // Estimated: `6099` + // Minimum execution time: 9_090_000 picoseconds. + Weight::from_parts(9_456_000, 6099) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `Identity::IdentityOf` (r:2 w:1) + /// Proof: `Identity::IdentityOf` (`max_values`: None, `max_size`: Some(7538), added: 10013, mode: `MaxEncodedLen`) + /// Storage: `Identity::UsernameOf` (r:0 w:1) + /// Proof: `Identity::UsernameOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn migration_v2_identity_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `7062` + // Estimated: `21016` + // Minimum execution time: 64_909_000 picoseconds. + Weight::from_parts(65_805_000, 21016) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } + /// Storage: `Identity::PendingUsernames` (r:2 w:1) + /// Proof: `Identity::PendingUsernames` (`max_values`: None, `max_size`: Some(102), added: 2577, mode: `MaxEncodedLen`) fn migration_v2_pending_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `201` + // Estimated: `6144` + // Minimum execution time: 8_518_000 picoseconds. + Weight::from_parts(8_933_000, 6144) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `Identity::AuthorityOf` (r:2 w:0) + /// Proof: `Identity::AuthorityOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f99622d1423cdd16f5c33e2b531c34a53d` (r:1 w:1) fn migration_v2_cleanup_authority_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `288` + // Estimated: `6044` + // Minimum execution time: 16_108_000 picoseconds. + Weight::from_parts(16_597_000, 6044) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } + /// Storage: `Identity::UsernameInfoOf` (r:2 w:0) + /// Proof: `Identity::UsernameInfoOf` (`max_values`: None, `max_size`: Some(98), added: 2573, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x2aeddc77fe58c98d50bd37f1b90840f97c182fead9255863460affdd63116be3` (r:1 w:1) fn migration_v2_cleanup_username_step() -> Weight { - Weight::zero() + // Proof Size summary in bytes: + // Measured: `290` + // Estimated: `6136` + // Minimum execution time: 11_336_000 picoseconds. + Weight::from_parts(11_938_000, 6136) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/im-online/src/weights.rs b/substrate/frame/im-online/src/weights.rs index 105a36fb209f..6fde451caf9e 100644 --- a/substrate/frame/im-online/src/weights.rs +++ b/substrate/frame/im-online/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_im_online` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -72,10 +72,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `327 + k * (32 ±0)` // Estimated: `321487 + k * (1761 ±0)` - // Minimum execution time: 64_011_000 picoseconds. - Weight::from_parts(80_632_380, 321487) - // Standard Error: 676 - .saturating_add(Weight::from_parts(34_921, 0).saturating_mul(k.into())) + // Minimum execution time: 70_883_000 picoseconds. + Weight::from_parts(93_034_812, 321487) + // Standard Error: 811 + .saturating_add(Weight::from_parts(37_349, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1761).saturating_mul(k.into())) @@ -99,10 +99,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `327 + k * (32 ±0)` // Estimated: `321487 + k * (1761 ±0)` - // Minimum execution time: 64_011_000 picoseconds. - Weight::from_parts(80_632_380, 321487) - // Standard Error: 676 - .saturating_add(Weight::from_parts(34_921, 0).saturating_mul(k.into())) + // Minimum execution time: 70_883_000 picoseconds. + Weight::from_parts(93_034_812, 321487) + // Standard Error: 811 + .saturating_add(Weight::from_parts(37_349, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1761).saturating_mul(k.into())) diff --git a/substrate/frame/indices/src/weights.rs b/substrate/frame/indices/src/weights.rs index e1bc90c9b128..567e9bab54bd 100644 --- a/substrate/frame/indices/src/weights.rs +++ b/substrate/frame/indices/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_indices` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -67,8 +67,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3534` - // Minimum execution time: 22_026_000 picoseconds. - Weight::from_parts(22_522_000, 3534) + // Minimum execution time: 23_283_000 picoseconds. + Weight::from_parts(24_326_000, 3534) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -78,10 +78,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `275` + // Measured: `312` // Estimated: `3593` - // Minimum execution time: 34_160_000 picoseconds. - Weight::from_parts(35_138_000, 3593) + // Minimum execution time: 40_906_000 picoseconds. + Weight::from_parts(42_117_000, 3593) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -91,8 +91,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `172` // Estimated: `3534` - // Minimum execution time: 23_736_000 picoseconds. - Weight::from_parts(24_247_000, 3534) + // Minimum execution time: 27_419_000 picoseconds. + Weight::from_parts(28_544_000, 3534) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -104,8 +104,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `275` // Estimated: `3593` - // Minimum execution time: 25_810_000 picoseconds. - Weight::from_parts(26_335_000, 3593) + // Minimum execution time: 30_098_000 picoseconds. + Weight::from_parts(31_368_000, 3593) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -115,8 +115,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `172` // Estimated: `3534` - // Minimum execution time: 24_502_000 picoseconds. - Weight::from_parts(25_425_000, 3534) + // Minimum execution time: 30_356_000 picoseconds. + Weight::from_parts(31_036_000, 3534) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -130,8 +130,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3534` - // Minimum execution time: 22_026_000 picoseconds. - Weight::from_parts(22_522_000, 3534) + // Minimum execution time: 23_283_000 picoseconds. + Weight::from_parts(24_326_000, 3534) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -141,10 +141,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `275` + // Measured: `312` // Estimated: `3593` - // Minimum execution time: 34_160_000 picoseconds. - Weight::from_parts(35_138_000, 3593) + // Minimum execution time: 40_906_000 picoseconds. + Weight::from_parts(42_117_000, 3593) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -154,8 +154,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `172` // Estimated: `3534` - // Minimum execution time: 23_736_000 picoseconds. - Weight::from_parts(24_247_000, 3534) + // Minimum execution time: 27_419_000 picoseconds. + Weight::from_parts(28_544_000, 3534) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -167,8 +167,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `275` // Estimated: `3593` - // Minimum execution time: 25_810_000 picoseconds. - Weight::from_parts(26_335_000, 3593) + // Minimum execution time: 30_098_000 picoseconds. + Weight::from_parts(31_368_000, 3593) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -178,8 +178,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `172` // Estimated: `3534` - // Minimum execution time: 24_502_000 picoseconds. - Weight::from_parts(25_425_000, 3534) + // Minimum execution time: 30_356_000 picoseconds. + Weight::from_parts(31_036_000, 3534) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/lottery/src/weights.rs b/substrate/frame/lottery/src/weights.rs index 0ab7f64509cd..cac6136a9ba9 100644 --- a/substrate/frame/lottery/src/weights.rs +++ b/substrate/frame/lottery/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_lottery` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -82,10 +82,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Lottery::Tickets` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn buy_ticket() -> Weight { // Proof Size summary in bytes: - // Measured: `492` + // Measured: `526` // Estimated: `3997` - // Minimum execution time: 60_979_000 picoseconds. - Weight::from_parts(63_452_000, 3997) + // Minimum execution time: 67_624_000 picoseconds. + Weight::from_parts(69_671_000, 3997) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -96,10 +96,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_245_000 picoseconds. - Weight::from_parts(6_113_777, 0) - // Standard Error: 3_280 - .saturating_add(Weight::from_parts(349_366, 0).saturating_mul(n.into())) + // Minimum execution time: 4_828_000 picoseconds. + Weight::from_parts(5_618_456, 0) + // Standard Error: 3_095 + .saturating_add(Weight::from_parts(367_041, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Lottery::Lottery` (r:1 w:1) @@ -110,10 +110,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn start_lottery() -> Weight { // Proof Size summary in bytes: - // Measured: `194` + // Measured: `181` // Estimated: `3593` - // Minimum execution time: 29_131_000 picoseconds. - Weight::from_parts(29_722_000, 3593) + // Minimum execution time: 29_189_000 picoseconds. + Weight::from_parts(29_952_000, 3593) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -123,8 +123,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `252` // Estimated: `1514` - // Minimum execution time: 6_413_000 picoseconds. - Weight::from_parts(6_702_000, 1514) + // Minimum execution time: 7_320_000 picoseconds. + Weight::from_parts(7_805_000, 1514) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -140,10 +140,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Lottery::Tickets` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn on_initialize_end() -> Weight { // Proof Size summary in bytes: - // Measured: `591` + // Measured: `677` // Estimated: `6196` - // Minimum execution time: 65_913_000 picoseconds. - Weight::from_parts(66_864_000, 6196) + // Minimum execution time: 72_030_000 picoseconds. + Weight::from_parts(73_116_000, 6196) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -161,10 +161,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Lottery::LotteryIndex` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn on_initialize_repeat() -> Weight { // Proof Size summary in bytes: - // Measured: `591` + // Measured: `677` // Estimated: `6196` - // Minimum execution time: 66_950_000 picoseconds. - Weight::from_parts(68_405_000, 6196) + // Minimum execution time: 73_263_000 picoseconds. + Weight::from_parts(74_616_000, 6196) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -192,10 +192,10 @@ impl WeightInfo for () { /// Proof: `Lottery::Tickets` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn buy_ticket() -> Weight { // Proof Size summary in bytes: - // Measured: `492` + // Measured: `526` // Estimated: `3997` - // Minimum execution time: 60_979_000 picoseconds. - Weight::from_parts(63_452_000, 3997) + // Minimum execution time: 67_624_000 picoseconds. + Weight::from_parts(69_671_000, 3997) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -206,10 +206,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_245_000 picoseconds. - Weight::from_parts(6_113_777, 0) - // Standard Error: 3_280 - .saturating_add(Weight::from_parts(349_366, 0).saturating_mul(n.into())) + // Minimum execution time: 4_828_000 picoseconds. + Weight::from_parts(5_618_456, 0) + // Standard Error: 3_095 + .saturating_add(Weight::from_parts(367_041, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Lottery::Lottery` (r:1 w:1) @@ -220,10 +220,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn start_lottery() -> Weight { // Proof Size summary in bytes: - // Measured: `194` + // Measured: `181` // Estimated: `3593` - // Minimum execution time: 29_131_000 picoseconds. - Weight::from_parts(29_722_000, 3593) + // Minimum execution time: 29_189_000 picoseconds. + Weight::from_parts(29_952_000, 3593) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -233,8 +233,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `252` // Estimated: `1514` - // Minimum execution time: 6_413_000 picoseconds. - Weight::from_parts(6_702_000, 1514) + // Minimum execution time: 7_320_000 picoseconds. + Weight::from_parts(7_805_000, 1514) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -250,10 +250,10 @@ impl WeightInfo for () { /// Proof: `Lottery::Tickets` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn on_initialize_end() -> Weight { // Proof Size summary in bytes: - // Measured: `591` + // Measured: `677` // Estimated: `6196` - // Minimum execution time: 65_913_000 picoseconds. - Weight::from_parts(66_864_000, 6196) + // Minimum execution time: 72_030_000 picoseconds. + Weight::from_parts(73_116_000, 6196) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -271,10 +271,10 @@ impl WeightInfo for () { /// Proof: `Lottery::LotteryIndex` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn on_initialize_repeat() -> Weight { // Proof Size summary in bytes: - // Measured: `591` + // Measured: `677` // Estimated: `6196` - // Minimum execution time: 66_950_000 picoseconds. - Weight::from_parts(68_405_000, 6196) + // Minimum execution time: 73_263_000 picoseconds. + Weight::from_parts(74_616_000, 6196) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } diff --git a/substrate/frame/membership/src/weights.rs b/substrate/frame/membership/src/weights.rs index 10e9c9afa582..2185319676c5 100644 --- a/substrate/frame/membership/src/weights.rs +++ b/substrate/frame/membership/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_membership` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -76,10 +76,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `207 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 12_827_000 picoseconds. - Weight::from_parts(13_743_651, 4687) - // Standard Error: 622 - .saturating_add(Weight::from_parts(35_417, 0).saturating_mul(m.into())) + // Minimum execution time: 17_738_000 picoseconds. + Weight::from_parts(18_805_035, 4687) + // Standard Error: 796 + .saturating_add(Weight::from_parts(26_172, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -99,10 +99,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_197_000 picoseconds. - Weight::from_parts(16_172_409, 4687) - // Standard Error: 650 - .saturating_add(Weight::from_parts(35_790, 0).saturating_mul(m.into())) + // Minimum execution time: 20_462_000 picoseconds. + Weight::from_parts(21_560_127, 4687) + // Standard Error: 581 + .saturating_add(Weight::from_parts(18_475, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -122,10 +122,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_558_000 picoseconds. - Weight::from_parts(16_370_827, 4687) - // Standard Error: 603 - .saturating_add(Weight::from_parts(45_739, 0).saturating_mul(m.into())) + // Minimum execution time: 20_345_000 picoseconds. + Weight::from_parts(21_400_566, 4687) + // Standard Error: 711 + .saturating_add(Weight::from_parts(39_733, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -145,10 +145,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_086_000 picoseconds. - Weight::from_parts(16_444_101, 4687) - // Standard Error: 967 - .saturating_add(Weight::from_parts(143_947, 0).saturating_mul(m.into())) + // Minimum execution time: 20_149_000 picoseconds. + Weight::from_parts(21_579_056, 4687) + // Standard Error: 693 + .saturating_add(Weight::from_parts(121_676, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -168,10 +168,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 16_146_000 picoseconds. - Weight::from_parts(17_269_755, 4687) - // Standard Error: 660 - .saturating_add(Weight::from_parts(42_082, 0).saturating_mul(m.into())) + // Minimum execution time: 21_033_000 picoseconds. + Weight::from_parts(21_867_983, 4687) + // Standard Error: 1_003 + .saturating_add(Weight::from_parts(44_414, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -187,10 +187,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `31 + m * (32 ±0)` // Estimated: `4687 + m * (32 ±0)` - // Minimum execution time: 5_937_000 picoseconds. - Weight::from_parts(6_501_085, 4687) - // Standard Error: 323 - .saturating_add(Weight::from_parts(18_285, 0).saturating_mul(m.into())) + // Minimum execution time: 6_849_000 picoseconds. + Weight::from_parts(7_199_679, 4687) + // Standard Error: 199 + .saturating_add(Weight::from_parts(9_242, 0).saturating_mul(m.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) @@ -203,8 +203,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_533_000 picoseconds. - Weight::from_parts(2_807_000, 0) + // Minimum execution time: 2_297_000 picoseconds. + Weight::from_parts(2_540_000, 0) .saturating_add(T::DbWeight::get().writes(2_u64)) } } @@ -224,10 +224,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `207 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 12_827_000 picoseconds. - Weight::from_parts(13_743_651, 4687) - // Standard Error: 622 - .saturating_add(Weight::from_parts(35_417, 0).saturating_mul(m.into())) + // Minimum execution time: 17_738_000 picoseconds. + Weight::from_parts(18_805_035, 4687) + // Standard Error: 796 + .saturating_add(Weight::from_parts(26_172, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -247,10 +247,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_197_000 picoseconds. - Weight::from_parts(16_172_409, 4687) - // Standard Error: 650 - .saturating_add(Weight::from_parts(35_790, 0).saturating_mul(m.into())) + // Minimum execution time: 20_462_000 picoseconds. + Weight::from_parts(21_560_127, 4687) + // Standard Error: 581 + .saturating_add(Weight::from_parts(18_475, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -270,10 +270,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_558_000 picoseconds. - Weight::from_parts(16_370_827, 4687) - // Standard Error: 603 - .saturating_add(Weight::from_parts(45_739, 0).saturating_mul(m.into())) + // Minimum execution time: 20_345_000 picoseconds. + Weight::from_parts(21_400_566, 4687) + // Standard Error: 711 + .saturating_add(Weight::from_parts(39_733, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -293,10 +293,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 15_086_000 picoseconds. - Weight::from_parts(16_444_101, 4687) - // Standard Error: 967 - .saturating_add(Weight::from_parts(143_947, 0).saturating_mul(m.into())) + // Minimum execution time: 20_149_000 picoseconds. + Weight::from_parts(21_579_056, 4687) + // Standard Error: 693 + .saturating_add(Weight::from_parts(121_676, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -316,10 +316,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `311 + m * (64 ±0)` // Estimated: `4687 + m * (64 ±0)` - // Minimum execution time: 16_146_000 picoseconds. - Weight::from_parts(17_269_755, 4687) - // Standard Error: 660 - .saturating_add(Weight::from_parts(42_082, 0).saturating_mul(m.into())) + // Minimum execution time: 21_033_000 picoseconds. + Weight::from_parts(21_867_983, 4687) + // Standard Error: 1_003 + .saturating_add(Weight::from_parts(44_414, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) @@ -335,10 +335,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `31 + m * (32 ±0)` // Estimated: `4687 + m * (32 ±0)` - // Minimum execution time: 5_937_000 picoseconds. - Weight::from_parts(6_501_085, 4687) - // Standard Error: 323 - .saturating_add(Weight::from_parts(18_285, 0).saturating_mul(m.into())) + // Minimum execution time: 6_849_000 picoseconds. + Weight::from_parts(7_199_679, 4687) + // Standard Error: 199 + .saturating_add(Weight::from_parts(9_242, 0).saturating_mul(m.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) @@ -351,8 +351,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_533_000 picoseconds. - Weight::from_parts(2_807_000, 0) + // Minimum execution time: 2_297_000 picoseconds. + Weight::from_parts(2_540_000, 0) .saturating_add(RocksDbWeight::get().writes(2_u64)) } } diff --git a/substrate/frame/message-queue/src/weights.rs b/substrate/frame/message-queue/src/weights.rs index 46fd52194bf2..7d36cb755106 100644 --- a/substrate/frame/message-queue/src/weights.rs +++ b/substrate/frame/message-queue/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_message_queue` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -74,8 +74,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `301` // Estimated: `6038` - // Minimum execution time: 11_674_000 picoseconds. - Weight::from_parts(12_105_000, 6038) + // Minimum execution time: 17_093_000 picoseconds. + Weight::from_parts(17_612_000, 6038) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -87,8 +87,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `301` // Estimated: `6038` - // Minimum execution time: 10_262_000 picoseconds. - Weight::from_parts(10_654_000, 6038) + // Minimum execution time: 15_482_000 picoseconds. + Weight::from_parts(16_159_000, 6038) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -98,8 +98,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3514` - // Minimum execution time: 4_363_000 picoseconds. - Weight::from_parts(4_589_000, 3514) + // Minimum execution time: 4_911_000 picoseconds. + Weight::from_parts(5_177_000, 3514) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -109,8 +109,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `147` // Estimated: `69049` - // Minimum execution time: 6_220_000 picoseconds. - Weight::from_parts(6_622_000, 69049) + // Minimum execution time: 7_108_000 picoseconds. + Weight::from_parts(7_477_000, 69049) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -120,8 +120,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `147` // Estimated: `69049` - // Minimum execution time: 6_342_000 picoseconds. - Weight::from_parts(6_727_000, 69049) + // Minimum execution time: 7_435_000 picoseconds. + Weight::from_parts(7_669_000, 69049) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -133,8 +133,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 112_729_000 picoseconds. - Weight::from_parts(114_076_000, 0) + // Minimum execution time: 173_331_000 picoseconds. + Weight::from_parts(174_170_000, 0) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) @@ -145,8 +145,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `246` // Estimated: `3514` - // Minimum execution time: 6_836_000 picoseconds. - Weight::from_parts(6_986_000, 3514) + // Minimum execution time: 11_817_000 picoseconds. + Weight::from_parts(12_351_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -158,8 +158,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 50_733_000 picoseconds. - Weight::from_parts(51_649_000, 69049) + // Minimum execution time: 60_883_000 picoseconds. + Weight::from_parts(62_584_000, 69049) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -171,8 +171,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 67_335_000 picoseconds. - Weight::from_parts(68_347_000, 69049) + // Minimum execution time: 77_569_000 picoseconds. + Weight::from_parts(79_165_000, 69049) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -184,8 +184,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 77_610_000 picoseconds. - Weight::from_parts(80_338_000, 69049) + // Minimum execution time: 120_786_000 picoseconds. + Weight::from_parts(122_457_000, 69049) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -201,8 +201,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `301` // Estimated: `6038` - // Minimum execution time: 11_674_000 picoseconds. - Weight::from_parts(12_105_000, 6038) + // Minimum execution time: 17_093_000 picoseconds. + Weight::from_parts(17_612_000, 6038) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -214,8 +214,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `301` // Estimated: `6038` - // Minimum execution time: 10_262_000 picoseconds. - Weight::from_parts(10_654_000, 6038) + // Minimum execution time: 15_482_000 picoseconds. + Weight::from_parts(16_159_000, 6038) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -225,8 +225,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3514` - // Minimum execution time: 4_363_000 picoseconds. - Weight::from_parts(4_589_000, 3514) + // Minimum execution time: 4_911_000 picoseconds. + Weight::from_parts(5_177_000, 3514) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -236,8 +236,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `147` // Estimated: `69049` - // Minimum execution time: 6_220_000 picoseconds. - Weight::from_parts(6_622_000, 69049) + // Minimum execution time: 7_108_000 picoseconds. + Weight::from_parts(7_477_000, 69049) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -247,8 +247,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `147` // Estimated: `69049` - // Minimum execution time: 6_342_000 picoseconds. - Weight::from_parts(6_727_000, 69049) + // Minimum execution time: 7_435_000 picoseconds. + Weight::from_parts(7_669_000, 69049) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -260,8 +260,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 112_729_000 picoseconds. - Weight::from_parts(114_076_000, 0) + // Minimum execution time: 173_331_000 picoseconds. + Weight::from_parts(174_170_000, 0) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) @@ -272,8 +272,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `246` // Estimated: `3514` - // Minimum execution time: 6_836_000 picoseconds. - Weight::from_parts(6_986_000, 3514) + // Minimum execution time: 11_817_000 picoseconds. + Weight::from_parts(12_351_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -285,8 +285,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 50_733_000 picoseconds. - Weight::from_parts(51_649_000, 69049) + // Minimum execution time: 60_883_000 picoseconds. + Weight::from_parts(62_584_000, 69049) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -298,8 +298,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 67_335_000 picoseconds. - Weight::from_parts(68_347_000, 69049) + // Minimum execution time: 77_569_000 picoseconds. + Weight::from_parts(79_165_000, 69049) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -311,8 +311,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `65744` // Estimated: `69049` - // Minimum execution time: 77_610_000 picoseconds. - Weight::from_parts(80_338_000, 69049) + // Minimum execution time: 120_786_000 picoseconds. + Weight::from_parts(122_457_000, 69049) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/frame/migrations/src/weights.rs b/substrate/frame/migrations/src/weights.rs index 6f5ac9715376..49ae379dba02 100644 --- a/substrate/frame/migrations/src/weights.rs +++ b/substrate/frame/migrations/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_migrations` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -74,10 +74,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) fn onboard_new_mbms() -> Weight { // Proof Size summary in bytes: - // Measured: `276` + // Measured: `309` // Estimated: `67035` - // Minimum execution time: 7_762_000 picoseconds. - Weight::from_parts(8_100_000, 67035) + // Minimum execution time: 9_520_000 picoseconds. + Weight::from_parts(9_934_000, 67035) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -87,8 +87,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `67035` - // Minimum execution time: 2_077_000 picoseconds. - Weight::from_parts(2_138_000, 67035) + // Minimum execution time: 2_993_000 picoseconds. + Weight::from_parts(3_088_000, 67035) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -97,10 +97,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) fn exec_migration_completed() -> Weight { // Proof Size summary in bytes: - // Measured: `134` - // Estimated: `3599` - // Minimum execution time: 5_868_000 picoseconds. - Weight::from_parts(6_143_000, 3599) + // Measured: `167` + // Estimated: `3632` + // Minimum execution time: 7_042_000 picoseconds. + Weight::from_parts(7_272_000, 3632) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -110,10 +110,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_skipped_historic() -> Weight { // Proof Size summary in bytes: - // Measured: `330` - // Estimated: `3795` - // Minimum execution time: 10_283_000 picoseconds. - Weight::from_parts(10_964_000, 3795) + // Measured: `363` + // Estimated: `3828` + // Minimum execution time: 16_522_000 picoseconds. + Weight::from_parts(17_082_000, 3828) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -122,10 +122,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_advance() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 9_900_000 picoseconds. - Weight::from_parts(10_396_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 12_445_000 picoseconds. + Weight::from_parts(12_797_000, 3774) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -134,10 +134,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_complete() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 11_411_000 picoseconds. - Weight::from_parts(11_956_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 14_057_000 picoseconds. + Weight::from_parts(14_254_000, 3774) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -149,10 +149,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) fn exec_migration_fail() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 12_398_000 picoseconds. - Weight::from_parts(12_910_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 14_578_000 picoseconds. + Weight::from_parts(14_825_000, 3774) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -160,8 +160,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 166_000 picoseconds. - Weight::from_parts(193_000, 0) + // Minimum execution time: 169_000 picoseconds. + Weight::from_parts(197_000, 0) } /// Storage: `MultiBlockMigrations::Cursor` (r:0 w:1) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) @@ -169,8 +169,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_686_000 picoseconds. - Weight::from_parts(2_859_000, 0) + // Minimum execution time: 2_634_000 picoseconds. + Weight::from_parts(2_798_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:0 w:1) @@ -179,8 +179,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_070_000 picoseconds. - Weight::from_parts(3_250_000, 0) + // Minimum execution time: 3_069_000 picoseconds. + Weight::from_parts(3_293_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) @@ -189,10 +189,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) fn force_onboard_mbms() -> Weight { // Proof Size summary in bytes: - // Measured: `251` + // Measured: `284` // Estimated: `67035` - // Minimum execution time: 5_901_000 picoseconds. - Weight::from_parts(6_320_000, 67035) + // Minimum execution time: 7_674_000 picoseconds. + Weight::from_parts(8_000_000, 67035) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `MultiBlockMigrations::Historic` (r:256 w:256) @@ -202,10 +202,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1122 + n * (271 ±0)` // Estimated: `3834 + n * (2740 ±0)` - // Minimum execution time: 15_952_000 picoseconds. - Weight::from_parts(14_358_665, 3834) - // Standard Error: 3_358 - .saturating_add(Weight::from_parts(1_323_674, 0).saturating_mul(n.into())) + // Minimum execution time: 16_937_000 picoseconds. + Weight::from_parts(15_713_121, 3834) + // Standard Error: 2_580 + .saturating_add(Weight::from_parts(1_424_239, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -221,10 +221,10 @@ impl WeightInfo for () { /// Proof: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) fn onboard_new_mbms() -> Weight { // Proof Size summary in bytes: - // Measured: `276` + // Measured: `309` // Estimated: `67035` - // Minimum execution time: 7_762_000 picoseconds. - Weight::from_parts(8_100_000, 67035) + // Minimum execution time: 9_520_000 picoseconds. + Weight::from_parts(9_934_000, 67035) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -234,8 +234,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `67035` - // Minimum execution time: 2_077_000 picoseconds. - Weight::from_parts(2_138_000, 67035) + // Minimum execution time: 2_993_000 picoseconds. + Weight::from_parts(3_088_000, 67035) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -244,10 +244,10 @@ impl WeightInfo for () { /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) fn exec_migration_completed() -> Weight { // Proof Size summary in bytes: - // Measured: `134` - // Estimated: `3599` - // Minimum execution time: 5_868_000 picoseconds. - Weight::from_parts(6_143_000, 3599) + // Measured: `167` + // Estimated: `3632` + // Minimum execution time: 7_042_000 picoseconds. + Weight::from_parts(7_272_000, 3632) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -257,10 +257,10 @@ impl WeightInfo for () { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_skipped_historic() -> Weight { // Proof Size summary in bytes: - // Measured: `330` - // Estimated: `3795` - // Minimum execution time: 10_283_000 picoseconds. - Weight::from_parts(10_964_000, 3795) + // Measured: `363` + // Estimated: `3828` + // Minimum execution time: 16_522_000 picoseconds. + Weight::from_parts(17_082_000, 3828) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -269,10 +269,10 @@ impl WeightInfo for () { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_advance() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 9_900_000 picoseconds. - Weight::from_parts(10_396_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 12_445_000 picoseconds. + Weight::from_parts(12_797_000, 3774) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) @@ -281,10 +281,10 @@ impl WeightInfo for () { /// Proof: `MultiBlockMigrations::Historic` (`max_values`: None, `max_size`: Some(266), added: 2741, mode: `MaxEncodedLen`) fn exec_migration_complete() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 11_411_000 picoseconds. - Weight::from_parts(11_956_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 14_057_000 picoseconds. + Weight::from_parts(14_254_000, 3774) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -296,10 +296,10 @@ impl WeightInfo for () { /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) fn exec_migration_fail() -> Weight { // Proof Size summary in bytes: - // Measured: `276` - // Estimated: `3741` - // Minimum execution time: 12_398_000 picoseconds. - Weight::from_parts(12_910_000, 3741) + // Measured: `309` + // Estimated: `3774` + // Minimum execution time: 14_578_000 picoseconds. + Weight::from_parts(14_825_000, 3774) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -307,8 +307,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 166_000 picoseconds. - Weight::from_parts(193_000, 0) + // Minimum execution time: 169_000 picoseconds. + Weight::from_parts(197_000, 0) } /// Storage: `MultiBlockMigrations::Cursor` (r:0 w:1) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) @@ -316,8 +316,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_686_000 picoseconds. - Weight::from_parts(2_859_000, 0) + // Minimum execution time: 2_634_000 picoseconds. + Weight::from_parts(2_798_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:0 w:1) @@ -326,8 +326,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_070_000 picoseconds. - Weight::from_parts(3_250_000, 0) + // Minimum execution time: 3_069_000 picoseconds. + Weight::from_parts(3_293_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) @@ -336,10 +336,10 @@ impl WeightInfo for () { /// Proof: UNKNOWN KEY `0x583359fe0e84d953a9dd84e8addb08a5` (r:1 w:0) fn force_onboard_mbms() -> Weight { // Proof Size summary in bytes: - // Measured: `251` + // Measured: `284` // Estimated: `67035` - // Minimum execution time: 5_901_000 picoseconds. - Weight::from_parts(6_320_000, 67035) + // Minimum execution time: 7_674_000 picoseconds. + Weight::from_parts(8_000_000, 67035) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `MultiBlockMigrations::Historic` (r:256 w:256) @@ -349,10 +349,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1122 + n * (271 ±0)` // Estimated: `3834 + n * (2740 ±0)` - // Minimum execution time: 15_952_000 picoseconds. - Weight::from_parts(14_358_665, 3834) - // Standard Error: 3_358 - .saturating_add(Weight::from_parts(1_323_674, 0).saturating_mul(n.into())) + // Minimum execution time: 16_937_000 picoseconds. + Weight::from_parts(15_713_121, 3834) + // Standard Error: 2_580 + .saturating_add(Weight::from_parts(1_424_239, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(n.into()))) diff --git a/substrate/frame/multisig/src/weights.rs b/substrate/frame/multisig/src/weights.rs index fb263116ea62..5c14922e0ef0 100644 --- a/substrate/frame/multisig/src/weights.rs +++ b/substrate/frame/multisig/src/weights.rs @@ -294,4 +294,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } -} +} \ No newline at end of file diff --git a/substrate/frame/nft-fractionalization/src/weights.rs b/substrate/frame/nft-fractionalization/src/weights.rs index bee6484d856e..a55d01eb4f2d 100644 --- a/substrate/frame/nft-fractionalization/src/weights.rs +++ b/substrate/frame/nft-fractionalization/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_nft_fractionalization` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -61,13 +61,15 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Nfts::Item` (r:1 w:0) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nfts::Attribute` (r:1 w:1) /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) /// Storage: `Nfts::Collection` (r:1 w:1) /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:1 w:1) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -78,11 +80,11 @@ impl WeightInfo for SubstrateWeight { /// Proof: `NftFractionalization::NftToAsset` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) fn fractionalize() -> Weight { // Proof Size summary in bytes: - // Measured: `609` + // Measured: `661` // Estimated: `4326` - // Minimum execution time: 174_545_000 picoseconds. - Weight::from_parts(177_765_000, 4326) - .saturating_add(T::DbWeight::get().reads(8_u64)) + // Minimum execution time: 186_614_000 picoseconds. + Weight::from_parts(192_990_000, 4326) + .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(8_u64)) } /// Storage: `NftFractionalization::NftToAsset` (r:1 w:1) @@ -102,7 +104,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Nfts::Item` (r:1 w:1) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nfts::Account` (r:0 w:1) /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) @@ -113,8 +115,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1422` // Estimated: `4326` - // Minimum execution time: 128_211_000 picoseconds. - Weight::from_parts(131_545_000, 4326) + // Minimum execution time: 140_234_000 picoseconds. + Weight::from_parts(144_124_000, 4326) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(10_u64)) } @@ -125,13 +127,15 @@ impl WeightInfo for () { /// Storage: `Nfts::Item` (r:1 w:0) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nfts::Attribute` (r:1 w:1) /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) /// Storage: `Nfts::Collection` (r:1 w:1) /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::NextAssetId` (r:1 w:0) + /// Proof: `Assets::NextAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:1 w:1) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -142,11 +146,11 @@ impl WeightInfo for () { /// Proof: `NftFractionalization::NftToAsset` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) fn fractionalize() -> Weight { // Proof Size summary in bytes: - // Measured: `609` + // Measured: `661` // Estimated: `4326` - // Minimum execution time: 174_545_000 picoseconds. - Weight::from_parts(177_765_000, 4326) - .saturating_add(RocksDbWeight::get().reads(8_u64)) + // Minimum execution time: 186_614_000 picoseconds. + Weight::from_parts(192_990_000, 4326) + .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(8_u64)) } /// Storage: `NftFractionalization::NftToAsset` (r:1 w:1) @@ -166,7 +170,7 @@ impl WeightInfo for () { /// Storage: `Nfts::Item` (r:1 w:1) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nfts::Account` (r:0 w:1) /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) @@ -177,8 +181,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1422` // Estimated: `4326` - // Minimum execution time: 128_211_000 picoseconds. - Weight::from_parts(131_545_000, 4326) + // Minimum execution time: 140_234_000 picoseconds. + Weight::from_parts(144_124_000, 4326) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(10_u64)) } diff --git a/substrate/frame/nfts/src/weights.rs b/substrate/frame/nfts/src/weights.rs index c5fb60a2206f..1182518e89f8 100644 --- a/substrate/frame/nfts/src/weights.rs +++ b/substrate/frame/nfts/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_nfts` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -109,8 +109,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `216` // Estimated: `3549` - // Minimum execution time: 34_863_000 picoseconds. - Weight::from_parts(36_679_000, 3549) + // Minimum execution time: 39_795_000 picoseconds. + Weight::from_parts(40_954_000, 3549) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -128,8 +128,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3549` - // Minimum execution time: 19_631_000 picoseconds. - Weight::from_parts(20_384_000, 3549) + // Minimum execution time: 19_590_000 picoseconds. + Weight::from_parts(20_452_000, 3549) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -152,14 +152,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `m` is `[0, 1000]`. /// The range of component `c` is `[0, 1000]`. /// The range of component `a` is `[0, 1000]`. - fn destroy(_m: u32, _c: u32, a: u32, ) -> Weight { + fn destroy(m: u32, _c: u32, a: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `32204 + a * (366 ±0)` // Estimated: `2523990 + a * (2954 ±0)` - // Minimum execution time: 1_282_083_000 picoseconds. - Weight::from_parts(1_249_191_963, 2523990) - // Standard Error: 4_719 - .saturating_add(Weight::from_parts(6_470_227, 0).saturating_mul(a.into())) + // Minimum execution time: 1_283_452_000 picoseconds. + Weight::from_parts(1_066_445_083, 2523990) + // Standard Error: 9_120 + .saturating_add(Weight::from_parts(195_960, 0).saturating_mul(m.into())) + // Standard Error: 9_120 + .saturating_add(Weight::from_parts(7_706_045, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(1004_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) .saturating_add(T::DbWeight::get().writes(1005_u64)) @@ -182,8 +184,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `455` // Estimated: `4326` - // Minimum execution time: 49_055_000 picoseconds. - Weight::from_parts(50_592_000, 4326) + // Minimum execution time: 55_122_000 picoseconds. + Weight::from_parts(56_437_000, 4326) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -203,8 +205,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `455` // Estimated: `4326` - // Minimum execution time: 47_102_000 picoseconds. - Weight::from_parts(48_772_000, 4326) + // Minimum execution time: 53_137_000 picoseconds. + Weight::from_parts(54_307_000, 4326) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -230,8 +232,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `564` // Estimated: `4326` - // Minimum execution time: 52_968_000 picoseconds. - Weight::from_parts(55_136_000, 4326) + // Minimum execution time: 59_107_000 picoseconds. + Weight::from_parts(60_638_000, 4326) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -255,8 +257,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `593` // Estimated: `4326` - // Minimum execution time: 41_140_000 picoseconds. - Weight::from_parts(43_288_000, 4326) + // Minimum execution time: 47_355_000 picoseconds. + Weight::from_parts(48_729_000, 4326) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -271,10 +273,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `763 + i * (108 ±0)` // Estimated: `3549 + i * (3336 ±0)` - // Minimum execution time: 14_433_000 picoseconds. - Weight::from_parts(14_664_000, 3549) - // Standard Error: 23_078 - .saturating_add(Weight::from_parts(15_911_377, 0).saturating_mul(i.into())) + // Minimum execution time: 19_597_000 picoseconds. + Weight::from_parts(19_920_000, 3549) + // Standard Error: 25_051 + .saturating_add(Weight::from_parts(18_457_577, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) @@ -288,8 +290,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 18_307_000 picoseconds. - Weight::from_parts(18_966_000, 3534) + // Minimum execution time: 23_838_000 picoseconds. + Weight::from_parts(24_765_000, 3534) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -301,8 +303,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 18_078_000 picoseconds. - Weight::from_parts(18_593_000, 3534) + // Minimum execution time: 24_030_000 picoseconds. + Weight::from_parts(24_589_000, 3534) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -314,8 +316,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `340` // Estimated: `3549` - // Minimum execution time: 15_175_000 picoseconds. - Weight::from_parts(15_762_000, 3549) + // Minimum execution time: 20_505_000 picoseconds. + Weight::from_parts(20_809_000, 3549) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -331,8 +333,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `562` // Estimated: `3593` - // Minimum execution time: 26_164_000 picoseconds. - Weight::from_parts(27_117_000, 3593) + // Minimum execution time: 32_314_000 picoseconds. + Weight::from_parts(33_213_000, 3593) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -344,8 +346,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `369` // Estimated: `6078` - // Minimum execution time: 38_523_000 picoseconds. - Weight::from_parts(39_486_000, 6078) + // Minimum execution time: 44_563_000 picoseconds. + Weight::from_parts(45_899_000, 6078) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -357,8 +359,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `311` // Estimated: `3549` - // Minimum execution time: 15_733_000 picoseconds. - Weight::from_parts(16_227_000, 3549) + // Minimum execution time: 20_515_000 picoseconds. + Weight::from_parts(21_125_000, 3549) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -370,8 +372,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `276` // Estimated: `3549` - // Minimum execution time: 12_042_000 picoseconds. - Weight::from_parts(12_690_000, 3549) + // Minimum execution time: 16_933_000 picoseconds. + Weight::from_parts(17_552_000, 3549) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -383,8 +385,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 17_165_000 picoseconds. - Weight::from_parts(17_769_000, 3534) + // Minimum execution time: 22_652_000 picoseconds. + Weight::from_parts(23_655_000, 3534) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -402,8 +404,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `539` // Estimated: `3944` - // Minimum execution time: 48_862_000 picoseconds. - Weight::from_parts(50_584_000, 3944) + // Minimum execution time: 56_832_000 picoseconds. + Weight::from_parts(58_480_000, 3944) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -415,8 +417,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `344` // Estimated: `3944` - // Minimum execution time: 24_665_000 picoseconds. - Weight::from_parts(25_465_000, 3944) + // Minimum execution time: 30_136_000 picoseconds. + Weight::from_parts(30_919_000, 3944) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -432,8 +434,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `983` // Estimated: `3944` - // Minimum execution time: 44_617_000 picoseconds. - Weight::from_parts(46_458_000, 3944) + // Minimum execution time: 52_264_000 picoseconds. + Weight::from_parts(53_806_000, 3944) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -445,8 +447,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `381` // Estimated: `4326` - // Minimum execution time: 15_710_000 picoseconds. - Weight::from_parts(16_191_000, 4326) + // Minimum execution time: 20_476_000 picoseconds. + Weight::from_parts(21_213_000, 4326) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -463,10 +465,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `831 + n * (398 ±0)` // Estimated: `4326 + n * (2954 ±0)` - // Minimum execution time: 24_447_000 picoseconds. - Weight::from_parts(25_144_000, 4326) - // Standard Error: 4_872 - .saturating_add(Weight::from_parts(6_523_101, 0).saturating_mul(n.into())) + // Minimum execution time: 30_667_000 picoseconds. + Weight::from_parts(31_079_000, 4326) + // Standard Error: 5_236 + .saturating_add(Weight::from_parts(7_517_246, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -487,8 +489,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `539` // Estimated: `3812` - // Minimum execution time: 39_990_000 picoseconds. - Weight::from_parts(41_098_000, 3812) + // Minimum execution time: 46_520_000 picoseconds. + Weight::from_parts(47_471_000, 3812) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -504,8 +506,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `849` // Estimated: `3812` - // Minimum execution time: 38_030_000 picoseconds. - Weight::from_parts(39_842_000, 3812) + // Minimum execution time: 44_199_000 picoseconds. + Weight::from_parts(45_621_000, 3812) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -521,8 +523,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `398` // Estimated: `3759` - // Minimum execution time: 36_778_000 picoseconds. - Weight::from_parts(38_088_000, 3759) + // Minimum execution time: 41_260_000 picoseconds. + Weight::from_parts(42_420_000, 3759) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -538,8 +540,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `716` // Estimated: `3759` - // Minimum execution time: 36_887_000 picoseconds. - Weight::from_parts(38_406_000, 3759) + // Minimum execution time: 40_975_000 picoseconds. + Weight::from_parts(42_367_000, 3759) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -551,8 +553,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `410` // Estimated: `4326` - // Minimum execution time: 18_734_000 picoseconds. - Weight::from_parts(19_267_000, 4326) + // Minimum execution time: 23_150_000 picoseconds. + Weight::from_parts(24_089_000, 4326) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -562,8 +564,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `418` // Estimated: `4326` - // Minimum execution time: 16_080_000 picoseconds. - Weight::from_parts(16_603_000, 4326) + // Minimum execution time: 20_362_000 picoseconds. + Weight::from_parts(21_102_000, 4326) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -573,8 +575,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `418` // Estimated: `4326` - // Minimum execution time: 15_013_000 picoseconds. - Weight::from_parts(15_607_000, 4326) + // Minimum execution time: 19_564_000 picoseconds. + Weight::from_parts(20_094_000, 4326) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -584,8 +586,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3517` - // Minimum execution time: 13_077_000 picoseconds. - Weight::from_parts(13_635_000, 3517) + // Minimum execution time: 13_360_000 picoseconds. + Weight::from_parts(13_943_000, 3517) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -597,8 +599,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `340` // Estimated: `3549` - // Minimum execution time: 17_146_000 picoseconds. - Weight::from_parts(17_453_000, 3549) + // Minimum execution time: 21_304_000 picoseconds. + Weight::from_parts(22_021_000, 3549) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -610,8 +612,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `323` // Estimated: `3538` - // Minimum execution time: 16_102_000 picoseconds. - Weight::from_parts(16_629_000, 3538) + // Minimum execution time: 20_888_000 picoseconds. + Weight::from_parts(21_600_000, 3538) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -627,8 +629,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `518` // Estimated: `4326` - // Minimum execution time: 22_118_000 picoseconds. - Weight::from_parts(22_849_000, 4326) + // Minimum execution time: 27_414_000 picoseconds. + Weight::from_parts(28_382_000, 4326) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -652,8 +654,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `705` // Estimated: `4326` - // Minimum execution time: 50_369_000 picoseconds. - Weight::from_parts(51_816_000, 4326) + // Minimum execution time: 55_660_000 picoseconds. + Weight::from_parts(57_720_000, 4326) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -662,10 +664,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_203_000 picoseconds. - Weight::from_parts(3_710_869, 0) - // Standard Error: 8_094 - .saturating_add(Weight::from_parts(2_201_869, 0).saturating_mul(n.into())) + // Minimum execution time: 2_064_000 picoseconds. + Weight::from_parts(3_432_697, 0) + // Standard Error: 6_920 + .saturating_add(Weight::from_parts(1_771_459, 0).saturating_mul(n.into())) } /// Storage: `Nfts::Item` (r:2 w:0) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) @@ -675,8 +677,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `494` // Estimated: `7662` - // Minimum execution time: 18_893_000 picoseconds. - Weight::from_parts(19_506_000, 7662) + // Minimum execution time: 24_590_000 picoseconds. + Weight::from_parts(25_395_000, 7662) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -688,8 +690,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `513` // Estimated: `4326` - // Minimum execution time: 19_086_000 picoseconds. - Weight::from_parts(19_609_000, 4326) + // Minimum execution time: 22_121_000 picoseconds. + Weight::from_parts(23_196_000, 4326) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -713,8 +715,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `834` // Estimated: `7662` - // Minimum execution time: 84_103_000 picoseconds. - Weight::from_parts(85_325_000, 7662) + // Minimum execution time: 85_761_000 picoseconds. + Weight::from_parts(88_382_000, 7662) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(10_u64)) } @@ -741,10 +743,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `629` // Estimated: `6078 + n * (2954 ±0)` - // Minimum execution time: 128_363_000 picoseconds. - Weight::from_parts(139_474_918, 6078) - // Standard Error: 79_252 - .saturating_add(Weight::from_parts(31_384_027, 0).saturating_mul(n.into())) + // Minimum execution time: 136_928_000 picoseconds. + Weight::from_parts(143_507_020, 6078) + // Standard Error: 45_424 + .saturating_add(Weight::from_parts(32_942_641, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(6_u64)) @@ -768,10 +770,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `659` // Estimated: `4326 + n * (2954 ±0)` - // Minimum execution time: 66_688_000 picoseconds. - Weight::from_parts(79_208_379, 4326) - // Standard Error: 74_020 - .saturating_add(Weight::from_parts(31_028_221, 0).saturating_mul(n.into())) + // Minimum execution time: 72_412_000 picoseconds. + Weight::from_parts(84_724_399, 4326) + // Standard Error: 68_965 + .saturating_add(Weight::from_parts(31_711_702, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -796,8 +798,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `216` // Estimated: `3549` - // Minimum execution time: 34_863_000 picoseconds. - Weight::from_parts(36_679_000, 3549) + // Minimum execution time: 39_795_000 picoseconds. + Weight::from_parts(40_954_000, 3549) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -815,8 +817,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3549` - // Minimum execution time: 19_631_000 picoseconds. - Weight::from_parts(20_384_000, 3549) + // Minimum execution time: 19_590_000 picoseconds. + Weight::from_parts(20_452_000, 3549) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -839,14 +841,16 @@ impl WeightInfo for () { /// The range of component `m` is `[0, 1000]`. /// The range of component `c` is `[0, 1000]`. /// The range of component `a` is `[0, 1000]`. - fn destroy(_m: u32, _c: u32, a: u32, ) -> Weight { + fn destroy(m: u32, _c: u32, a: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `32204 + a * (366 ±0)` // Estimated: `2523990 + a * (2954 ±0)` - // Minimum execution time: 1_282_083_000 picoseconds. - Weight::from_parts(1_249_191_963, 2523990) - // Standard Error: 4_719 - .saturating_add(Weight::from_parts(6_470_227, 0).saturating_mul(a.into())) + // Minimum execution time: 1_283_452_000 picoseconds. + Weight::from_parts(1_066_445_083, 2523990) + // Standard Error: 9_120 + .saturating_add(Weight::from_parts(195_960, 0).saturating_mul(m.into())) + // Standard Error: 9_120 + .saturating_add(Weight::from_parts(7_706_045, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(1004_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(a.into()))) .saturating_add(RocksDbWeight::get().writes(1005_u64)) @@ -869,8 +873,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `455` // Estimated: `4326` - // Minimum execution time: 49_055_000 picoseconds. - Weight::from_parts(50_592_000, 4326) + // Minimum execution time: 55_122_000 picoseconds. + Weight::from_parts(56_437_000, 4326) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -890,8 +894,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `455` // Estimated: `4326` - // Minimum execution time: 47_102_000 picoseconds. - Weight::from_parts(48_772_000, 4326) + // Minimum execution time: 53_137_000 picoseconds. + Weight::from_parts(54_307_000, 4326) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -917,8 +921,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `564` // Estimated: `4326` - // Minimum execution time: 52_968_000 picoseconds. - Weight::from_parts(55_136_000, 4326) + // Minimum execution time: 59_107_000 picoseconds. + Weight::from_parts(60_638_000, 4326) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -942,8 +946,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `593` // Estimated: `4326` - // Minimum execution time: 41_140_000 picoseconds. - Weight::from_parts(43_288_000, 4326) + // Minimum execution time: 47_355_000 picoseconds. + Weight::from_parts(48_729_000, 4326) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -958,10 +962,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `763 + i * (108 ±0)` // Estimated: `3549 + i * (3336 ±0)` - // Minimum execution time: 14_433_000 picoseconds. - Weight::from_parts(14_664_000, 3549) - // Standard Error: 23_078 - .saturating_add(Weight::from_parts(15_911_377, 0).saturating_mul(i.into())) + // Minimum execution time: 19_597_000 picoseconds. + Weight::from_parts(19_920_000, 3549) + // Standard Error: 25_051 + .saturating_add(Weight::from_parts(18_457_577, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(i.into()))) @@ -975,8 +979,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 18_307_000 picoseconds. - Weight::from_parts(18_966_000, 3534) + // Minimum execution time: 23_838_000 picoseconds. + Weight::from_parts(24_765_000, 3534) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -988,8 +992,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 18_078_000 picoseconds. - Weight::from_parts(18_593_000, 3534) + // Minimum execution time: 24_030_000 picoseconds. + Weight::from_parts(24_589_000, 3534) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1001,8 +1005,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `340` // Estimated: `3549` - // Minimum execution time: 15_175_000 picoseconds. - Weight::from_parts(15_762_000, 3549) + // Minimum execution time: 20_505_000 picoseconds. + Weight::from_parts(20_809_000, 3549) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1018,8 +1022,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `562` // Estimated: `3593` - // Minimum execution time: 26_164_000 picoseconds. - Weight::from_parts(27_117_000, 3593) + // Minimum execution time: 32_314_000 picoseconds. + Weight::from_parts(33_213_000, 3593) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -1031,8 +1035,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `369` // Estimated: `6078` - // Minimum execution time: 38_523_000 picoseconds. - Weight::from_parts(39_486_000, 6078) + // Minimum execution time: 44_563_000 picoseconds. + Weight::from_parts(45_899_000, 6078) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -1044,8 +1048,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `311` // Estimated: `3549` - // Minimum execution time: 15_733_000 picoseconds. - Weight::from_parts(16_227_000, 3549) + // Minimum execution time: 20_515_000 picoseconds. + Weight::from_parts(21_125_000, 3549) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1057,8 +1061,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `276` // Estimated: `3549` - // Minimum execution time: 12_042_000 picoseconds. - Weight::from_parts(12_690_000, 3549) + // Minimum execution time: 16_933_000 picoseconds. + Weight::from_parts(17_552_000, 3549) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1070,8 +1074,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `435` // Estimated: `3534` - // Minimum execution time: 17_165_000 picoseconds. - Weight::from_parts(17_769_000, 3534) + // Minimum execution time: 22_652_000 picoseconds. + Weight::from_parts(23_655_000, 3534) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1089,8 +1093,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `539` // Estimated: `3944` - // Minimum execution time: 48_862_000 picoseconds. - Weight::from_parts(50_584_000, 3944) + // Minimum execution time: 56_832_000 picoseconds. + Weight::from_parts(58_480_000, 3944) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1102,8 +1106,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `344` // Estimated: `3944` - // Minimum execution time: 24_665_000 picoseconds. - Weight::from_parts(25_465_000, 3944) + // Minimum execution time: 30_136_000 picoseconds. + Weight::from_parts(30_919_000, 3944) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1119,8 +1123,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `983` // Estimated: `3944` - // Minimum execution time: 44_617_000 picoseconds. - Weight::from_parts(46_458_000, 3944) + // Minimum execution time: 52_264_000 picoseconds. + Weight::from_parts(53_806_000, 3944) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1132,8 +1136,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `381` // Estimated: `4326` - // Minimum execution time: 15_710_000 picoseconds. - Weight::from_parts(16_191_000, 4326) + // Minimum execution time: 20_476_000 picoseconds. + Weight::from_parts(21_213_000, 4326) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1150,10 +1154,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `831 + n * (398 ±0)` // Estimated: `4326 + n * (2954 ±0)` - // Minimum execution time: 24_447_000 picoseconds. - Weight::from_parts(25_144_000, 4326) - // Standard Error: 4_872 - .saturating_add(Weight::from_parts(6_523_101, 0).saturating_mul(n.into())) + // Minimum execution time: 30_667_000 picoseconds. + Weight::from_parts(31_079_000, 4326) + // Standard Error: 5_236 + .saturating_add(Weight::from_parts(7_517_246, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -1174,8 +1178,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `539` // Estimated: `3812` - // Minimum execution time: 39_990_000 picoseconds. - Weight::from_parts(41_098_000, 3812) + // Minimum execution time: 46_520_000 picoseconds. + Weight::from_parts(47_471_000, 3812) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1191,8 +1195,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `849` // Estimated: `3812` - // Minimum execution time: 38_030_000 picoseconds. - Weight::from_parts(39_842_000, 3812) + // Minimum execution time: 44_199_000 picoseconds. + Weight::from_parts(45_621_000, 3812) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1208,8 +1212,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `398` // Estimated: `3759` - // Minimum execution time: 36_778_000 picoseconds. - Weight::from_parts(38_088_000, 3759) + // Minimum execution time: 41_260_000 picoseconds. + Weight::from_parts(42_420_000, 3759) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1225,8 +1229,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `716` // Estimated: `3759` - // Minimum execution time: 36_887_000 picoseconds. - Weight::from_parts(38_406_000, 3759) + // Minimum execution time: 40_975_000 picoseconds. + Weight::from_parts(42_367_000, 3759) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1238,8 +1242,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `410` // Estimated: `4326` - // Minimum execution time: 18_734_000 picoseconds. - Weight::from_parts(19_267_000, 4326) + // Minimum execution time: 23_150_000 picoseconds. + Weight::from_parts(24_089_000, 4326) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1249,8 +1253,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `418` // Estimated: `4326` - // Minimum execution time: 16_080_000 picoseconds. - Weight::from_parts(16_603_000, 4326) + // Minimum execution time: 20_362_000 picoseconds. + Weight::from_parts(21_102_000, 4326) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1260,8 +1264,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `418` // Estimated: `4326` - // Minimum execution time: 15_013_000 picoseconds. - Weight::from_parts(15_607_000, 4326) + // Minimum execution time: 19_564_000 picoseconds. + Weight::from_parts(20_094_000, 4326) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1271,8 +1275,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `3517` - // Minimum execution time: 13_077_000 picoseconds. - Weight::from_parts(13_635_000, 3517) + // Minimum execution time: 13_360_000 picoseconds. + Weight::from_parts(13_943_000, 3517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1284,8 +1288,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `340` // Estimated: `3549` - // Minimum execution time: 17_146_000 picoseconds. - Weight::from_parts(17_453_000, 3549) + // Minimum execution time: 21_304_000 picoseconds. + Weight::from_parts(22_021_000, 3549) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1297,8 +1301,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `323` // Estimated: `3538` - // Minimum execution time: 16_102_000 picoseconds. - Weight::from_parts(16_629_000, 3538) + // Minimum execution time: 20_888_000 picoseconds. + Weight::from_parts(21_600_000, 3538) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1314,8 +1318,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `518` // Estimated: `4326` - // Minimum execution time: 22_118_000 picoseconds. - Weight::from_parts(22_849_000, 4326) + // Minimum execution time: 27_414_000 picoseconds. + Weight::from_parts(28_382_000, 4326) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1339,8 +1343,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `705` // Estimated: `4326` - // Minimum execution time: 50_369_000 picoseconds. - Weight::from_parts(51_816_000, 4326) + // Minimum execution time: 55_660_000 picoseconds. + Weight::from_parts(57_720_000, 4326) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -1349,10 +1353,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_203_000 picoseconds. - Weight::from_parts(3_710_869, 0) - // Standard Error: 8_094 - .saturating_add(Weight::from_parts(2_201_869, 0).saturating_mul(n.into())) + // Minimum execution time: 2_064_000 picoseconds. + Weight::from_parts(3_432_697, 0) + // Standard Error: 6_920 + .saturating_add(Weight::from_parts(1_771_459, 0).saturating_mul(n.into())) } /// Storage: `Nfts::Item` (r:2 w:0) /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) @@ -1362,8 +1366,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `494` // Estimated: `7662` - // Minimum execution time: 18_893_000 picoseconds. - Weight::from_parts(19_506_000, 7662) + // Minimum execution time: 24_590_000 picoseconds. + Weight::from_parts(25_395_000, 7662) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1375,8 +1379,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `513` // Estimated: `4326` - // Minimum execution time: 19_086_000 picoseconds. - Weight::from_parts(19_609_000, 4326) + // Minimum execution time: 22_121_000 picoseconds. + Weight::from_parts(23_196_000, 4326) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1400,8 +1404,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `834` // Estimated: `7662` - // Minimum execution time: 84_103_000 picoseconds. - Weight::from_parts(85_325_000, 7662) + // Minimum execution time: 85_761_000 picoseconds. + Weight::from_parts(88_382_000, 7662) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(10_u64)) } @@ -1428,10 +1432,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `629` // Estimated: `6078 + n * (2954 ±0)` - // Minimum execution time: 128_363_000 picoseconds. - Weight::from_parts(139_474_918, 6078) - // Standard Error: 79_252 - .saturating_add(Weight::from_parts(31_384_027, 0).saturating_mul(n.into())) + // Minimum execution time: 136_928_000 picoseconds. + Weight::from_parts(143_507_020, 6078) + // Standard Error: 45_424 + .saturating_add(Weight::from_parts(32_942_641, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(6_u64)) @@ -1455,10 +1459,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `659` // Estimated: `4326 + n * (2954 ±0)` - // Minimum execution time: 66_688_000 picoseconds. - Weight::from_parts(79_208_379, 4326) - // Standard Error: 74_020 - .saturating_add(Weight::from_parts(31_028_221, 0).saturating_mul(n.into())) + // Minimum execution time: 72_412_000 picoseconds. + Weight::from_parts(84_724_399, 4326) + // Standard Error: 68_965 + .saturating_add(Weight::from_parts(31_711_702, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) diff --git a/substrate/frame/nis/src/weights.rs b/substrate/frame/nis/src/weights.rs index a2411c1e39a6..4f476fd22c21 100644 --- a/substrate/frame/nis/src/weights.rs +++ b/substrate/frame/nis/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_nis` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -70,7 +70,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 999]`. @@ -78,32 +78,32 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `6210 + l * (48 ±0)` // Estimated: `51487` - // Minimum execution time: 47_065_000 picoseconds. - Weight::from_parts(52_894_557, 51487) - // Standard Error: 275 - .saturating_add(Weight::from_parts(48_441, 0).saturating_mul(l.into())) + // Minimum execution time: 47_511_000 picoseconds. + Weight::from_parts(49_908_184, 51487) + // Standard Error: 1_434 + .saturating_add(Weight::from_parts(104_320, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) fn place_bid_max() -> Weight { // Proof Size summary in bytes: // Measured: `54212` // Estimated: `51487` - // Minimum execution time: 111_930_000 picoseconds. - Weight::from_parts(114_966_000, 51487) + // Minimum execution time: 163_636_000 picoseconds. + Weight::from_parts(172_874_000, 51487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) /// The range of component `l` is `[1, 1000]`. @@ -111,10 +111,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `6210 + l * (48 ±0)` // Estimated: `51487` - // Minimum execution time: 47_726_000 picoseconds. - Weight::from_parts(48_162_043, 51487) - // Standard Error: 187 - .saturating_add(Weight::from_parts(38_372, 0).saturating_mul(l.into())) + // Minimum execution time: 52_140_000 picoseconds. + Weight::from_parts(46_062_457, 51487) + // Standard Error: 1_320 + .saturating_add(Weight::from_parts(91_098, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -126,15 +126,15 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `225` // Estimated: `3593` - // Minimum execution time: 31_194_000 picoseconds. - Weight::from_parts(32_922_000, 3593) + // Minimum execution time: 35_741_000 picoseconds. + Weight::from_parts(36_659_000, 3593) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Nis::Receipts` (r:1 w:1) /// Proof: `Nis::Receipts` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Nis::Summary` (r:1 w:1) @@ -146,9 +146,9 @@ impl WeightInfo for SubstrateWeight { fn communify() -> Weight { // Proof Size summary in bytes: // Measured: `702` - // Estimated: `3675` - // Minimum execution time: 73_288_000 picoseconds. - Weight::from_parts(76_192_000, 3675) + // Estimated: `3820` + // Minimum execution time: 78_797_000 picoseconds. + Weight::from_parts(81_863_000, 3820) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -163,13 +163,13 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Assets::Account` (r:1 w:1) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn privatize() -> Weight { // Proof Size summary in bytes: // Measured: `863` - // Estimated: `3675` - // Minimum execution time: 94_307_000 picoseconds. - Weight::from_parts(96_561_000, 3675) + // Estimated: `3820` + // Minimum execution time: 100_374_000 picoseconds. + Weight::from_parts(103_660_000, 3820) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -180,13 +180,13 @@ impl WeightInfo for SubstrateWeight { /// Storage: `System::Account` (r:1 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn thaw_private() -> Weight { // Proof Size summary in bytes: // Measured: `388` - // Estimated: `3658` - // Minimum execution time: 49_873_000 picoseconds. - Weight::from_parts(51_361_000, 3658) + // Estimated: `3820` + // Minimum execution time: 58_624_000 picoseconds. + Weight::from_parts(60_177_000, 3820) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -204,8 +204,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `807` // Estimated: `3675` - // Minimum execution time: 96_884_000 picoseconds. - Weight::from_parts(98_867_000, 3675) + // Minimum execution time: 98_193_000 picoseconds. + Weight::from_parts(101_255_000, 3675) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -219,8 +219,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `6658` // Estimated: `7487` - // Minimum execution time: 21_019_000 picoseconds. - Weight::from_parts(22_057_000, 7487) + // Minimum execution time: 29_640_000 picoseconds. + Weight::from_parts(31_768_000, 7487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -230,8 +230,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `51487` - // Minimum execution time: 4_746_000 picoseconds. - Weight::from_parts(4_953_000, 51487) + // Minimum execution time: 5_273_000 picoseconds. + Weight::from_parts(5_461_000, 51487) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -241,8 +241,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_836_000 picoseconds. - Weight::from_parts(5_093_000, 0) + // Minimum execution time: 4_553_000 picoseconds. + Weight::from_parts(4_726_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } } @@ -252,7 +252,7 @@ impl WeightInfo for () { /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 999]`. @@ -260,32 +260,32 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `6210 + l * (48 ±0)` // Estimated: `51487` - // Minimum execution time: 47_065_000 picoseconds. - Weight::from_parts(52_894_557, 51487) - // Standard Error: 275 - .saturating_add(Weight::from_parts(48_441, 0).saturating_mul(l.into())) + // Minimum execution time: 47_511_000 picoseconds. + Weight::from_parts(49_908_184, 51487) + // Standard Error: 1_434 + .saturating_add(Weight::from_parts(104_320, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) fn place_bid_max() -> Weight { // Proof Size summary in bytes: // Measured: `54212` // Estimated: `51487` - // Minimum execution time: 111_930_000 picoseconds. - Weight::from_parts(114_966_000, 51487) + // Minimum execution time: 163_636_000 picoseconds. + Weight::from_parts(172_874_000, 51487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: `Nis::Queues` (r:1 w:1) /// Proof: `Nis::Queues` (`max_values`: None, `max_size`: Some(48022), added: 50497, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Nis::QueueTotals` (r:1 w:1) /// Proof: `Nis::QueueTotals` (`max_values`: Some(1), `max_size`: Some(6002), added: 6497, mode: `MaxEncodedLen`) /// The range of component `l` is `[1, 1000]`. @@ -293,10 +293,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `6210 + l * (48 ±0)` // Estimated: `51487` - // Minimum execution time: 47_726_000 picoseconds. - Weight::from_parts(48_162_043, 51487) - // Standard Error: 187 - .saturating_add(Weight::from_parts(38_372, 0).saturating_mul(l.into())) + // Minimum execution time: 52_140_000 picoseconds. + Weight::from_parts(46_062_457, 51487) + // Standard Error: 1_320 + .saturating_add(Weight::from_parts(91_098, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -308,15 +308,15 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `225` // Estimated: `3593` - // Minimum execution time: 31_194_000 picoseconds. - Weight::from_parts(32_922_000, 3593) + // Minimum execution time: 35_741_000 picoseconds. + Weight::from_parts(36_659_000, 3593) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Nis::Receipts` (r:1 w:1) /// Proof: `Nis::Receipts` (`max_values`: None, `max_size`: Some(81), added: 2556, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Nis::Summary` (r:1 w:1) @@ -328,9 +328,9 @@ impl WeightInfo for () { fn communify() -> Weight { // Proof Size summary in bytes: // Measured: `702` - // Estimated: `3675` - // Minimum execution time: 73_288_000 picoseconds. - Weight::from_parts(76_192_000, 3675) + // Estimated: `3820` + // Minimum execution time: 78_797_000 picoseconds. + Weight::from_parts(81_863_000, 3820) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -345,13 +345,13 @@ impl WeightInfo for () { /// Storage: `Assets::Account` (r:1 w:1) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn privatize() -> Weight { // Proof Size summary in bytes: // Measured: `863` - // Estimated: `3675` - // Minimum execution time: 94_307_000 picoseconds. - Weight::from_parts(96_561_000, 3675) + // Estimated: `3820` + // Minimum execution time: 100_374_000 picoseconds. + Weight::from_parts(103_660_000, 3820) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -362,13 +362,13 @@ impl WeightInfo for () { /// Storage: `System::Account` (r:1 w:0) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn thaw_private() -> Weight { // Proof Size summary in bytes: // Measured: `388` - // Estimated: `3658` - // Minimum execution time: 49_873_000 picoseconds. - Weight::from_parts(51_361_000, 3658) + // Estimated: `3820` + // Minimum execution time: 58_624_000 picoseconds. + Weight::from_parts(60_177_000, 3820) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -386,8 +386,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `807` // Estimated: `3675` - // Minimum execution time: 96_884_000 picoseconds. - Weight::from_parts(98_867_000, 3675) + // Minimum execution time: 98_193_000 picoseconds. + Weight::from_parts(101_255_000, 3675) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -401,8 +401,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `6658` // Estimated: `7487` - // Minimum execution time: 21_019_000 picoseconds. - Weight::from_parts(22_057_000, 7487) + // Minimum execution time: 29_640_000 picoseconds. + Weight::from_parts(31_768_000, 7487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -412,8 +412,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `51487` - // Minimum execution time: 4_746_000 picoseconds. - Weight::from_parts(4_953_000, 51487) + // Minimum execution time: 5_273_000 picoseconds. + Weight::from_parts(5_461_000, 51487) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -423,8 +423,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_836_000 picoseconds. - Weight::from_parts(5_093_000, 0) + // Minimum execution time: 4_553_000 picoseconds. + Weight::from_parts(4_726_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/nomination-pools/src/weights.rs b/substrate/frame/nomination-pools/src/weights.rs index 21711a499b62..086def4759a8 100644 --- a/substrate/frame/nomination-pools/src/weights.rs +++ b/substrate/frame/nomination-pools/src/weights.rs @@ -1382,4 +1382,4 @@ impl WeightInfo for () { Weight::from_parts(37_038_000, 27847) .saturating_add(RocksDbWeight::get().reads(6_u64)) } -} +} \ No newline at end of file diff --git a/substrate/frame/parameters/src/weights.rs b/substrate/frame/parameters/src/weights.rs index 6510db9ebce5..5601247dad2b 100644 --- a/substrate/frame/parameters/src/weights.rs +++ b/substrate/frame/parameters/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_parameters` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -63,8 +63,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3` // Estimated: `3501` - // Minimum execution time: 8_360_000 picoseconds. - Weight::from_parts(8_568_000, 3501) + // Minimum execution time: 8_202_000 picoseconds. + Weight::from_parts(8_485_000, 3501) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -78,8 +78,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3` // Estimated: `3501` - // Minimum execution time: 8_360_000 picoseconds. - Weight::from_parts(8_568_000, 3501) + // Minimum execution time: 8_202_000 picoseconds. + Weight::from_parts(8_485_000, 3501) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/preimage/src/weights.rs b/substrate/frame/preimage/src/weights.rs index 4e389e3a7340..edb2eed9c75a 100644 --- a/substrate/frame/preimage/src/weights.rs +++ b/substrate/frame/preimage/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_preimage` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -76,18 +76,18 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Parameters::Parameters` (r:2 w:0) /// Proof: `Parameters::Parameters` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 4194304]`. fn note_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `112` + // Measured: `7` // Estimated: `6012` - // Minimum execution time: 52_531_000 picoseconds. - Weight::from_parts(53_245_000, 6012) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_744, 0).saturating_mul(s.into())) + // Minimum execution time: 51_981_000 picoseconds. + Weight::from_parts(52_228_000, 6012) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_392, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -100,12 +100,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 4194304]`. fn note_requested_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_601_000 picoseconds. - Weight::from_parts(15_871_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_836, 0).saturating_mul(s.into())) + // Minimum execution time: 15_835_000 picoseconds. + Weight::from_parts(16_429_000, 3556) + // Standard Error: 8 + .saturating_add(Weight::from_parts(2_647, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -118,12 +118,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 4194304]`. fn note_no_deposit_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_614_000 picoseconds. - Weight::from_parts(15_934_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_832, 0).saturating_mul(s.into())) + // Minimum execution time: 15_263_000 picoseconds. + Weight::from_parts(15_578_000, 3556) + // Standard Error: 7 + .saturating_add(Weight::from_parts(2_598, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -132,15 +132,15 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unnote_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `311` - // Estimated: `3658` - // Minimum execution time: 53_001_000 picoseconds. - Weight::from_parts(55_866_000, 3658) + // Measured: `206` + // Estimated: `3820` + // Minimum execution time: 64_189_000 picoseconds. + Weight::from_parts(70_371_000, 3820) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -152,10 +152,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unnote_no_deposit_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 26_901_000 picoseconds. - Weight::from_parts(28_079_000, 3556) + // Minimum execution time: 27_582_000 picoseconds. + Weight::from_parts(31_256_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -165,10 +165,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `255` + // Measured: `150` // Estimated: `3556` - // Minimum execution time: 21_716_000 picoseconds. - Weight::from_parts(25_318_000, 3556) + // Minimum execution time: 27_667_000 picoseconds. + Weight::from_parts(32_088_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -178,10 +178,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_no_deposit_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 13_890_000 picoseconds. - Weight::from_parts(14_744_000, 3556) + // Minimum execution time: 16_065_000 picoseconds. + Weight::from_parts(20_550_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -191,10 +191,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_unnoted_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `4` // Estimated: `3556` - // Minimum execution time: 14_192_000 picoseconds. - Weight::from_parts(15_113_000, 3556) + // Minimum execution time: 13_638_000 picoseconds. + Weight::from_parts(16_979_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -204,10 +204,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_requested_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 9_909_000 picoseconds. - Weight::from_parts(10_134_000, 3556) + // Minimum execution time: 11_383_000 picoseconds. + Weight::from_parts(12_154_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -219,10 +219,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unrequest_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 21_725_000 picoseconds. - Weight::from_parts(24_058_000, 3556) + // Minimum execution time: 22_832_000 picoseconds. + Weight::from_parts(30_716_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -232,10 +232,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn unrequest_unnoted_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 9_854_000 picoseconds. - Weight::from_parts(10_175_000, 3556) + // Minimum execution time: 10_685_000 picoseconds. + Weight::from_parts(12_129_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -245,10 +245,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn unrequest_multi_referenced_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_143_000 picoseconds. - Weight::from_parts(10_539_000, 3556) + // Minimum execution time: 10_394_000 picoseconds. + Weight::from_parts(10_951_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -259,22 +259,22 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Parameters::Parameters` (r:2 w:0) /// Proof: `Parameters::Parameters` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1023 w:1023) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::RequestStatusFor` (r:0 w:1023) /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// The range of component `n` is `[1, 1024]`. fn ensure_updated(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + n * (227 ±0)` - // Estimated: `6012 + n * (2668 ±0)` - // Minimum execution time: 59_384_000 picoseconds. - Weight::from_parts(60_000_000, 6012) - // Standard Error: 39_890 - .saturating_add(Weight::from_parts(56_317_686, 0).saturating_mul(n.into())) + // Estimated: `6012 + n * (2830 ±0)` + // Minimum execution time: 62_203_000 picoseconds. + Weight::from_parts(63_735_000, 6012) + // Standard Error: 59_589 + .saturating_add(Weight::from_parts(59_482_352, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((4_u64).saturating_mul(n.into()))) - .saturating_add(Weight::from_parts(0, 2668).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(0, 2830).saturating_mul(n.into())) } } @@ -287,18 +287,18 @@ impl WeightInfo for () { /// Storage: `Parameters::Parameters` (r:2 w:0) /// Proof: `Parameters::Parameters` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 4194304]`. fn note_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `112` + // Measured: `7` // Estimated: `6012` - // Minimum execution time: 52_531_000 picoseconds. - Weight::from_parts(53_245_000, 6012) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_744, 0).saturating_mul(s.into())) + // Minimum execution time: 51_981_000 picoseconds. + Weight::from_parts(52_228_000, 6012) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_392, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -311,12 +311,12 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 4194304]`. fn note_requested_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_601_000 picoseconds. - Weight::from_parts(15_871_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_836, 0).saturating_mul(s.into())) + // Minimum execution time: 15_835_000 picoseconds. + Weight::from_parts(16_429_000, 3556) + // Standard Error: 8 + .saturating_add(Weight::from_parts(2_647, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -329,12 +329,12 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 4194304]`. fn note_no_deposit_preimage(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_614_000 picoseconds. - Weight::from_parts(15_934_000, 3556) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_832, 0).saturating_mul(s.into())) + // Minimum execution time: 15_263_000 picoseconds. + Weight::from_parts(15_578_000, 3556) + // Standard Error: 7 + .saturating_add(Weight::from_parts(2_598, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -343,15 +343,15 @@ impl WeightInfo for () { /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::PreimageFor` (r:0 w:1) /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unnote_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `311` - // Estimated: `3658` - // Minimum execution time: 53_001_000 picoseconds. - Weight::from_parts(55_866_000, 3658) + // Measured: `206` + // Estimated: `3820` + // Minimum execution time: 64_189_000 picoseconds. + Weight::from_parts(70_371_000, 3820) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -363,10 +363,10 @@ impl WeightInfo for () { /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unnote_no_deposit_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 26_901_000 picoseconds. - Weight::from_parts(28_079_000, 3556) + // Minimum execution time: 27_582_000 picoseconds. + Weight::from_parts(31_256_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -376,10 +376,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `255` + // Measured: `150` // Estimated: `3556` - // Minimum execution time: 21_716_000 picoseconds. - Weight::from_parts(25_318_000, 3556) + // Minimum execution time: 27_667_000 picoseconds. + Weight::from_parts(32_088_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -389,10 +389,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_no_deposit_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 13_890_000 picoseconds. - Weight::from_parts(14_744_000, 3556) + // Minimum execution time: 16_065_000 picoseconds. + Weight::from_parts(20_550_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -402,10 +402,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_unnoted_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `4` // Estimated: `3556` - // Minimum execution time: 14_192_000 picoseconds. - Weight::from_parts(15_113_000, 3556) + // Minimum execution time: 13_638_000 picoseconds. + Weight::from_parts(16_979_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -415,10 +415,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn request_requested_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 9_909_000 picoseconds. - Weight::from_parts(10_134_000, 3556) + // Minimum execution time: 11_383_000 picoseconds. + Weight::from_parts(12_154_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -430,10 +430,10 @@ impl WeightInfo for () { /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) fn unrequest_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `211` + // Measured: `106` // Estimated: `3556` - // Minimum execution time: 21_725_000 picoseconds. - Weight::from_parts(24_058_000, 3556) + // Minimum execution time: 22_832_000 picoseconds. + Weight::from_parts(30_716_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -443,10 +443,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn unrequest_unnoted_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 9_854_000 picoseconds. - Weight::from_parts(10_175_000, 3556) + // Minimum execution time: 10_685_000 picoseconds. + Weight::from_parts(12_129_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -456,10 +456,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn unrequest_multi_referenced_preimage() -> Weight { // Proof Size summary in bytes: - // Measured: `173` + // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_143_000 picoseconds. - Weight::from_parts(10_539_000, 3556) + // Minimum execution time: 10_394_000 picoseconds. + Weight::from_parts(10_951_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -470,21 +470,21 @@ impl WeightInfo for () { /// Storage: `Parameters::Parameters` (r:2 w:0) /// Proof: `Parameters::Parameters` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1023 w:1023) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `Preimage::RequestStatusFor` (r:0 w:1023) /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// The range of component `n` is `[1, 1024]`. fn ensure_updated(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + n * (227 ±0)` - // Estimated: `6012 + n * (2668 ±0)` - // Minimum execution time: 59_384_000 picoseconds. - Weight::from_parts(60_000_000, 6012) - // Standard Error: 39_890 - .saturating_add(Weight::from_parts(56_317_686, 0).saturating_mul(n.into())) + // Estimated: `6012 + n * (2830 ±0)` + // Minimum execution time: 62_203_000 picoseconds. + Weight::from_parts(63_735_000, 6012) + // Standard Error: 59_589 + .saturating_add(Weight::from_parts(59_482_352, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((4_u64).saturating_mul(n.into()))) - .saturating_add(Weight::from_parts(0, 2668).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(0, 2830).saturating_mul(n.into())) } } diff --git a/substrate/frame/proxy/src/weights.rs b/substrate/frame/proxy/src/weights.rs index eab2cb4b2683..851c0ba98a82 100644 --- a/substrate/frame/proxy/src/weights.rs +++ b/substrate/frame/proxy/src/weights.rs @@ -411,4 +411,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } -} +} \ No newline at end of file diff --git a/substrate/frame/ranked-collective/src/weights.rs b/substrate/frame/ranked-collective/src/weights.rs index e728635f2e72..09215c1ec096 100644 --- a/substrate/frame/ranked-collective/src/weights.rs +++ b/substrate/frame/ranked-collective/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_ranked_collective` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -75,8 +75,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3507` - // Minimum execution time: 15_440_000 picoseconds. - Weight::from_parts(15_990_000, 3507) + // Minimum execution time: 16_363_000 picoseconds. + Weight::from_parts(16_792_000, 3507) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -93,10 +93,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `616 + r * (281 ±0)` // Estimated: `3519 + r * (2529 ±0)` - // Minimum execution time: 30_171_000 picoseconds. - Weight::from_parts(33_395_037, 3519) - // Standard Error: 21_741 - .saturating_add(Weight::from_parts(16_589_950, 0).saturating_mul(r.into())) + // Minimum execution time: 37_472_000 picoseconds. + Weight::from_parts(38_888_667, 3519) + // Standard Error: 36_527 + .saturating_add(Weight::from_parts(18_271_687, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(6_u64)) @@ -116,10 +116,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `314 + r * (17 ±0)` // Estimated: `3507` - // Minimum execution time: 18_597_000 picoseconds. - Weight::from_parts(19_774_947, 3507) - // Standard Error: 5_735 - .saturating_add(Weight::from_parts(339_013, 0).saturating_mul(r.into())) + // Minimum execution time: 20_069_000 picoseconds. + Weight::from_parts(21_231_820, 3507) + // Standard Error: 5_686 + .saturating_add(Weight::from_parts(415_623, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -136,10 +136,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `632 + r * (72 ±0)` // Estimated: `3519` - // Minimum execution time: 29_670_000 picoseconds. - Weight::from_parts(33_022_564, 3519) - // Standard Error: 28_521 - .saturating_add(Weight::from_parts(817_563, 0).saturating_mul(r.into())) + // Minimum execution time: 37_085_000 picoseconds. + Weight::from_parts(40_627_931, 3519) + // Standard Error: 23_398 + .saturating_add(Weight::from_parts(847_496, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -157,8 +157,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `628` // Estimated: `219984` - // Minimum execution time: 42_072_000 picoseconds. - Weight::from_parts(43_360_000, 219984) + // Minimum execution time: 49_474_000 picoseconds. + Weight::from_parts(50_506_000, 219984) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -173,10 +173,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `462 + n * (50 ±0)` // Estimated: `3795 + n * (2540 ±0)` - // Minimum execution time: 14_338_000 picoseconds. - Weight::from_parts(18_144_424, 3795) - // Standard Error: 2_482 - .saturating_add(Weight::from_parts(1_200_576, 0).saturating_mul(n.into())) + // Minimum execution time: 20_009_000 picoseconds. + Weight::from_parts(23_414_747, 3795) + // Standard Error: 2_751 + .saturating_add(Weight::from_parts(1_314_498, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -200,8 +200,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `625` // Estimated: `19894` - // Minimum execution time: 73_317_000 picoseconds. - Weight::from_parts(75_103_000, 19894) + // Minimum execution time: 79_257_000 picoseconds. + Weight::from_parts(81_293_000, 19894) .saturating_add(T::DbWeight::get().reads(11_u64)) .saturating_add(T::DbWeight::get().writes(14_u64)) } @@ -221,8 +221,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3507` - // Minimum execution time: 15_440_000 picoseconds. - Weight::from_parts(15_990_000, 3507) + // Minimum execution time: 16_363_000 picoseconds. + Weight::from_parts(16_792_000, 3507) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -239,10 +239,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `616 + r * (281 ±0)` // Estimated: `3519 + r * (2529 ±0)` - // Minimum execution time: 30_171_000 picoseconds. - Weight::from_parts(33_395_037, 3519) - // Standard Error: 21_741 - .saturating_add(Weight::from_parts(16_589_950, 0).saturating_mul(r.into())) + // Minimum execution time: 37_472_000 picoseconds. + Weight::from_parts(38_888_667, 3519) + // Standard Error: 36_527 + .saturating_add(Weight::from_parts(18_271_687, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(6_u64)) @@ -262,10 +262,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `314 + r * (17 ±0)` // Estimated: `3507` - // Minimum execution time: 18_597_000 picoseconds. - Weight::from_parts(19_774_947, 3507) - // Standard Error: 5_735 - .saturating_add(Weight::from_parts(339_013, 0).saturating_mul(r.into())) + // Minimum execution time: 20_069_000 picoseconds. + Weight::from_parts(21_231_820, 3507) + // Standard Error: 5_686 + .saturating_add(Weight::from_parts(415_623, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -282,10 +282,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `632 + r * (72 ±0)` // Estimated: `3519` - // Minimum execution time: 29_670_000 picoseconds. - Weight::from_parts(33_022_564, 3519) - // Standard Error: 28_521 - .saturating_add(Weight::from_parts(817_563, 0).saturating_mul(r.into())) + // Minimum execution time: 37_085_000 picoseconds. + Weight::from_parts(40_627_931, 3519) + // Standard Error: 23_398 + .saturating_add(Weight::from_parts(847_496, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -303,8 +303,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `628` // Estimated: `219984` - // Minimum execution time: 42_072_000 picoseconds. - Weight::from_parts(43_360_000, 219984) + // Minimum execution time: 49_474_000 picoseconds. + Weight::from_parts(50_506_000, 219984) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -319,10 +319,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `462 + n * (50 ±0)` // Estimated: `3795 + n * (2540 ±0)` - // Minimum execution time: 14_338_000 picoseconds. - Weight::from_parts(18_144_424, 3795) - // Standard Error: 2_482 - .saturating_add(Weight::from_parts(1_200_576, 0).saturating_mul(n.into())) + // Minimum execution time: 20_009_000 picoseconds. + Weight::from_parts(23_414_747, 3795) + // Standard Error: 2_751 + .saturating_add(Weight::from_parts(1_314_498, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(n.into()))) @@ -346,8 +346,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `625` // Estimated: `19894` - // Minimum execution time: 73_317_000 picoseconds. - Weight::from_parts(75_103_000, 19894) + // Minimum execution time: 79_257_000 picoseconds. + Weight::from_parts(81_293_000, 19894) .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().writes(14_u64)) } diff --git a/substrate/frame/recovery/src/weights.rs b/substrate/frame/recovery/src/weights.rs index e38ad0461afd..38b085f0a293 100644 --- a/substrate/frame/recovery/src/weights.rs +++ b/substrate/frame/recovery/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_recovery` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -73,10 +73,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `TxPause::PausedCalls` (`max_values`: None, `max_size`: Some(532), added: 3007, mode: `MaxEncodedLen`) fn as_recovered() -> Weight { // Proof Size summary in bytes: - // Measured: `497` + // Measured: `530` // Estimated: `3997` - // Minimum execution time: 15_318_000 picoseconds. - Weight::from_parts(15_767_000, 3997) + // Minimum execution time: 21_063_000 picoseconds. + Weight::from_parts(21_784_000, 3997) .saturating_add(T::DbWeight::get().reads(3_u64)) } /// Storage: `Recovery::Proxy` (r:0 w:1) @@ -85,8 +85,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_153_000 picoseconds. - Weight::from_parts(7_578_000, 0) + // Minimum execution time: 6_653_000 picoseconds. + Weight::from_parts(7_009_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Recovery::Recoverable` (r:1 w:1) @@ -94,12 +94,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 9]`. fn create_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `246` + // Measured: `279` // Estimated: `3816` - // Minimum execution time: 23_303_000 picoseconds. - Weight::from_parts(24_725_158, 3816) - // Standard Error: 5_723 - .saturating_add(Weight::from_parts(13_638, 0).saturating_mul(n.into())) + // Minimum execution time: 27_992_000 picoseconds. + Weight::from_parts(29_149_096, 3816) + // Standard Error: 5_733 + .saturating_add(Weight::from_parts(87_755, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -109,10 +109,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Recovery::ActiveRecoveries` (`max_values`: None, `max_size`: Some(389), added: 2864, mode: `MaxEncodedLen`) fn initiate_recovery() -> Weight { // Proof Size summary in bytes: - // Measured: `343` + // Measured: `376` // Estimated: `3854` - // Minimum execution time: 26_914_000 picoseconds. - Weight::from_parts(28_041_000, 3854) + // Minimum execution time: 32_675_000 picoseconds. + Weight::from_parts(34_217_000, 3854) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -123,12 +123,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 9]`. fn vouch_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `431 + n * (64 ±0)` + // Measured: `464 + n * (64 ±0)` // Estimated: `3854` - // Minimum execution time: 17_695_000 picoseconds. - Weight::from_parts(18_591_642, 3854) - // Standard Error: 5_582 - .saturating_add(Weight::from_parts(188_668, 0).saturating_mul(n.into())) + // Minimum execution time: 23_557_000 picoseconds. + Weight::from_parts(24_517_150, 3854) + // Standard Error: 5_550 + .saturating_add(Weight::from_parts(156_378, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -141,12 +141,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 9]`. fn claim_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `463 + n * (64 ±0)` + // Measured: `496 + n * (64 ±0)` // Estimated: `3854` - // Minimum execution time: 22_580_000 picoseconds. - Weight::from_parts(23_526_020, 3854) - // Standard Error: 6_604 - .saturating_add(Weight::from_parts(134_340, 0).saturating_mul(n.into())) + // Minimum execution time: 28_261_000 picoseconds. + Weight::from_parts(29_298_729, 3854) + // Standard Error: 5_392 + .saturating_add(Weight::from_parts(162_096, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -157,12 +157,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 9]`. fn close_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `584 + n * (32 ±0)` + // Measured: `617 + n * (32 ±0)` // Estimated: `3854` - // Minimum execution time: 32_017_000 picoseconds. - Weight::from_parts(33_401_086, 3854) - // Standard Error: 6_498 - .saturating_add(Weight::from_parts(95_507, 0).saturating_mul(n.into())) + // Minimum execution time: 38_953_000 picoseconds. + Weight::from_parts(40_675_824, 3854) + // Standard Error: 6_163 + .saturating_add(Weight::from_parts(144_246, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -173,12 +173,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 9]`. fn remove_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `341 + n * (32 ±0)` + // Measured: `374 + n * (32 ±0)` // Estimated: `3854` - // Minimum execution time: 28_641_000 picoseconds. - Weight::from_parts(30_230_511, 3854) - // Standard Error: 7_058 - .saturating_add(Weight::from_parts(61_004, 0).saturating_mul(n.into())) + // Minimum execution time: 32_735_000 picoseconds. + Weight::from_parts(33_830_787, 3854) + // Standard Error: 7_758 + .saturating_add(Weight::from_parts(194_601, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -186,10 +186,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Recovery::Proxy` (`max_values`: None, `max_size`: Some(80), added: 2555, mode: `MaxEncodedLen`) fn cancel_recovered() -> Weight { // Proof Size summary in bytes: - // Measured: `352` + // Measured: `385` // Estimated: `3545` - // Minimum execution time: 11_767_000 picoseconds. - Weight::from_parts(12_275_000, 3545) + // Minimum execution time: 17_356_000 picoseconds. + Weight::from_parts(18_101_000, 3545) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -205,10 +205,10 @@ impl WeightInfo for () { /// Proof: `TxPause::PausedCalls` (`max_values`: None, `max_size`: Some(532), added: 3007, mode: `MaxEncodedLen`) fn as_recovered() -> Weight { // Proof Size summary in bytes: - // Measured: `497` + // Measured: `530` // Estimated: `3997` - // Minimum execution time: 15_318_000 picoseconds. - Weight::from_parts(15_767_000, 3997) + // Minimum execution time: 21_063_000 picoseconds. + Weight::from_parts(21_784_000, 3997) .saturating_add(RocksDbWeight::get().reads(3_u64)) } /// Storage: `Recovery::Proxy` (r:0 w:1) @@ -217,8 +217,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_153_000 picoseconds. - Weight::from_parts(7_578_000, 0) + // Minimum execution time: 6_653_000 picoseconds. + Weight::from_parts(7_009_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Recovery::Recoverable` (r:1 w:1) @@ -226,12 +226,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 9]`. fn create_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `246` + // Measured: `279` // Estimated: `3816` - // Minimum execution time: 23_303_000 picoseconds. - Weight::from_parts(24_725_158, 3816) - // Standard Error: 5_723 - .saturating_add(Weight::from_parts(13_638, 0).saturating_mul(n.into())) + // Minimum execution time: 27_992_000 picoseconds. + Weight::from_parts(29_149_096, 3816) + // Standard Error: 5_733 + .saturating_add(Weight::from_parts(87_755, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -241,10 +241,10 @@ impl WeightInfo for () { /// Proof: `Recovery::ActiveRecoveries` (`max_values`: None, `max_size`: Some(389), added: 2864, mode: `MaxEncodedLen`) fn initiate_recovery() -> Weight { // Proof Size summary in bytes: - // Measured: `343` + // Measured: `376` // Estimated: `3854` - // Minimum execution time: 26_914_000 picoseconds. - Weight::from_parts(28_041_000, 3854) + // Minimum execution time: 32_675_000 picoseconds. + Weight::from_parts(34_217_000, 3854) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -255,12 +255,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 9]`. fn vouch_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `431 + n * (64 ±0)` + // Measured: `464 + n * (64 ±0)` // Estimated: `3854` - // Minimum execution time: 17_695_000 picoseconds. - Weight::from_parts(18_591_642, 3854) - // Standard Error: 5_582 - .saturating_add(Weight::from_parts(188_668, 0).saturating_mul(n.into())) + // Minimum execution time: 23_557_000 picoseconds. + Weight::from_parts(24_517_150, 3854) + // Standard Error: 5_550 + .saturating_add(Weight::from_parts(156_378, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -273,12 +273,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 9]`. fn claim_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `463 + n * (64 ±0)` + // Measured: `496 + n * (64 ±0)` // Estimated: `3854` - // Minimum execution time: 22_580_000 picoseconds. - Weight::from_parts(23_526_020, 3854) - // Standard Error: 6_604 - .saturating_add(Weight::from_parts(134_340, 0).saturating_mul(n.into())) + // Minimum execution time: 28_261_000 picoseconds. + Weight::from_parts(29_298_729, 3854) + // Standard Error: 5_392 + .saturating_add(Weight::from_parts(162_096, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -289,12 +289,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 9]`. fn close_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `584 + n * (32 ±0)` + // Measured: `617 + n * (32 ±0)` // Estimated: `3854` - // Minimum execution time: 32_017_000 picoseconds. - Weight::from_parts(33_401_086, 3854) - // Standard Error: 6_498 - .saturating_add(Weight::from_parts(95_507, 0).saturating_mul(n.into())) + // Minimum execution time: 38_953_000 picoseconds. + Weight::from_parts(40_675_824, 3854) + // Standard Error: 6_163 + .saturating_add(Weight::from_parts(144_246, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -305,12 +305,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 9]`. fn remove_recovery(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `341 + n * (32 ±0)` + // Measured: `374 + n * (32 ±0)` // Estimated: `3854` - // Minimum execution time: 28_641_000 picoseconds. - Weight::from_parts(30_230_511, 3854) - // Standard Error: 7_058 - .saturating_add(Weight::from_parts(61_004, 0).saturating_mul(n.into())) + // Minimum execution time: 32_735_000 picoseconds. + Weight::from_parts(33_830_787, 3854) + // Standard Error: 7_758 + .saturating_add(Weight::from_parts(194_601, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -318,10 +318,10 @@ impl WeightInfo for () { /// Proof: `Recovery::Proxy` (`max_values`: None, `max_size`: Some(80), added: 2555, mode: `MaxEncodedLen`) fn cancel_recovered() -> Weight { // Proof Size summary in bytes: - // Measured: `352` + // Measured: `385` // Estimated: `3545` - // Minimum execution time: 11_767_000 picoseconds. - Weight::from_parts(12_275_000, 3545) + // Minimum execution time: 17_356_000 picoseconds. + Weight::from_parts(18_101_000, 3545) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/referenda/src/weights.rs b/substrate/frame/referenda/src/weights.rs index b34758ee4667..7c94b2b1799f 100644 --- a/substrate/frame/referenda/src/weights.rs +++ b/substrate/frame/referenda/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_referenda` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -96,8 +96,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `286` // Estimated: `110487` - // Minimum execution time: 33_162_000 picoseconds. - Weight::from_parts(34_217_000, 110487) + // Minimum execution time: 38_152_000 picoseconds. + Weight::from_parts(39_632_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -111,8 +111,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 45_276_000 picoseconds. - Weight::from_parts(46_903_000, 219984) + // Minimum execution time: 52_369_000 picoseconds. + Weight::from_parts(55_689_000, 219984) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -130,8 +130,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3326` // Estimated: `110487` - // Minimum execution time: 63_832_000 picoseconds. - Weight::from_parts(65_616_000, 110487) + // Minimum execution time: 68_807_000 picoseconds. + Weight::from_parts(71_917_000, 110487) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -149,8 +149,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3346` // Estimated: `110487` - // Minimum execution time: 63_726_000 picoseconds. - Weight::from_parts(64_909_000, 110487) + // Minimum execution time: 68_971_000 picoseconds. + Weight::from_parts(71_317_000, 110487) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -166,8 +166,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 53_001_000 picoseconds. - Weight::from_parts(54_489_000, 219984) + // Minimum execution time: 59_447_000 picoseconds. + Weight::from_parts(61_121_000, 219984) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -183,8 +183,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 51_021_000 picoseconds. - Weight::from_parts(53_006_000, 219984) + // Minimum execution time: 58_243_000 picoseconds. + Weight::from_parts(59_671_000, 219984) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -194,8 +194,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `417` // Estimated: `3831` - // Minimum execution time: 26_572_000 picoseconds. - Weight::from_parts(27_534_000, 3831) + // Minimum execution time: 31_621_000 picoseconds. + Weight::from_parts(32_628_000, 3831) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -205,8 +205,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `407` // Estimated: `3831` - // Minimum execution time: 26_897_000 picoseconds. - Weight::from_parts(27_883_000, 3831) + // Minimum execution time: 32_483_000 picoseconds. + Weight::from_parts(33_427_000, 3831) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -220,8 +220,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `219984` - // Minimum execution time: 31_767_000 picoseconds. - Weight::from_parts(33_045_000, 219984) + // Minimum execution time: 36_283_000 picoseconds. + Weight::from_parts(37_748_000, 219984) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -237,8 +237,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `688` // Estimated: `219984` - // Minimum execution time: 67_798_000 picoseconds. - Weight::from_parts(70_044_000, 219984) + // Minimum execution time: 75_460_000 picoseconds. + Weight::from_parts(77_956_000, 219984) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -250,8 +250,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `240` // Estimated: `5477` - // Minimum execution time: 10_056_000 picoseconds. - Weight::from_parts(10_460_000, 5477) + // Minimum execution time: 15_139_000 picoseconds. + Weight::from_parts(15_651_000, 5477) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -265,8 +265,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3216` // Estimated: `110487` - // Minimum execution time: 44_293_000 picoseconds. - Weight::from_parts(45_784_000, 110487) + // Minimum execution time: 48_590_000 picoseconds. + Weight::from_parts(50_207_000, 110487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -280,8 +280,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3216` // Estimated: `110487` - // Minimum execution time: 45_642_000 picoseconds. - Weight::from_parts(47_252_000, 110487) + // Minimum execution time: 48_555_000 picoseconds. + Weight::from_parts(49_956_000, 110487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -293,8 +293,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3077` // Estimated: `5477` - // Minimum execution time: 22_096_000 picoseconds. - Weight::from_parts(22_496_000, 5477) + // Minimum execution time: 28_326_000 picoseconds. + Weight::from_parts(29_735_000, 5477) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -306,8 +306,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3077` // Estimated: `5477` - // Minimum execution time: 21_931_000 picoseconds. - Weight::from_parts(22_312_000, 5477) + // Minimum execution time: 28_209_000 picoseconds. + Weight::from_parts(29_375_000, 5477) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -321,8 +321,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3081` // Estimated: `5477` - // Minimum execution time: 28_890_000 picoseconds. - Weight::from_parts(29_679_000, 5477) + // Minimum execution time: 33_973_000 picoseconds. + Weight::from_parts(35_732_000, 5477) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -336,8 +336,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3101` // Estimated: `5477` - // Minimum execution time: 28_875_000 picoseconds. - Weight::from_parts(29_492_000, 5477) + // Minimum execution time: 34_112_000 picoseconds. + Weight::from_parts(35_748_000, 5477) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -349,8 +349,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `399` // Estimated: `110487` - // Minimum execution time: 19_787_000 picoseconds. - Weight::from_parts(20_493_000, 110487) + // Minimum execution time: 26_135_000 picoseconds. + Weight::from_parts(27_080_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -362,8 +362,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 19_987_000 picoseconds. - Weight::from_parts(20_860_000, 110487) + // Minimum execution time: 26_494_000 picoseconds. + Weight::from_parts(27_290_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -373,8 +373,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `344` // Estimated: `3831` - // Minimum execution time: 13_416_000 picoseconds. - Weight::from_parts(13_857_000, 3831) + // Minimum execution time: 15_294_000 picoseconds. + Weight::from_parts(15_761_000, 3831) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -388,8 +388,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 27_199_000 picoseconds. - Weight::from_parts(28_562_000, 110487) + // Minimum execution time: 32_360_000 picoseconds. + Weight::from_parts(33_747_000, 110487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -403,8 +403,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 29_205_000 picoseconds. - Weight::from_parts(30_407_000, 110487) + // Minimum execution time: 34_133_000 picoseconds. + Weight::from_parts(35_784_000, 110487) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -416,8 +416,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 24_136_000 picoseconds. - Weight::from_parts(24_868_000, 110487) + // Minimum execution time: 30_009_000 picoseconds. + Weight::from_parts(30_985_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -429,8 +429,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `483` // Estimated: `110487` - // Minimum execution time: 23_860_000 picoseconds. - Weight::from_parts(24_556_000, 110487) + // Minimum execution time: 29_439_000 picoseconds. + Weight::from_parts(30_386_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -442,8 +442,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 23_409_000 picoseconds. - Weight::from_parts(24_354_000, 110487) + // Minimum execution time: 29_293_000 picoseconds. + Weight::from_parts(30_577_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -455,8 +455,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `504` // Estimated: `110487` - // Minimum execution time: 21_947_000 picoseconds. - Weight::from_parts(22_485_000, 110487) + // Minimum execution time: 27_418_000 picoseconds. + Weight::from_parts(28_718_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -470,8 +470,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `504` // Estimated: `219984` - // Minimum execution time: 34_643_000 picoseconds. - Weight::from_parts(36_193_000, 219984) + // Minimum execution time: 40_020_000 picoseconds. + Weight::from_parts(40_861_000, 219984) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -483,8 +483,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 24_097_000 picoseconds. - Weight::from_parts(24_881_000, 110487) + // Minimum execution time: 29_843_000 picoseconds. + Weight::from_parts(30_764_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -498,10 +498,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Referenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn set_some_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `555` + // Measured: `450` // Estimated: `3831` - // Minimum execution time: 19_947_000 picoseconds. - Weight::from_parts(20_396_000, 3831) + // Minimum execution time: 24_642_000 picoseconds. + Weight::from_parts(25_498_000, 3831) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -513,8 +513,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `421` // Estimated: `3831` - // Minimum execution time: 15_516_000 picoseconds. - Weight::from_parts(16_094_000, 3831) + // Minimum execution time: 20_867_000 picoseconds. + Weight::from_parts(21_803_000, 3831) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -532,8 +532,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `286` // Estimated: `110487` - // Minimum execution time: 33_162_000 picoseconds. - Weight::from_parts(34_217_000, 110487) + // Minimum execution time: 38_152_000 picoseconds. + Weight::from_parts(39_632_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -547,8 +547,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 45_276_000 picoseconds. - Weight::from_parts(46_903_000, 219984) + // Minimum execution time: 52_369_000 picoseconds. + Weight::from_parts(55_689_000, 219984) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -566,8 +566,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3326` // Estimated: `110487` - // Minimum execution time: 63_832_000 picoseconds. - Weight::from_parts(65_616_000, 110487) + // Minimum execution time: 68_807_000 picoseconds. + Weight::from_parts(71_917_000, 110487) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -585,8 +585,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3346` // Estimated: `110487` - // Minimum execution time: 63_726_000 picoseconds. - Weight::from_parts(64_909_000, 110487) + // Minimum execution time: 68_971_000 picoseconds. + Weight::from_parts(71_317_000, 110487) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -602,8 +602,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 53_001_000 picoseconds. - Weight::from_parts(54_489_000, 219984) + // Minimum execution time: 59_447_000 picoseconds. + Weight::from_parts(61_121_000, 219984) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -619,8 +619,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `539` // Estimated: `219984` - // Minimum execution time: 51_021_000 picoseconds. - Weight::from_parts(53_006_000, 219984) + // Minimum execution time: 58_243_000 picoseconds. + Weight::from_parts(59_671_000, 219984) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -630,8 +630,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `417` // Estimated: `3831` - // Minimum execution time: 26_572_000 picoseconds. - Weight::from_parts(27_534_000, 3831) + // Minimum execution time: 31_621_000 picoseconds. + Weight::from_parts(32_628_000, 3831) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -641,8 +641,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `407` // Estimated: `3831` - // Minimum execution time: 26_897_000 picoseconds. - Weight::from_parts(27_883_000, 3831) + // Minimum execution time: 32_483_000 picoseconds. + Weight::from_parts(33_427_000, 3831) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -656,8 +656,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `219984` - // Minimum execution time: 31_767_000 picoseconds. - Weight::from_parts(33_045_000, 219984) + // Minimum execution time: 36_283_000 picoseconds. + Weight::from_parts(37_748_000, 219984) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -673,8 +673,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `688` // Estimated: `219984` - // Minimum execution time: 67_798_000 picoseconds. - Weight::from_parts(70_044_000, 219984) + // Minimum execution time: 75_460_000 picoseconds. + Weight::from_parts(77_956_000, 219984) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -686,8 +686,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `240` // Estimated: `5477` - // Minimum execution time: 10_056_000 picoseconds. - Weight::from_parts(10_460_000, 5477) + // Minimum execution time: 15_139_000 picoseconds. + Weight::from_parts(15_651_000, 5477) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -701,8 +701,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3216` // Estimated: `110487` - // Minimum execution time: 44_293_000 picoseconds. - Weight::from_parts(45_784_000, 110487) + // Minimum execution time: 48_590_000 picoseconds. + Weight::from_parts(50_207_000, 110487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -716,8 +716,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3216` // Estimated: `110487` - // Minimum execution time: 45_642_000 picoseconds. - Weight::from_parts(47_252_000, 110487) + // Minimum execution time: 48_555_000 picoseconds. + Weight::from_parts(49_956_000, 110487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -729,8 +729,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3077` // Estimated: `5477` - // Minimum execution time: 22_096_000 picoseconds. - Weight::from_parts(22_496_000, 5477) + // Minimum execution time: 28_326_000 picoseconds. + Weight::from_parts(29_735_000, 5477) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -742,8 +742,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3077` // Estimated: `5477` - // Minimum execution time: 21_931_000 picoseconds. - Weight::from_parts(22_312_000, 5477) + // Minimum execution time: 28_209_000 picoseconds. + Weight::from_parts(29_375_000, 5477) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -757,8 +757,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3081` // Estimated: `5477` - // Minimum execution time: 28_890_000 picoseconds. - Weight::from_parts(29_679_000, 5477) + // Minimum execution time: 33_973_000 picoseconds. + Weight::from_parts(35_732_000, 5477) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -772,8 +772,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3101` // Estimated: `5477` - // Minimum execution time: 28_875_000 picoseconds. - Weight::from_parts(29_492_000, 5477) + // Minimum execution time: 34_112_000 picoseconds. + Weight::from_parts(35_748_000, 5477) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -785,8 +785,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `399` // Estimated: `110487` - // Minimum execution time: 19_787_000 picoseconds. - Weight::from_parts(20_493_000, 110487) + // Minimum execution time: 26_135_000 picoseconds. + Weight::from_parts(27_080_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -798,8 +798,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 19_987_000 picoseconds. - Weight::from_parts(20_860_000, 110487) + // Minimum execution time: 26_494_000 picoseconds. + Weight::from_parts(27_290_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -809,8 +809,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `344` // Estimated: `3831` - // Minimum execution time: 13_416_000 picoseconds. - Weight::from_parts(13_857_000, 3831) + // Minimum execution time: 15_294_000 picoseconds. + Weight::from_parts(15_761_000, 3831) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -824,8 +824,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 27_199_000 picoseconds. - Weight::from_parts(28_562_000, 110487) + // Minimum execution time: 32_360_000 picoseconds. + Weight::from_parts(33_747_000, 110487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -839,8 +839,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `110487` - // Minimum execution time: 29_205_000 picoseconds. - Weight::from_parts(30_407_000, 110487) + // Minimum execution time: 34_133_000 picoseconds. + Weight::from_parts(35_784_000, 110487) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -852,8 +852,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 24_136_000 picoseconds. - Weight::from_parts(24_868_000, 110487) + // Minimum execution time: 30_009_000 picoseconds. + Weight::from_parts(30_985_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -865,8 +865,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `483` // Estimated: `110487` - // Minimum execution time: 23_860_000 picoseconds. - Weight::from_parts(24_556_000, 110487) + // Minimum execution time: 29_439_000 picoseconds. + Weight::from_parts(30_386_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -878,8 +878,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 23_409_000 picoseconds. - Weight::from_parts(24_354_000, 110487) + // Minimum execution time: 29_293_000 picoseconds. + Weight::from_parts(30_577_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -891,8 +891,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `504` // Estimated: `110487` - // Minimum execution time: 21_947_000 picoseconds. - Weight::from_parts(22_485_000, 110487) + // Minimum execution time: 27_418_000 picoseconds. + Weight::from_parts(28_718_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -906,8 +906,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `504` // Estimated: `219984` - // Minimum execution time: 34_643_000 picoseconds. - Weight::from_parts(36_193_000, 219984) + // Minimum execution time: 40_020_000 picoseconds. + Weight::from_parts(40_861_000, 219984) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -919,8 +919,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `500` // Estimated: `110487` - // Minimum execution time: 24_097_000 picoseconds. - Weight::from_parts(24_881_000, 110487) + // Minimum execution time: 29_843_000 picoseconds. + Weight::from_parts(30_764_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -934,10 +934,10 @@ impl WeightInfo for () { /// Proof: `Referenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn set_some_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `555` + // Measured: `450` // Estimated: `3831` - // Minimum execution time: 19_947_000 picoseconds. - Weight::from_parts(20_396_000, 3831) + // Minimum execution time: 24_642_000 picoseconds. + Weight::from_parts(25_498_000, 3831) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -949,8 +949,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `421` // Estimated: `3831` - // Minimum execution time: 15_516_000 picoseconds. - Weight::from_parts(16_094_000, 3831) + // Minimum execution time: 20_867_000 picoseconds. + Weight::from_parts(21_803_000, 3831) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/remark/src/weights.rs b/substrate/frame/remark/src/weights.rs index 8a8bdef6dd0f..26838f74a319 100644 --- a/substrate/frame/remark/src/weights.rs +++ b/substrate/frame/remark/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_remark` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -62,10 +62,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_652_000 picoseconds. - Weight::from_parts(6_793_000, 0) + // Minimum execution time: 6_242_000 picoseconds. + Weight::from_parts(15_241_545, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_364, 0).saturating_mul(l.into())) + .saturating_add(Weight::from_parts(1_643, 0).saturating_mul(l.into())) } } @@ -76,9 +76,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_652_000 picoseconds. - Weight::from_parts(6_793_000, 0) + // Minimum execution time: 6_242_000 picoseconds. + Weight::from_parts(15_241_545, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_364, 0).saturating_mul(l.into())) + .saturating_add(Weight::from_parts(1_643, 0).saturating_mul(l.into())) } } diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index bfff5e79e3ae..c27edac93500 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -542,6 +542,7 @@ mod test { &result.function, &result.function.get_dispatch_info(), encoded_len, + 0, )?; Ok((result.function, extra)) diff --git a/substrate/frame/revive/src/weights.rs b/substrate/frame/revive/src/weights.rs index 3c6a0be6ee75..96654432a5cc 100644 --- a/substrate/frame/revive/src/weights.rs +++ b/substrate/frame/revive/src/weights.rs @@ -18,25 +18,27 @@ //! Autogenerated weights for `pallet_revive` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-10-30, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-wmcgzesc-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// target/production/substrate-node +// ./target/production/substrate-node // benchmark // pallet +// --chain=dev // --steps=50 // --repeat=20 +// --pallet=pallet_revive +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_revive -// --chain=dev -// --header=./substrate/HEADER-APACHE2 // --output=./substrate/frame/revive/src/weights.rs +// --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -131,8 +133,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `1594` - // Minimum execution time: 2_649_000 picoseconds. - Weight::from_parts(2_726_000, 1594) + // Minimum execution time: 2_818_000 picoseconds. + Weight::from_parts(3_058_000, 1594) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -142,10 +144,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `425 + k * (69 ±0)` // Estimated: `415 + k * (70 ±0)` - // Minimum execution time: 12_756_000 picoseconds. - Weight::from_parts(13_112_000, 415) - // Standard Error: 988 - .saturating_add(Weight::from_parts(1_131_927, 0).saturating_mul(k.into())) + // Minimum execution time: 15_916_000 picoseconds. + Weight::from_parts(16_132_000, 415) + // Standard Error: 1_482 + .saturating_add(Weight::from_parts(1_185_583, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -167,10 +169,10 @@ impl WeightInfo for SubstrateWeight { /// The range of component `c` is `[0, 262144]`. fn call_with_code_per_byte(_c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1465` - // Estimated: `7405` - // Minimum execution time: 86_553_000 picoseconds. - Weight::from_parts(89_689_079, 7405) + // Measured: `1502` + // Estimated: `7442` + // Minimum execution time: 88_115_000 picoseconds. + Weight::from_parts(92_075_651, 7442) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -190,14 +192,16 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. /// The range of component `i` is `[0, 262144]`. - fn instantiate_with_code(_c: u32, i: u32, ) -> Weight { + fn instantiate_with_code(c: u32, i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `416` - // Estimated: `6333` - // Minimum execution time: 180_721_000 picoseconds. - Weight::from_parts(155_866_981, 6333) + // Measured: `403` + // Estimated: `6326` + // Minimum execution time: 188_274_000 picoseconds. + Weight::from_parts(157_773_869, 6326) + // Standard Error: 11 + .saturating_add(Weight::from_parts(16, 0).saturating_mul(c.into())) // Standard Error: 11 - .saturating_add(Weight::from_parts(4_514, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(4_464, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -219,11 +223,11 @@ impl WeightInfo for SubstrateWeight { fn instantiate(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `1296` - // Estimated: `4741` - // Minimum execution time: 151_590_000 picoseconds. - Weight::from_parts(128_110_988, 4741) - // Standard Error: 16 - .saturating_add(Weight::from_parts(4_453, 0).saturating_mul(i.into())) + // Estimated: `4739` + // Minimum execution time: 158_616_000 picoseconds. + Weight::from_parts(134_329_076, 4739) + // Standard Error: 15 + .saturating_add(Weight::from_parts(4_358, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -241,10 +245,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) fn call() -> Weight { // Proof Size summary in bytes: - // Measured: `1465` - // Estimated: `7405` - // Minimum execution time: 136_371_000 picoseconds. - Weight::from_parts(140_508_000, 7405) + // Measured: `1502` + // Estimated: `7442` + // Minimum execution time: 134_935_000 picoseconds. + Weight::from_parts(141_040_000, 7442) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -255,14 +259,12 @@ impl WeightInfo for SubstrateWeight { /// Storage: `Revive::PristineCode` (r:0 w:1) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. - fn upload_code(c: u32, ) -> Weight { + fn upload_code(_c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 51_255_000 picoseconds. - Weight::from_parts(52_668_809, 3574) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1, 0).saturating_mul(c.into())) + // Minimum execution time: 51_026_000 picoseconds. + Weight::from_parts(53_309_143, 3574) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -276,8 +278,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `285` // Estimated: `3750` - // Minimum execution time: 41_664_000 picoseconds. - Weight::from_parts(42_981_000, 3750) + // Minimum execution time: 44_338_000 picoseconds. + Weight::from_parts(45_398_000, 3750) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -289,8 +291,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `529` // Estimated: `6469` - // Minimum execution time: 27_020_000 picoseconds. - Weight::from_parts(27_973_000, 6469) + // Minimum execution time: 26_420_000 picoseconds. + Weight::from_parts(27_141_000, 6469) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -302,8 +304,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 42_342_000 picoseconds. - Weight::from_parts(43_210_000, 3574) + // Minimum execution time: 39_735_000 picoseconds. + Weight::from_parts(41_260_000, 3574) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -315,8 +317,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `56` // Estimated: `3521` - // Minimum execution time: 31_881_000 picoseconds. - Weight::from_parts(32_340_000, 3521) + // Minimum execution time: 32_059_000 picoseconds. + Weight::from_parts(32_776_000, 3521) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -328,8 +330,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 11_087_000 picoseconds. - Weight::from_parts(11_416_000, 3610) + // Minimum execution time: 13_553_000 picoseconds. + Weight::from_parts(14_121_000, 3610) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// The range of component `r` is `[0, 1600]`. @@ -337,24 +339,24 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_403_000 picoseconds. - Weight::from_parts(7_751_101, 0) - // Standard Error: 99 - .saturating_add(Weight::from_parts(179_467, 0).saturating_mul(r.into())) + // Minimum execution time: 6_392_000 picoseconds. + Weight::from_parts(7_692_248, 0) + // Standard Error: 105 + .saturating_add(Weight::from_parts(180_036, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 272_000 picoseconds. - Weight::from_parts(306_000, 0) + // Minimum execution time: 287_000 picoseconds. + Weight::from_parts(317_000, 0) } fn seal_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 226_000 picoseconds. - Weight::from_parts(261_000, 0) + // Minimum execution time: 235_000 picoseconds. + Weight::from_parts(288_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -362,8 +364,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `306` // Estimated: `3771` - // Minimum execution time: 6_727_000 picoseconds. - Weight::from_parts(7_122_000, 3771) + // Minimum execution time: 10_101_000 picoseconds. + Weight::from_parts(10_420_000, 3771) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) @@ -372,16 +374,16 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `403` // Estimated: `3868` - // Minimum execution time: 7_542_000 picoseconds. - Weight::from_parts(7_846_000, 3868) + // Minimum execution time: 11_422_000 picoseconds. + Weight::from_parts(11_829_000, 3868) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 243_000 picoseconds. - Weight::from_parts(275_000, 0) + // Minimum execution time: 247_000 picoseconds. + Weight::from_parts(282_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -391,44 +393,44 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `473` // Estimated: `3938` - // Minimum execution time: 11_948_000 picoseconds. - Weight::from_parts(12_406_000, 3938) + // Minimum execution time: 14_856_000 picoseconds. + Weight::from_parts(15_528_000, 3938) .saturating_add(T::DbWeight::get().reads(2_u64)) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 329_000 picoseconds. - Weight::from_parts(362_000, 0) + // Minimum execution time: 303_000 picoseconds. + Weight::from_parts(361_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 276_000 picoseconds. - Weight::from_parts(303_000, 0) + // Minimum execution time: 253_000 picoseconds. + Weight::from_parts(287_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 251_000 picoseconds. - Weight::from_parts(286_000, 0) + // Minimum execution time: 231_000 picoseconds. + Weight::from_parts(263_000, 0) } fn seal_weight_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 611_000 picoseconds. - Weight::from_parts(669_000, 0) + // Minimum execution time: 628_000 picoseconds. + Weight::from_parts(697_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `0` - // Minimum execution time: 4_439_000 picoseconds. - Weight::from_parts(4_572_000, 0) + // Minimum execution time: 4_531_000 picoseconds. + Weight::from_parts(4_726_000, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -438,8 +440,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `264` // Estimated: `3729` - // Minimum execution time: 9_336_000 picoseconds. - Weight::from_parts(9_622_000, 3729) + // Minimum execution time: 8_787_000 picoseconds. + Weight::from_parts(9_175_000, 3729) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Revive::ImmutableDataOf` (r:1 w:0) @@ -449,10 +451,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `238 + n * (1 ±0)` // Estimated: `3703 + n * (1 ±0)` - // Minimum execution time: 5_660_000 picoseconds. - Weight::from_parts(6_291_437, 3703) + // Minimum execution time: 5_760_000 picoseconds. + Weight::from_parts(6_591_336, 3703) // Standard Error: 4 - .saturating_add(Weight::from_parts(741, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(628, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -463,32 +465,32 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_909_000 picoseconds. - Weight::from_parts(2_154_705, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(643, 0).saturating_mul(n.into())) + // Minimum execution time: 1_971_000 picoseconds. + Weight::from_parts(2_206_252, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(529, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 241_000 picoseconds. - Weight::from_parts(283_000, 0) + // Minimum execution time: 246_000 picoseconds. + Weight::from_parts(279_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 263_000 picoseconds. - Weight::from_parts(294_000, 0) + // Minimum execution time: 223_000 picoseconds. + Weight::from_parts(274_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 218_000 picoseconds. - Weight::from_parts(281_000, 0) + // Minimum execution time: 213_000 picoseconds. + Weight::from_parts(270_000, 0) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `Measured`) @@ -496,46 +498,43 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `30` // Estimated: `3495` - // Minimum execution time: 3_373_000 picoseconds. - Weight::from_parts(3_610_000, 3495) + // Minimum execution time: 3_502_000 picoseconds. + Weight::from_parts(3_777_000, 3495) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 247_000 picoseconds. - Weight::from_parts(299_000, 0) + // Minimum execution time: 232_000 picoseconds. + Weight::from_parts(277_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) fn seal_weight_to_fee() -> Weight { // Proof Size summary in bytes: - // Measured: `67` - // Estimated: `1552` - // Minimum execution time: 5_523_000 picoseconds. - Weight::from_parts(5_757_000, 1552) - .saturating_add(T::DbWeight::get().reads(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_293_000 picoseconds. + Weight::from_parts(1_426_000, 0) } /// The range of component `n` is `[0, 262140]`. fn seal_input(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 450_000 picoseconds. - Weight::from_parts(584_658, 0) + // Minimum execution time: 449_000 picoseconds. + Weight::from_parts(446_268, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(113, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262140]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 232_000 picoseconds. - Weight::from_parts(611_960, 0) + // Minimum execution time: 244_000 picoseconds. + Weight::from_parts(612_733, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(294, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(200, 0).saturating_mul(n.into())) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -550,12 +549,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[0, 32]`. fn seal_terminate(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `321 + n * (88 ±0)` - // Estimated: `3787 + n * (2563 ±0)` - // Minimum execution time: 19_158_000 picoseconds. - Weight::from_parts(20_900_189, 3787) - // Standard Error: 9_648 - .saturating_add(Weight::from_parts(4_239_910, 0).saturating_mul(n.into())) + // Measured: `324 + n * (88 ±0)` + // Estimated: `3789 + n * (2563 ±0)` + // Minimum execution time: 21_822_000 picoseconds. + Weight::from_parts(22_468_601, 3789) + // Standard Error: 7_303 + .saturating_add(Weight::from_parts(4_138_073, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -568,22 +567,22 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_097_000 picoseconds. - Weight::from_parts(3_956_608, 0) - // Standard Error: 2_678 - .saturating_add(Weight::from_parts(178_555, 0).saturating_mul(t.into())) - // Standard Error: 23 - .saturating_add(Weight::from_parts(1_127, 0).saturating_mul(n.into())) + // Minimum execution time: 4_127_000 picoseconds. + Weight::from_parts(4_043_097, 0) + // Standard Error: 3_136 + .saturating_add(Weight::from_parts(209_603, 0).saturating_mul(t.into())) + // Standard Error: 28 + .saturating_add(Weight::from_parts(988, 0).saturating_mul(n.into())) } /// The range of component `i` is `[0, 262144]`. fn seal_debug_message(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 277_000 picoseconds. - Weight::from_parts(1_044_051, 0) + // Minimum execution time: 276_000 picoseconds. + Weight::from_parts(1_111_301, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(794, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(706, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -591,8 +590,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 7_745_000 picoseconds. - Weight::from_parts(8_370_000, 744) + // Minimum execution time: 7_869_000 picoseconds. + Weight::from_parts(8_190_000, 744) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -601,8 +600,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 43_559_000 picoseconds. - Weight::from_parts(44_310_000, 10754) + // Minimum execution time: 42_793_000 picoseconds. + Weight::from_parts(43_861_000, 10754) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -611,8 +610,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 8_866_000 picoseconds. - Weight::from_parts(9_072_000, 744) + // Minimum execution time: 8_753_000 picoseconds. + Weight::from_parts(9_235_000, 744) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -622,8 +621,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 44_481_000 picoseconds. - Weight::from_parts(45_157_000, 10754) + // Minimum execution time: 44_446_000 picoseconds. + Weight::from_parts(45_586_000, 10754) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -635,12 +634,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + o * (1 ±0)` // Estimated: `247 + o * (1 ±0)` - // Minimum execution time: 9_130_000 picoseconds. - Weight::from_parts(9_709_648, 247) - // Standard Error: 40 - .saturating_add(Weight::from_parts(435, 0).saturating_mul(n.into())) - // Standard Error: 40 - .saturating_add(Weight::from_parts(384, 0).saturating_mul(o.into())) + // Minimum execution time: 9_214_000 picoseconds. + Weight::from_parts(9_888_060, 247) + // Standard Error: 41 + .saturating_add(Weight::from_parts(151, 0).saturating_mul(n.into())) + // Standard Error: 41 + .saturating_add(Weight::from_parts(315, 0).saturating_mul(o.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -652,10 +651,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 8_753_000 picoseconds. - Weight::from_parts(9_558_399, 247) - // Standard Error: 56 - .saturating_add(Weight::from_parts(483, 0).saturating_mul(n.into())) + // Minimum execution time: 8_647_000 picoseconds. + Weight::from_parts(9_553_009, 247) + // Standard Error: 48 + .saturating_add(Weight::from_parts(651, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -667,10 +666,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 8_328_000 picoseconds. - Weight::from_parts(9_120_157, 247) - // Standard Error: 58 - .saturating_add(Weight::from_parts(1_637, 0).saturating_mul(n.into())) + // Minimum execution time: 8_457_000 picoseconds. + Weight::from_parts(9_199_745, 247) + // Standard Error: 59 + .saturating_add(Weight::from_parts(1_562, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -681,10 +680,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 7_977_000 picoseconds. - Weight::from_parts(8_582_869, 247) - // Standard Error: 52 - .saturating_add(Weight::from_parts(854, 0).saturating_mul(n.into())) + // Minimum execution time: 8_025_000 picoseconds. + Weight::from_parts(8_700_911, 247) + // Standard Error: 49 + .saturating_add(Weight::from_parts(635, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -695,10 +694,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 9_193_000 picoseconds. - Weight::from_parts(10_112_966, 247) - // Standard Error: 63 - .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) + // Minimum execution time: 9_346_000 picoseconds. + Weight::from_parts(10_297_284, 247) + // Standard Error: 62 + .saturating_add(Weight::from_parts(1_396, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -707,36 +706,36 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_398_000 picoseconds. - Weight::from_parts(1_490_000, 0) + // Minimum execution time: 1_428_000 picoseconds. + Weight::from_parts(1_517_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_762_000 picoseconds. - Weight::from_parts(1_926_000, 0) + // Minimum execution time: 1_868_000 picoseconds. + Weight::from_parts(1_942_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_413_000 picoseconds. - Weight::from_parts(1_494_000, 0) + // Minimum execution time: 1_403_000 picoseconds. + Weight::from_parts(1_539_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_606_000 picoseconds. - Weight::from_parts(1_659_000, 0) + // Minimum execution time: 1_676_000 picoseconds. + Weight::from_parts(1_760_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_010_000 picoseconds. - Weight::from_parts(1_117_000, 0) + // Minimum execution time: 1_119_000 picoseconds. + Weight::from_parts(1_205_000, 0) } /// The range of component `n` is `[0, 512]`. /// The range of component `o` is `[0, 512]`. @@ -744,50 +743,50 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_194_000 picoseconds. - Weight::from_parts(2_290_633, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(341, 0).saturating_mul(n.into())) - // Standard Error: 11 - .saturating_add(Weight::from_parts(377, 0).saturating_mul(o.into())) + // Minimum execution time: 2_146_000 picoseconds. + Weight::from_parts(2_315_339, 0) + // Standard Error: 13 + .saturating_add(Weight::from_parts(327, 0).saturating_mul(n.into())) + // Standard Error: 13 + .saturating_add(Weight::from_parts(366, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 512]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_896_000 picoseconds. - Weight::from_parts(2_254_323, 0) - // Standard Error: 17 - .saturating_add(Weight::from_parts(439, 0).saturating_mul(n.into())) + // Minimum execution time: 1_950_000 picoseconds. + Weight::from_parts(2_271_073, 0) + // Standard Error: 15 + .saturating_add(Weight::from_parts(373, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_800_000 picoseconds. - Weight::from_parts(1_948_552, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(360, 0).saturating_mul(n.into())) + // Minimum execution time: 1_839_000 picoseconds. + Weight::from_parts(2_049_659, 0) + // Standard Error: 14 + .saturating_add(Weight::from_parts(291, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_615_000 picoseconds. - Weight::from_parts(1_812_731, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(177, 0).saturating_mul(n.into())) + // Minimum execution time: 1_716_000 picoseconds. + Weight::from_parts(1_893_932, 0) + // Standard Error: 12 + .saturating_add(Weight::from_parts(172, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_430_000 picoseconds. - Weight::from_parts(2_669_757, 0) + // Minimum execution time: 2_448_000 picoseconds. + Weight::from_parts(2_676_764, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -797,19 +796,24 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) /// Storage: `Revive::PristineCode` (r:1 w:0) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// The range of component `t` is `[0, 1]`. /// The range of component `i` is `[0, 262144]`. fn seal_call(t: u32, i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1292 + t * (103 ±0)` - // Estimated: `4757 + t * (103 ±0)` - // Minimum execution time: 37_280_000 picoseconds. - Weight::from_parts(41_639_379, 4757) + // Measured: `1294 + t * (242 ±0)` + // Estimated: `4759 + t * (2501 ±0)` + // Minimum execution time: 39_786_000 picoseconds. + Weight::from_parts(41_175_457, 4759) + // Standard Error: 45_251 + .saturating_add(Weight::from_parts(2_375_617, 0).saturating_mul(t.into())) // Standard Error: 0 .saturating_add(Weight::from_parts(2, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) - .saturating_add(Weight::from_parts(0, 103).saturating_mul(t.into())) + .saturating_add(Weight::from_parts(0, 2501).saturating_mul(t.into())) } /// Storage: `Revive::CodeInfoOf` (r:1 w:0) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -819,8 +823,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1064` // Estimated: `4529` - // Minimum execution time: 27_564_000 picoseconds. - Weight::from_parts(28_809_000, 4529) + // Minimum execution time: 29_762_000 picoseconds. + Weight::from_parts(31_345_000, 4529) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) @@ -834,12 +838,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `i` is `[0, 262144]`. fn seal_instantiate(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1273` - // Estimated: `4732` - // Minimum execution time: 115_581_000 picoseconds. - Weight::from_parts(105_196_218, 4732) + // Measured: `1310` + // Estimated: `4748` + // Minimum execution time: 117_791_000 picoseconds. + Weight::from_parts(105_413_907, 4748) // Standard Error: 11 - .saturating_add(Weight::from_parts(4_134, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(4_038, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -848,64 +852,64 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 605_000 picoseconds. - Weight::from_parts(3_425_431, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_461, 0).saturating_mul(n.into())) + // Minimum execution time: 638_000 picoseconds. + Weight::from_parts(4_703_710, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_349, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_113_000 picoseconds. - Weight::from_parts(4_611_854, 0) + // Minimum execution time: 1_085_000 picoseconds. + Weight::from_parts(3_630_716, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(3_652, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_567, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 610_000 picoseconds. - Weight::from_parts(3_872_321, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_584, 0).saturating_mul(n.into())) + // Minimum execution time: 643_000 picoseconds. + Weight::from_parts(3_733_026, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_492, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 559_000 picoseconds. - Weight::from_parts(4_721_584, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(4_627_285, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(1_570, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_478, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 261889]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_467_000 picoseconds. - Weight::from_parts(36_639_352, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(5_216, 0).saturating_mul(n.into())) + // Minimum execution time: 45_786_000 picoseconds. + Weight::from_parts(36_383_470, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(5_396, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_106_000 picoseconds. - Weight::from_parts(49_352_000, 0) + // Minimum execution time: 48_140_000 picoseconds. + Weight::from_parts(49_720_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_616_000 picoseconds. - Weight::from_parts(12_796_000, 0) + // Minimum execution time: 12_565_000 picoseconds. + Weight::from_parts(12_704_000, 0) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -913,8 +917,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `300` // Estimated: `3765` - // Minimum execution time: 14_055_000 picoseconds. - Weight::from_parts(14_526_000, 3765) + // Minimum execution time: 17_208_000 picoseconds. + Weight::from_parts(18_307_000, 3765) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -922,10 +926,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) fn lock_delegate_dependency() -> Weight { // Proof Size summary in bytes: - // Measured: `337` - // Estimated: `3802` - // Minimum execution time: 10_338_000 picoseconds. - Weight::from_parts(10_677_000, 3802) + // Measured: `338` + // Estimated: `3803` + // Minimum execution time: 13_686_000 picoseconds. + Weight::from_parts(14_186_000, 3803) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -933,10 +937,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `MaxEncodedLen`) fn unlock_delegate_dependency() -> Weight { // Proof Size summary in bytes: - // Measured: `337` + // Measured: `338` // Estimated: `3561` - // Minimum execution time: 8_740_000 picoseconds. - Weight::from_parts(9_329_000, 3561) + // Minimum execution time: 12_381_000 picoseconds. + Weight::from_parts(13_208_000, 3561) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -945,10 +949,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_846_000 picoseconds. - Weight::from_parts(9_717_991, 0) - // Standard Error: 49 - .saturating_add(Weight::from_parts(72_062, 0).saturating_mul(r.into())) + // Minimum execution time: 8_118_000 picoseconds. + Weight::from_parts(9_813_514, 0) + // Standard Error: 40 + .saturating_add(Weight::from_parts(71_154, 0).saturating_mul(r.into())) } } @@ -960,8 +964,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `109` // Estimated: `1594` - // Minimum execution time: 2_649_000 picoseconds. - Weight::from_parts(2_726_000, 1594) + // Minimum execution time: 2_818_000 picoseconds. + Weight::from_parts(3_058_000, 1594) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -971,10 +975,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `425 + k * (69 ±0)` // Estimated: `415 + k * (70 ±0)` - // Minimum execution time: 12_756_000 picoseconds. - Weight::from_parts(13_112_000, 415) - // Standard Error: 988 - .saturating_add(Weight::from_parts(1_131_927, 0).saturating_mul(k.into())) + // Minimum execution time: 15_916_000 picoseconds. + Weight::from_parts(16_132_000, 415) + // Standard Error: 1_482 + .saturating_add(Weight::from_parts(1_185_583, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -996,10 +1000,10 @@ impl WeightInfo for () { /// The range of component `c` is `[0, 262144]`. fn call_with_code_per_byte(_c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1465` - // Estimated: `7405` - // Minimum execution time: 86_553_000 picoseconds. - Weight::from_parts(89_689_079, 7405) + // Measured: `1502` + // Estimated: `7442` + // Minimum execution time: 88_115_000 picoseconds. + Weight::from_parts(92_075_651, 7442) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1019,14 +1023,16 @@ impl WeightInfo for () { /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. /// The range of component `i` is `[0, 262144]`. - fn instantiate_with_code(_c: u32, i: u32, ) -> Weight { + fn instantiate_with_code(c: u32, i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `416` - // Estimated: `6333` - // Minimum execution time: 180_721_000 picoseconds. - Weight::from_parts(155_866_981, 6333) + // Measured: `403` + // Estimated: `6326` + // Minimum execution time: 188_274_000 picoseconds. + Weight::from_parts(157_773_869, 6326) // Standard Error: 11 - .saturating_add(Weight::from_parts(4_514, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(16, 0).saturating_mul(c.into())) + // Standard Error: 11 + .saturating_add(Weight::from_parts(4_464, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -1048,11 +1054,11 @@ impl WeightInfo for () { fn instantiate(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `1296` - // Estimated: `4741` - // Minimum execution time: 151_590_000 picoseconds. - Weight::from_parts(128_110_988, 4741) - // Standard Error: 16 - .saturating_add(Weight::from_parts(4_453, 0).saturating_mul(i.into())) + // Estimated: `4739` + // Minimum execution time: 158_616_000 picoseconds. + Weight::from_parts(134_329_076, 4739) + // Standard Error: 15 + .saturating_add(Weight::from_parts(4_358, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -1070,10 +1076,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) fn call() -> Weight { // Proof Size summary in bytes: - // Measured: `1465` - // Estimated: `7405` - // Minimum execution time: 136_371_000 picoseconds. - Weight::from_parts(140_508_000, 7405) + // Measured: `1502` + // Estimated: `7442` + // Minimum execution time: 134_935_000 picoseconds. + Weight::from_parts(141_040_000, 7442) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1084,14 +1090,12 @@ impl WeightInfo for () { /// Storage: `Revive::PristineCode` (r:0 w:1) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) /// The range of component `c` is `[0, 262144]`. - fn upload_code(c: u32, ) -> Weight { + fn upload_code(_c: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 51_255_000 picoseconds. - Weight::from_parts(52_668_809, 3574) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1, 0).saturating_mul(c.into())) + // Minimum execution time: 51_026_000 picoseconds. + Weight::from_parts(53_309_143, 3574) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1105,8 +1109,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `285` // Estimated: `3750` - // Minimum execution time: 41_664_000 picoseconds. - Weight::from_parts(42_981_000, 3750) + // Minimum execution time: 44_338_000 picoseconds. + Weight::from_parts(45_398_000, 3750) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1118,8 +1122,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `529` // Estimated: `6469` - // Minimum execution time: 27_020_000 picoseconds. - Weight::from_parts(27_973_000, 6469) + // Minimum execution time: 26_420_000 picoseconds. + Weight::from_parts(27_141_000, 6469) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1131,8 +1135,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 42_342_000 picoseconds. - Weight::from_parts(43_210_000, 3574) + // Minimum execution time: 39_735_000 picoseconds. + Weight::from_parts(41_260_000, 3574) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1144,8 +1148,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `56` // Estimated: `3521` - // Minimum execution time: 31_881_000 picoseconds. - Weight::from_parts(32_340_000, 3521) + // Minimum execution time: 32_059_000 picoseconds. + Weight::from_parts(32_776_000, 3521) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1157,8 +1161,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 11_087_000 picoseconds. - Weight::from_parts(11_416_000, 3610) + // Minimum execution time: 13_553_000 picoseconds. + Weight::from_parts(14_121_000, 3610) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// The range of component `r` is `[0, 1600]`. @@ -1166,24 +1170,24 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_403_000 picoseconds. - Weight::from_parts(7_751_101, 0) - // Standard Error: 99 - .saturating_add(Weight::from_parts(179_467, 0).saturating_mul(r.into())) + // Minimum execution time: 6_392_000 picoseconds. + Weight::from_parts(7_692_248, 0) + // Standard Error: 105 + .saturating_add(Weight::from_parts(180_036, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 272_000 picoseconds. - Weight::from_parts(306_000, 0) + // Minimum execution time: 287_000 picoseconds. + Weight::from_parts(317_000, 0) } fn seal_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 226_000 picoseconds. - Weight::from_parts(261_000, 0) + // Minimum execution time: 235_000 picoseconds. + Weight::from_parts(288_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -1191,8 +1195,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `306` // Estimated: `3771` - // Minimum execution time: 6_727_000 picoseconds. - Weight::from_parts(7_122_000, 3771) + // Minimum execution time: 10_101_000 picoseconds. + Weight::from_parts(10_420_000, 3771) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) @@ -1201,16 +1205,16 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `403` // Estimated: `3868` - // Minimum execution time: 7_542_000 picoseconds. - Weight::from_parts(7_846_000, 3868) + // Minimum execution time: 11_422_000 picoseconds. + Weight::from_parts(11_829_000, 3868) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 243_000 picoseconds. - Weight::from_parts(275_000, 0) + // Minimum execution time: 247_000 picoseconds. + Weight::from_parts(282_000, 0) } /// Storage: `Revive::ContractInfoOf` (r:1 w:0) /// Proof: `Revive::ContractInfoOf` (`max_values`: None, `max_size`: Some(1779), added: 4254, mode: `Measured`) @@ -1220,44 +1224,44 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `473` // Estimated: `3938` - // Minimum execution time: 11_948_000 picoseconds. - Weight::from_parts(12_406_000, 3938) + // Minimum execution time: 14_856_000 picoseconds. + Weight::from_parts(15_528_000, 3938) .saturating_add(RocksDbWeight::get().reads(2_u64)) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 329_000 picoseconds. - Weight::from_parts(362_000, 0) + // Minimum execution time: 303_000 picoseconds. + Weight::from_parts(361_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 276_000 picoseconds. - Weight::from_parts(303_000, 0) + // Minimum execution time: 253_000 picoseconds. + Weight::from_parts(287_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 251_000 picoseconds. - Weight::from_parts(286_000, 0) + // Minimum execution time: 231_000 picoseconds. + Weight::from_parts(263_000, 0) } fn seal_weight_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 611_000 picoseconds. - Weight::from_parts(669_000, 0) + // Minimum execution time: 628_000 picoseconds. + Weight::from_parts(697_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `103` // Estimated: `0` - // Minimum execution time: 4_439_000 picoseconds. - Weight::from_parts(4_572_000, 0) + // Minimum execution time: 4_531_000 picoseconds. + Weight::from_parts(4_726_000, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1267,8 +1271,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `264` // Estimated: `3729` - // Minimum execution time: 9_336_000 picoseconds. - Weight::from_parts(9_622_000, 3729) + // Minimum execution time: 8_787_000 picoseconds. + Weight::from_parts(9_175_000, 3729) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Revive::ImmutableDataOf` (r:1 w:0) @@ -1278,10 +1282,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `238 + n * (1 ±0)` // Estimated: `3703 + n * (1 ±0)` - // Minimum execution time: 5_660_000 picoseconds. - Weight::from_parts(6_291_437, 3703) + // Minimum execution time: 5_760_000 picoseconds. + Weight::from_parts(6_591_336, 3703) // Standard Error: 4 - .saturating_add(Weight::from_parts(741, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(628, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1292,32 +1296,32 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_909_000 picoseconds. - Weight::from_parts(2_154_705, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(643, 0).saturating_mul(n.into())) + // Minimum execution time: 1_971_000 picoseconds. + Weight::from_parts(2_206_252, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(529, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 241_000 picoseconds. - Weight::from_parts(283_000, 0) + // Minimum execution time: 246_000 picoseconds. + Weight::from_parts(279_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 263_000 picoseconds. - Weight::from_parts(294_000, 0) + // Minimum execution time: 223_000 picoseconds. + Weight::from_parts(274_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 218_000 picoseconds. - Weight::from_parts(281_000, 0) + // Minimum execution time: 213_000 picoseconds. + Weight::from_parts(270_000, 0) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `Measured`) @@ -1325,46 +1329,43 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `30` // Estimated: `3495` - // Minimum execution time: 3_373_000 picoseconds. - Weight::from_parts(3_610_000, 3495) + // Minimum execution time: 3_502_000 picoseconds. + Weight::from_parts(3_777_000, 3495) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 247_000 picoseconds. - Weight::from_parts(299_000, 0) + // Minimum execution time: 232_000 picoseconds. + Weight::from_parts(277_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) fn seal_weight_to_fee() -> Weight { // Proof Size summary in bytes: - // Measured: `67` - // Estimated: `1552` - // Minimum execution time: 5_523_000 picoseconds. - Weight::from_parts(5_757_000, 1552) - .saturating_add(RocksDbWeight::get().reads(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_293_000 picoseconds. + Weight::from_parts(1_426_000, 0) } /// The range of component `n` is `[0, 262140]`. fn seal_input(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 450_000 picoseconds. - Weight::from_parts(584_658, 0) + // Minimum execution time: 449_000 picoseconds. + Weight::from_parts(446_268, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(113, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262140]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 232_000 picoseconds. - Weight::from_parts(611_960, 0) + // Minimum execution time: 244_000 picoseconds. + Weight::from_parts(612_733, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(294, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(200, 0).saturating_mul(n.into())) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1379,12 +1380,12 @@ impl WeightInfo for () { /// The range of component `n` is `[0, 32]`. fn seal_terminate(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `321 + n * (88 ±0)` - // Estimated: `3787 + n * (2563 ±0)` - // Minimum execution time: 19_158_000 picoseconds. - Weight::from_parts(20_900_189, 3787) - // Standard Error: 9_648 - .saturating_add(Weight::from_parts(4_239_910, 0).saturating_mul(n.into())) + // Measured: `324 + n * (88 ±0)` + // Estimated: `3789 + n * (2563 ±0)` + // Minimum execution time: 21_822_000 picoseconds. + Weight::from_parts(22_468_601, 3789) + // Standard Error: 7_303 + .saturating_add(Weight::from_parts(4_138_073, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -1397,22 +1398,22 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_097_000 picoseconds. - Weight::from_parts(3_956_608, 0) - // Standard Error: 2_678 - .saturating_add(Weight::from_parts(178_555, 0).saturating_mul(t.into())) - // Standard Error: 23 - .saturating_add(Weight::from_parts(1_127, 0).saturating_mul(n.into())) + // Minimum execution time: 4_127_000 picoseconds. + Weight::from_parts(4_043_097, 0) + // Standard Error: 3_136 + .saturating_add(Weight::from_parts(209_603, 0).saturating_mul(t.into())) + // Standard Error: 28 + .saturating_add(Weight::from_parts(988, 0).saturating_mul(n.into())) } /// The range of component `i` is `[0, 262144]`. fn seal_debug_message(i: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 277_000 picoseconds. - Weight::from_parts(1_044_051, 0) + // Minimum execution time: 276_000 picoseconds. + Weight::from_parts(1_111_301, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(794, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(706, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -1420,8 +1421,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 7_745_000 picoseconds. - Weight::from_parts(8_370_000, 744) + // Minimum execution time: 7_869_000 picoseconds. + Weight::from_parts(8_190_000, 744) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1430,8 +1431,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 43_559_000 picoseconds. - Weight::from_parts(44_310_000, 10754) + // Minimum execution time: 42_793_000 picoseconds. + Weight::from_parts(43_861_000, 10754) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1440,8 +1441,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `744` // Estimated: `744` - // Minimum execution time: 8_866_000 picoseconds. - Weight::from_parts(9_072_000, 744) + // Minimum execution time: 8_753_000 picoseconds. + Weight::from_parts(9_235_000, 744) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1451,8 +1452,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `10754` // Estimated: `10754` - // Minimum execution time: 44_481_000 picoseconds. - Weight::from_parts(45_157_000, 10754) + // Minimum execution time: 44_446_000 picoseconds. + Weight::from_parts(45_586_000, 10754) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1464,12 +1465,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + o * (1 ±0)` // Estimated: `247 + o * (1 ±0)` - // Minimum execution time: 9_130_000 picoseconds. - Weight::from_parts(9_709_648, 247) - // Standard Error: 40 - .saturating_add(Weight::from_parts(435, 0).saturating_mul(n.into())) - // Standard Error: 40 - .saturating_add(Weight::from_parts(384, 0).saturating_mul(o.into())) + // Minimum execution time: 9_214_000 picoseconds. + Weight::from_parts(9_888_060, 247) + // Standard Error: 41 + .saturating_add(Weight::from_parts(151, 0).saturating_mul(n.into())) + // Standard Error: 41 + .saturating_add(Weight::from_parts(315, 0).saturating_mul(o.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -1481,10 +1482,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 8_753_000 picoseconds. - Weight::from_parts(9_558_399, 247) - // Standard Error: 56 - .saturating_add(Weight::from_parts(483, 0).saturating_mul(n.into())) + // Minimum execution time: 8_647_000 picoseconds. + Weight::from_parts(9_553_009, 247) + // Standard Error: 48 + .saturating_add(Weight::from_parts(651, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1496,10 +1497,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 8_328_000 picoseconds. - Weight::from_parts(9_120_157, 247) - // Standard Error: 58 - .saturating_add(Weight::from_parts(1_637, 0).saturating_mul(n.into())) + // Minimum execution time: 8_457_000 picoseconds. + Weight::from_parts(9_199_745, 247) + // Standard Error: 59 + .saturating_add(Weight::from_parts(1_562, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1510,10 +1511,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 7_977_000 picoseconds. - Weight::from_parts(8_582_869, 247) - // Standard Error: 52 - .saturating_add(Weight::from_parts(854, 0).saturating_mul(n.into())) + // Minimum execution time: 8_025_000 picoseconds. + Weight::from_parts(8_700_911, 247) + // Standard Error: 49 + .saturating_add(Weight::from_parts(635, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1524,10 +1525,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `247 + n * (1 ±0)` - // Minimum execution time: 9_193_000 picoseconds. - Weight::from_parts(10_112_966, 247) - // Standard Error: 63 - .saturating_add(Weight::from_parts(1_320, 0).saturating_mul(n.into())) + // Minimum execution time: 9_346_000 picoseconds. + Weight::from_parts(10_297_284, 247) + // Standard Error: 62 + .saturating_add(Weight::from_parts(1_396, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1536,36 +1537,36 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_398_000 picoseconds. - Weight::from_parts(1_490_000, 0) + // Minimum execution time: 1_428_000 picoseconds. + Weight::from_parts(1_517_000, 0) } fn set_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_762_000 picoseconds. - Weight::from_parts(1_926_000, 0) + // Minimum execution time: 1_868_000 picoseconds. + Weight::from_parts(1_942_000, 0) } fn get_transient_storage_empty() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_413_000 picoseconds. - Weight::from_parts(1_494_000, 0) + // Minimum execution time: 1_403_000 picoseconds. + Weight::from_parts(1_539_000, 0) } fn get_transient_storage_full() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_606_000 picoseconds. - Weight::from_parts(1_659_000, 0) + // Minimum execution time: 1_676_000 picoseconds. + Weight::from_parts(1_760_000, 0) } fn rollback_transient_storage() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_010_000 picoseconds. - Weight::from_parts(1_117_000, 0) + // Minimum execution time: 1_119_000 picoseconds. + Weight::from_parts(1_205_000, 0) } /// The range of component `n` is `[0, 512]`. /// The range of component `o` is `[0, 512]`. @@ -1573,50 +1574,50 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_194_000 picoseconds. - Weight::from_parts(2_290_633, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(341, 0).saturating_mul(n.into())) - // Standard Error: 11 - .saturating_add(Weight::from_parts(377, 0).saturating_mul(o.into())) + // Minimum execution time: 2_146_000 picoseconds. + Weight::from_parts(2_315_339, 0) + // Standard Error: 13 + .saturating_add(Weight::from_parts(327, 0).saturating_mul(n.into())) + // Standard Error: 13 + .saturating_add(Weight::from_parts(366, 0).saturating_mul(o.into())) } /// The range of component `n` is `[0, 512]`. fn seal_clear_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_896_000 picoseconds. - Weight::from_parts(2_254_323, 0) - // Standard Error: 17 - .saturating_add(Weight::from_parts(439, 0).saturating_mul(n.into())) + // Minimum execution time: 1_950_000 picoseconds. + Weight::from_parts(2_271_073, 0) + // Standard Error: 15 + .saturating_add(Weight::from_parts(373, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_get_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_800_000 picoseconds. - Weight::from_parts(1_948_552, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(360, 0).saturating_mul(n.into())) + // Minimum execution time: 1_839_000 picoseconds. + Weight::from_parts(2_049_659, 0) + // Standard Error: 14 + .saturating_add(Weight::from_parts(291, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_contains_transient_storage(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_615_000 picoseconds. - Weight::from_parts(1_812_731, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(177, 0).saturating_mul(n.into())) + // Minimum execution time: 1_716_000 picoseconds. + Weight::from_parts(1_893_932, 0) + // Standard Error: 12 + .saturating_add(Weight::from_parts(172, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 512]`. fn seal_take_transient_storage(_n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_430_000 picoseconds. - Weight::from_parts(2_669_757, 0) + // Minimum execution time: 2_448_000 picoseconds. + Weight::from_parts(2_676_764, 0) } /// Storage: `Revive::AddressSuffix` (r:1 w:0) /// Proof: `Revive::AddressSuffix` (`max_values`: None, `max_size`: Some(32), added: 2507, mode: `Measured`) @@ -1626,19 +1627,24 @@ impl WeightInfo for () { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) /// Storage: `Revive::PristineCode` (r:1 w:0) /// Proof: `Revive::PristineCode` (`max_values`: None, `max_size`: Some(262180), added: 264655, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:0) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `Measured`) /// The range of component `t` is `[0, 1]`. /// The range of component `i` is `[0, 262144]`. fn seal_call(t: u32, i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1292 + t * (103 ±0)` - // Estimated: `4757 + t * (103 ±0)` - // Minimum execution time: 37_280_000 picoseconds. - Weight::from_parts(41_639_379, 4757) + // Measured: `1294 + t * (242 ±0)` + // Estimated: `4759 + t * (2501 ±0)` + // Minimum execution time: 39_786_000 picoseconds. + Weight::from_parts(41_175_457, 4759) + // Standard Error: 45_251 + .saturating_add(Weight::from_parts(2_375_617, 0).saturating_mul(t.into())) // Standard Error: 0 .saturating_add(Weight::from_parts(2, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) - .saturating_add(Weight::from_parts(0, 103).saturating_mul(t.into())) + .saturating_add(Weight::from_parts(0, 2501).saturating_mul(t.into())) } /// Storage: `Revive::CodeInfoOf` (r:1 w:0) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -1648,8 +1654,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1064` // Estimated: `4529` - // Minimum execution time: 27_564_000 picoseconds. - Weight::from_parts(28_809_000, 4529) + // Minimum execution time: 29_762_000 picoseconds. + Weight::from_parts(31_345_000, 4529) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) @@ -1663,12 +1669,12 @@ impl WeightInfo for () { /// The range of component `i` is `[0, 262144]`. fn seal_instantiate(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1273` - // Estimated: `4732` - // Minimum execution time: 115_581_000 picoseconds. - Weight::from_parts(105_196_218, 4732) + // Measured: `1310` + // Estimated: `4748` + // Minimum execution time: 117_791_000 picoseconds. + Weight::from_parts(105_413_907, 4748) // Standard Error: 11 - .saturating_add(Weight::from_parts(4_134, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(4_038, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1677,64 +1683,64 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 605_000 picoseconds. - Weight::from_parts(3_425_431, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_461, 0).saturating_mul(n.into())) + // Minimum execution time: 638_000 picoseconds. + Weight::from_parts(4_703_710, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_349, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_113_000 picoseconds. - Weight::from_parts(4_611_854, 0) + // Minimum execution time: 1_085_000 picoseconds. + Weight::from_parts(3_630_716, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(3_652, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_567, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 610_000 picoseconds. - Weight::from_parts(3_872_321, 0) - // Standard Error: 2 - .saturating_add(Weight::from_parts(1_584, 0).saturating_mul(n.into())) + // Minimum execution time: 643_000 picoseconds. + Weight::from_parts(3_733_026, 0) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_492, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 262144]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 559_000 picoseconds. - Weight::from_parts(4_721_584, 0) + // Minimum execution time: 653_000 picoseconds. + Weight::from_parts(4_627_285, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(1_570, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_478, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 261889]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_467_000 picoseconds. - Weight::from_parts(36_639_352, 0) - // Standard Error: 11 - .saturating_add(Weight::from_parts(5_216, 0).saturating_mul(n.into())) + // Minimum execution time: 45_786_000 picoseconds. + Weight::from_parts(36_383_470, 0) + // Standard Error: 10 + .saturating_add(Weight::from_parts(5_396, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_106_000 picoseconds. - Weight::from_parts(49_352_000, 0) + // Minimum execution time: 48_140_000 picoseconds. + Weight::from_parts(49_720_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 12_616_000 picoseconds. - Weight::from_parts(12_796_000, 0) + // Minimum execution time: 12_565_000 picoseconds. + Weight::from_parts(12_704_000, 0) } /// Storage: `Revive::CodeInfoOf` (r:1 w:1) /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) @@ -1742,8 +1748,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `300` // Estimated: `3765` - // Minimum execution time: 14_055_000 picoseconds. - Weight::from_parts(14_526_000, 3765) + // Minimum execution time: 17_208_000 picoseconds. + Weight::from_parts(18_307_000, 3765) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1751,10 +1757,10 @@ impl WeightInfo for () { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `Measured`) fn lock_delegate_dependency() -> Weight { // Proof Size summary in bytes: - // Measured: `337` - // Estimated: `3802` - // Minimum execution time: 10_338_000 picoseconds. - Weight::from_parts(10_677_000, 3802) + // Measured: `338` + // Estimated: `3803` + // Minimum execution time: 13_686_000 picoseconds. + Weight::from_parts(14_186_000, 3803) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1762,10 +1768,10 @@ impl WeightInfo for () { /// Proof: `Revive::CodeInfoOf` (`max_values`: None, `max_size`: Some(96), added: 2571, mode: `MaxEncodedLen`) fn unlock_delegate_dependency() -> Weight { // Proof Size summary in bytes: - // Measured: `337` + // Measured: `338` // Estimated: `3561` - // Minimum execution time: 8_740_000 picoseconds. - Weight::from_parts(9_329_000, 3561) + // Minimum execution time: 12_381_000 picoseconds. + Weight::from_parts(13_208_000, 3561) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1774,9 +1780,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_846_000 picoseconds. - Weight::from_parts(9_717_991, 0) - // Standard Error: 49 - .saturating_add(Weight::from_parts(72_062, 0).saturating_mul(r.into())) + // Minimum execution time: 8_118_000 picoseconds. + Weight::from_parts(9_813_514, 0) + // Standard Error: 40 + .saturating_add(Weight::from_parts(71_154, 0).saturating_mul(r.into())) } } diff --git a/substrate/frame/safe-mode/src/weights.rs b/substrate/frame/safe-mode/src/weights.rs index c2ce2cfab9b9..631853b19462 100644 --- a/substrate/frame/safe-mode/src/weights.rs +++ b/substrate/frame/safe-mode/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_safe_mode` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -72,8 +72,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1489` - // Minimum execution time: 2_152_000 picoseconds. - Weight::from_parts(2_283_000, 1489) + // Minimum execution time: 2_982_000 picoseconds. + Weight::from_parts(3_104_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) @@ -82,23 +82,23 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 6_657_000 picoseconds. - Weight::from_parts(6_955_000, 1489) + // Minimum execution time: 7_338_000 picoseconds. + Weight::from_parts(7_813_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `SafeMode::Deposits` (r:0 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn enter() -> Weight { // Proof Size summary in bytes: // Measured: `142` - // Estimated: `3658` - // Minimum execution time: 49_366_000 picoseconds. - Weight::from_parts(50_506_000, 3658) + // Estimated: `3820` + // Minimum execution time: 48_807_000 picoseconds. + Weight::from_parts(49_731_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -108,23 +108,23 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1489` - // Minimum execution time: 7_843_000 picoseconds. - Weight::from_parts(8_205_000, 1489) + // Minimum execution time: 8_207_000 picoseconds. + Weight::from_parts(8_645_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `SafeMode::Deposits` (r:0 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn extend() -> Weight { // Proof Size summary in bytes: // Measured: `169` - // Estimated: `3658` - // Minimum execution time: 50_487_000 picoseconds. - Weight::from_parts(52_101_000, 3658) + // Estimated: `3820` + // Minimum execution time: 53_540_000 picoseconds. + Weight::from_parts(54_315_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -134,8 +134,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 8_517_000 picoseconds. - Weight::from_parts(8_894_000, 1489) + // Minimum execution time: 9_494_000 picoseconds. + Weight::from_parts(9_751_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -145,8 +145,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 8_451_000 picoseconds. - Weight::from_parts(8_745_000, 1489) + // Minimum execution time: 8_970_000 picoseconds. + Weight::from_parts(9_318_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -155,39 +155,39 @@ impl WeightInfo for SubstrateWeight { /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn release_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 42_504_000 picoseconds. - Weight::from_parts(45_493_000, 3658) + // Estimated: `3820` + // Minimum execution time: 46_187_000 picoseconds. + Weight::from_parts(47_068_000, 3820) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `SafeMode::Deposits` (r:1 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn force_release_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 40_864_000 picoseconds. - Weight::from_parts(41_626_000, 3658) + // Estimated: `3820` + // Minimum execution time: 44_809_000 picoseconds. + Weight::from_parts(45_501_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `SafeMode::Deposits` (r:1 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn force_slash_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 31_943_000 picoseconds. - Weight::from_parts(33_033_000, 3658) + // Estimated: `3820` + // Minimum execution time: 36_977_000 picoseconds. + Weight::from_parts(37_694_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -201,8 +201,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1489` - // Minimum execution time: 2_152_000 picoseconds. - Weight::from_parts(2_283_000, 1489) + // Minimum execution time: 2_982_000 picoseconds. + Weight::from_parts(3_104_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) @@ -211,23 +211,23 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 6_657_000 picoseconds. - Weight::from_parts(6_955_000, 1489) + // Minimum execution time: 7_338_000 picoseconds. + Weight::from_parts(7_813_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `SafeMode::Deposits` (r:0 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn enter() -> Weight { // Proof Size summary in bytes: // Measured: `142` - // Estimated: `3658` - // Minimum execution time: 49_366_000 picoseconds. - Weight::from_parts(50_506_000, 3658) + // Estimated: `3820` + // Minimum execution time: 48_807_000 picoseconds. + Weight::from_parts(49_731_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -237,23 +237,23 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1489` - // Minimum execution time: 7_843_000 picoseconds. - Weight::from_parts(8_205_000, 1489) + // Minimum execution time: 8_207_000 picoseconds. + Weight::from_parts(8_645_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:1) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `SafeMode::Deposits` (r:0 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn extend() -> Weight { // Proof Size summary in bytes: // Measured: `169` - // Estimated: `3658` - // Minimum execution time: 50_487_000 picoseconds. - Weight::from_parts(52_101_000, 3658) + // Estimated: `3820` + // Minimum execution time: 53_540_000 picoseconds. + Weight::from_parts(54_315_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -263,8 +263,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 8_517_000 picoseconds. - Weight::from_parts(8_894_000, 1489) + // Minimum execution time: 9_494_000 picoseconds. + Weight::from_parts(9_751_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -274,8 +274,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `169` // Estimated: `1489` - // Minimum execution time: 8_451_000 picoseconds. - Weight::from_parts(8_745_000, 1489) + // Minimum execution time: 8_970_000 picoseconds. + Weight::from_parts(9_318_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -284,39 +284,39 @@ impl WeightInfo for () { /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn release_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 42_504_000 picoseconds. - Weight::from_parts(45_493_000, 3658) + // Estimated: `3820` + // Minimum execution time: 46_187_000 picoseconds. + Weight::from_parts(47_068_000, 3820) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `SafeMode::Deposits` (r:1 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn force_release_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 40_864_000 picoseconds. - Weight::from_parts(41_626_000, 3658) + // Estimated: `3820` + // Minimum execution time: 44_809_000 picoseconds. + Weight::from_parts(45_501_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `SafeMode::Deposits` (r:1 w:1) /// Proof: `SafeMode::Deposits` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn force_slash_deposit() -> Weight { // Proof Size summary in bytes: // Measured: `292` - // Estimated: `3658` - // Minimum execution time: 31_943_000 picoseconds. - Weight::from_parts(33_033_000, 3658) + // Estimated: `3820` + // Minimum execution time: 36_977_000 picoseconds. + Weight::from_parts(37_694_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/frame/salary/src/weights.rs b/substrate/frame/salary/src/weights.rs index d4e6331919b6..f1cdaaa225a4 100644 --- a/substrate/frame/salary/src/weights.rs +++ b/substrate/frame/salary/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_salary` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -69,8 +69,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4` // Estimated: `1541` - // Minimum execution time: 7_382_000 picoseconds. - Weight::from_parts(7_793_000, 1541) + // Minimum execution time: 7_583_000 picoseconds. + Weight::from_parts(8_073_000, 1541) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -80,8 +80,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `86` // Estimated: `1541` - // Minimum execution time: 8_744_000 picoseconds. - Weight::from_parts(9_216_000, 1541) + // Minimum execution time: 9_648_000 picoseconds. + Weight::from_parts(10_016_000, 1541) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -95,8 +95,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `395` // Estimated: `3543` - // Minimum execution time: 16_728_000 picoseconds. - Weight::from_parts(17_387_000, 3543) + // Minimum execution time: 22_534_000 picoseconds. + Weight::from_parts(23_265_000, 3543) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -110,8 +110,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `462` // Estimated: `3543` - // Minimum execution time: 19_744_000 picoseconds. - Weight::from_parts(20_225_000, 3543) + // Minimum execution time: 25_764_000 picoseconds. + Weight::from_parts(26_531_000, 3543) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -125,8 +125,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `462` // Estimated: `3543` - // Minimum execution time: 56_084_000 picoseconds. - Weight::from_parts(58_484_000, 3543) + // Minimum execution time: 62_575_000 picoseconds. + Weight::from_parts(63_945_000, 3543) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -140,10 +140,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout_other() -> Weight { // Proof Size summary in bytes: - // Measured: `462` + // Measured: `514` // Estimated: `3593` - // Minimum execution time: 57_341_000 picoseconds. - Weight::from_parts(59_882_000, 3593) + // Minimum execution time: 64_043_000 picoseconds. + Weight::from_parts(65_938_000, 3593) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -155,8 +155,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `170` // Estimated: `3543` - // Minimum execution time: 10_788_000 picoseconds. - Weight::from_parts(11_109_000, 3543) + // Minimum execution time: 12_303_000 picoseconds. + Weight::from_parts(12_797_000, 3543) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -170,8 +170,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4` // Estimated: `1541` - // Minimum execution time: 7_382_000 picoseconds. - Weight::from_parts(7_793_000, 1541) + // Minimum execution time: 7_583_000 picoseconds. + Weight::from_parts(8_073_000, 1541) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -181,8 +181,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `86` // Estimated: `1541` - // Minimum execution time: 8_744_000 picoseconds. - Weight::from_parts(9_216_000, 1541) + // Minimum execution time: 9_648_000 picoseconds. + Weight::from_parts(10_016_000, 1541) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -196,8 +196,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `395` // Estimated: `3543` - // Minimum execution time: 16_728_000 picoseconds. - Weight::from_parts(17_387_000, 3543) + // Minimum execution time: 22_534_000 picoseconds. + Weight::from_parts(23_265_000, 3543) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -211,8 +211,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `462` // Estimated: `3543` - // Minimum execution time: 19_744_000 picoseconds. - Weight::from_parts(20_225_000, 3543) + // Minimum execution time: 25_764_000 picoseconds. + Weight::from_parts(26_531_000, 3543) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -226,8 +226,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `462` // Estimated: `3543` - // Minimum execution time: 56_084_000 picoseconds. - Weight::from_parts(58_484_000, 3543) + // Minimum execution time: 62_575_000 picoseconds. + Weight::from_parts(63_945_000, 3543) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -241,10 +241,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout_other() -> Weight { // Proof Size summary in bytes: - // Measured: `462` + // Measured: `514` // Estimated: `3593` - // Minimum execution time: 57_341_000 picoseconds. - Weight::from_parts(59_882_000, 3593) + // Minimum execution time: 64_043_000 picoseconds. + Weight::from_parts(65_938_000, 3593) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -256,8 +256,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `170` // Estimated: `3543` - // Minimum execution time: 10_788_000 picoseconds. - Weight::from_parts(11_109_000, 3543) + // Minimum execution time: 12_303_000 picoseconds. + Weight::from_parts(12_797_000, 3543) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/frame/scheduler/src/weights.rs b/substrate/frame/scheduler/src/weights.rs index 62d2fe78049d..dc34ae556e70 100644 --- a/substrate/frame/scheduler/src/weights.rs +++ b/substrate/frame/scheduler/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_scheduler` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -79,8 +79,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `31` // Estimated: `1489` - // Minimum execution time: 3_099_000 picoseconds. - Weight::from_parts(3_298_000, 1489) + // Minimum execution time: 3_735_000 picoseconds. + Weight::from_parts(3_928_000, 1489) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -91,10 +91,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 3_558_000 picoseconds. - Weight::from_parts(5_984_191, 110487) - // Standard Error: 564 - .saturating_add(Weight::from_parts(334_983, 0).saturating_mul(s.into())) + // Minimum execution time: 3_944_000 picoseconds. + Weight::from_parts(4_034_000, 110487) + // Standard Error: 1_119 + .saturating_add(Weight::from_parts(468_891, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -102,11 +102,11 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_389_000 picoseconds. - Weight::from_parts(3_609_000, 0) + // Minimum execution time: 3_235_000 picoseconds. + Weight::from_parts(3_423_000, 0) } /// Storage: `Preimage::PreimageFor` (r:1 w:1) - /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `Measured`) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// Storage: `Preimage::StatusFor` (r:1 w:0) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) @@ -114,15 +114,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[128, 4194304]`. fn service_task_fetched(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `246 + s * (1 ±0)` - // Estimated: `3711 + s * (1 ±0)` - // Minimum execution time: 18_292_000 picoseconds. - Weight::from_parts(18_574_000, 3711) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_189, 0).saturating_mul(s.into())) + // Measured: `141 + s * (1 ±0)` + // Estimated: `4197809` + // Minimum execution time: 18_976_000 picoseconds. + Weight::from_parts(19_220_000, 4197809) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_871, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(Weight::from_parts(0, 1).saturating_mul(s.into())) } /// Storage: `Scheduler::Lookup` (r:0 w:1) /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) @@ -130,16 +129,16 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_216_000 picoseconds. - Weight::from_parts(5_439_000, 0) + // Minimum execution time: 4_858_000 picoseconds. + Weight::from_parts(5_041_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } fn service_task_periodic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_383_000 picoseconds. - Weight::from_parts(3_661_000, 0) + // Minimum execution time: 3_249_000 picoseconds. + Weight::from_parts(3_377_000, 0) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -149,16 +148,16 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 6_692_000 picoseconds. - Weight::from_parts(7_069_000, 3997) + // Minimum execution time: 8_482_000 picoseconds. + Weight::from_parts(9_252_000, 3997) .saturating_add(T::DbWeight::get().reads(2_u64)) } fn execute_dispatch_unsigned() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_165_000 picoseconds. - Weight::from_parts(2_332_000, 0) + // Minimum execution time: 2_391_000 picoseconds. + Weight::from_parts(2_591_000, 0) } /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(107022), added: 109497, mode: `MaxEncodedLen`) @@ -167,10 +166,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 10_209_000 picoseconds. - Weight::from_parts(11_235_511, 110487) - // Standard Error: 906 - .saturating_add(Weight::from_parts(375_445, 0).saturating_mul(s.into())) + // Minimum execution time: 10_698_000 picoseconds. + Weight::from_parts(7_346_814, 110487) + // Standard Error: 2_513 + .saturating_add(Weight::from_parts(535_729, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -185,10 +184,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 15_906_000 picoseconds. - Weight::from_parts(13_697_344, 110487) - // Standard Error: 949 - .saturating_add(Weight::from_parts(564_461, 0).saturating_mul(s.into())) + // Minimum execution time: 16_371_000 picoseconds. + Weight::from_parts(9_559_789, 110487) + // Standard Error: 2_542 + .saturating_add(Weight::from_parts(723_961, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -201,10 +200,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `596 + s * (178 ±0)` // Estimated: `110487` - // Minimum execution time: 13_618_000 picoseconds. - Weight::from_parts(17_489_572, 110487) - // Standard Error: 766 - .saturating_add(Weight::from_parts(377_559, 0).saturating_mul(s.into())) + // Minimum execution time: 13_995_000 picoseconds. + Weight::from_parts(16_677_389, 110487) + // Standard Error: 2_606 + .saturating_add(Weight::from_parts(555_434, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -219,10 +218,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `709 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 17_954_000 picoseconds. - Weight::from_parts(18_459_344, 110487) - // Standard Error: 835 - .saturating_add(Weight::from_parts(585_557, 0).saturating_mul(s.into())) + // Minimum execution time: 18_962_000 picoseconds. + Weight::from_parts(17_610_180, 110487) + // Standard Error: 2_556 + .saturating_add(Weight::from_parts(743_494, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -235,10 +234,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `118` // Estimated: `110487` - // Minimum execution time: 9_446_000 picoseconds. - Weight::from_parts(10_797_672, 110487) - // Standard Error: 184 - .saturating_add(Weight::from_parts(13_971, 0).saturating_mul(s.into())) + // Minimum execution time: 10_303_000 picoseconds. + Weight::from_parts(12_180_080, 110487) + // Standard Error: 286 + .saturating_add(Weight::from_parts(16_437, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -250,8 +249,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `90705` // Estimated: `110487` - // Minimum execution time: 137_044_000 picoseconds. - Weight::from_parts(142_855_000, 110487) + // Minimum execution time: 156_198_000 picoseconds. + Weight::from_parts(167_250_000, 110487) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -265,8 +264,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `91747` // Estimated: `110487` - // Minimum execution time: 144_333_000 picoseconds. - Weight::from_parts(149_251_000, 110487) + // Minimum execution time: 169_418_000 picoseconds. + Weight::from_parts(176_781_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -278,8 +277,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `90717` // Estimated: `110487` - // Minimum execution time: 132_387_000 picoseconds. - Weight::from_parts(139_222_000, 110487) + // Minimum execution time: 154_106_000 picoseconds. + Weight::from_parts(166_893_000, 110487) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -293,8 +292,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `91759` // Estimated: `110487` - // Minimum execution time: 141_082_000 picoseconds. - Weight::from_parts(146_117_000, 110487) + // Minimum execution time: 167_121_000 picoseconds. + Weight::from_parts(175_510_000, 110487) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -308,8 +307,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `31` // Estimated: `1489` - // Minimum execution time: 3_099_000 picoseconds. - Weight::from_parts(3_298_000, 1489) + // Minimum execution time: 3_735_000 picoseconds. + Weight::from_parts(3_928_000, 1489) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -320,10 +319,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 3_558_000 picoseconds. - Weight::from_parts(5_984_191, 110487) - // Standard Error: 564 - .saturating_add(Weight::from_parts(334_983, 0).saturating_mul(s.into())) + // Minimum execution time: 3_944_000 picoseconds. + Weight::from_parts(4_034_000, 110487) + // Standard Error: 1_119 + .saturating_add(Weight::from_parts(468_891, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -331,11 +330,11 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_389_000 picoseconds. - Weight::from_parts(3_609_000, 0) + // Minimum execution time: 3_235_000 picoseconds. + Weight::from_parts(3_423_000, 0) } /// Storage: `Preimage::PreimageFor` (r:1 w:1) - /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `Measured`) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) /// Storage: `Preimage::StatusFor` (r:1 w:0) /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) /// Storage: `Preimage::RequestStatusFor` (r:1 w:1) @@ -343,15 +342,14 @@ impl WeightInfo for () { /// The range of component `s` is `[128, 4194304]`. fn service_task_fetched(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `246 + s * (1 ±0)` - // Estimated: `3711 + s * (1 ±0)` - // Minimum execution time: 18_292_000 picoseconds. - Weight::from_parts(18_574_000, 3711) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_189, 0).saturating_mul(s.into())) + // Measured: `141 + s * (1 ±0)` + // Estimated: `4197809` + // Minimum execution time: 18_976_000 picoseconds. + Weight::from_parts(19_220_000, 4197809) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_871, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) - .saturating_add(Weight::from_parts(0, 1).saturating_mul(s.into())) } /// Storage: `Scheduler::Lookup` (r:0 w:1) /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) @@ -359,16 +357,16 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_216_000 picoseconds. - Weight::from_parts(5_439_000, 0) + // Minimum execution time: 4_858_000 picoseconds. + Weight::from_parts(5_041_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } fn service_task_periodic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_383_000 picoseconds. - Weight::from_parts(3_661_000, 0) + // Minimum execution time: 3_249_000 picoseconds. + Weight::from_parts(3_377_000, 0) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -378,16 +376,16 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 6_692_000 picoseconds. - Weight::from_parts(7_069_000, 3997) + // Minimum execution time: 8_482_000 picoseconds. + Weight::from_parts(9_252_000, 3997) .saturating_add(RocksDbWeight::get().reads(2_u64)) } fn execute_dispatch_unsigned() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_165_000 picoseconds. - Weight::from_parts(2_332_000, 0) + // Minimum execution time: 2_391_000 picoseconds. + Weight::from_parts(2_591_000, 0) } /// Storage: `Scheduler::Agenda` (r:1 w:1) /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(107022), added: 109497, mode: `MaxEncodedLen`) @@ -396,10 +394,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 10_209_000 picoseconds. - Weight::from_parts(11_235_511, 110487) - // Standard Error: 906 - .saturating_add(Weight::from_parts(375_445, 0).saturating_mul(s.into())) + // Minimum execution time: 10_698_000 picoseconds. + Weight::from_parts(7_346_814, 110487) + // Standard Error: 2_513 + .saturating_add(Weight::from_parts(535_729, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -414,10 +412,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `81 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 15_906_000 picoseconds. - Weight::from_parts(13_697_344, 110487) - // Standard Error: 949 - .saturating_add(Weight::from_parts(564_461, 0).saturating_mul(s.into())) + // Minimum execution time: 16_371_000 picoseconds. + Weight::from_parts(9_559_789, 110487) + // Standard Error: 2_542 + .saturating_add(Weight::from_parts(723_961, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -430,10 +428,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `596 + s * (178 ±0)` // Estimated: `110487` - // Minimum execution time: 13_618_000 picoseconds. - Weight::from_parts(17_489_572, 110487) - // Standard Error: 766 - .saturating_add(Weight::from_parts(377_559, 0).saturating_mul(s.into())) + // Minimum execution time: 13_995_000 picoseconds. + Weight::from_parts(16_677_389, 110487) + // Standard Error: 2_606 + .saturating_add(Weight::from_parts(555_434, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -448,10 +446,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `709 + s * (177 ±0)` // Estimated: `110487` - // Minimum execution time: 17_954_000 picoseconds. - Weight::from_parts(18_459_344, 110487) - // Standard Error: 835 - .saturating_add(Weight::from_parts(585_557, 0).saturating_mul(s.into())) + // Minimum execution time: 18_962_000 picoseconds. + Weight::from_parts(17_610_180, 110487) + // Standard Error: 2_556 + .saturating_add(Weight::from_parts(743_494, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -464,10 +462,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `118` // Estimated: `110487` - // Minimum execution time: 9_446_000 picoseconds. - Weight::from_parts(10_797_672, 110487) - // Standard Error: 184 - .saturating_add(Weight::from_parts(13_971, 0).saturating_mul(s.into())) + // Minimum execution time: 10_303_000 picoseconds. + Weight::from_parts(12_180_080, 110487) + // Standard Error: 286 + .saturating_add(Weight::from_parts(16_437, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -479,8 +477,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `90705` // Estimated: `110487` - // Minimum execution time: 137_044_000 picoseconds. - Weight::from_parts(142_855_000, 110487) + // Minimum execution time: 156_198_000 picoseconds. + Weight::from_parts(167_250_000, 110487) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -494,8 +492,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `91747` // Estimated: `110487` - // Minimum execution time: 144_333_000 picoseconds. - Weight::from_parts(149_251_000, 110487) + // Minimum execution time: 169_418_000 picoseconds. + Weight::from_parts(176_781_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -507,8 +505,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `90717` // Estimated: `110487` - // Minimum execution time: 132_387_000 picoseconds. - Weight::from_parts(139_222_000, 110487) + // Minimum execution time: 154_106_000 picoseconds. + Weight::from_parts(166_893_000, 110487) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -522,8 +520,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `91759` // Estimated: `110487` - // Minimum execution time: 141_082_000 picoseconds. - Weight::from_parts(146_117_000, 110487) + // Minimum execution time: 167_121_000 picoseconds. + Weight::from_parts(175_510_000, 110487) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/session/src/weights.rs b/substrate/frame/session/src/weights.rs index 2908a7563f07..a52db0645701 100644 --- a/substrate/frame/session/src/weights.rs +++ b/substrate/frame/session/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_session` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -66,10 +66,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) fn set_keys() -> Weight { // Proof Size summary in bytes: - // Measured: `1919` - // Estimated: `17759` - // Minimum execution time: 58_466_000 picoseconds. - Weight::from_parts(59_558_000, 17759) + // Measured: `1952` + // Estimated: `17792` + // Minimum execution time: 68_425_000 picoseconds. + Weight::from_parts(69_632_000, 17792) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -81,10 +81,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) fn purge_keys() -> Weight { // Proof Size summary in bytes: - // Measured: `1817` - // Estimated: `5282` - // Minimum execution time: 41_730_000 picoseconds. - Weight::from_parts(42_476_000, 5282) + // Measured: `1850` + // Estimated: `5315` + // Minimum execution time: 49_086_000 picoseconds. + Weight::from_parts(50_131_000, 5315) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -100,10 +100,10 @@ impl WeightInfo for () { /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) fn set_keys() -> Weight { // Proof Size summary in bytes: - // Measured: `1919` - // Estimated: `17759` - // Minimum execution time: 58_466_000 picoseconds. - Weight::from_parts(59_558_000, 17759) + // Measured: `1952` + // Estimated: `17792` + // Minimum execution time: 68_425_000 picoseconds. + Weight::from_parts(69_632_000, 17792) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -115,10 +115,10 @@ impl WeightInfo for () { /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) fn purge_keys() -> Weight { // Proof Size summary in bytes: - // Measured: `1817` - // Estimated: `5282` - // Minimum execution time: 41_730_000 picoseconds. - Weight::from_parts(42_476_000, 5282) + // Measured: `1850` + // Estimated: `5315` + // Minimum execution time: 49_086_000 picoseconds. + Weight::from_parts(50_131_000, 5315) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } diff --git a/substrate/frame/society/src/weights.rs b/substrate/frame/society/src/weights.rs index 17ff0318f6a6..f6f59d20d659 100644 --- a/substrate/frame/society/src/weights.rs +++ b/substrate/frame/society/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_society` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -90,8 +90,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `444` // Estimated: `3909` - // Minimum execution time: 31_464_000 picoseconds. - Weight::from_parts(32_533_000, 3909) + // Minimum execution time: 37_812_000 picoseconds. + Weight::from_parts(38_375_000, 3909) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -101,8 +101,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `461` // Estimated: `1946` - // Minimum execution time: 24_132_000 picoseconds. - Weight::from_parts(24_936_000, 1946) + // Minimum execution time: 28_526_000 picoseconds. + Weight::from_parts(29_680_000, 1946) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -118,8 +118,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `481` // Estimated: `6421` - // Minimum execution time: 22_568_000 picoseconds. - Weight::from_parts(24_273_000, 6421) + // Minimum execution time: 28_051_000 picoseconds. + Weight::from_parts(29_088_000, 6421) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -131,8 +131,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `535` // Estimated: `4000` - // Minimum execution time: 15_524_000 picoseconds. - Weight::from_parts(16_324_000, 4000) + // Minimum execution time: 20_861_000 picoseconds. + Weight::from_parts(21_379_000, 4000) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -146,8 +146,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `569` // Estimated: `4034` - // Minimum execution time: 22_360_000 picoseconds. - Weight::from_parts(23_318_000, 4034) + // Minimum execution time: 27_803_000 picoseconds. + Weight::from_parts(28_621_000, 4034) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -163,8 +163,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `561` // Estimated: `4026` - // Minimum execution time: 19_457_000 picoseconds. - Weight::from_parts(20_461_000, 4026) + // Minimum execution time: 24_774_000 picoseconds. + Weight::from_parts(26_040_000, 4026) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -176,10 +176,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout() -> Weight { // Proof Size summary in bytes: - // Measured: `650` - // Estimated: `4115` - // Minimum execution time: 52_032_000 picoseconds. - Weight::from_parts(52_912_000, 4115) + // Measured: `687` + // Estimated: `4152` + // Minimum execution time: 58_072_000 picoseconds. + Weight::from_parts(59_603_000, 4152) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -191,8 +191,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `547` // Estimated: `4012` - // Minimum execution time: 19_479_000 picoseconds. - Weight::from_parts(20_120_000, 4012) + // Minimum execution time: 24_809_000 picoseconds. + Weight::from_parts(25_927_000, 4012) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -214,8 +214,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `180` // Estimated: `1665` - // Minimum execution time: 15_843_000 picoseconds. - Weight::from_parts(16_617_000, 1665) + // Minimum execution time: 15_541_000 picoseconds. + Weight::from_parts(15_950_000, 1665) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -255,8 +255,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1654` // Estimated: `15019` - // Minimum execution time: 58_302_000 picoseconds. - Weight::from_parts(59_958_000, 15019) + // Minimum execution time: 62_275_000 picoseconds. + Weight::from_parts(64_251_000, 15019) .saturating_add(T::DbWeight::get().reads(20_u64)) .saturating_add(T::DbWeight::get().writes(30_u64)) } @@ -272,8 +272,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `505` // Estimated: `3970` - // Minimum execution time: 20_044_000 picoseconds. - Weight::from_parts(20_884_000, 3970) + // Minimum execution time: 25_561_000 picoseconds. + Weight::from_parts(26_796_000, 3970) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -287,8 +287,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `387` // Estimated: `1872` - // Minimum execution time: 11_183_000 picoseconds. - Weight::from_parts(11_573_000, 1872) + // Minimum execution time: 12_183_000 picoseconds. + Weight::from_parts(12_813_000, 1872) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -308,8 +308,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `636` // Estimated: `4101` - // Minimum execution time: 24_149_000 picoseconds. - Weight::from_parts(25_160_000, 4101) + // Minimum execution time: 30_355_000 picoseconds. + Weight::from_parts(31_281_000, 4101) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -333,8 +333,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `632` // Estimated: `4097` - // Minimum execution time: 37_992_000 picoseconds. - Weight::from_parts(39_226_000, 4097) + // Minimum execution time: 43_935_000 picoseconds. + Weight::from_parts(45_511_000, 4097) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -360,8 +360,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `650` // Estimated: `4115` - // Minimum execution time: 39_383_000 picoseconds. - Weight::from_parts(40_367_000, 4115) + // Minimum execution time: 46_043_000 picoseconds. + Weight::from_parts(47_190_000, 4115) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -377,8 +377,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `776` // Estimated: `6196` - // Minimum execution time: 40_060_000 picoseconds. - Weight::from_parts(40_836_000, 6196) + // Minimum execution time: 46_161_000 picoseconds. + Weight::from_parts(47_207_000, 6196) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -392,8 +392,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `746` // Estimated: `6196` - // Minimum execution time: 37_529_000 picoseconds. - Weight::from_parts(38_342_000, 6196) + // Minimum execution time: 43_176_000 picoseconds. + Weight::from_parts(44_714_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -407,8 +407,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `758` // Estimated: `6196` - // Minimum execution time: 37_992_000 picoseconds. - Weight::from_parts(39_002_000, 6196) + // Minimum execution time: 43_972_000 picoseconds. + Weight::from_parts(45_094_000, 6196) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -422,8 +422,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 17_266_000 picoseconds. - Weight::from_parts(18_255_000, 6492) + // Minimum execution time: 19_900_000 picoseconds. + Weight::from_parts(20_940_000, 6492) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -435,8 +435,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `510` // Estimated: `3975` - // Minimum execution time: 11_636_000 picoseconds. - Weight::from_parts(12_122_000, 3975) + // Minimum execution time: 14_358_000 picoseconds. + Weight::from_parts(15_014_000, 3975) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -458,8 +458,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `444` // Estimated: `3909` - // Minimum execution time: 31_464_000 picoseconds. - Weight::from_parts(32_533_000, 3909) + // Minimum execution time: 37_812_000 picoseconds. + Weight::from_parts(38_375_000, 3909) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -469,8 +469,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `461` // Estimated: `1946` - // Minimum execution time: 24_132_000 picoseconds. - Weight::from_parts(24_936_000, 1946) + // Minimum execution time: 28_526_000 picoseconds. + Weight::from_parts(29_680_000, 1946) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -486,8 +486,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `481` // Estimated: `6421` - // Minimum execution time: 22_568_000 picoseconds. - Weight::from_parts(24_273_000, 6421) + // Minimum execution time: 28_051_000 picoseconds. + Weight::from_parts(29_088_000, 6421) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -499,8 +499,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `535` // Estimated: `4000` - // Minimum execution time: 15_524_000 picoseconds. - Weight::from_parts(16_324_000, 4000) + // Minimum execution time: 20_861_000 picoseconds. + Weight::from_parts(21_379_000, 4000) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -514,8 +514,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `569` // Estimated: `4034` - // Minimum execution time: 22_360_000 picoseconds. - Weight::from_parts(23_318_000, 4034) + // Minimum execution time: 27_803_000 picoseconds. + Weight::from_parts(28_621_000, 4034) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -531,8 +531,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `561` // Estimated: `4026` - // Minimum execution time: 19_457_000 picoseconds. - Weight::from_parts(20_461_000, 4026) + // Minimum execution time: 24_774_000 picoseconds. + Weight::from_parts(26_040_000, 4026) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -544,10 +544,10 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout() -> Weight { // Proof Size summary in bytes: - // Measured: `650` - // Estimated: `4115` - // Minimum execution time: 52_032_000 picoseconds. - Weight::from_parts(52_912_000, 4115) + // Measured: `687` + // Estimated: `4152` + // Minimum execution time: 58_072_000 picoseconds. + Weight::from_parts(59_603_000, 4152) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -559,8 +559,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `547` // Estimated: `4012` - // Minimum execution time: 19_479_000 picoseconds. - Weight::from_parts(20_120_000, 4012) + // Minimum execution time: 24_809_000 picoseconds. + Weight::from_parts(25_927_000, 4012) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -582,8 +582,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `180` // Estimated: `1665` - // Minimum execution time: 15_843_000 picoseconds. - Weight::from_parts(16_617_000, 1665) + // Minimum execution time: 15_541_000 picoseconds. + Weight::from_parts(15_950_000, 1665) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -623,8 +623,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1654` // Estimated: `15019` - // Minimum execution time: 58_302_000 picoseconds. - Weight::from_parts(59_958_000, 15019) + // Minimum execution time: 62_275_000 picoseconds. + Weight::from_parts(64_251_000, 15019) .saturating_add(RocksDbWeight::get().reads(20_u64)) .saturating_add(RocksDbWeight::get().writes(30_u64)) } @@ -640,8 +640,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `505` // Estimated: `3970` - // Minimum execution time: 20_044_000 picoseconds. - Weight::from_parts(20_884_000, 3970) + // Minimum execution time: 25_561_000 picoseconds. + Weight::from_parts(26_796_000, 3970) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -655,8 +655,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `387` // Estimated: `1872` - // Minimum execution time: 11_183_000 picoseconds. - Weight::from_parts(11_573_000, 1872) + // Minimum execution time: 12_183_000 picoseconds. + Weight::from_parts(12_813_000, 1872) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -676,8 +676,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `636` // Estimated: `4101` - // Minimum execution time: 24_149_000 picoseconds. - Weight::from_parts(25_160_000, 4101) + // Minimum execution time: 30_355_000 picoseconds. + Weight::from_parts(31_281_000, 4101) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -701,8 +701,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `632` // Estimated: `4097` - // Minimum execution time: 37_992_000 picoseconds. - Weight::from_parts(39_226_000, 4097) + // Minimum execution time: 43_935_000 picoseconds. + Weight::from_parts(45_511_000, 4097) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -728,8 +728,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `650` // Estimated: `4115` - // Minimum execution time: 39_383_000 picoseconds. - Weight::from_parts(40_367_000, 4115) + // Minimum execution time: 46_043_000 picoseconds. + Weight::from_parts(47_190_000, 4115) .saturating_add(RocksDbWeight::get().reads(7_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -745,8 +745,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `776` // Estimated: `6196` - // Minimum execution time: 40_060_000 picoseconds. - Weight::from_parts(40_836_000, 6196) + // Minimum execution time: 46_161_000 picoseconds. + Weight::from_parts(47_207_000, 6196) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -760,8 +760,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `746` // Estimated: `6196` - // Minimum execution time: 37_529_000 picoseconds. - Weight::from_parts(38_342_000, 6196) + // Minimum execution time: 43_176_000 picoseconds. + Weight::from_parts(44_714_000, 6196) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -775,8 +775,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `758` // Estimated: `6196` - // Minimum execution time: 37_992_000 picoseconds. - Weight::from_parts(39_002_000, 6196) + // Minimum execution time: 43_972_000 picoseconds. + Weight::from_parts(45_094_000, 6196) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -790,8 +790,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 17_266_000 picoseconds. - Weight::from_parts(18_255_000, 6492) + // Minimum execution time: 19_900_000 picoseconds. + Weight::from_parts(20_940_000, 6492) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -803,8 +803,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `510` // Estimated: `3975` - // Minimum execution time: 11_636_000 picoseconds. - Weight::from_parts(12_122_000, 3975) + // Minimum execution time: 14_358_000 picoseconds. + Weight::from_parts(15_014_000, 3975) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/staking/src/weights.rs b/substrate/frame/staking/src/weights.rs index cd4e7f973ce3..56f561679cfc 100644 --- a/substrate/frame/staking/src/weights.rs +++ b/substrate/frame/staking/src/weights.rs @@ -1584,4 +1584,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } -} +} \ No newline at end of file diff --git a/substrate/frame/state-trie-migration/src/weights.rs b/substrate/frame/state-trie-migration/src/weights.rs index ddc9236f7af6..478960392bca 100644 --- a/substrate/frame/state-trie-migration/src/weights.rs +++ b/substrate/frame/state-trie-migration/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_state_trie_migration` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -66,15 +66,15 @@ impl WeightInfo for SubstrateWeight { /// Storage: `StateTrieMigration::SignedMigrationMaxLimits` (r:1 w:0) /// Proof: `StateTrieMigration::SignedMigrationMaxLimits` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `StateTrieMigration::MigrationProcess` (r:1 w:1) /// Proof: `StateTrieMigration::MigrationProcess` (`max_values`: Some(1), `max_size`: Some(1042), added: 1537, mode: `MaxEncodedLen`) fn continue_migrate() -> Weight { // Proof Size summary in bytes: // Measured: `108` - // Estimated: `3658` - // Minimum execution time: 18_293_000 picoseconds. - Weight::from_parts(18_577_000, 3658) + // Estimated: `3820` + // Minimum execution time: 19_111_000 picoseconds. + Weight::from_parts(19_611_000, 3820) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -84,53 +84,53 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1493` - // Minimum execution time: 4_240_000 picoseconds. - Weight::from_parts(4_369_000, 1493) + // Minimum execution time: 4_751_000 picoseconds. + Weight::from_parts(5_052_000, 1493) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn migrate_custom_top_success() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `3658` - // Minimum execution time: 11_909_000 picoseconds. - Weight::from_parts(12_453_000, 3658) + // Estimated: `3820` + // Minimum execution time: 11_907_000 picoseconds. + Weight::from_parts(12_264_000, 3820) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x666f6f` (r:1 w:1) /// Proof: UNKNOWN KEY `0x666f6f` (r:1 w:1) fn migrate_custom_top_fail() -> Weight { // Proof Size summary in bytes: // Measured: `113` - // Estimated: `3658` - // Minimum execution time: 65_631_000 picoseconds. - Weight::from_parts(66_506_000, 3658) + // Estimated: `3820` + // Minimum execution time: 68_089_000 picoseconds. + Weight::from_parts(68_998_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn migrate_custom_child_success() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `3658` - // Minimum execution time: 12_208_000 picoseconds. - Weight::from_parts(12_690_000, 3658) + // Estimated: `3820` + // Minimum execution time: 12_021_000 picoseconds. + Weight::from_parts(12_466_000, 3820) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x666f6f` (r:1 w:1) /// Proof: UNKNOWN KEY `0x666f6f` (r:1 w:1) fn migrate_custom_child_fail() -> Weight { // Proof Size summary in bytes: // Measured: `106` - // Estimated: `3658` - // Minimum execution time: 66_988_000 picoseconds. - Weight::from_parts(68_616_000, 3658) + // Estimated: `3820` + // Minimum execution time: 69_553_000 picoseconds. + Weight::from_parts(71_125_000, 3820) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -139,12 +139,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `v` is `[1, 4194304]`. fn process_top_key(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `197 + v * (1 ±0)` - // Estimated: `3662 + v * (1 ±0)` - // Minimum execution time: 5_365_000 picoseconds. - Weight::from_parts(5_460_000, 3662) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_150, 0).saturating_mul(v.into())) + // Measured: `192 + v * (1 ±0)` + // Estimated: `3657 + v * (1 ±0)` + // Minimum execution time: 5_418_000 picoseconds. + Weight::from_parts(5_526_000, 3657) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_914, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(v.into())) @@ -156,15 +156,15 @@ impl WeightInfo for () { /// Storage: `StateTrieMigration::SignedMigrationMaxLimits` (r:1 w:0) /// Proof: `StateTrieMigration::SignedMigrationMaxLimits` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `StateTrieMigration::MigrationProcess` (r:1 w:1) /// Proof: `StateTrieMigration::MigrationProcess` (`max_values`: Some(1), `max_size`: Some(1042), added: 1537, mode: `MaxEncodedLen`) fn continue_migrate() -> Weight { // Proof Size summary in bytes: // Measured: `108` - // Estimated: `3658` - // Minimum execution time: 18_293_000 picoseconds. - Weight::from_parts(18_577_000, 3658) + // Estimated: `3820` + // Minimum execution time: 19_111_000 picoseconds. + Weight::from_parts(19_611_000, 3820) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -174,53 +174,53 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1493` - // Minimum execution time: 4_240_000 picoseconds. - Weight::from_parts(4_369_000, 1493) + // Minimum execution time: 4_751_000 picoseconds. + Weight::from_parts(5_052_000, 1493) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn migrate_custom_top_success() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `3658` - // Minimum execution time: 11_909_000 picoseconds. - Weight::from_parts(12_453_000, 3658) + // Estimated: `3820` + // Minimum execution time: 11_907_000 picoseconds. + Weight::from_parts(12_264_000, 3820) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x666f6f` (r:1 w:1) /// Proof: UNKNOWN KEY `0x666f6f` (r:1 w:1) fn migrate_custom_top_fail() -> Weight { // Proof Size summary in bytes: // Measured: `113` - // Estimated: `3658` - // Minimum execution time: 65_631_000 picoseconds. - Weight::from_parts(66_506_000, 3658) + // Estimated: `3820` + // Minimum execution time: 68_089_000 picoseconds. + Weight::from_parts(68_998_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Balances::Holds` (r:1 w:0) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) fn migrate_custom_child_success() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `3658` - // Minimum execution time: 12_208_000 picoseconds. - Weight::from_parts(12_690_000, 3658) + // Estimated: `3820` + // Minimum execution time: 12_021_000 picoseconds. + Weight::from_parts(12_466_000, 3820) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x666f6f` (r:1 w:1) /// Proof: UNKNOWN KEY `0x666f6f` (r:1 w:1) fn migrate_custom_child_fail() -> Weight { // Proof Size summary in bytes: // Measured: `106` - // Estimated: `3658` - // Minimum execution time: 66_988_000 picoseconds. - Weight::from_parts(68_616_000, 3658) + // Estimated: `3820` + // Minimum execution time: 69_553_000 picoseconds. + Weight::from_parts(71_125_000, 3820) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -229,12 +229,12 @@ impl WeightInfo for () { /// The range of component `v` is `[1, 4194304]`. fn process_top_key(v: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `197 + v * (1 ±0)` - // Estimated: `3662 + v * (1 ±0)` - // Minimum execution time: 5_365_000 picoseconds. - Weight::from_parts(5_460_000, 3662) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_150, 0).saturating_mul(v.into())) + // Measured: `192 + v * (1 ±0)` + // Estimated: `3657 + v * (1 ±0)` + // Minimum execution time: 5_418_000 picoseconds. + Weight::from_parts(5_526_000, 3657) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_914, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(v.into())) diff --git a/substrate/frame/sudo/src/benchmarking.rs b/substrate/frame/sudo/src/benchmarking.rs index ff34cc3a7003..cf96562a30cf 100644 --- a/substrate/frame/sudo/src/benchmarking.rs +++ b/substrate/frame/sudo/src/benchmarking.rs @@ -110,7 +110,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, |_| Ok( + .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok( Default::default() )) .unwrap() diff --git a/substrate/frame/sudo/src/weights.rs b/substrate/frame/sudo/src/weights.rs index ac5557e68a63..1b3bdbaaf42c 100644 --- a/substrate/frame/sudo/src/weights.rs +++ b/substrate/frame/sudo/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_sudo` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -65,10 +65,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn set_key() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 9_486_000 picoseconds. - Weight::from_parts(9_663_000, 1517) + // Minimum execution time: 10_426_000 picoseconds. + Weight::from_parts(10_822_000, 1517) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -76,30 +76,30 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn sudo() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 10_501_000 picoseconds. - Weight::from_parts(10_729_000, 1517) + // Minimum execution time: 11_218_000 picoseconds. + Weight::from_parts(11_501_000, 1517) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Sudo::Key` (r:1 w:0) /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn sudo_as() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 10_742_000 picoseconds. - Weight::from_parts(11_003_000, 1517) + // Minimum execution time: 11_161_000 picoseconds. + Weight::from_parts(11_618_000, 1517) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Sudo::Key` (r:1 w:1) /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn remove_key() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 8_837_000 picoseconds. - Weight::from_parts(9_127_000, 1517) + // Minimum execution time: 9_617_000 picoseconds. + Weight::from_parts(10_092_000, 1517) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -107,10 +107,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn check_only_sudo_account() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 3_416_000 picoseconds. - Weight::from_parts(3_645_000, 1517) + // Minimum execution time: 4_903_000 picoseconds. + Weight::from_parts(5_046_000, 1517) .saturating_add(T::DbWeight::get().reads(1_u64)) } } @@ -121,10 +121,10 @@ impl WeightInfo for () { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn set_key() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 9_486_000 picoseconds. - Weight::from_parts(9_663_000, 1517) + // Minimum execution time: 10_426_000 picoseconds. + Weight::from_parts(10_822_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -132,30 +132,30 @@ impl WeightInfo for () { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn sudo() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 10_501_000 picoseconds. - Weight::from_parts(10_729_000, 1517) + // Minimum execution time: 11_218_000 picoseconds. + Weight::from_parts(11_501_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Sudo::Key` (r:1 w:0) /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn sudo_as() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 10_742_000 picoseconds. - Weight::from_parts(11_003_000, 1517) + // Minimum execution time: 11_161_000 picoseconds. + Weight::from_parts(11_618_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Sudo::Key` (r:1 w:1) /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn remove_key() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 8_837_000 picoseconds. - Weight::from_parts(9_127_000, 1517) + // Minimum execution time: 9_617_000 picoseconds. + Weight::from_parts(10_092_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -163,10 +163,10 @@ impl WeightInfo for () { /// Proof: `Sudo::Key` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) fn check_only_sudo_account() -> Weight { // Proof Size summary in bytes: - // Measured: `165` + // Measured: `198` // Estimated: `1517` - // Minimum execution time: 3_416_000 picoseconds. - Weight::from_parts(3_645_000, 1517) + // Minimum execution time: 4_903_000 picoseconds. + Weight::from_parts(5_046_000, 1517) .saturating_add(RocksDbWeight::get().reads(1_u64)) } } diff --git a/substrate/frame/support/src/dispatch.rs b/substrate/frame/support/src/dispatch.rs index 3678f958980a..483a3dce77f6 100644 --- a/substrate/frame/support/src/dispatch.rs +++ b/substrate/frame/support/src/dispatch.rs @@ -1403,7 +1403,7 @@ mod extension_weight_tests { let mut info = call.get_dispatch_info(); assert_eq!(info.total_weight(), Weight::from_parts(1000, 0)); info.extension_weight = ext.weight(&call); - let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0, 0).unwrap(); let res = call.dispatch(Some(0).into()); let mut post_info = res.unwrap(); assert!(post_info.actual_weight.is_none()); @@ -1430,7 +1430,7 @@ mod extension_weight_tests { assert_eq!(info.total_weight(), Weight::from_parts(1000, 0)); info.extension_weight = ext.weight(&call); let post_info = - ext.dispatch_transaction(Some(0).into(), call, &info, 0).unwrap().unwrap(); + ext.dispatch_transaction(Some(0).into(), call, &info, 0, 0).unwrap().unwrap(); // 1000 call weight + 50 + 200 + 0 assert_eq!(post_info.actual_weight, Some(Weight::from_parts(1250, 0))); }); @@ -1449,7 +1449,7 @@ mod extension_weight_tests { assert_eq!(info.call_weight, Weight::from_parts(1000, 0)); info.extension_weight = ext.weight(&call); assert_eq!(info.total_weight(), Weight::from_parts(1600, 0)); - let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0, 0).unwrap(); let res = call.clone().dispatch(Some(0).into()); let mut post_info = res.unwrap(); // 500 actual call weight @@ -1469,7 +1469,7 @@ mod extension_weight_tests { // Second testcase let ext: TxExtension = (HalfCostIf(false), FreeIfUnder(1100), ActualWeightIs(200)); - let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0, 0).unwrap(); let res = call.clone().dispatch(Some(0).into()); let mut post_info = res.unwrap(); // 500 actual call weight @@ -1489,7 +1489,7 @@ mod extension_weight_tests { // Third testcase let ext: TxExtension = (HalfCostIf(true), FreeIfUnder(1060), ActualWeightIs(200)); - let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0, 0).unwrap(); let res = call.clone().dispatch(Some(0).into()); let mut post_info = res.unwrap(); // 500 actual call weight @@ -1509,7 +1509,7 @@ mod extension_weight_tests { // Fourth testcase let ext: TxExtension = (HalfCostIf(false), FreeIfUnder(100), ActualWeightIs(300)); - let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(0).into(), &call, &info, 0, 0).unwrap(); let res = call.clone().dispatch(Some(0).into()); let mut post_info = res.unwrap(); // 500 actual call weight diff --git a/substrate/frame/support/src/weights/block_weights.rs b/substrate/frame/support/src/weights/block_weights.rs index 38f2ba3f023d..b4c12aa5d421 100644 --- a/substrate/frame/support/src/weights/block_weights.rs +++ b/substrate/frame/support/src/weights/block_weights.rs @@ -16,8 +16,8 @@ // limitations under the License. //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08 (Y/M/D) -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! DATE: 2024-11-08 (Y/M/D) +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! //! SHORT-NAME: `block`, LONG-NAME: `BlockExecution`, RUNTIME: `Development` //! WARMUPS: `10`, REPEAT: `100` @@ -39,21 +39,21 @@ use sp_core::parameter_types; use sp_weights::{constants::WEIGHT_REF_TIME_PER_NANOS, Weight}; parameter_types! { - /// Time to execute an empty block. + /// Weight of executing an empty block. /// Calculated by multiplying the *Average* with `1.0` and adding `0`. /// /// Stats nanoseconds: - /// Min, Max: 440_235, 661_535 - /// Average: 453_383 - /// Median: 449_925 - /// Std-Dev: 22021.99 + /// Min, Max: 419_969, 685_012 + /// Average: 431_614 + /// Median: 427_388 + /// Std-Dev: 26437.34 /// /// Percentiles nanoseconds: - /// 99th: 474_045 - /// 95th: 466_455 - /// 75th: 455_056 + /// 99th: 456_205 + /// 95th: 443_420 + /// 75th: 431_833 pub const BlockExecutionWeight: Weight = - Weight::from_parts(WEIGHT_REF_TIME_PER_NANOS.saturating_mul(453_383), 0); + Weight::from_parts(WEIGHT_REF_TIME_PER_NANOS.saturating_mul(431_614), 0); } #[cfg(test)] diff --git a/substrate/frame/support/src/weights/extrinsic_weights.rs b/substrate/frame/support/src/weights/extrinsic_weights.rs index 75c7ffa60705..95d966a412d0 100644 --- a/substrate/frame/support/src/weights/extrinsic_weights.rs +++ b/substrate/frame/support/src/weights/extrinsic_weights.rs @@ -16,8 +16,8 @@ // limitations under the License. //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08 (Y/M/D) -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! DATE: 2024-11-08 (Y/M/D) +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! //! SHORT-NAME: `extrinsic`, LONG-NAME: `ExtrinsicBase`, RUNTIME: `Development` //! WARMUPS: `10`, REPEAT: `100` @@ -39,21 +39,21 @@ use sp_core::parameter_types; use sp_weights::{constants::WEIGHT_REF_TIME_PER_NANOS, Weight}; parameter_types! { - /// Time to execute a NO-OP extrinsic, for example `System::remark`. + /// Weight of executing a NO-OP extrinsic, for example `System::remark`. /// Calculated by multiplying the *Average* with `1.0` and adding `0`. /// /// Stats nanoseconds: - /// Min, Max: 106_559, 107_788 - /// Average: 107_074 - /// Median: 107_067 - /// Std-Dev: 242.67 + /// Min, Max: 107_464, 109_127 + /// Average: 108_157 + /// Median: 108_119 + /// Std-Dev: 353.52 /// /// Percentiles nanoseconds: - /// 99th: 107_675 - /// 95th: 107_513 - /// 75th: 107_225 + /// 99th: 109_041 + /// 95th: 108_748 + /// 75th: 108_405 pub const ExtrinsicBaseWeight: Weight = - Weight::from_parts(WEIGHT_REF_TIME_PER_NANOS.saturating_mul(107_074), 0); + Weight::from_parts(WEIGHT_REF_TIME_PER_NANOS.saturating_mul(108_157), 0); } #[cfg(test)] diff --git a/substrate/frame/system/benchmarking/src/extensions.rs b/substrate/frame/system/benchmarking/src/extensions.rs index 3c6626030e22..01e4687bc4bc 100644 --- a/substrate/frame/system/benchmarking/src/extensions.rs +++ b/substrate/frame/system/benchmarking/src/extensions.rs @@ -23,6 +23,7 @@ use alloc::vec; use frame_benchmarking::{account, v2::*, BenchmarkError}; use frame_support::{ dispatch::{DispatchClass, DispatchInfo, PostDispatchInfo}, + pallet_prelude::Zero, weights::Weight, }; use frame_system::{ @@ -53,11 +54,14 @@ mod benchmarks { let caller = account("caller", 0, 0); let info = DispatchInfo { call_weight: Weight::zero(), ..Default::default() }; let call: T::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::BlockHash::::hashed_key_for(BlockNumberFor::::zero()).into(), + ); #[block] { CheckGenesis::::new() - .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -81,10 +85,13 @@ mod benchmarks { ..Default::default() }; let call: T::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::BlockHash::::hashed_key_for(prev_block).into(), + ); #[block] { - ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -109,10 +116,13 @@ mod benchmarks { ..Default::default() }; let call: T::RuntimeCall = frame_system::Call::remark { remark: vec![] }.into(); + frame_benchmarking::benchmarking::add_to_whitelist( + frame_system::BlockHash::::hashed_key_for(BlockNumberFor::::zero()).into(), + ); #[block] { - ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -129,7 +139,7 @@ mod benchmarks { #[block] { - ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -151,7 +161,7 @@ mod benchmarks { #[block] { - ext.test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, len, |_| { + ext.test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, len, 0, |_| { Ok(().into()) }) .unwrap() @@ -173,7 +183,7 @@ mod benchmarks { #[block] { CheckSpecVersion::::new() - .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -190,7 +200,7 @@ mod benchmarks { #[block] { CheckTxVersion::::new() - .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(().into())) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(().into())) .unwrap() .unwrap(); } @@ -230,7 +240,7 @@ mod benchmarks { #[block] { - ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, |_| Ok(post_info)) + ext.test_run(RawOrigin::Signed(caller).into(), &call, &info, len, 0, |_| Ok(post_info)) .unwrap() .unwrap(); } diff --git a/substrate/frame/system/src/extensions/check_mortality.rs b/substrate/frame/system/src/extensions/check_mortality.rs index 75e1fc2fc11a..e2c22a07a3fe 100644 --- a/substrate/frame/system/src/extensions/check_mortality.rs +++ b/substrate/frame/system/src/extensions/check_mortality.rs @@ -155,7 +155,7 @@ mod tests { >::insert(16, H256::repeat_byte(1)); assert_eq!( - ext.validate_only(Some(1).into(), CALL, &normal, len, External) + ext.validate_only(Some(1).into(), CALL, &normal, len, External, 0) .unwrap() .0 .longevity, diff --git a/substrate/frame/system/src/extensions/check_non_zero_sender.rs b/substrate/frame/system/src/extensions/check_non_zero_sender.rs index a4e54954dc2c..577e2b324fca 100644 --- a/substrate/frame/system/src/extensions/check_non_zero_sender.rs +++ b/substrate/frame/system/src/extensions/check_non_zero_sender.rs @@ -97,7 +97,7 @@ mod tests { let len = 0_usize; assert_eq!( CheckNonZeroSender::::new() - .validate_only(Some(0).into(), CALL, &info, len, External) + .validate_only(Some(0).into(), CALL, &info, len, External, 0) .unwrap_err(), TransactionValidityError::from(InvalidTransaction::BadSigner) ); @@ -107,6 +107,7 @@ mod tests { &info, len, External, + 0, )); }) } diff --git a/substrate/frame/system/src/extensions/check_nonce.rs b/substrate/frame/system/src/extensions/check_nonce.rs index eed08050338b..004ec08a26f2 100644 --- a/substrate/frame/system/src/extensions/check_nonce.rs +++ b/substrate/frame/system/src/extensions/check_nonce.rs @@ -209,13 +209,13 @@ mod tests { assert_storage_noop!({ assert_eq!( CheckNonce::(0u64.into()) - .validate_only(Some(1).into(), CALL, &info, len, External) + .validate_only(Some(1).into(), CALL, &info, len, External, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Stale) ); assert_eq!( CheckNonce::(0u64.into()) - .validate_and_prepare(Some(1).into(), CALL, &info, len) + .validate_and_prepare(Some(1).into(), CALL, &info, len, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Stale) ); @@ -227,12 +227,14 @@ mod tests { &info, len, External, + 0, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(1).into(), CALL, &info, - len + len, + 0, )); // future assert_ok!(CheckNonce::(5u64.into()).validate_only( @@ -241,10 +243,11 @@ mod tests { &info, len, External, + 0, )); assert_eq!( CheckNonce::(5u64.into()) - .validate_and_prepare(Some(1).into(), CALL, &info, len) + .validate_and_prepare(Some(1).into(), CALL, &info, len, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Future) ); @@ -280,13 +283,13 @@ mod tests { assert_storage_noop!({ assert_eq!( CheckNonce::(1u64.into()) - .validate_only(Some(1).into(), CALL, &info, len, External) + .validate_only(Some(1).into(), CALL, &info, len, External, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Payment) ); assert_eq!( CheckNonce::(1u64.into()) - .validate_and_prepare(Some(1).into(), CALL, &info, len) + .validate_and_prepare(Some(1).into(), CALL, &info, len, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Payment) ); @@ -298,12 +301,14 @@ mod tests { &info, len, External, + 0, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(2).into(), CALL, &info, - len + len, + 0, )); // Non-zero sufficients assert_ok!(CheckNonce::(1u64.into()).validate_only( @@ -312,12 +317,14 @@ mod tests { &info, len, External, + 0, )); assert_ok!(CheckNonce::(1u64.into()).validate_and_prepare( Some(3).into(), CALL, &info, - len + len, + 0, )); }) } @@ -386,7 +393,7 @@ mod tests { let len = CALL.encoded_size(); let origin = crate::RawOrigin::Root.into(); - let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len).unwrap(); + let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len, 0).unwrap(); assert!(origin.as_system_ref().unwrap().is_root()); diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index 435c96c8741f..ee91478b90f3 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -548,7 +548,7 @@ mod tests { // will not fit. assert_eq!( CheckWeight::(PhantomData) - .validate_and_prepare(Some(1).into(), CALL, &normal, len) + .validate_and_prepare(Some(1).into(), CALL, &normal, len, 0) .unwrap_err(), InvalidTransaction::ExhaustsResources.into() ); @@ -557,7 +557,8 @@ mod tests { Some(1).into(), CALL, &op, - len + len, + 0, )); // likewise for length limit. @@ -565,7 +566,7 @@ mod tests { AllExtrinsicsLen::::put(normal_length_limit()); assert_eq!( CheckWeight::(PhantomData) - .validate_and_prepare(Some(1).into(), CALL, &normal, len) + .validate_and_prepare(Some(1).into(), CALL, &normal, len, 0) .unwrap_err(), InvalidTransaction::ExhaustsResources.into() ); @@ -573,7 +574,8 @@ mod tests { Some(1).into(), CALL, &op, - len + len, + 0, )); }) } @@ -590,6 +592,7 @@ mod tests { CALL, tx, s, + 0, ); if f { assert!(r.is_err()) @@ -640,6 +643,7 @@ mod tests { CALL, i, len, + 0, ); if f { assert!(r.is_err()) @@ -675,7 +679,7 @@ mod tests { }); let pre = CheckWeight::(PhantomData) - .validate_and_prepare(Some(1).into(), CALL, &info, len) + .validate_and_prepare(Some(1).into(), CALL, &info, len, 0) .unwrap() .0; assert_eq!( @@ -714,7 +718,7 @@ mod tests { }); let pre = CheckWeight::(PhantomData) - .validate_and_prepare(Some(1).into(), CALL, &info, len) + .validate_and_prepare(Some(1).into(), CALL, &info, len, 0) .unwrap() .0; assert_eq!( @@ -753,7 +757,8 @@ mod tests { Some(1).into(), CALL, &free, - len + len, + 0, )); assert_eq!( System::block_weight().total(), diff --git a/substrate/frame/system/src/extensions/weights.rs b/substrate/frame/system/src/extensions/weights.rs index 1c0136ae7802..b3c296899be5 100644 --- a/substrate/frame/system/src/extensions/weights.rs +++ b/substrate/frame/system/src/extensions/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `frame_system_extensions` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -68,38 +68,38 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_genesis() -> Weight { // Proof Size summary in bytes: - // Measured: `54` + // Measured: `30` // Estimated: `3509` - // Minimum execution time: 3_876_000 picoseconds. - Weight::from_parts(4_160_000, 3509) + // Minimum execution time: 3_388_000 picoseconds. + Weight::from_parts(3_577_000, 3509) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_mortality_mortal_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 6_296_000 picoseconds. - Weight::from_parts(6_523_000, 3509) + // Minimum execution time: 6_442_000 picoseconds. + Weight::from_parts(6_703_000, 3509) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_mortality_immortal_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 6_296_000 picoseconds. - Weight::from_parts(6_523_000, 3509) + // Minimum execution time: 6_357_000 picoseconds. + Weight::from_parts(6_605_000, 3509) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn check_non_zero_sender() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 449_000 picoseconds. - Weight::from_parts(527_000, 0) + // Minimum execution time: 457_000 picoseconds. + Weight::from_parts(570_000, 0) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -107,8 +107,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 5_689_000 picoseconds. - Weight::from_parts(6_000_000, 3593) + // Minimum execution time: 6_936_000 picoseconds. + Weight::from_parts(7_261_000, 3593) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -116,26 +116,22 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 399_000 picoseconds. - Weight::from_parts(461_000, 0) + // Minimum execution time: 336_000 picoseconds. + Weight::from_parts(430_000, 0) } fn check_tx_version() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 390_000 picoseconds. - Weight::from_parts(439_000, 0) + // Minimum execution time: 348_000 picoseconds. + Weight::from_parts(455_000, 0) } - /// Storage: `System::AllExtrinsicsLen` (r:1 w:1) - /// Proof: `System::AllExtrinsicsLen` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn check_weight() -> Weight { // Proof Size summary in bytes: - // Measured: `24` - // Estimated: `1489` - // Minimum execution time: 4_375_000 picoseconds. - Weight::from_parts(4_747_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_887_000 picoseconds. + Weight::from_parts(3_006_000, 0) } } @@ -145,38 +141,38 @@ impl WeightInfo for () { /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_genesis() -> Weight { // Proof Size summary in bytes: - // Measured: `54` + // Measured: `30` // Estimated: `3509` - // Minimum execution time: 3_876_000 picoseconds. - Weight::from_parts(4_160_000, 3509) + // Minimum execution time: 3_388_000 picoseconds. + Weight::from_parts(3_577_000, 3509) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_mortality_mortal_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 6_296_000 picoseconds. - Weight::from_parts(6_523_000, 3509) + // Minimum execution time: 6_442_000 picoseconds. + Weight::from_parts(6_703_000, 3509) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `System::BlockHash` (r:1 w:0) /// Proof: `System::BlockHash` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) fn check_mortality_immortal_transaction() -> Weight { // Proof Size summary in bytes: - // Measured: `92` + // Measured: `68` // Estimated: `3509` - // Minimum execution time: 6_296_000 picoseconds. - Weight::from_parts(6_523_000, 3509) + // Minimum execution time: 6_357_000 picoseconds. + Weight::from_parts(6_605_000, 3509) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn check_non_zero_sender() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 449_000 picoseconds. - Weight::from_parts(527_000, 0) + // Minimum execution time: 457_000 picoseconds. + Weight::from_parts(570_000, 0) } /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) @@ -184,8 +180,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 5_689_000 picoseconds. - Weight::from_parts(6_000_000, 3593) + // Minimum execution time: 6_936_000 picoseconds. + Weight::from_parts(7_261_000, 3593) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -193,25 +189,21 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 399_000 picoseconds. - Weight::from_parts(461_000, 0) + // Minimum execution time: 336_000 picoseconds. + Weight::from_parts(430_000, 0) } fn check_tx_version() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 390_000 picoseconds. - Weight::from_parts(439_000, 0) + // Minimum execution time: 348_000 picoseconds. + Weight::from_parts(455_000, 0) } - /// Storage: `System::AllExtrinsicsLen` (r:1 w:1) - /// Proof: `System::AllExtrinsicsLen` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn check_weight() -> Weight { // Proof Size summary in bytes: - // Measured: `24` - // Estimated: `1489` - // Minimum execution time: 4_375_000 picoseconds. - Weight::from_parts(4_747_000, 1489) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_887_000 picoseconds. + Weight::from_parts(3_006_000, 0) } } diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 3c0c9eb1bf15..862fb4cf9faf 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -973,6 +973,7 @@ pub mod pallet { /// Digest of the current block, also part of the block header. #[pallet::storage] + #[pallet::whitelist_storage] #[pallet::unbounded] #[pallet::getter(fn digest)] pub(super) type Digest = StorageValue<_, generic::Digest, ValueQuery>; diff --git a/substrate/frame/system/src/weights.rs b/substrate/frame/system/src/weights.rs index fca14e452657..8450e0e7fb94 100644 --- a/substrate/frame/system/src/weights.rs +++ b/substrate/frame/system/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `frame_system` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -70,8 +70,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_078_000 picoseconds. - Weight::from_parts(1_137_744, 0) + // Minimum execution time: 2_093_000 picoseconds. + Weight::from_parts(2_169_000, 0) // Standard Error: 0 .saturating_add(Weight::from_parts(387, 0).saturating_mul(b.into())) } @@ -80,38 +80,33 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_980_000 picoseconds. - Weight::from_parts(2_562_415, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_391, 0).saturating_mul(b.into())) + // Minimum execution time: 5_750_000 picoseconds. + Weight::from_parts(23_611_490, 0) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_613, 0).saturating_mul(b.into())) } - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) fn set_heap_pages() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `1485` - // Minimum execution time: 3_834_000 picoseconds. - Weight::from_parts(4_109_000, 1485) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Estimated: `0` + // Minimum execution time: 3_465_000 picoseconds. + Weight::from_parts(3_616_000, 0) + .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) fn set_code() -> Weight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `67035` - // Minimum execution time: 81_326_496_000 picoseconds. - Weight::from_parts(81_880_651_000, 67035) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + // Minimum execution time: 90_830_152_000 picoseconds. + Weight::from_parts(96_270_304_000, 67035) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -120,10 +115,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_059_000 picoseconds. - Weight::from_parts(2_192_000, 0) - // Standard Error: 720 - .saturating_add(Weight::from_parts(742_610, 0).saturating_mul(i.into())) + // Minimum execution time: 2_147_000 picoseconds. + Weight::from_parts(2_239_000, 0) + // Standard Error: 2_137 + .saturating_add(Weight::from_parts(748_304, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -133,10 +128,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_038_000 picoseconds. - Weight::from_parts(2_159_000, 0) - // Standard Error: 774 - .saturating_add(Weight::from_parts(569_424, 0).saturating_mul(i.into())) + // Minimum execution time: 2_053_000 picoseconds. + Weight::from_parts(2_188_000, 0) + // Standard Error: 878 + .saturating_add(Weight::from_parts(560_728, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -144,12 +139,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `p` is `[0, 1000]`. fn kill_prefix(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `127 + p * (69 ±0)` + // Measured: `120 + p * (69 ±0)` // Estimated: `134 + p * (70 ±0)` - // Minimum execution time: 3_990_000 picoseconds. - Weight::from_parts(4_172_000, 134) - // Standard Error: 1_485 - .saturating_add(Weight::from_parts(1_227_281, 0).saturating_mul(p.into())) + // Minimum execution time: 4_244_000 picoseconds. + Weight::from_parts(4_397_000, 134) + // Standard Error: 1_410 + .saturating_add(Weight::from_parts(1_307_089, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) @@ -160,26 +155,24 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_851_000 picoseconds. - Weight::from_parts(9_643_000, 0) + // Minimum execution time: 10_037_000 picoseconds. + Weight::from_parts(16_335_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `System::AuthorizedUpgrade` (r:1 w:1) /// Proof: `System::AuthorizedUpgrade` (`max_values`: Some(1), `max_size`: Some(33), added: 528, mode: `MaxEncodedLen`) /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) fn apply_authorized_upgrade() -> Weight { // Proof Size summary in bytes: // Measured: `164` // Estimated: `67035` - // Minimum execution time: 86_295_879_000 picoseconds. - Weight::from_parts(87_636_595_000, 67035) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 95_970_737_000 picoseconds. + Weight::from_parts(98_826_505_000, 67035) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } } @@ -190,8 +183,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_078_000 picoseconds. - Weight::from_parts(1_137_744, 0) + // Minimum execution time: 2_093_000 picoseconds. + Weight::from_parts(2_169_000, 0) // Standard Error: 0 .saturating_add(Weight::from_parts(387, 0).saturating_mul(b.into())) } @@ -200,38 +193,33 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_980_000 picoseconds. - Weight::from_parts(2_562_415, 0) - // Standard Error: 1 - .saturating_add(Weight::from_parts(1_391, 0).saturating_mul(b.into())) + // Minimum execution time: 5_750_000 picoseconds. + Weight::from_parts(23_611_490, 0) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_613, 0).saturating_mul(b.into())) } - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) fn set_heap_pages() -> Weight { // Proof Size summary in bytes: // Measured: `0` - // Estimated: `1485` - // Minimum execution time: 3_834_000 picoseconds. - Weight::from_parts(4_109_000, 1485) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) + // Estimated: `0` + // Minimum execution time: 3_465_000 picoseconds. + Weight::from_parts(3_616_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) fn set_code() -> Weight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `67035` - // Minimum execution time: 81_326_496_000 picoseconds. - Weight::from_parts(81_880_651_000, 67035) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) + // Minimum execution time: 90_830_152_000 picoseconds. + Weight::from_parts(96_270_304_000, 67035) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -240,10 +228,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_059_000 picoseconds. - Weight::from_parts(2_192_000, 0) - // Standard Error: 720 - .saturating_add(Weight::from_parts(742_610, 0).saturating_mul(i.into())) + // Minimum execution time: 2_147_000 picoseconds. + Weight::from_parts(2_239_000, 0) + // Standard Error: 2_137 + .saturating_add(Weight::from_parts(748_304, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -253,10 +241,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_038_000 picoseconds. - Weight::from_parts(2_159_000, 0) - // Standard Error: 774 - .saturating_add(Weight::from_parts(569_424, 0).saturating_mul(i.into())) + // Minimum execution time: 2_053_000 picoseconds. + Weight::from_parts(2_188_000, 0) + // Standard Error: 878 + .saturating_add(Weight::from_parts(560_728, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(i.into()))) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -264,12 +252,12 @@ impl WeightInfo for () { /// The range of component `p` is `[0, 1000]`. fn kill_prefix(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `127 + p * (69 ±0)` + // Measured: `120 + p * (69 ±0)` // Estimated: `134 + p * (70 ±0)` - // Minimum execution time: 3_990_000 picoseconds. - Weight::from_parts(4_172_000, 134) - // Standard Error: 1_485 - .saturating_add(Weight::from_parts(1_227_281, 0).saturating_mul(p.into())) + // Minimum execution time: 4_244_000 picoseconds. + Weight::from_parts(4_397_000, 134) + // Standard Error: 1_410 + .saturating_add(Weight::from_parts(1_307_089, 0).saturating_mul(p.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(p.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(p.into()))) .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) @@ -280,25 +268,23 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_851_000 picoseconds. - Weight::from_parts(9_643_000, 0) + // Minimum execution time: 10_037_000 picoseconds. + Weight::from_parts(16_335_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `System::AuthorizedUpgrade` (r:1 w:1) /// Proof: `System::AuthorizedUpgrade` (`max_values`: Some(1), `max_size`: Some(33), added: 528, mode: `MaxEncodedLen`) /// Storage: `MultiBlockMigrations::Cursor` (r:1 w:0) /// Proof: `MultiBlockMigrations::Cursor` (`max_values`: Some(1), `max_size`: Some(65550), added: 66045, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) /// Proof: UNKNOWN KEY `0x3a636f6465` (r:0 w:1) fn apply_authorized_upgrade() -> Weight { // Proof Size summary in bytes: // Measured: `164` // Estimated: `67035` - // Minimum execution time: 86_295_879_000 picoseconds. - Weight::from_parts(87_636_595_000, 67035) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Minimum execution time: 95_970_737_000 picoseconds. + Weight::from_parts(98_826_505_000, 67035) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } } diff --git a/substrate/frame/timestamp/src/weights.rs b/substrate/frame/timestamp/src/weights.rs index 9f2cbf7ccd12..9f16a82653a9 100644 --- a/substrate/frame/timestamp/src/weights.rs +++ b/substrate/frame/timestamp/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_timestamp` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -66,8 +66,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `345` // Estimated: `1493` - // Minimum execution time: 8_356_000 picoseconds. - Weight::from_parts(8_684_000, 1493) + // Minimum execution time: 10_176_000 picoseconds. + Weight::from_parts(10_560_000, 1493) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -75,8 +75,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `194` // Estimated: `0` - // Minimum execution time: 3_886_000 picoseconds. - Weight::from_parts(4_118_000, 0) + // Minimum execution time: 4_915_000 picoseconds. + Weight::from_parts(5_192_000, 0) } } @@ -90,8 +90,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `345` // Estimated: `1493` - // Minimum execution time: 8_356_000 picoseconds. - Weight::from_parts(8_684_000, 1493) + // Minimum execution time: 10_176_000 picoseconds. + Weight::from_parts(10_560_000, 1493) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -99,7 +99,7 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `194` // Estimated: `0` - // Minimum execution time: 3_886_000 picoseconds. - Weight::from_parts(4_118_000, 0) + // Minimum execution time: 4_915_000 picoseconds. + Weight::from_parts(5_192_000, 0) } } diff --git a/substrate/frame/tips/src/weights.rs b/substrate/frame/tips/src/weights.rs index 7e1bba3c73e7..e9805e9cc9bf 100644 --- a/substrate/frame/tips/src/weights.rs +++ b/substrate/frame/tips/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_tips` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -71,10 +71,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4` // Estimated: `3469` - // Minimum execution time: 26_549_000 picoseconds. - Weight::from_parts(27_804_619, 3469) - // Standard Error: 173 - .saturating_add(Weight::from_parts(1_718, 0).saturating_mul(r.into())) + // Minimum execution time: 26_606_000 picoseconds. + Weight::from_parts(27_619_942, 3469) + // Standard Error: 179 + .saturating_add(Weight::from_parts(2_750, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -86,8 +86,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `221` // Estimated: `3686` - // Minimum execution time: 25_430_000 picoseconds. - Weight::from_parts(26_056_000, 3686) + // Minimum execution time: 29_286_000 picoseconds. + Weight::from_parts(30_230_000, 3686) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -101,14 +101,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `t` is `[1, 13]`. fn tip_new(r: u32, t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `526 + t * (64 ±0)` - // Estimated: `3991 + t * (64 ±0)` - // Minimum execution time: 17_309_000 picoseconds. - Weight::from_parts(17_493_185, 3991) - // Standard Error: 126 - .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(r.into())) - // Standard Error: 3_011 - .saturating_add(Weight::from_parts(88_592, 0).saturating_mul(t.into())) + // Measured: `623 + t * (64 ±0)` + // Estimated: `4088 + t * (64 ±0)` + // Minimum execution time: 21_690_000 picoseconds. + Weight::from_parts(22_347_457, 4088) + // Standard Error: 125 + .saturating_add(Weight::from_parts(2_332, 0).saturating_mul(r.into())) + // Standard Error: 2_974 + .saturating_add(Weight::from_parts(20_772, 0).saturating_mul(t.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(t.into())) @@ -120,12 +120,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `t` is `[1, 13]`. fn tip(t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `747 + t * (112 ±0)` - // Estimated: `4212 + t * (112 ±0)` - // Minimum execution time: 14_148_000 picoseconds. - Weight::from_parts(14_434_268, 4212) - // Standard Error: 4_666 - .saturating_add(Weight::from_parts(210_867, 0).saturating_mul(t.into())) + // Measured: `844 + t * (112 ±0)` + // Estimated: `4309 + t * (112 ±0)` + // Minimum execution time: 20_588_000 picoseconds. + Weight::from_parts(21_241_034, 4309) + // Standard Error: 2_448 + .saturating_add(Weight::from_parts(133_643, 0).saturating_mul(t.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 112).saturating_mul(t.into())) @@ -141,29 +141,27 @@ impl WeightInfo for SubstrateWeight { /// The range of component `t` is `[1, 13]`. fn close_tip(t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `786 + t * (112 ±0)` - // Estimated: `4242 + t * (112 ±0)` - // Minimum execution time: 56_060_000 picoseconds. - Weight::from_parts(57_913_972, 4242) - // Standard Error: 11_691 - .saturating_add(Weight::from_parts(229_579, 0).saturating_mul(t.into())) + // Measured: `896 + t * (112 ±0)` + // Estimated: `4353 + t * (111 ±0)` + // Minimum execution time: 60_824_000 picoseconds. + Weight::from_parts(63_233_742, 4353) + // Standard Error: 9_841 + .saturating_add(Weight::from_parts(77_920, 0).saturating_mul(t.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 112).saturating_mul(t.into())) + .saturating_add(Weight::from_parts(0, 111).saturating_mul(t.into())) } /// Storage: `Tips::Tips` (r:1 w:1) /// Proof: `Tips::Tips` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Tips::Reasons` (r:0 w:1) /// Proof: `Tips::Reasons` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `t` is `[1, 13]`. - fn slash_tip(t: u32, ) -> Weight { + fn slash_tip(_t: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `269` // Estimated: `3734` - // Minimum execution time: 12_034_000 picoseconds. - Weight::from_parts(12_934_534, 3734) - // Standard Error: 2_420 - .saturating_add(Weight::from_parts(4_167, 0).saturating_mul(t.into())) + // Minimum execution time: 13_281_000 picoseconds. + Weight::from_parts(14_089_409, 3734) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -180,10 +178,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4` // Estimated: `3469` - // Minimum execution time: 26_549_000 picoseconds. - Weight::from_parts(27_804_619, 3469) - // Standard Error: 173 - .saturating_add(Weight::from_parts(1_718, 0).saturating_mul(r.into())) + // Minimum execution time: 26_606_000 picoseconds. + Weight::from_parts(27_619_942, 3469) + // Standard Error: 179 + .saturating_add(Weight::from_parts(2_750, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -195,8 +193,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `221` // Estimated: `3686` - // Minimum execution time: 25_430_000 picoseconds. - Weight::from_parts(26_056_000, 3686) + // Minimum execution time: 29_286_000 picoseconds. + Weight::from_parts(30_230_000, 3686) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -210,14 +208,14 @@ impl WeightInfo for () { /// The range of component `t` is `[1, 13]`. fn tip_new(r: u32, t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `526 + t * (64 ±0)` - // Estimated: `3991 + t * (64 ±0)` - // Minimum execution time: 17_309_000 picoseconds. - Weight::from_parts(17_493_185, 3991) - // Standard Error: 126 - .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(r.into())) - // Standard Error: 3_011 - .saturating_add(Weight::from_parts(88_592, 0).saturating_mul(t.into())) + // Measured: `623 + t * (64 ±0)` + // Estimated: `4088 + t * (64 ±0)` + // Minimum execution time: 21_690_000 picoseconds. + Weight::from_parts(22_347_457, 4088) + // Standard Error: 125 + .saturating_add(Weight::from_parts(2_332, 0).saturating_mul(r.into())) + // Standard Error: 2_974 + .saturating_add(Weight::from_parts(20_772, 0).saturating_mul(t.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 64).saturating_mul(t.into())) @@ -229,12 +227,12 @@ impl WeightInfo for () { /// The range of component `t` is `[1, 13]`. fn tip(t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `747 + t * (112 ±0)` - // Estimated: `4212 + t * (112 ±0)` - // Minimum execution time: 14_148_000 picoseconds. - Weight::from_parts(14_434_268, 4212) - // Standard Error: 4_666 - .saturating_add(Weight::from_parts(210_867, 0).saturating_mul(t.into())) + // Measured: `844 + t * (112 ±0)` + // Estimated: `4309 + t * (112 ±0)` + // Minimum execution time: 20_588_000 picoseconds. + Weight::from_parts(21_241_034, 4309) + // Standard Error: 2_448 + .saturating_add(Weight::from_parts(133_643, 0).saturating_mul(t.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 112).saturating_mul(t.into())) @@ -250,29 +248,27 @@ impl WeightInfo for () { /// The range of component `t` is `[1, 13]`. fn close_tip(t: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `786 + t * (112 ±0)` - // Estimated: `4242 + t * (112 ±0)` - // Minimum execution time: 56_060_000 picoseconds. - Weight::from_parts(57_913_972, 4242) - // Standard Error: 11_691 - .saturating_add(Weight::from_parts(229_579, 0).saturating_mul(t.into())) + // Measured: `896 + t * (112 ±0)` + // Estimated: `4353 + t * (111 ±0)` + // Minimum execution time: 60_824_000 picoseconds. + Weight::from_parts(63_233_742, 4353) + // Standard Error: 9_841 + .saturating_add(Weight::from_parts(77_920, 0).saturating_mul(t.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) - .saturating_add(Weight::from_parts(0, 112).saturating_mul(t.into())) + .saturating_add(Weight::from_parts(0, 111).saturating_mul(t.into())) } /// Storage: `Tips::Tips` (r:1 w:1) /// Proof: `Tips::Tips` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Tips::Reasons` (r:0 w:1) /// Proof: `Tips::Reasons` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `t` is `[1, 13]`. - fn slash_tip(t: u32, ) -> Weight { + fn slash_tip(_t: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `269` // Estimated: `3734` - // Minimum execution time: 12_034_000 picoseconds. - Weight::from_parts(12_934_534, 3734) - // Standard Error: 2_420 - .saturating_add(Weight::from_parts(4_167, 0).saturating_mul(t.into())) + // Minimum execution time: 13_281_000 picoseconds. + Weight::from_parts(14_089_409, 3734) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/benchmarking.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/benchmarking.rs index 97eff03d849d..eb2635694e9c 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/benchmarking.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/benchmarking.rs @@ -59,7 +59,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, |_| Ok(post_info)) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info)) .unwrap() .is_ok()); } @@ -86,7 +86,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, |_| Ok(post_info)) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info)) .unwrap() .is_ok()); } @@ -115,7 +115,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 0, |_| Ok( + .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 0, 0, |_| Ok( post_info )) .unwrap() diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs index 4312aa9a452f..6ce4652fd42f 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/tests.rs @@ -168,7 +168,7 @@ fn transaction_payment_in_native_possible() { let mut info = info_from_weight(WEIGHT_5); let ext = ChargeAssetTxPayment::::from(0, None); info.extension_weight = ext.weight(CALL); - let (pre, _) = ext.validate_and_prepare(Some(1).into(), CALL, &info, len).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(1).into(), CALL, &info, len, 0).unwrap(); let initial_balance = 10 * balance_factor; assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 15 - 10); @@ -185,7 +185,7 @@ fn transaction_payment_in_native_possible() { let ext = ChargeAssetTxPayment::::from(5 /* tipped */, None); let extension_weight = ext.weight(CALL); info.extension_weight = extension_weight; - let (pre, _) = ext.validate_and_prepare(Some(2).into(), CALL, &info, len).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(2).into(), CALL, &info, len, 0).unwrap(); let initial_balance_for_2 = 20 * balance_factor; assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 100 - 15 - 5); @@ -255,7 +255,13 @@ fn transaction_payment_in_asset_possible() { assert_eq!(Assets::balance(asset_id, caller), balance); let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_weight(WEIGHT_5), len) + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_weight(WEIGHT_5), + len, + 0, + ) .unwrap(); // assert that native balance is not used assert_eq!(Balances::free_balance(caller), 10 * balance_factor); @@ -313,7 +319,13 @@ fn transaction_payment_in_asset_fails_if_no_pool_for_that_asset() { let len = 10; let pre = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_weight(WEIGHT_5), len); + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_weight(WEIGHT_5), + len, + 0, + ); // As there is no pool in the dex set up for this asset, conversion should fail. assert!(pre.is_err()); @@ -364,7 +376,13 @@ fn transaction_payment_without_fee() { let fee_in_asset = input_quote.unwrap(); let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_weight(WEIGHT_5), len) + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_weight(WEIGHT_5), + len, + 0, + ) .unwrap(); // assert that native balance is not used @@ -445,7 +463,8 @@ fn asset_transaction_payment_with_tip_and_refund() { let mut info = info_from_weight(WEIGHT_100); let ext = ChargeAssetTxPayment::::from(tip, Some(asset_id.into())); info.extension_weight = ext.weight(CALL); - let (pre, _) = ext.validate_and_prepare(Some(caller).into(), CALL, &info, len).unwrap(); + let (pre, _) = + ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap(); assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset); let final_weight = 50; @@ -539,7 +558,13 @@ fn payment_from_account_with_only_assets() { assert_eq!(fee_in_asset, 201); let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_weight(WEIGHT_5), len) + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_weight(WEIGHT_5), + len, + 0, + ) .unwrap(); // check that fee was charged in the given asset assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset); @@ -595,7 +620,13 @@ fn converted_fee_is_never_zero_if_input_fee_is_not() { // there will be no conversion when the fee is zero { let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len) + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_pays(Pays::No), + len, + 0, + ) .unwrap(); // `Pays::No` implies there are no fees assert_eq!(Assets::balance(asset_id, caller), balance); @@ -626,6 +657,7 @@ fn converted_fee_is_never_zero_if_input_fee_is_not() { CALL, &info_from_weight(Weight::from_parts(weight, 0)), len, + 0, ) .unwrap(); assert_eq!(Assets::balance(asset_id, caller), balance - fee_in_asset); @@ -676,7 +708,7 @@ fn post_dispatch_fee_is_zero_if_pre_dispatch_fee_is_zero() { assert!(fee > 0); let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len) + .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len, 0) .unwrap(); // `Pays::No` implies no pre-dispatch fees @@ -730,7 +762,8 @@ fn fee_with_native_asset_passed_with_id() { let mut info = info_from_weight(WEIGHT_100); info.extension_weight = extension_weight; - let (pre, _) = ext.validate_and_prepare(Some(caller).into(), CALL, &info, len).unwrap(); + let (pre, _) = + ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap(); assert_eq!(Balances::free_balance(caller), caller_balance - initial_fee); let final_weight = 50; @@ -809,7 +842,7 @@ fn transfer_add_and_remove_account() { let mut info = info_from_weight(WEIGHT_100); info.extension_weight = extension_weight; let (pre, _) = ChargeAssetTxPayment::::from(tip, Some(asset_id.into())) - .validate_and_prepare(Some(caller).into(), CALL, &info, len) + .validate_and_prepare(Some(caller).into(), CALL, &info, len, 0) .unwrap(); assert_eq!(Assets::balance(asset_id, &caller), balance - fee_in_asset); @@ -869,7 +902,7 @@ fn no_fee_and_no_weight_for_other_origins() { let len = CALL.encoded_size(); let origin = frame_system::RawOrigin::Root.into(); - let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len).unwrap(); + let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len, 0).unwrap(); assert!(origin.as_system_ref().unwrap().is_root()); diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/weights.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/weights.rs index f95e49f80730..587a399634b7 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/weights.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_asset_conversion_tx_payment` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -63,42 +63,33 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 628_000 picoseconds. - Weight::from_parts(694_000, 0) + // Minimum execution time: 735_000 picoseconds. + Weight::from_parts(805_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn charge_asset_tx_payment_native() -> Weight { // Proof Size summary in bytes: - // Measured: `248` - // Estimated: `1733` - // Minimum execution time: 34_410_000 picoseconds. - Weight::from_parts(35_263_000, 1733) - .saturating_add(T::DbWeight::get().reads(3_u64)) + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 45_111_000 picoseconds. + Weight::from_parts(45_685_000, 3593) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:2 w:2) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn charge_asset_tx_payment_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `888` + // Measured: `711` // Estimated: `6208` - // Minimum execution time: 112_432_000 picoseconds. - Weight::from_parts(113_992_000, 6208) - .saturating_add(T::DbWeight::get().reads(7_u64)) + // Minimum execution time: 164_069_000 picoseconds. + Weight::from_parts(166_667_000, 6208) + .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } } @@ -109,42 +100,33 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 628_000 picoseconds. - Weight::from_parts(694_000, 0) + // Minimum execution time: 735_000 picoseconds. + Weight::from_parts(805_000, 0) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn charge_asset_tx_payment_native() -> Weight { // Proof Size summary in bytes: - // Measured: `248` - // Estimated: `1733` - // Minimum execution time: 34_410_000 picoseconds. - Weight::from_parts(35_263_000, 1733) - .saturating_add(RocksDbWeight::get().reads(3_u64)) + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 45_111_000 picoseconds. + Weight::from_parts(45_685_000, 3593) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:2 w:2) /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn charge_asset_tx_payment_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `888` + // Measured: `711` // Estimated: `6208` - // Minimum execution time: 112_432_000 picoseconds. - Weight::from_parts(113_992_000, 6208) - .saturating_add(RocksDbWeight::get().reads(7_u64)) + // Minimum execution time: 164_069_000 picoseconds. + Weight::from_parts(166_667_000, 6208) + .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } } diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/benchmarking.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/benchmarking.rs index 25902bf452b2..e4340cc6a152 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/benchmarking.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/benchmarking.rs @@ -59,7 +59,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, |_| Ok(post_info)) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info)) .unwrap() .is_ok()); } @@ -87,7 +87,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, |_| Ok(post_info)) + .test_run(RawOrigin::Signed(caller).into(), &call, &info, 0, 0, |_| Ok(post_info)) .unwrap() .is_ok()); } @@ -119,7 +119,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 0, |_| Ok( + .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 0, 0, |_| Ok( post_info )) .unwrap() diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/tests.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/tests.rs index cd694c3e81a7..6de2e8e7da55 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/tests.rs @@ -122,7 +122,7 @@ fn transaction_payment_in_native_possible() { let mut info = info_from_weight(Weight::from_parts(5, 0)); let ext = ChargeAssetTxPayment::::from(0, None); info.extension_weight = ext.weight(CALL); - let (pre, _) = ext.validate_and_prepare(Some(1).into(), CALL, &info, len).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(1).into(), CALL, &info, len, 0).unwrap(); let initial_balance = 10 * balance_factor; assert_eq!(Balances::free_balance(1), initial_balance - 5 - 5 - 15 - 10); @@ -138,7 +138,7 @@ fn transaction_payment_in_native_possible() { let mut info = info_from_weight(Weight::from_parts(100, 0)); let ext = ChargeAssetTxPayment::::from(5 /* tipped */, None); info.extension_weight = ext.weight(CALL); - let (pre, _) = ext.validate_and_prepare(Some(2).into(), CALL, &info, len).unwrap(); + let (pre, _) = ext.validate_and_prepare(Some(2).into(), CALL, &info, len, 0).unwrap(); let initial_balance_for_2 = 20 * balance_factor; assert_eq!(Balances::free_balance(2), initial_balance_for_2 - 5 - 10 - 100 - 15 - 5); @@ -204,6 +204,7 @@ fn transaction_payment_in_asset_possible() { CALL, &info_from_weight(Weight::from_parts(weight, 0)), len, + 0, ) .unwrap(); // assert that native balance is not used @@ -274,6 +275,7 @@ fn transaction_payment_without_fee() { CALL, &info_from_weight(Weight::from_parts(weight, 0)), len, + 0, ) .unwrap(); // assert that native balance is not used @@ -334,7 +336,8 @@ fn asset_transaction_payment_with_tip_and_refund() { min_balance / ExistentialDeposit::get(); let mut info = info_from_weight(Weight::from_parts(weight, 0)); info.extension_weight = ext_weight; - let (pre, _) = ext.validate_and_prepare(Some(caller).into(), CALL, &info, len).unwrap(); + let (pre, _) = + ext.validate_and_prepare(Some(caller).into(), CALL, &info, len, 0).unwrap(); assert_eq!(Assets::balance(asset_id, caller), balance - fee_with_tip); System::assert_has_event(RuntimeEvent::Assets(pallet_assets::Event::Withdrawn { @@ -409,6 +412,7 @@ fn payment_from_account_with_only_assets() { CALL, &info_from_weight(Weight::from_parts(weight, 0)), len, + 0, ) .unwrap(); assert_eq!(Balances::free_balance(caller), 0); @@ -445,7 +449,8 @@ fn payment_only_with_existing_sufficient_asset() { Some(caller).into(), CALL, &info_from_weight(Weight::from_parts(weight, 0)), - len + len, + 0, ) .is_err()); @@ -464,7 +469,8 @@ fn payment_only_with_existing_sufficient_asset() { Some(caller).into(), CALL, &info_from_weight(Weight::from_parts(weight, 0)), - len + len, + 0, ) .is_err()); }); @@ -504,7 +510,13 @@ fn converted_fee_is_never_zero_if_input_fee_is_not() { assert_eq!(fee, 0); { let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id)) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len) + .validate_and_prepare( + Some(caller).into(), + CALL, + &info_from_pays(Pays::No), + len, + 0, + ) .unwrap(); // `Pays::No` still implies no fees assert_eq!(Assets::balance(asset_id, caller), balance); @@ -524,6 +536,7 @@ fn converted_fee_is_never_zero_if_input_fee_is_not() { CALL, &info_from_weight(Weight::from_parts(weight, 0)), len, + 0, ) .unwrap(); // check that at least one coin was charged in the given asset @@ -573,7 +586,7 @@ fn post_dispatch_fee_is_zero_if_pre_dispatch_fee_is_zero() { // calculated fee is greater than 0 assert!(fee > 0); let (pre, _) = ChargeAssetTxPayment::::from(0, Some(asset_id)) - .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len) + .validate_and_prepare(Some(caller).into(), CALL, &info_from_pays(Pays::No), len, 0) .unwrap(); // `Pays::No` implies no pre-dispatch fees assert_eq!(Assets::balance(asset_id, caller), balance); @@ -613,7 +626,7 @@ fn no_fee_and_no_weight_for_other_origins() { let len = CALL.encoded_size(); let origin = frame_system::RawOrigin::Root.into(); - let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len).unwrap(); + let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len, 0).unwrap(); assert!(origin.as_system_ref().unwrap().is_root()); diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs index 1940110a1f1d..b6ecbf9d5764 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/tests.rs @@ -24,13 +24,13 @@ use sp_runtime::{traits::DispatchTransaction, transaction_validity::TransactionS fn skip_feeless_payment_works() { let call = RuntimeCall::DummyPallet(Call::::aux { data: 1 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0) .unwrap(); assert_eq!(PrepareCount::get(), 1); let call = RuntimeCall::DummyPallet(Call::::aux { data: 0 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0) .unwrap(); assert_eq!(PrepareCount::get(), 1); } @@ -47,6 +47,7 @@ fn validate_works() { &DispatchInfo::default(), 0, TransactionSource::External, + 0, ) .unwrap(); assert_eq!(ValidateCount::get(), 1); @@ -60,6 +61,7 @@ fn validate_works() { &DispatchInfo::default(), 0, TransactionSource::External, + 0, ) .unwrap(); assert_eq!(ValidateCount::get(), 1); @@ -72,14 +74,14 @@ fn validate_prepare_works() { let call = RuntimeCall::DummyPallet(Call::::aux { data: 1 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0) .unwrap(); assert_eq!(ValidateCount::get(), 1); assert_eq!(PrepareCount::get(), 1); let call = RuntimeCall::DummyPallet(Call::::aux { data: 0 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0) .unwrap(); assert_eq!(ValidateCount::get(), 1); assert_eq!(PrepareCount::get(), 1); @@ -87,7 +89,7 @@ fn validate_prepare_works() { // Changes from previous prepare calls persist. let call = RuntimeCall::DummyPallet(Call::::aux { data: 1 }); SkipCheckIfFeeless::::from(DummyExtension) - .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0) + .validate_and_prepare(Some(0).into(), &call, &DispatchInfo::default(), 0, 0) .unwrap(); assert_eq!(ValidateCount::get(), 2); assert_eq!(PrepareCount::get(), 2); diff --git a/substrate/frame/transaction-payment/src/benchmarking.rs b/substrate/frame/transaction-payment/src/benchmarking.rs index c5f87fb8c12c..eba4c0964ce7 100644 --- a/substrate/frame/transaction-payment/src/benchmarking.rs +++ b/substrate/frame/transaction-payment/src/benchmarking.rs @@ -68,7 +68,7 @@ mod benchmarks { #[block] { assert!(ext - .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 10, |_| Ok( + .test_run(RawOrigin::Signed(caller.clone()).into(), &call, &info, 10, 0, |_| Ok( post_info )) .unwrap() diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 018c2f6b5919..216697beac69 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -403,6 +403,7 @@ pub mod pallet { } #[pallet::storage] + #[pallet::whitelist_storage] pub type NextFeeMultiplier = StorageValue<_, Multiplier, ValueQuery, NextFeeMultiplierOnEmpty>; diff --git a/substrate/frame/transaction-payment/src/tests.rs b/substrate/frame/transaction-payment/src/tests.rs index dde696f09c2a..572c1d4961dd 100644 --- a/substrate/frame/transaction-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/src/tests.rs @@ -144,7 +144,7 @@ fn transaction_extension_transaction_payment_work() { let ext = Ext::from(0); let ext_weight = ext.weight(CALL); info.extension_weight = ext_weight; - ext.test_run(Some(1).into(), CALL, &info, 10, |_| { + ext.test_run(Some(1).into(), CALL, &info, 10, 0, |_| { assert_eq!(Balances::free_balance(1), 100 - 5 - 5 - 10 - 10); Ok(default_post_info()) }) @@ -159,7 +159,7 @@ fn transaction_extension_transaction_payment_work() { let mut info = info_from_weight(Weight::from_parts(100, 0)); info.extension_weight = ext_weight; Ext::from(5 /* tipped */) - .test_run(Some(2).into(), CALL, &info, 10, |_| { + .test_run(Some(2).into(), CALL, &info, 10, 0, |_| { assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 10 - 5); Ok(post_info_from_weight(Weight::from_parts(50, 0))) }) @@ -186,7 +186,7 @@ fn transaction_extension_transaction_payment_multiplied_refund_works() { let ext = Ext::from(5 /* tipped */); let ext_weight = ext.weight(CALL); info.extension_weight = ext_weight; - ext.test_run(origin, CALL, &info, len, |_| { + ext.test_run(origin, CALL, &info, len, 0, |_| { // 5 base fee, 10 byte fee, 3/2 * (100 call weight fee + 10 ext weight fee), 5 // tip assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 165 - 5); @@ -206,7 +206,7 @@ fn transaction_extension_transaction_payment_is_bounded() { ExtBuilder::default().balance_factor(1000).byte_fee(0).build().execute_with(|| { // maximum weight possible let info = info_from_weight(Weight::MAX); - assert_ok!(Ext::from(0).validate_and_prepare(Some(1).into(), CALL, &info, 10)); + assert_ok!(Ext::from(0).validate_and_prepare(Some(1).into(), CALL, &info, 10, 0)); // fee will be proportional to what is the actual maximum weight in the runtime. assert_eq!( Balances::free_balance(&1), @@ -235,7 +235,7 @@ fn transaction_extension_allows_free_transactions() { class: DispatchClass::Operational, pays_fee: Pays::No, }; - assert_ok!(Ext::from(0).validate_only(Some(1).into(), CALL, &op_tx, len, External)); + assert_ok!(Ext::from(0).validate_only(Some(1).into(), CALL, &op_tx, len, External, 0)); // like a InsecureFreeNormal let free_tx = DispatchInfo { @@ -246,7 +246,7 @@ fn transaction_extension_allows_free_transactions() { }; assert_eq!( Ext::from(0) - .validate_only(Some(1).into(), CALL, &free_tx, len, External) + .validate_only(Some(1).into(), CALL, &free_tx, len, External, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::Payment), ); @@ -264,7 +264,7 @@ fn transaction_ext_length_fee_is_also_updated_per_congestion() { NextFeeMultiplier::::put(Multiplier::saturating_from_rational(3, 2)); let len = 10; let info = info_from_weight(Weight::from_parts(3, 0)); - assert_ok!(Ext::from(10).validate_and_prepare(Some(1).into(), CALL, &info, len)); + assert_ok!(Ext::from(10).validate_and_prepare(Some(1).into(), CALL, &info, len, 0)); assert_eq!( Balances::free_balance(1), 100 // original @@ -526,7 +526,7 @@ fn refund_does_not_recreate_account() { System::set_block_number(10); let info = info_from_weight(Weight::from_parts(100, 0)); Ext::from(5 /* tipped */) - .test_run(Some(2).into(), CALL, &info, 10, |origin| { + .test_run(Some(2).into(), CALL, &info, 10, 0, |origin| { assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5); // kill the account between pre and post dispatch @@ -564,7 +564,7 @@ fn actual_weight_higher_than_max_refunds_nothing() { .execute_with(|| { let info = info_from_weight(Weight::from_parts(100, 0)); Ext::from(5 /* tipped */) - .test_run(Some(2).into(), CALL, &info, 10, |_| { + .test_run(Some(2).into(), CALL, &info, 10, 0, |_| { assert_eq!(Balances::free_balance(2), 200 - 5 - 10 - 100 - 5); Ok(post_info_from_weight(Weight::from_parts(101, 0))) }) @@ -591,7 +591,7 @@ fn zero_transfer_on_free_transaction() { }; let user = 69; Ext::from(0) - .test_run(Some(user).into(), CALL, &info, 10, |_| { + .test_run(Some(user).into(), CALL, &info, 10, 0, |_| { assert_eq!(Balances::total_balance(&user), 0); Ok(default_post_info()) }) @@ -628,7 +628,7 @@ fn refund_consistent_with_actual_weight() { NextFeeMultiplier::::put(Multiplier::saturating_from_rational(5, 4)); let actual_post_info = ext - .test_run(Some(2).into(), CALL, &info, len, |_| Ok(post_info)) + .test_run(Some(2).into(), CALL, &info, len, 0, |_| Ok(post_info)) .unwrap() .unwrap(); post_info @@ -662,7 +662,7 @@ fn should_alter_operational_priority() { let ext = Ext::from(tip); let priority = ext - .validate_only(Some(2).into(), CALL, &normal, len, External) + .validate_only(Some(2).into(), CALL, &normal, len, External, 0) .unwrap() .0 .priority; @@ -670,7 +670,7 @@ fn should_alter_operational_priority() { let ext = Ext::from(2 * tip); let priority = ext - .validate_only(Some(2).into(), CALL, &normal, len, External) + .validate_only(Some(2).into(), CALL, &normal, len, External, 0) .unwrap() .0 .priority; @@ -686,13 +686,19 @@ fn should_alter_operational_priority() { }; let ext = Ext::from(tip); - let priority = - ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &op, len, External, 0) + .unwrap() + .0 + .priority; assert_eq!(priority, 5810); let ext = Ext::from(2 * tip); - let priority = - ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &op, len, External, 0) + .unwrap() + .0 + .priority; assert_eq!(priority, 6110); }); } @@ -711,7 +717,7 @@ fn no_tip_has_some_priority() { }; let ext = Ext::from(tip); let priority = ext - .validate_only(Some(2).into(), CALL, &normal, len, External) + .validate_only(Some(2).into(), CALL, &normal, len, External, 0) .unwrap() .0 .priority; @@ -726,8 +732,11 @@ fn no_tip_has_some_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - let priority = - ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; + let priority = ext + .validate_only(Some(2).into(), CALL, &op, len, External, 0) + .unwrap() + .0 + .priority; assert_eq!(priority, 5510); }); } @@ -746,8 +755,9 @@ fn higher_tip_have_higher_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); + pri1 = ext - .validate_only(Some(2).into(), CALL, &normal, len, External) + .validate_only(Some(2).into(), CALL, &normal, len, External, 0) .unwrap() .0 .priority; @@ -761,7 +771,11 @@ fn higher_tip_have_higher_priority() { pays_fee: Pays::Yes, }; let ext = Ext::from(tip); - pri2 = ext.validate_only(Some(2).into(), CALL, &op, len, External).unwrap().0.priority; + pri2 = ext + .validate_only(Some(2).into(), CALL, &op, len, External, 0) + .unwrap() + .0 + .priority; }); (pri1, pri2) @@ -793,7 +807,7 @@ fn post_info_can_change_pays_fee() { NextFeeMultiplier::::put(Multiplier::saturating_from_rational(5, 4)); let post_info = ChargeTransactionPayment::::from(tip) - .test_run(Some(2).into(), CALL, &info, len, |_| Ok(post_info)) + .test_run(Some(2).into(), CALL, &info, len, 0, |_| Ok(post_info)) .unwrap() .unwrap(); @@ -841,7 +855,7 @@ fn no_fee_and_no_weight_for_other_origins() { let len = CALL.encoded_size(); let origin = frame_system::RawOrigin::Root.into(); - let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len).unwrap(); + let (pre, origin) = ext.validate_and_prepare(origin, CALL, &info, len, 0).unwrap(); assert!(origin.as_system_ref().unwrap().is_root()); diff --git a/substrate/frame/transaction-payment/src/weights.rs b/substrate/frame/transaction-payment/src/weights.rs index bcffb2eb331a..59d5cac7a2b7 100644 --- a/substrate/frame/transaction-payment/src/weights.rs +++ b/substrate/frame/transaction-payment/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_transaction_payment` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-bn-ce5rx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -57,36 +57,30 @@ pub trait WeightInfo { /// Weights for `pallet_transaction_payment` using the Substrate node and recommended hardware. pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn charge_transaction_payment() -> Weight { // Proof Size summary in bytes: - // Measured: `248` - // Estimated: `1733` - // Minimum execution time: 40_506_000 picoseconds. - Weight::from_parts(41_647_000, 1733) - .saturating_add(T::DbWeight::get().reads(3_u64)) + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 39_528_000 picoseconds. + Weight::from_parts(40_073_000, 3593) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) } } // For backwards compatibility and tests. impl WeightInfo for () { - /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) - /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Authorship::Author` (r:1 w:0) - /// Proof: `Authorship::Author` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:0) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn charge_transaction_payment() -> Weight { // Proof Size summary in bytes: - // Measured: `248` - // Estimated: `1733` - // Minimum execution time: 40_506_000 picoseconds. - Weight::from_parts(41_647_000, 1733) - .saturating_add(RocksDbWeight::get().reads(3_u64)) + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 39_528_000 picoseconds. + Weight::from_parts(40_073_000, 3593) + .saturating_add(RocksDbWeight::get().reads(1_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/transaction-storage/src/weights.rs b/substrate/frame/transaction-storage/src/weights.rs index 4d51daa17b40..36681f0abd8b 100644 --- a/substrate/frame/transaction-storage/src/weights.rs +++ b/substrate/frame/transaction-storage/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_transaction_storage` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -64,7 +64,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `TransactionStorage::EntryFee` (r:1 w:0) /// Proof: `TransactionStorage::EntryFee` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `TransactionStorage::BlockTransactions` (r:1 w:1) /// Proof: `TransactionStorage::BlockTransactions` (`max_values`: Some(1), `max_size`: Some(36866), added: 37361, mode: `MaxEncodedLen`) /// The range of component `l` is `[1, 8388608]`. @@ -72,10 +72,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `242` // Estimated: `38351` - // Minimum execution time: 62_024_000 picoseconds. - Weight::from_parts(63_536_000, 38351) - // Standard Error: 13 - .saturating_add(Weight::from_parts(7_178, 0).saturating_mul(l.into())) + // Minimum execution time: 65_899_000 picoseconds. + Weight::from_parts(66_814_000, 38351) + // Standard Error: 7 + .saturating_add(Weight::from_parts(7_678, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -86,15 +86,15 @@ impl WeightInfo for SubstrateWeight { /// Storage: `TransactionStorage::EntryFee` (r:1 w:0) /// Proof: `TransactionStorage::EntryFee` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `TransactionStorage::BlockTransactions` (r:1 w:1) /// Proof: `TransactionStorage::BlockTransactions` (`max_values`: Some(1), `max_size`: Some(36866), added: 37361, mode: `MaxEncodedLen`) fn renew() -> Weight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `40351` - // Minimum execution time: 81_473_000 picoseconds. - Weight::from_parts(84_000_000, 40351) + // Minimum execution time: 87_876_000 picoseconds. + Weight::from_parts(91_976_000, 40351) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -112,8 +112,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `37211` // Estimated: `40351` - // Minimum execution time: 68_167_000 picoseconds. - Weight::from_parts(75_532_000, 40351) + // Minimum execution time: 78_423_000 picoseconds. + Weight::from_parts(82_423_000, 40351) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -126,7 +126,7 @@ impl WeightInfo for () { /// Storage: `TransactionStorage::EntryFee` (r:1 w:0) /// Proof: `TransactionStorage::EntryFee` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `TransactionStorage::BlockTransactions` (r:1 w:1) /// Proof: `TransactionStorage::BlockTransactions` (`max_values`: Some(1), `max_size`: Some(36866), added: 37361, mode: `MaxEncodedLen`) /// The range of component `l` is `[1, 8388608]`. @@ -134,10 +134,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `242` // Estimated: `38351` - // Minimum execution time: 62_024_000 picoseconds. - Weight::from_parts(63_536_000, 38351) - // Standard Error: 13 - .saturating_add(Weight::from_parts(7_178, 0).saturating_mul(l.into())) + // Minimum execution time: 65_899_000 picoseconds. + Weight::from_parts(66_814_000, 38351) + // Standard Error: 7 + .saturating_add(Weight::from_parts(7_678, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -148,15 +148,15 @@ impl WeightInfo for () { /// Storage: `TransactionStorage::EntryFee` (r:1 w:0) /// Proof: `TransactionStorage::EntryFee` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `Balances::Holds` (r:1 w:1) - /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(193), added: 2668, mode: `MaxEncodedLen`) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(355), added: 2830, mode: `MaxEncodedLen`) /// Storage: `TransactionStorage::BlockTransactions` (r:1 w:1) /// Proof: `TransactionStorage::BlockTransactions` (`max_values`: Some(1), `max_size`: Some(36866), added: 37361, mode: `MaxEncodedLen`) fn renew() -> Weight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `40351` - // Minimum execution time: 81_473_000 picoseconds. - Weight::from_parts(84_000_000, 40351) + // Minimum execution time: 87_876_000 picoseconds. + Weight::from_parts(91_976_000, 40351) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -174,8 +174,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `37211` // Estimated: `40351` - // Minimum execution time: 68_167_000 picoseconds. - Weight::from_parts(75_532_000, 40351) + // Minimum execution time: 78_423_000 picoseconds. + Weight::from_parts(82_423_000, 40351) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/treasury/src/weights.rs b/substrate/frame/treasury/src/weights.rs index 8c9c6eb1d0fb..f5063eb881c4 100644 --- a/substrate/frame/treasury/src/weights.rs +++ b/substrate/frame/treasury/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_treasury` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -73,64 +73,55 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1887` - // Minimum execution time: 11_910_000 picoseconds. - Weight::from_parts(12_681_000, 1887) + // Minimum execution time: 11_807_000 picoseconds. + Weight::from_parts(12_313_000, 1887) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) + /// Storage: `Treasury::Approvals` (r:1 w:1) + /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn remove_approval() -> Weight { // Proof Size summary in bytes: // Measured: `161` // Estimated: `1887` - // Minimum execution time: 6_372_000 picoseconds. - Weight::from_parts(6_567_000, 1887) + // Minimum execution time: 7_217_000 picoseconds. + Weight::from_parts(7_516_000, 1887) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Treasury::Deactivated` (r:1 w:1) /// Proof: `Treasury::Deactivated` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:99 w:99) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:198 w:198) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Bounties::BountyApprovals` (r:1 w:1) - /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + /// Storage: `Treasury::LastSpendPeriod` (r:1 w:1) + /// Proof: `Treasury::LastSpendPeriod` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 99]`. fn on_initialize_proposals(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `451 + p * (251 ±0)` - // Estimated: `1887 + p * (5206 ±0)` - // Minimum execution time: 33_150_000 picoseconds. - Weight::from_parts(41_451_020, 1887) - // Standard Error: 19_018 - .saturating_add(Weight::from_parts(34_410_759, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(p.into()))) - .saturating_add(T::DbWeight::get().writes(3_u64)) - .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(p.into()))) - .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) + // Measured: `170` + // Estimated: `1501` + // Minimum execution time: 10_929_000 picoseconds. + Weight::from_parts(13_737_454, 1501) + // Standard Error: 790 + .saturating_add(Weight::from_parts(33_673, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:0) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) /// Storage: `Treasury::SpendCount` (r:1 w:1) /// Proof: `Treasury::SpendCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Treasury::Spends` (r:0 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn spend() -> Weight { // Proof Size summary in bytes: - // Measured: `140` - // Estimated: `3501` - // Minimum execution time: 14_233_000 picoseconds. - Weight::from_parts(14_842_000, 3501) + // Measured: `141` + // Estimated: `3502` + // Minimum execution time: 16_082_000 picoseconds. + Weight::from_parts(16_542_000, 3502) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:2 w:2) @@ -139,32 +130,32 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout() -> Weight { // Proof Size summary in bytes: - // Measured: `709` + // Measured: `710` // Estimated: `6208` - // Minimum execution time: 58_857_000 picoseconds. - Weight::from_parts(61_291_000, 6208) + // Minimum execution time: 64_180_000 picoseconds. + Weight::from_parts(65_783_000, 6208) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn check_status() -> Weight { // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 12_116_000 picoseconds. - Weight::from_parts(12_480_000, 3538) + // Measured: `199` + // Estimated: `3539` + // Minimum execution time: 13_379_000 picoseconds. + Weight::from_parts(13_751_000, 3539) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn void_spend() -> Weight { // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 10_834_000 picoseconds. - Weight::from_parts(11_427_000, 3538) + // Measured: `199` + // Estimated: `3539` + // Minimum execution time: 12_014_000 picoseconds. + Weight::from_parts(12_423_000, 3539) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -182,64 +173,55 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1887` - // Minimum execution time: 11_910_000 picoseconds. - Weight::from_parts(12_681_000, 1887) + // Minimum execution time: 11_807_000 picoseconds. + Weight::from_parts(12_313_000, 1887) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) + /// Storage: `Treasury::Approvals` (r:1 w:1) + /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn remove_approval() -> Weight { // Proof Size summary in bytes: // Measured: `161` // Estimated: `1887` - // Minimum execution time: 6_372_000 picoseconds. - Weight::from_parts(6_567_000, 1887) + // Minimum execution time: 7_217_000 picoseconds. + Weight::from_parts(7_516_000, 1887) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Treasury::Deactivated` (r:1 w:1) /// Proof: `Treasury::Deactivated` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:99 w:99) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:198 w:198) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `Bounties::BountyApprovals` (r:1 w:1) - /// Proof: `Bounties::BountyApprovals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + /// Storage: `Treasury::LastSpendPeriod` (r:1 w:1) + /// Proof: `Treasury::LastSpendPeriod` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// The range of component `p` is `[0, 99]`. fn on_initialize_proposals(p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `451 + p * (251 ±0)` - // Estimated: `1887 + p * (5206 ±0)` - // Minimum execution time: 33_150_000 picoseconds. - Weight::from_parts(41_451_020, 1887) - // Standard Error: 19_018 - .saturating_add(Weight::from_parts(34_410_759, 0).saturating_mul(p.into())) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(p.into()))) - .saturating_add(RocksDbWeight::get().writes(3_u64)) - .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(p.into()))) - .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) + // Measured: `170` + // Estimated: `1501` + // Minimum execution time: 10_929_000 picoseconds. + Weight::from_parts(13_737_454, 1501) + // Standard Error: 790 + .saturating_add(Weight::from_parts(33_673, 0).saturating_mul(p.into())) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:0) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(36), added: 2511, mode: `MaxEncodedLen`) + /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(37), added: 2512, mode: `MaxEncodedLen`) /// Storage: `Treasury::SpendCount` (r:1 w:1) /// Proof: `Treasury::SpendCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Treasury::Spends` (r:0 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn spend() -> Weight { // Proof Size summary in bytes: - // Measured: `140` - // Estimated: `3501` - // Minimum execution time: 14_233_000 picoseconds. - Weight::from_parts(14_842_000, 3501) + // Measured: `141` + // Estimated: `3502` + // Minimum execution time: 16_082_000 picoseconds. + Weight::from_parts(16_542_000, 3502) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) /// Storage: `Assets::Asset` (r:1 w:1) /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) /// Storage: `Assets::Account` (r:2 w:2) @@ -248,32 +230,32 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn payout() -> Weight { // Proof Size summary in bytes: - // Measured: `709` + // Measured: `710` // Estimated: `6208` - // Minimum execution time: 58_857_000 picoseconds. - Weight::from_parts(61_291_000, 6208) + // Minimum execution time: 64_180_000 picoseconds. + Weight::from_parts(65_783_000, 6208) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn check_status() -> Weight { // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 12_116_000 picoseconds. - Weight::from_parts(12_480_000, 3538) + // Measured: `199` + // Estimated: `3539` + // Minimum execution time: 13_379_000 picoseconds. + Weight::from_parts(13_751_000, 3539) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Treasury::Spends` (r:1 w:1) - /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Proof: `Treasury::Spends` (`max_values`: None, `max_size`: Some(74), added: 2549, mode: `MaxEncodedLen`) fn void_spend() -> Weight { // Proof Size summary in bytes: - // Measured: `198` - // Estimated: `3538` - // Minimum execution time: 10_834_000 picoseconds. - Weight::from_parts(11_427_000, 3538) + // Measured: `199` + // Estimated: `3539` + // Minimum execution time: 12_014_000 picoseconds. + Weight::from_parts(12_423_000, 3539) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/tx-pause/src/weights.rs b/substrate/frame/tx-pause/src/weights.rs index e7837e9ca89c..67e1390e9c7d 100644 --- a/substrate/frame/tx-pause/src/weights.rs +++ b/substrate/frame/tx-pause/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_tx_pause` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -64,8 +64,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3` // Estimated: `3997` - // Minimum execution time: 12_218_000 picoseconds. - Weight::from_parts(12_542_000, 3997) + // Minimum execution time: 12_474_000 picoseconds. + Weight::from_parts(12_922_000, 3997) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -75,8 +75,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `565` // Estimated: `3997` - // Minimum execution time: 18_314_000 picoseconds. - Weight::from_parts(18_990_000, 3997) + // Minimum execution time: 19_918_000 picoseconds. + Weight::from_parts(20_380_000, 3997) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -90,8 +90,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3` // Estimated: `3997` - // Minimum execution time: 12_218_000 picoseconds. - Weight::from_parts(12_542_000, 3997) + // Minimum execution time: 12_474_000 picoseconds. + Weight::from_parts(12_922_000, 3997) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -101,8 +101,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `565` // Estimated: `3997` - // Minimum execution time: 18_314_000 picoseconds. - Weight::from_parts(18_990_000, 3997) + // Minimum execution time: 19_918_000 picoseconds. + Weight::from_parts(20_380_000, 3997) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/uniques/src/weights.rs b/substrate/frame/uniques/src/weights.rs index 5576c8921f9c..60c6f9316ec7 100644 --- a/substrate/frame/uniques/src/weights.rs +++ b/substrate/frame/uniques/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_uniques` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -88,10 +88,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: - // Measured: `249` + // Measured: `282` // Estimated: `3643` - // Minimum execution time: 27_074_000 picoseconds. - Weight::from_parts(28_213_000, 3643) + // Minimum execution time: 31_956_000 picoseconds. + Weight::from_parts(33_104_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -101,10 +101,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn force_create() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `142` // Estimated: `3643` - // Minimum execution time: 12_034_000 picoseconds. - Weight::from_parts(12_669_000, 3643) + // Minimum execution time: 12_757_000 picoseconds. + Weight::from_parts(13_327_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -129,16 +129,16 @@ impl WeightInfo for SubstrateWeight { /// The range of component `a` is `[0, 1000]`. fn destroy(n: u32, m: u32, a: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `418 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` + // Measured: `451 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` // Estimated: `3643 + a * (2647 ±0) + m * (2662 ±0) + n * (2597 ±0)` - // Minimum execution time: 2_928_174_000 picoseconds. - Weight::from_parts(2_970_367_000, 3643) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(7_336_699, 0).saturating_mul(n.into())) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(401_816, 0).saturating_mul(m.into())) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(346_952, 0).saturating_mul(a.into())) + // Minimum execution time: 3_236_461_000 picoseconds. + Weight::from_parts(3_291_013_000, 3643) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(8_285_170, 0).saturating_mul(n.into())) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(469_210, 0).saturating_mul(m.into())) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(546_865, 0).saturating_mul(a.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(m.into()))) @@ -161,10 +161,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) fn mint() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 33_733_000 picoseconds. - Weight::from_parts(35_366_000, 3643) + // Minimum execution time: 39_056_000 picoseconds. + Weight::from_parts(40_157_000, 3643) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -178,10 +178,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn burn() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 35_064_000 picoseconds. - Weight::from_parts(35_747_000, 3643) + // Minimum execution time: 39_462_000 picoseconds. + Weight::from_parts(41_368_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -195,10 +195,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 24_955_000 picoseconds. - Weight::from_parts(25_661_000, 3643) + // Minimum execution time: 30_639_000 picoseconds. + Weight::from_parts(31_523_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -209,12 +209,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `i` is `[0, 5000]`. fn redeposit(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `805 + i * (76 ±0)` + // Measured: `838 + i * (76 ±0)` // Estimated: `3643 + i * (2597 ±0)` - // Minimum execution time: 12_119_000 picoseconds. - Weight::from_parts(12_490_000, 3643) - // Standard Error: 14_697 - .saturating_add(Weight::from_parts(15_720_495, 0).saturating_mul(i.into())) + // Minimum execution time: 16_920_000 picoseconds. + Weight::from_parts(17_096_000, 3643) + // Standard Error: 24_966 + .saturating_add(Weight::from_parts(18_491_945, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -227,10 +227,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn freeze() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_183_000 picoseconds. - Weight::from_parts(16_716_000, 3643) + // Minimum execution time: 21_752_000 picoseconds. + Weight::from_parts(22_743_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -240,10 +240,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn thaw() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_119_000 picoseconds. - Weight::from_parts(16_725_000, 3643) + // Minimum execution time: 21_892_000 picoseconds. + Weight::from_parts(22_583_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -251,10 +251,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn freeze_collection() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 10_889_000 picoseconds. - Weight::from_parts(11_480_000, 3643) + // Minimum execution time: 15_920_000 picoseconds. + Weight::from_parts(16_470_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -262,10 +262,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn thaw_collection() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 10_903_000 picoseconds. - Weight::from_parts(11_241_000, 3643) + // Minimum execution time: 15_489_000 picoseconds. + Weight::from_parts(16_232_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -279,10 +279,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn transfer_ownership() -> Weight { // Proof Size summary in bytes: - // Measured: `597` + // Measured: `630` // Estimated: `3643` - // Minimum execution time: 24_942_000 picoseconds. - Weight::from_parts(25_715_000, 3643) + // Minimum execution time: 31_035_000 picoseconds. + Weight::from_parts(31_987_000, 3643) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -290,10 +290,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn set_team() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 11_488_000 picoseconds. - Weight::from_parts(11_752_000, 3643) + // Minimum execution time: 15_914_000 picoseconds. + Weight::from_parts(16_494_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -303,10 +303,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn force_item_status() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 14_721_000 picoseconds. - Weight::from_parts(15_187_000, 3643) + // Minimum execution time: 19_490_000 picoseconds. + Weight::from_parts(20_121_000, 3643) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -318,10 +318,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) fn set_attribute() -> Weight { // Proof Size summary in bytes: - // Measured: `626` + // Measured: `659` // Estimated: `3652` - // Minimum execution time: 36_665_000 picoseconds. - Weight::from_parts(37_587_000, 3652) + // Minimum execution time: 42_331_000 picoseconds. + Weight::from_parts(44_248_000, 3652) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -333,10 +333,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) fn clear_attribute() -> Weight { // Proof Size summary in bytes: - // Measured: `823` + // Measured: `856` // Estimated: `3652` - // Minimum execution time: 35_066_000 picoseconds. - Weight::from_parts(36_380_000, 3652) + // Minimum execution time: 42_378_000 picoseconds. + Weight::from_parts(43_407_000, 3652) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -346,10 +346,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) fn set_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `415` + // Measured: `448` // Estimated: `3652` - // Minimum execution time: 27_060_000 picoseconds. - Weight::from_parts(27_813_000, 3652) + // Minimum execution time: 32_461_000 picoseconds. + Weight::from_parts(33_579_000, 3652) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -359,10 +359,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) fn clear_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `626` + // Measured: `659` // Estimated: `3652` - // Minimum execution time: 27_776_000 picoseconds. - Weight::from_parts(28_582_000, 3652) + // Minimum execution time: 34_123_000 picoseconds. + Weight::from_parts(35_283_000, 3652) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -372,10 +372,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) fn set_collection_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 27_636_000 picoseconds. - Weight::from_parts(29_118_000, 3643) + // Minimum execution time: 33_300_000 picoseconds. + Weight::from_parts(34_163_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -385,10 +385,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) fn clear_collection_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `540` + // Measured: `573` // Estimated: `3643` - // Minimum execution time: 28_246_000 picoseconds. - Weight::from_parts(29_059_000, 3643) + // Minimum execution time: 32_810_000 picoseconds. + Weight::from_parts(33_865_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -398,10 +398,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) fn approve_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_793_000 picoseconds. - Weight::from_parts(17_396_000, 3643) + // Minimum execution time: 22_203_000 picoseconds. + Weight::from_parts(22_831_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -411,10 +411,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) fn cancel_approval() -> Weight { // Proof Size summary in bytes: - // Measured: `528` + // Measured: `561` // Estimated: `3643` - // Minimum execution time: 16_726_000 picoseconds. - Weight::from_parts(17_357_000, 3643) + // Minimum execution time: 22_182_000 picoseconds. + Weight::from_parts(22_739_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -422,10 +422,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn set_accept_ownership() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `142` // Estimated: `3517` - // Minimum execution time: 12_686_000 picoseconds. - Weight::from_parts(13_182_000, 3517) + // Minimum execution time: 13_384_000 picoseconds. + Weight::from_parts(13_850_000, 3517) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -435,10 +435,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn set_collection_max_supply() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 13_508_000 picoseconds. - Weight::from_parts(13_906_000, 3643) + // Minimum execution time: 18_516_000 picoseconds. + Weight::from_parts(19_043_000, 3643) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -448,10 +448,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn set_price() -> Weight { // Proof Size summary in bytes: - // Measured: `326` + // Measured: `359` // Estimated: `3587` - // Minimum execution time: 13_742_000 picoseconds. - Weight::from_parts(14_200_000, 3587) + // Minimum execution time: 18_536_000 picoseconds. + Weight::from_parts(19_118_000, 3587) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -465,10 +465,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) fn buy_item() -> Weight { // Proof Size summary in bytes: - // Measured: `607` + // Measured: `640` // Estimated: `3643` - // Minimum execution time: 32_931_000 picoseconds. - Weight::from_parts(34_023_000, 3643) + // Minimum execution time: 38_751_000 picoseconds. + Weight::from_parts(39_570_000, 3643) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -482,10 +482,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: - // Measured: `249` + // Measured: `282` // Estimated: `3643` - // Minimum execution time: 27_074_000 picoseconds. - Weight::from_parts(28_213_000, 3643) + // Minimum execution time: 31_956_000 picoseconds. + Weight::from_parts(33_104_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -495,10 +495,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn force_create() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `142` // Estimated: `3643` - // Minimum execution time: 12_034_000 picoseconds. - Weight::from_parts(12_669_000, 3643) + // Minimum execution time: 12_757_000 picoseconds. + Weight::from_parts(13_327_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -523,16 +523,16 @@ impl WeightInfo for () { /// The range of component `a` is `[0, 1000]`. fn destroy(n: u32, m: u32, a: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `418 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` + // Measured: `451 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` // Estimated: `3643 + a * (2647 ±0) + m * (2662 ±0) + n * (2597 ±0)` - // Minimum execution time: 2_928_174_000 picoseconds. - Weight::from_parts(2_970_367_000, 3643) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(7_336_699, 0).saturating_mul(n.into())) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(401_816, 0).saturating_mul(m.into())) - // Standard Error: 30_368 - .saturating_add(Weight::from_parts(346_952, 0).saturating_mul(a.into())) + // Minimum execution time: 3_236_461_000 picoseconds. + Weight::from_parts(3_291_013_000, 3643) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(8_285_170, 0).saturating_mul(n.into())) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(469_210, 0).saturating_mul(m.into())) + // Standard Error: 39_603 + .saturating_add(Weight::from_parts(546_865, 0).saturating_mul(a.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(m.into()))) @@ -555,10 +555,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) fn mint() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 33_733_000 picoseconds. - Weight::from_parts(35_366_000, 3643) + // Minimum execution time: 39_056_000 picoseconds. + Weight::from_parts(40_157_000, 3643) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -572,10 +572,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn burn() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 35_064_000 picoseconds. - Weight::from_parts(35_747_000, 3643) + // Minimum execution time: 39_462_000 picoseconds. + Weight::from_parts(41_368_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -589,10 +589,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 24_955_000 picoseconds. - Weight::from_parts(25_661_000, 3643) + // Minimum execution time: 30_639_000 picoseconds. + Weight::from_parts(31_523_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -603,12 +603,12 @@ impl WeightInfo for () { /// The range of component `i` is `[0, 5000]`. fn redeposit(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `805 + i * (76 ±0)` + // Measured: `838 + i * (76 ±0)` // Estimated: `3643 + i * (2597 ±0)` - // Minimum execution time: 12_119_000 picoseconds. - Weight::from_parts(12_490_000, 3643) - // Standard Error: 14_697 - .saturating_add(Weight::from_parts(15_720_495, 0).saturating_mul(i.into())) + // Minimum execution time: 16_920_000 picoseconds. + Weight::from_parts(17_096_000, 3643) + // Standard Error: 24_966 + .saturating_add(Weight::from_parts(18_491_945, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(i.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -621,10 +621,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn freeze() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_183_000 picoseconds. - Weight::from_parts(16_716_000, 3643) + // Minimum execution time: 21_752_000 picoseconds. + Weight::from_parts(22_743_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -634,10 +634,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn thaw() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_119_000 picoseconds. - Weight::from_parts(16_725_000, 3643) + // Minimum execution time: 21_892_000 picoseconds. + Weight::from_parts(22_583_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -645,10 +645,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn freeze_collection() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 10_889_000 picoseconds. - Weight::from_parts(11_480_000, 3643) + // Minimum execution time: 15_920_000 picoseconds. + Weight::from_parts(16_470_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -656,10 +656,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn thaw_collection() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 10_903_000 picoseconds. - Weight::from_parts(11_241_000, 3643) + // Minimum execution time: 15_489_000 picoseconds. + Weight::from_parts(16_232_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -673,10 +673,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn transfer_ownership() -> Weight { // Proof Size summary in bytes: - // Measured: `597` + // Measured: `630` // Estimated: `3643` - // Minimum execution time: 24_942_000 picoseconds. - Weight::from_parts(25_715_000, 3643) + // Minimum execution time: 31_035_000 picoseconds. + Weight::from_parts(31_987_000, 3643) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -684,10 +684,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn set_team() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 11_488_000 picoseconds. - Weight::from_parts(11_752_000, 3643) + // Minimum execution time: 15_914_000 picoseconds. + Weight::from_parts(16_494_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -697,10 +697,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) fn force_item_status() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 14_721_000 picoseconds. - Weight::from_parts(15_187_000, 3643) + // Minimum execution time: 19_490_000 picoseconds. + Weight::from_parts(20_121_000, 3643) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -712,10 +712,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) fn set_attribute() -> Weight { // Proof Size summary in bytes: - // Measured: `626` + // Measured: `659` // Estimated: `3652` - // Minimum execution time: 36_665_000 picoseconds. - Weight::from_parts(37_587_000, 3652) + // Minimum execution time: 42_331_000 picoseconds. + Weight::from_parts(44_248_000, 3652) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -727,10 +727,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) fn clear_attribute() -> Weight { // Proof Size summary in bytes: - // Measured: `823` + // Measured: `856` // Estimated: `3652` - // Minimum execution time: 35_066_000 picoseconds. - Weight::from_parts(36_380_000, 3652) + // Minimum execution time: 42_378_000 picoseconds. + Weight::from_parts(43_407_000, 3652) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -740,10 +740,10 @@ impl WeightInfo for () { /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) fn set_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `415` + // Measured: `448` // Estimated: `3652` - // Minimum execution time: 27_060_000 picoseconds. - Weight::from_parts(27_813_000, 3652) + // Minimum execution time: 32_461_000 picoseconds. + Weight::from_parts(33_579_000, 3652) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -753,10 +753,10 @@ impl WeightInfo for () { /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) fn clear_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `626` + // Measured: `659` // Estimated: `3652` - // Minimum execution time: 27_776_000 picoseconds. - Weight::from_parts(28_582_000, 3652) + // Minimum execution time: 34_123_000 picoseconds. + Weight::from_parts(35_283_000, 3652) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -766,10 +766,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) fn set_collection_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 27_636_000 picoseconds. - Weight::from_parts(29_118_000, 3643) + // Minimum execution time: 33_300_000 picoseconds. + Weight::from_parts(34_163_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -779,10 +779,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) fn clear_collection_metadata() -> Weight { // Proof Size summary in bytes: - // Measured: `540` + // Measured: `573` // Estimated: `3643` - // Minimum execution time: 28_246_000 picoseconds. - Weight::from_parts(29_059_000, 3643) + // Minimum execution time: 32_810_000 picoseconds. + Weight::from_parts(33_865_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -792,10 +792,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) fn approve_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `495` + // Measured: `528` // Estimated: `3643` - // Minimum execution time: 16_793_000 picoseconds. - Weight::from_parts(17_396_000, 3643) + // Minimum execution time: 22_203_000 picoseconds. + Weight::from_parts(22_831_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -805,10 +805,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) fn cancel_approval() -> Weight { // Proof Size summary in bytes: - // Measured: `528` + // Measured: `561` // Estimated: `3643` - // Minimum execution time: 16_726_000 picoseconds. - Weight::from_parts(17_357_000, 3643) + // Minimum execution time: 22_182_000 picoseconds. + Weight::from_parts(22_739_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -816,10 +816,10 @@ impl WeightInfo for () { /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) fn set_accept_ownership() -> Weight { // Proof Size summary in bytes: - // Measured: `109` + // Measured: `142` // Estimated: `3517` - // Minimum execution time: 12_686_000 picoseconds. - Weight::from_parts(13_182_000, 3517) + // Minimum execution time: 13_384_000 picoseconds. + Weight::from_parts(13_850_000, 3517) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -829,10 +829,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) fn set_collection_max_supply() -> Weight { // Proof Size summary in bytes: - // Measured: `349` + // Measured: `382` // Estimated: `3643` - // Minimum execution time: 13_508_000 picoseconds. - Weight::from_parts(13_906_000, 3643) + // Minimum execution time: 18_516_000 picoseconds. + Weight::from_parts(19_043_000, 3643) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -842,10 +842,10 @@ impl WeightInfo for () { /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) fn set_price() -> Weight { // Proof Size summary in bytes: - // Measured: `326` + // Measured: `359` // Estimated: `3587` - // Minimum execution time: 13_742_000 picoseconds. - Weight::from_parts(14_200_000, 3587) + // Minimum execution time: 18_536_000 picoseconds. + Weight::from_parts(19_118_000, 3587) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -859,10 +859,10 @@ impl WeightInfo for () { /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) fn buy_item() -> Weight { // Proof Size summary in bytes: - // Measured: `607` + // Measured: `640` // Estimated: `3643` - // Minimum execution time: 32_931_000 picoseconds. - Weight::from_parts(34_023_000, 3643) + // Minimum execution time: 38_751_000 picoseconds. + Weight::from_parts(39_570_000, 3643) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } diff --git a/substrate/frame/utility/src/weights.rs b/substrate/frame/utility/src/weights.rs index 502f85a3f178..8b31eb2ced85 100644 --- a/substrate/frame/utility/src/weights.rs +++ b/substrate/frame/utility/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_utility` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -70,10 +70,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_312_000 picoseconds. - Weight::from_parts(2_694_370, 3997) - // Standard Error: 5_055 - .saturating_add(Weight::from_parts(5_005_941, 0).saturating_mul(c.into())) + // Minimum execution time: 4_830_000 picoseconds. + Weight::from_parts(19_388_813, 3997) + // Standard Error: 2_694 + .saturating_add(Weight::from_parts(4_591_113, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) @@ -84,8 +84,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 9_263_000 picoseconds. - Weight::from_parts(9_639_000, 3997) + // Minimum execution time: 10_474_000 picoseconds. + Weight::from_parts(10_896_000, 3997) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) @@ -97,18 +97,18 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_120_000 picoseconds. - Weight::from_parts(12_948_874, 3997) - // Standard Error: 4_643 - .saturating_add(Weight::from_parts(5_162_821, 0).saturating_mul(c.into())) + // Minimum execution time: 4_773_000 picoseconds. + Weight::from_parts(22_628_420, 3997) + // Standard Error: 2_405 + .saturating_add(Weight::from_parts(4_797_007, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) } fn dispatch_as() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_126_000 picoseconds. - Weight::from_parts(7_452_000, 0) + // Minimum execution time: 6_668_000 picoseconds. + Weight::from_parts(6_985_000, 0) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -119,10 +119,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_254_000 picoseconds. - Weight::from_parts(4_879_712, 3997) - // Standard Error: 4_988 - .saturating_add(Weight::from_parts(4_955_816, 0).saturating_mul(c.into())) + // Minimum execution time: 5_434_000 picoseconds. + Weight::from_parts(23_270_604, 3997) + // Standard Error: 2_511 + .saturating_add(Weight::from_parts(4_570_923, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) } } @@ -138,10 +138,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_312_000 picoseconds. - Weight::from_parts(2_694_370, 3997) - // Standard Error: 5_055 - .saturating_add(Weight::from_parts(5_005_941, 0).saturating_mul(c.into())) + // Minimum execution time: 4_830_000 picoseconds. + Weight::from_parts(19_388_813, 3997) + // Standard Error: 2_694 + .saturating_add(Weight::from_parts(4_591_113, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) @@ -152,8 +152,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 9_263_000 picoseconds. - Weight::from_parts(9_639_000, 3997) + // Minimum execution time: 10_474_000 picoseconds. + Weight::from_parts(10_896_000, 3997) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) @@ -165,18 +165,18 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_120_000 picoseconds. - Weight::from_parts(12_948_874, 3997) - // Standard Error: 4_643 - .saturating_add(Weight::from_parts(5_162_821, 0).saturating_mul(c.into())) + // Minimum execution time: 4_773_000 picoseconds. + Weight::from_parts(22_628_420, 3997) + // Standard Error: 2_405 + .saturating_add(Weight::from_parts(4_797_007, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) } fn dispatch_as() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_126_000 picoseconds. - Weight::from_parts(7_452_000, 0) + // Minimum execution time: 6_668_000 picoseconds. + Weight::from_parts(6_985_000, 0) } /// Storage: `SafeMode::EnteredUntil` (r:1 w:0) /// Proof: `SafeMode::EnteredUntil` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -187,10 +187,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3997` - // Minimum execution time: 5_254_000 picoseconds. - Weight::from_parts(4_879_712, 3997) - // Standard Error: 4_988 - .saturating_add(Weight::from_parts(4_955_816, 0).saturating_mul(c.into())) + // Minimum execution time: 5_434_000 picoseconds. + Weight::from_parts(23_270_604, 3997) + // Standard Error: 2_511 + .saturating_add(Weight::from_parts(4_570_923, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) } } diff --git a/substrate/frame/verify-signature/src/benchmarking.rs b/substrate/frame/verify-signature/src/benchmarking.rs index 475cf4cec591..99e893e6f6ab 100644 --- a/substrate/frame/verify-signature/src/benchmarking.rs +++ b/substrate/frame/verify-signature/src/benchmarking.rs @@ -33,7 +33,10 @@ use frame_support::{ }; use frame_system::{Call as SystemCall, RawOrigin}; use sp_io::hashing::blake2_256; -use sp_runtime::traits::{AsTransactionAuthorizedOrigin, Dispatchable, TransactionExtension}; +use sp_runtime::{ + generic::ExtensionVersion, + traits::{AsTransactionAuthorizedOrigin, DispatchTransaction, Dispatchable}, +}; pub trait BenchmarkHelper { fn create_signature(entropy: &[u8], msg: &[u8]) -> (Signature, Signer); @@ -51,22 +54,22 @@ mod benchmarks { fn verify_signature() -> Result<(), BenchmarkError> { let entropy = [42u8; 256]; let call: T::RuntimeCall = SystemCall::remark { remark: vec![] }.into(); + let ext_version: ExtensionVersion = 0; let info = call.get_dispatch_info(); - let msg = call.using_encoded(blake2_256).to_vec(); + let msg = (ext_version, &call).using_encoded(blake2_256).to_vec(); let (signature, signer) = T::BenchmarkHelper::create_signature(&entropy, &msg[..]); let ext = VerifySignature::::new_with_signature(signature, signer); #[block] { assert!(ext - .validate( + .validate_only( RawOrigin::None.into(), &call, &info, 0, - (), - &call, - TransactionSource::External + TransactionSource::External, + ext_version ) .is_ok()); } diff --git a/substrate/frame/verify-signature/src/tests.rs b/substrate/frame/verify-signature/src/tests.rs index 505a33a883c2..63a310506eec 100644 --- a/substrate/frame/verify-signature/src/tests.rs +++ b/substrate/frame/verify-signature/src/tests.rs @@ -31,6 +31,7 @@ use frame_support::{ use frame_system::Call as SystemCall; use sp_io::hashing::blake2_256; use sp_runtime::{ + generic::ExtensionVersion, testing::{TestSignature, UintAuthorityId}, traits::DispatchTransaction, }; @@ -80,15 +81,32 @@ pub fn new_test_ext() -> sp_io::TestExternalities { fn verification_works() { let who = 0; let call: RuntimeCall = SystemCall::remark { remark: vec![] }.into(); - let sig = TestSignature(0, call.using_encoded(blake2_256).to_vec()); + let ext_version: ExtensionVersion = 0; + let sig = TestSignature(0, (ext_version, &call).using_encoded(blake2_256).to_vec()); let info = call.get_dispatch_info(); let (_, _, origin) = VerifySignature::::new_with_signature(sig, who) - .validate_only(None.into(), &call, &info, 0, TransactionSource::External) + .validate_only(None.into(), &call, &info, 0, TransactionSource::External, 0) .unwrap(); assert_eq!(origin.as_signer().unwrap(), &who) } +#[test] +fn bad_inherited_implication() { + let who = 0; + let call: RuntimeCall = SystemCall::remark { remark: vec![] }.into(); + // Inherited implication should include extension version byte. + let sig = TestSignature(0, call.using_encoded(blake2_256).to_vec()); + let info = call.get_dispatch_info(); + + assert_eq!( + VerifySignature::::new_with_signature(sig, who) + .validate_only(None.into(), &call, &info, 0, TransactionSource::External, 0) + .unwrap_err(), + TransactionValidityError::Invalid(InvalidTransaction::BadProof) + ); +} + #[test] fn bad_signature() { let who = 0; @@ -98,7 +116,7 @@ fn bad_signature() { assert_eq!( VerifySignature::::new_with_signature(sig, who) - .validate_only(None.into(), &call, &info, 0, TransactionSource::External) + .validate_only(None.into(), &call, &info, 0, TransactionSource::External, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::BadProof) ); @@ -113,7 +131,7 @@ fn bad_starting_origin() { assert_eq!( VerifySignature::::new_with_signature(sig, who) - .validate_only(Some(42).into(), &call, &info, 0, TransactionSource::External) + .validate_only(Some(42).into(), &call, &info, 0, TransactionSource::External, 0) .unwrap_err(), TransactionValidityError::Invalid(InvalidTransaction::BadSigner) ); @@ -126,7 +144,7 @@ fn disabled_extension_works() { let info = call.get_dispatch_info(); let (_, _, origin) = VerifySignature::::new_disabled() - .validate_only(Some(who).into(), &call, &info, 0, TransactionSource::External) + .validate_only(Some(who).into(), &call, &info, 0, TransactionSource::External, 0) .unwrap(); assert_eq!(origin.as_signer().unwrap(), &who) } diff --git a/substrate/frame/verify-signature/src/weights.rs b/substrate/frame/verify-signature/src/weights.rs index 2c1f0f795422..a8bfa9ea902d 100644 --- a/substrate/frame/verify-signature/src/weights.rs +++ b/substrate/frame/verify-signature/src/weights.rs @@ -18,22 +18,25 @@ //! Autogenerated weights for `pallet_verify_signature` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-09-24, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `gleipnir`, CPU: `AMD Ryzen 9 7900X 12-Core Processor` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// ./target/debug/substrate-node +// ./target/production/substrate-node // benchmark // pallet -// --steps=2 -// --repeat=2 +// --chain=dev +// --steps=50 +// --repeat=20 +// --pallet=pallet_verify_signature +// --no-storage-info +// --no-median-slopes +// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --pallet=pallet-verify-signature -// --chain=dev // --output=./substrate/frame/verify-signature/src/weights.rs // --header=./substrate/HEADER-APACHE2 // --template=./substrate/.maintain/frame-weight-template.hbs @@ -58,8 +61,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_953_000 picoseconds. - Weight::from_parts(49_254_000, 0) + // Minimum execution time: 46_215_000 picoseconds. + Weight::from_parts(46_714_000, 0) } } @@ -69,7 +72,7 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 48_953_000 picoseconds. - Weight::from_parts(49_254_000, 0) + // Minimum execution time: 46_215_000 picoseconds. + Weight::from_parts(46_714_000, 0) } } diff --git a/substrate/frame/vesting/src/weights.rs b/substrate/frame/vesting/src/weights.rs index efb8cbcc41c4..3ab161e822e8 100644 --- a/substrate/frame/vesting/src/weights.rs +++ b/substrate/frame/vesting/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_vesting` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -75,14 +75,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[1, 28]`. fn vest_locked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `381 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 32_202_000 picoseconds. - Weight::from_parts(31_586_520, 4764) - // Standard Error: 1_513 - .saturating_add(Weight::from_parts(67_257, 0).saturating_mul(l.into())) - // Standard Error: 2_693 - .saturating_add(Weight::from_parts(69_725, 0).saturating_mul(s.into())) + // Minimum execution time: 39_505_000 picoseconds. + Weight::from_parts(39_835_306, 4764) + // Standard Error: 1_394 + .saturating_add(Weight::from_parts(21_450, 0).saturating_mul(l.into())) + // Standard Error: 2_481 + .saturating_add(Weight::from_parts(70_901, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -96,14 +96,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[1, 28]`. fn vest_unlocked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `381 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_847_000 picoseconds. - Weight::from_parts(34_690_456, 4764) - // Standard Error: 1_681 - .saturating_add(Weight::from_parts(51_103, 0).saturating_mul(l.into())) - // Standard Error: 2_991 - .saturating_add(Weight::from_parts(55_094, 0).saturating_mul(s.into())) + // Minimum execution time: 40_781_000 picoseconds. + Weight::from_parts(40_777_528, 4764) + // Standard Error: 1_209 + .saturating_add(Weight::from_parts(35_116, 0).saturating_mul(l.into())) + // Standard Error: 2_151 + .saturating_add(Weight::from_parts(83_093, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -119,14 +119,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[1, 28]`. fn vest_other_locked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `484 + l * (25 ±0) + s * (36 ±0)` + // Measured: `517 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_027_000 picoseconds. - Weight::from_parts(33_353_168, 4764) - // Standard Error: 1_477 - .saturating_add(Weight::from_parts(72_605, 0).saturating_mul(l.into())) - // Standard Error: 2_629 - .saturating_add(Weight::from_parts(64_115, 0).saturating_mul(s.into())) + // Minimum execution time: 41_590_000 picoseconds. + Weight::from_parts(40_756_231, 4764) + // Standard Error: 1_420 + .saturating_add(Weight::from_parts(45_223, 0).saturating_mul(l.into())) + // Standard Error: 2_527 + .saturating_add(Weight::from_parts(102_603, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -142,14 +142,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[1, 28]`. fn vest_other_unlocked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `484 + l * (25 ±0) + s * (36 ±0)` + // Measured: `517 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 36_816_000 picoseconds. - Weight::from_parts(36_467_447, 4764) - // Standard Error: 1_689 - .saturating_add(Weight::from_parts(51_855, 0).saturating_mul(l.into())) - // Standard Error: 3_006 - .saturating_add(Weight::from_parts(58_233, 0).saturating_mul(s.into())) + // Minimum execution time: 43_490_000 picoseconds. + Weight::from_parts(43_900_384, 4764) + // Standard Error: 1_670 + .saturating_add(Weight::from_parts(31_084, 0).saturating_mul(l.into())) + // Standard Error: 2_971 + .saturating_add(Weight::from_parts(66_673, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -165,14 +165,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 27]`. fn vested_transfer(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `555 + l * (25 ±0) + s * (36 ±0)` + // Measured: `588 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 70_906_000 picoseconds. - Weight::from_parts(72_663_428, 4764) - // Standard Error: 2_877 - .saturating_add(Weight::from_parts(81_242, 0).saturating_mul(l.into())) - // Standard Error: 5_118 - .saturating_add(Weight::from_parts(103_344, 0).saturating_mul(s.into())) + // Minimum execution time: 76_194_000 picoseconds. + Weight::from_parts(77_923_603, 4764) + // Standard Error: 2_141 + .saturating_add(Weight::from_parts(50_161, 0).saturating_mul(l.into())) + // Standard Error: 3_810 + .saturating_add(Weight::from_parts(97_415, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -188,14 +188,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 27]`. fn force_vested_transfer(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `658 + l * (25 ±0) + s * (36 ±0)` + // Measured: `691 + l * (25 ±0) + s * (36 ±0)` // Estimated: `6196` - // Minimum execution time: 72_730_000 picoseconds. - Weight::from_parts(75_050_411, 6196) - // Standard Error: 2_748 - .saturating_add(Weight::from_parts(73_218, 0).saturating_mul(l.into())) - // Standard Error: 4_889 - .saturating_add(Weight::from_parts(112_868, 0).saturating_mul(s.into())) + // Minimum execution time: 78_333_000 picoseconds. + Weight::from_parts(80_199_350, 6196) + // Standard Error: 1_903 + .saturating_add(Weight::from_parts(46_798, 0).saturating_mul(l.into())) + // Standard Error: 3_385 + .saturating_add(Weight::from_parts(106_311, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -205,22 +205,20 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 49]`. /// The range of component `s` is `[2, 28]`. fn not_unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `482 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_698_000 picoseconds. - Weight::from_parts(34_504_324, 4764) - // Standard Error: 1_703 - .saturating_add(Weight::from_parts(56_321, 0).saturating_mul(l.into())) - // Standard Error: 3_145 - .saturating_add(Weight::from_parts(55_503, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 40_102_000 picoseconds. + Weight::from_parts(39_552_301, 4764) + // Standard Error: 1_309 + .saturating_add(Weight::from_parts(37_184, 0).saturating_mul(l.into())) + // Standard Error: 2_418 + .saturating_add(Weight::from_parts(91_621, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Vesting::Vesting` (r:1 w:1) /// Proof: `Vesting::Vesting` (`max_values`: None, `max_size`: Some(1057), added: 3532, mode: `MaxEncodedLen`) @@ -228,22 +226,20 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 49]`. /// The range of component `s` is `[2, 28]`. fn unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `482 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 36_951_000 picoseconds. - Weight::from_parts(37_020_649, 4764) - // Standard Error: 1_791 - .saturating_add(Weight::from_parts(65_437, 0).saturating_mul(l.into())) - // Standard Error: 3_308 - .saturating_add(Weight::from_parts(54_146, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 42_287_000 picoseconds. + Weight::from_parts(41_937_484, 4764) + // Standard Error: 1_306 + .saturating_add(Weight::from_parts(39_880, 0).saturating_mul(l.into())) + // Standard Error: 2_412 + .saturating_add(Weight::from_parts(85_247, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `Vesting::Vesting` (r:1 w:1) /// Proof: `Vesting::Vesting` (`max_values`: None, `max_size`: Some(1057), added: 3532, mode: `MaxEncodedLen`) @@ -257,14 +253,14 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[2, 28]`. fn force_remove_vesting_schedule(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `555 + l * (25 ±0) + s * (36 ±0)` + // Measured: `588 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 38_849_000 picoseconds. - Weight::from_parts(38_488_577, 4764) - // Standard Error: 1_911 - .saturating_add(Weight::from_parts(72_338, 0).saturating_mul(l.into())) - // Standard Error: 3_529 - .saturating_add(Weight::from_parts(62_206, 0).saturating_mul(s.into())) + // Minimum execution time: 46_462_000 picoseconds. + Weight::from_parts(46_571_504, 4764) + // Standard Error: 1_298 + .saturating_add(Weight::from_parts(42_091, 0).saturating_mul(l.into())) + // Standard Error: 2_397 + .saturating_add(Weight::from_parts(77_382, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -282,14 +278,14 @@ impl WeightInfo for () { /// The range of component `s` is `[1, 28]`. fn vest_locked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `381 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 32_202_000 picoseconds. - Weight::from_parts(31_586_520, 4764) - // Standard Error: 1_513 - .saturating_add(Weight::from_parts(67_257, 0).saturating_mul(l.into())) - // Standard Error: 2_693 - .saturating_add(Weight::from_parts(69_725, 0).saturating_mul(s.into())) + // Minimum execution time: 39_505_000 picoseconds. + Weight::from_parts(39_835_306, 4764) + // Standard Error: 1_394 + .saturating_add(Weight::from_parts(21_450, 0).saturating_mul(l.into())) + // Standard Error: 2_481 + .saturating_add(Weight::from_parts(70_901, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -303,14 +299,14 @@ impl WeightInfo for () { /// The range of component `s` is `[1, 28]`. fn vest_unlocked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `381 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_847_000 picoseconds. - Weight::from_parts(34_690_456, 4764) - // Standard Error: 1_681 - .saturating_add(Weight::from_parts(51_103, 0).saturating_mul(l.into())) - // Standard Error: 2_991 - .saturating_add(Weight::from_parts(55_094, 0).saturating_mul(s.into())) + // Minimum execution time: 40_781_000 picoseconds. + Weight::from_parts(40_777_528, 4764) + // Standard Error: 1_209 + .saturating_add(Weight::from_parts(35_116, 0).saturating_mul(l.into())) + // Standard Error: 2_151 + .saturating_add(Weight::from_parts(83_093, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -326,14 +322,14 @@ impl WeightInfo for () { /// The range of component `s` is `[1, 28]`. fn vest_other_locked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `484 + l * (25 ±0) + s * (36 ±0)` + // Measured: `517 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_027_000 picoseconds. - Weight::from_parts(33_353_168, 4764) - // Standard Error: 1_477 - .saturating_add(Weight::from_parts(72_605, 0).saturating_mul(l.into())) - // Standard Error: 2_629 - .saturating_add(Weight::from_parts(64_115, 0).saturating_mul(s.into())) + // Minimum execution time: 41_590_000 picoseconds. + Weight::from_parts(40_756_231, 4764) + // Standard Error: 1_420 + .saturating_add(Weight::from_parts(45_223, 0).saturating_mul(l.into())) + // Standard Error: 2_527 + .saturating_add(Weight::from_parts(102_603, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -349,14 +345,14 @@ impl WeightInfo for () { /// The range of component `s` is `[1, 28]`. fn vest_other_unlocked(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `484 + l * (25 ±0) + s * (36 ±0)` + // Measured: `517 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 36_816_000 picoseconds. - Weight::from_parts(36_467_447, 4764) - // Standard Error: 1_689 - .saturating_add(Weight::from_parts(51_855, 0).saturating_mul(l.into())) - // Standard Error: 3_006 - .saturating_add(Weight::from_parts(58_233, 0).saturating_mul(s.into())) + // Minimum execution time: 43_490_000 picoseconds. + Weight::from_parts(43_900_384, 4764) + // Standard Error: 1_670 + .saturating_add(Weight::from_parts(31_084, 0).saturating_mul(l.into())) + // Standard Error: 2_971 + .saturating_add(Weight::from_parts(66_673, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -372,14 +368,14 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 27]`. fn vested_transfer(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `555 + l * (25 ±0) + s * (36 ±0)` + // Measured: `588 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 70_906_000 picoseconds. - Weight::from_parts(72_663_428, 4764) - // Standard Error: 2_877 - .saturating_add(Weight::from_parts(81_242, 0).saturating_mul(l.into())) - // Standard Error: 5_118 - .saturating_add(Weight::from_parts(103_344, 0).saturating_mul(s.into())) + // Minimum execution time: 76_194_000 picoseconds. + Weight::from_parts(77_923_603, 4764) + // Standard Error: 2_141 + .saturating_add(Weight::from_parts(50_161, 0).saturating_mul(l.into())) + // Standard Error: 3_810 + .saturating_add(Weight::from_parts(97_415, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -395,14 +391,14 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 27]`. fn force_vested_transfer(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `658 + l * (25 ±0) + s * (36 ±0)` + // Measured: `691 + l * (25 ±0) + s * (36 ±0)` // Estimated: `6196` - // Minimum execution time: 72_730_000 picoseconds. - Weight::from_parts(75_050_411, 6196) - // Standard Error: 2_748 - .saturating_add(Weight::from_parts(73_218, 0).saturating_mul(l.into())) - // Standard Error: 4_889 - .saturating_add(Weight::from_parts(112_868, 0).saturating_mul(s.into())) + // Minimum execution time: 78_333_000 picoseconds. + Weight::from_parts(80_199_350, 6196) + // Standard Error: 1_903 + .saturating_add(Weight::from_parts(46_798, 0).saturating_mul(l.into())) + // Standard Error: 3_385 + .saturating_add(Weight::from_parts(106_311, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -412,22 +408,20 @@ impl WeightInfo for () { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 49]`. /// The range of component `s` is `[2, 28]`. fn not_unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `482 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 34_698_000 picoseconds. - Weight::from_parts(34_504_324, 4764) - // Standard Error: 1_703 - .saturating_add(Weight::from_parts(56_321, 0).saturating_mul(l.into())) - // Standard Error: 3_145 - .saturating_add(Weight::from_parts(55_503, 0).saturating_mul(s.into())) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Minimum execution time: 40_102_000 picoseconds. + Weight::from_parts(39_552_301, 4764) + // Standard Error: 1_309 + .saturating_add(Weight::from_parts(37_184, 0).saturating_mul(l.into())) + // Standard Error: 2_418 + .saturating_add(Weight::from_parts(91_621, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Vesting::Vesting` (r:1 w:1) /// Proof: `Vesting::Vesting` (`max_values`: None, `max_size`: Some(1057), added: 3532, mode: `MaxEncodedLen`) @@ -435,22 +429,20 @@ impl WeightInfo for () { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// The range of component `l` is `[0, 49]`. /// The range of component `s` is `[2, 28]`. fn unlocking_merge_schedules(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `482 + l * (25 ±0) + s * (36 ±0)` + // Measured: `414 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 36_951_000 picoseconds. - Weight::from_parts(37_020_649, 4764) - // Standard Error: 1_791 - .saturating_add(Weight::from_parts(65_437, 0).saturating_mul(l.into())) - // Standard Error: 3_308 - .saturating_add(Weight::from_parts(54_146, 0).saturating_mul(s.into())) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Minimum execution time: 42_287_000 picoseconds. + Weight::from_parts(41_937_484, 4764) + // Standard Error: 1_306 + .saturating_add(Weight::from_parts(39_880, 0).saturating_mul(l.into())) + // Standard Error: 2_412 + .saturating_add(Weight::from_parts(85_247, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `Vesting::Vesting` (r:1 w:1) /// Proof: `Vesting::Vesting` (`max_values`: None, `max_size`: Some(1057), added: 3532, mode: `MaxEncodedLen`) @@ -464,14 +456,14 @@ impl WeightInfo for () { /// The range of component `s` is `[2, 28]`. fn force_remove_vesting_schedule(l: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `555 + l * (25 ±0) + s * (36 ±0)` + // Measured: `588 + l * (25 ±0) + s * (36 ±0)` // Estimated: `4764` - // Minimum execution time: 38_849_000 picoseconds. - Weight::from_parts(38_488_577, 4764) - // Standard Error: 1_911 - .saturating_add(Weight::from_parts(72_338, 0).saturating_mul(l.into())) - // Standard Error: 3_529 - .saturating_add(Weight::from_parts(62_206, 0).saturating_mul(s.into())) + // Minimum execution time: 46_462_000 picoseconds. + Weight::from_parts(46_571_504, 4764) + // Standard Error: 1_298 + .saturating_add(Weight::from_parts(42_091, 0).saturating_mul(l.into())) + // Standard Error: 2_397 + .saturating_add(Weight::from_parts(77_382, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } diff --git a/substrate/frame/whitelist/src/weights.rs b/substrate/frame/whitelist/src/weights.rs index 2e28d4fcf7e5..12a18a8f0107 100644 --- a/substrate/frame/whitelist/src/weights.rs +++ b/substrate/frame/whitelist/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_whitelist` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -68,10 +68,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn whitelist_call() -> Weight { // Proof Size summary in bytes: - // Measured: `317` + // Measured: `245` // Estimated: `3556` - // Minimum execution time: 19_521_000 picoseconds. - Weight::from_parts(20_136_000, 3556) + // Minimum execution time: 18_287_000 picoseconds. + Weight::from_parts(18_733_000, 3556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -83,10 +83,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn remove_whitelisted_call() -> Weight { // Proof Size summary in bytes: - // Measured: `446` + // Measured: `374` // Estimated: `3556` - // Minimum execution time: 18_530_000 picoseconds. - Weight::from_parts(19_004_000, 3556) + // Minimum execution time: 22_887_000 picoseconds. + Weight::from_parts(23_352_000, 3556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -101,12 +101,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 4194294]`. fn dispatch_whitelisted_call(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `522 + n * (1 ±0)` - // Estimated: `3986 + n * (1 ±0)` - // Minimum execution time: 29_721_000 picoseconds. - Weight::from_parts(30_140_000, 3986) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_179, 0).saturating_mul(n.into())) + // Measured: `450 + n * (1 ±0)` + // Estimated: `3914 + n * (1 ±0)` + // Minimum execution time: 33_692_000 picoseconds. + Weight::from_parts(34_105_000, 3914) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_800, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -120,12 +120,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 10000]`. fn dispatch_whitelisted_call_with_preimage(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `446` + // Measured: `374` // Estimated: `3556` - // Minimum execution time: 22_608_000 picoseconds. - Weight::from_parts(23_682_511, 3556) + // Minimum execution time: 26_380_000 picoseconds. + Weight::from_parts(27_186_471, 3556) // Standard Error: 6 - .saturating_add(Weight::from_parts(1_420, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_423, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -141,10 +141,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn whitelist_call() -> Weight { // Proof Size summary in bytes: - // Measured: `317` + // Measured: `245` // Estimated: `3556` - // Minimum execution time: 19_521_000 picoseconds. - Weight::from_parts(20_136_000, 3556) + // Minimum execution time: 18_287_000 picoseconds. + Weight::from_parts(18_733_000, 3556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -156,10 +156,10 @@ impl WeightInfo for () { /// Proof: `Preimage::RequestStatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) fn remove_whitelisted_call() -> Weight { // Proof Size summary in bytes: - // Measured: `446` + // Measured: `374` // Estimated: `3556` - // Minimum execution time: 18_530_000 picoseconds. - Weight::from_parts(19_004_000, 3556) + // Minimum execution time: 22_887_000 picoseconds. + Weight::from_parts(23_352_000, 3556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -174,12 +174,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 4194294]`. fn dispatch_whitelisted_call(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `522 + n * (1 ±0)` - // Estimated: `3986 + n * (1 ±0)` - // Minimum execution time: 29_721_000 picoseconds. - Weight::from_parts(30_140_000, 3986) - // Standard Error: 0 - .saturating_add(Weight::from_parts(1_179, 0).saturating_mul(n.into())) + // Measured: `450 + n * (1 ±0)` + // Estimated: `3914 + n * (1 ±0)` + // Minimum execution time: 33_692_000 picoseconds. + Weight::from_parts(34_105_000, 3914) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_800, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -193,12 +193,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 10000]`. fn dispatch_whitelisted_call_with_preimage(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `446` + // Measured: `374` // Estimated: `3556` - // Minimum execution time: 22_608_000 picoseconds. - Weight::from_parts(23_682_511, 3556) + // Minimum execution time: 26_380_000 picoseconds. + Weight::from_parts(27_186_471, 3556) // Standard Error: 6 - .saturating_add(Weight::from_parts(1_420, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_423, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs index 521f54bf4afd..1842b1631621 100644 --- a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs @@ -30,6 +30,12 @@ use crate::{ transaction_validity::{TransactionSource, TransactionValidity}, }; +use super::unchecked_extrinsic::ExtensionVersion; + +/// Default version of the [Extension](TransactionExtension) used to construct the inherited +/// implication for legacy transactions. +const DEFAULT_EXTENSION_VERSION: ExtensionVersion = 0; + /// The kind of extrinsic this is, including any fields required of that kind. This is basically /// the full extrinsic except the `Call`. #[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)] @@ -42,7 +48,7 @@ pub enum ExtrinsicFormat { Signed(AccountId, Extension), /// Extrinsic has a default `Origin` of `None` and must pass all `TransactionExtension`s. /// regular checks and includes all extension data. - General(Extension), + General(ExtensionVersion, Extension), } /// Definition of something that the external world might want to say; its existence implies that it @@ -85,10 +91,19 @@ where }, ExtrinsicFormat::Signed(ref signer, ref extension) => { let origin = Some(signer.clone()).into(); - extension.validate_only(origin, &self.function, info, len, source).map(|x| x.0) + extension + .validate_only( + origin, + &self.function, + info, + len, + source, + DEFAULT_EXTENSION_VERSION, + ) + .map(|x| x.0) }, - ExtrinsicFormat::General(ref extension) => extension - .validate_only(None.into(), &self.function, info, len, source) + ExtrinsicFormat::General(extension_version, ref extension) => extension + .validate_only(None.into(), &self.function, info, len, source, extension_version) .map(|x| x.0), } } @@ -112,10 +127,15 @@ where Extension::bare_post_dispatch(info, &mut post_info, len, &pd_res)?; Ok(res) }, - ExtrinsicFormat::Signed(signer, extension) => - extension.dispatch_transaction(Some(signer).into(), self.function, info, len), - ExtrinsicFormat::General(extension) => - extension.dispatch_transaction(None.into(), self.function, info, len), + ExtrinsicFormat::Signed(signer, extension) => extension.dispatch_transaction( + Some(signer).into(), + self.function, + info, + len, + DEFAULT_EXTENSION_VERSION, + ), + ExtrinsicFormat::General(extension_version, extension) => extension + .dispatch_transaction(None.into(), self.function, info, len, extension_version), } } } @@ -128,7 +148,7 @@ impl> pub fn extension_weight(&self) -> Weight { match &self.format { ExtrinsicFormat::Bare => Weight::zero(), - ExtrinsicFormat::Signed(_, ext) | ExtrinsicFormat::General(ext) => + ExtrinsicFormat::Signed(_, ext) | ExtrinsicFormat::General(_, ext) => ext.weight(&self.function), } } diff --git a/substrate/primitives/runtime/src/generic/mod.rs b/substrate/primitives/runtime/src/generic/mod.rs index 007dee2684b0..f79058e270ed 100644 --- a/substrate/primitives/runtime/src/generic/mod.rs +++ b/substrate/primitives/runtime/src/generic/mod.rs @@ -33,6 +33,8 @@ pub use self::{ digest::{Digest, DigestItem, DigestItemRef, OpaqueDigestItemId}, era::{Era, Phase}, header::Header, - unchecked_extrinsic::{Preamble, SignedPayload, UncheckedExtrinsic, EXTRINSIC_FORMAT_VERSION}, + unchecked_extrinsic::{ + ExtensionVersion, Preamble, SignedPayload, UncheckedExtrinsic, EXTRINSIC_FORMAT_VERSION, + }, }; pub use unchecked_extrinsic::UncheckedSignaturePayload; diff --git a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs index 8c44e147f90b..91ba37451909 100644 --- a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -83,7 +83,7 @@ pub enum Preamble { Bare(ExtrinsicVersion), /// An old-school transaction extrinsic which includes a signature of some hard-coded crypto. /// Available only on extrinsic version 4. - Signed(Address, Signature, ExtensionVersion, Extension), + Signed(Address, Signature, Extension), /// A new-school transaction extrinsic which does not include a signature by default. The /// origin authorization, through signatures or other means, is performed by the transaction /// extension in this extrinsic. Available starting with extrinsic version 5. @@ -117,7 +117,7 @@ where let address = Address::decode(input)?; let signature = Signature::decode(input)?; let ext = Extension::decode(input)?; - Self::Signed(address, signature, 0, ext) + Self::Signed(address, signature, ext) }, (EXTRINSIC_FORMAT_VERSION, GENERAL_EXTRINSIC) => { let ext_version = ExtensionVersion::decode(input)?; @@ -140,7 +140,7 @@ where fn size_hint(&self) -> usize { match &self { Preamble::Bare(_) => EXTRINSIC_FORMAT_VERSION.size_hint(), - Preamble::Signed(address, signature, _, ext) => LEGACY_EXTRINSIC_FORMAT_VERSION + Preamble::Signed(address, signature, ext) => LEGACY_EXTRINSIC_FORMAT_VERSION .size_hint() .saturating_add(address.size_hint()) .saturating_add(signature.size_hint()) @@ -157,7 +157,7 @@ where Preamble::Bare(extrinsic_version) => { (extrinsic_version | BARE_EXTRINSIC).encode_to(dest); }, - Preamble::Signed(address, signature, _, ext) => { + Preamble::Signed(address, signature, ext) => { (LEGACY_EXTRINSIC_FORMAT_VERSION | SIGNED_EXTRINSIC).encode_to(dest); address.encode_to(dest); signature.encode_to(dest); @@ -176,7 +176,7 @@ impl Preamble { /// Returns `Some` if this is a signed extrinsic, together with the relevant inner fields. pub fn to_signed(self) -> Option<(Address, Signature, Extension)> { match self { - Self::Signed(a, s, _, e) => Some((a, s, e)), + Self::Signed(a, s, e) => Some((a, s, e)), _ => None, } } @@ -190,8 +190,7 @@ where fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Bare(_) => write!(f, "Bare"), - Self::Signed(address, _, ext_version, tx_ext) => - write!(f, "Signed({:?}, {:?}, {:?})", address, ext_version, tx_ext), + Self::Signed(address, _, tx_ext) => write!(f, "Signed({:?}, {:?})", address, tx_ext), Self::General(ext_version, tx_ext) => write!(f, "General({:?}, {:?})", ext_version, tx_ext), } @@ -305,7 +304,7 @@ impl UncheckedExtrinsic Self { - Self { preamble: Preamble::Signed(signed, signature, 0, tx_ext), function } + Self { preamble: Preamble::Signed(signed, signature, tx_ext), function } } /// New instance of an new-school unsigned transaction. @@ -345,7 +344,7 @@ where fn check(self, lookup: &Lookup) -> Result { Ok(match self.preamble { - Preamble::Signed(signed, signature, _, tx_ext) => { + Preamble::Signed(signed, signature, tx_ext) => { let signed = lookup.lookup(signed)?; // The `Implicit` is "implicitly" included in the payload. let raw_payload = SignedPayload::new(self.function, tx_ext)?; @@ -355,8 +354,8 @@ where let (function, tx_ext, _) = raw_payload.deconstruct(); CheckedExtrinsic { format: ExtrinsicFormat::Signed(signed, tx_ext), function } }, - Preamble::General(_, tx_ext) => CheckedExtrinsic { - format: ExtrinsicFormat::General(tx_ext), + Preamble::General(extension_version, tx_ext) => CheckedExtrinsic { + format: ExtrinsicFormat::General(extension_version, tx_ext), function: self.function, }, Preamble::Bare(_) => @@ -370,15 +369,15 @@ where lookup: &Lookup, ) -> Result { Ok(match self.preamble { - Preamble::Signed(signed, _, _, extra) => { + Preamble::Signed(signed, _, tx_ext) => { let signed = lookup.lookup(signed)?; CheckedExtrinsic { - format: ExtrinsicFormat::Signed(signed, extra), + format: ExtrinsicFormat::Signed(signed, tx_ext), function: self.function, } }, - Preamble::General(_, extra) => CheckedExtrinsic { - format: ExtrinsicFormat::General(extra), + Preamble::General(extension_version, tx_ext) => CheckedExtrinsic { + format: ExtrinsicFormat::General(extension_version, tx_ext), function: self.function, }, Preamble::Bare(_) => @@ -403,8 +402,7 @@ impl Weight { match &self.preamble { Preamble::Bare(_) => Weight::zero(), - Preamble::Signed(_, _, _, ext) | Preamble::General(_, ext) => - ext.weight(&self.function), + Preamble::Signed(_, _, ext) | Preamble::General(_, ext) => ext.weight(&self.function), } } } @@ -839,7 +837,7 @@ mod tests { assert_eq!( >::check(ux, &Default::default()), Ok(CEx { - format: ExtrinsicFormat::General(DummyExtension), + format: ExtrinsicFormat::General(0, DummyExtension), function: vec![0u8; 0].into() }), ); @@ -915,7 +913,7 @@ mod tests { assert_eq!(decoded_old_ux.function, call); assert_eq!( decoded_old_ux.preamble, - Preamble::Signed(signed, legacy_signature.clone(), 0, extension.clone()) + Preamble::Signed(signed, legacy_signature.clone(), extension.clone()) ); let new_ux = @@ -952,7 +950,7 @@ mod tests { assert_eq!(decoded_old_ux.function, call); assert_eq!( decoded_old_ux.preamble, - Preamble::Signed(signed, signature.clone(), 0, extension.clone()) + Preamble::Signed(signed, signature.clone(), extension.clone()) ); let new_ux = Ex::new_signed(call.clone(), signed, signature.clone(), extension.clone()); diff --git a/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs b/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs index 19c8a2b2d496..28030d12fc9f 100644 --- a/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs +++ b/substrate/primitives/runtime/src/traits/transaction_extension/dispatch_transaction.rs @@ -18,6 +18,7 @@ //! The [DispatchTransaction] trait. use crate::{ + generic::ExtensionVersion, traits::AsTransactionAuthorizedOrigin, transaction_validity::{InvalidTransaction, TransactionSource}, }; @@ -49,6 +50,7 @@ pub trait DispatchTransaction { info: &Self::Info, len: usize, source: TransactionSource, + extension_version: ExtensionVersion, ) -> Result<(ValidTransaction, Self::Val, Self::Origin), TransactionValidityError>; /// Validate and prepare a transaction, ready for dispatch. fn validate_and_prepare( @@ -57,6 +59,7 @@ pub trait DispatchTransaction { call: &Call, info: &Self::Info, len: usize, + extension_version: ExtensionVersion, ) -> Result<(Self::Pre, Self::Origin), TransactionValidityError>; /// Dispatch a transaction with the given base origin and call. fn dispatch_transaction( @@ -65,6 +68,7 @@ pub trait DispatchTransaction { call: Call, info: &Self::Info, len: usize, + extension_version: ExtensionVersion, ) -> Self::Result; /// Do everything which would be done in a [dispatch_transaction](Self::dispatch_transaction), /// but instead of executing the call, execute `substitute` instead. Since this doesn't actually @@ -75,6 +79,7 @@ pub trait DispatchTransaction { call: &Call, info: &Self::Info, len: usize, + extension_version: ExtensionVersion, substitute: impl FnOnce( Self::Origin, ) -> crate::DispatchResultWithInfo<::PostInfo>, @@ -98,8 +103,17 @@ where info: &DispatchInfoOf, len: usize, source: TransactionSource, + extension_version: ExtensionVersion, ) -> Result<(ValidTransaction, T::Val, Self::Origin), TransactionValidityError> { - match self.validate(origin, call, info, len, self.implicit()?, call, source) { + match self.validate( + origin, + call, + info, + len, + self.implicit()?, + &(extension_version, call), + source, + ) { // After validation, some origin must have been authorized. Ok((_, _, origin)) if !origin.is_transaction_authorized() => Err(InvalidTransaction::UnknownOrigin.into()), @@ -112,9 +126,16 @@ where call: &Call, info: &DispatchInfoOf, len: usize, + extension_version: ExtensionVersion, ) -> Result<(T::Pre, Self::Origin), TransactionValidityError> { - let (_, val, origin) = - self.validate_only(origin, call, info, len, TransactionSource::InBlock)?; + let (_, val, origin) = self.validate_only( + origin, + call, + info, + len, + TransactionSource::InBlock, + extension_version, + )?; let pre = self.prepare(val, &origin, &call, info, len)?; Ok((pre, origin)) } @@ -124,8 +145,10 @@ where call: Call, info: &DispatchInfoOf, len: usize, + extension_version: ExtensionVersion, ) -> Self::Result { - let (pre, origin) = self.validate_and_prepare(origin, &call, info, len)?; + let (pre, origin) = + self.validate_and_prepare(origin, &call, info, len, extension_version)?; let mut res = call.dispatch(origin); let pd_res = res.map(|_| ()).map_err(|e| e.error); let post_info = match &mut res { @@ -142,11 +165,13 @@ where call: &Call, info: &Self::Info, len: usize, + extension_version: ExtensionVersion, substitute: impl FnOnce( Self::Origin, ) -> crate::DispatchResultWithInfo<::PostInfo>, ) -> Self::Result { - let (pre, origin) = self.validate_and_prepare(origin, &call, info, len)?; + let (pre, origin) = + self.validate_and_prepare(origin, &call, info, len, extension_version)?; let mut res = substitute(origin); let pd_res = res.map(|_| ()).map_err(|e| e.error); let post_info = match &mut res { diff --git a/substrate/test-utils/runtime/src/extrinsic.rs b/substrate/test-utils/runtime/src/extrinsic.rs index 8f94dd10a834..4c884d4174ff 100644 --- a/substrate/test-utils/runtime/src/extrinsic.rs +++ b/substrate/test-utils/runtime/src/extrinsic.rs @@ -69,7 +69,7 @@ impl TryFrom<&Extrinsic> for TransferData { match uxt { Extrinsic { function: RuntimeCall::Balances(BalancesCall::transfer_allow_death { dest, value }), - preamble: Preamble::Signed(from, _, _, ((CheckNonce(nonce), ..), ..)), + preamble: Preamble::Signed(from, _, ((CheckNonce(nonce), ..), ..)), } => Ok(TransferData { from: *from, to: *dest, amount: *value, nonce: *nonce }), Extrinsic { function: RuntimeCall::SubstrateTest(PalletCall::bench_call { transfer }), diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index d565f65e8d36..461d583b5cc6 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -1213,6 +1213,7 @@ mod tests { &info, len, External, + 0, ) .unwrap() .0 @@ -1228,6 +1229,7 @@ mod tests { &info, len, External, + 0, ) .unwrap() .0 From 5da406378ee21e0d13d3f32f8c531be04f366bed Mon Sep 17 00:00:00 2001 From: Viraj Bhartiya Date: Fri, 15 Nov 2024 01:47:18 +0530 Subject: [PATCH 094/166] feat: add workflow to test readme generation (#6359) # Description Created a workflow to search for README.docify.md in the repo, and run cargo build --features generate-readme in the dir of the file (assuming it is related to a crate). If the git diff shows some output for the README.md, then the file update wasn't pushed on the branch, and the workflow fails. Closes #6331 ## Integration Downstream projects that want to adopt this README checking workflow should: 1. Copy the `.github/workflows/readme-check.yml` file to their repository 2. Ensure any `README.docify.md` files in their project follow the expected format 3. Implement the `generate-readme` feature flag in their Cargo.toml if not already present ## Review Notes This PR adds a GitHub Actions workflow that automatically verifies README.md files are up-to-date with their corresponding README.docify.md sources. Key implementation details: - The workflow runs on both PRs and pushes to main - It finds all `README.docify.md` files recursively in the repository - For each file found: - Builds the project with `--features generate-readme` in that directory - Checks if the README.md has any uncommitted changes - Fails if any README.md is out of sync --------- Co-authored-by: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Co-authored-by: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> --- .../check-missing-readme-generation.sh | 36 +++++++++++++++++++ .github/workflows/checks-quick.yml | 28 ++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100755 .github/scripts/check-missing-readme-generation.sh diff --git a/.github/scripts/check-missing-readme-generation.sh b/.github/scripts/check-missing-readme-generation.sh new file mode 100755 index 000000000000..13f2b6a7cb28 --- /dev/null +++ b/.github/scripts/check-missing-readme-generation.sh @@ -0,0 +1,36 @@ +#!/bin/bash +echo "Running script relative to `pwd`" +# Find all README.docify.md files +DOCIFY_FILES=$(find . -name "README.docify.md") + +# Initialize a variable to track directories needing README regeneration +NEED_REGENERATION="" + +for file in $DOCIFY_FILES; do + echo "Processing $file" + + # Get the directory containing the docify file + DIR=$(dirname "$file") + + # Go to the directory and run cargo build + cd "$DIR" + cargo check --features generate-readme || { echo "Readme generation for $DIR failed. Ensure the crate compiles successfully and has a `generate-readme` feature which guards markdown compilation in the crate as follows: https://docs.rs/docify/latest/docify/macro.compile_markdown.html#conventions." && exit 1; } + + # Check if README.md has any uncommitted changes + git diff --exit-code README.md + + if [ $? -ne 0 ]; then + echo "Error: Found uncommitted changes in $DIR/README.md" + NEED_REGENERATION="$NEED_REGENERATION $DIR" + fi + + # Return to the original directory + cd - > /dev/null +done + +# Check if any directories need README regeneration +if [ -n "$NEED_REGENERATION" ]; then + echo "The following directories need README regeneration:" + echo "$NEED_REGENERATION" + exit 1 +fi \ No newline at end of file diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index 36deba7dfb78..28f5bf932e2c 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -15,7 +15,6 @@ concurrency: permissions: {} jobs: - preflight: uses: ./.github/workflows/reusable-preflight.yml @@ -172,6 +171,32 @@ jobs: env: ASSERT_REGEX: "FAIL-CI" GIT_DEPTH: 1 + check-readme: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + + - name: Install prerequisites + run: | + sudo apt-get update + sudo apt-get install -y protobuf-compiler + + - name: Set rust version from env file + run: | + RUST_VERSION=$(cat .github/env | sed -E 's/.*ci-unified:([^-]+)-([^-]+).*/\2/') + echo $RUST_VERSION + echo "RUST_VERSION=${RUST_VERSION}" >> $GITHUB_ENV + + - name: Install Rust + uses: actions-rust-lang/setup-rust-toolchain@11df97af8e8102fd60b60a77dfbf58d40cd843b8 # v1.10.1 + with: + cache: false + toolchain: ${{ env.RUST_VERSION }} + components: cargo, clippy, rust-docs, rust-src, rustfmt, rustc, rust-std + + - name: Find README.docify.md files and check generated READMEs + run: .github/scripts/check-missing-readme-generation.sh confirm-required-checks-quick-jobs-passed: runs-on: ubuntu-latest @@ -187,6 +212,7 @@ jobs: - check-markdown - check-umbrella - check-fail-ci + - check-readme if: always() && !cancelled() steps: - run: | From dbeea184b9afbb41e5ef12f88c4b2db7e80cd45f Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Thu, 14 Nov 2024 21:40:58 +0100 Subject: [PATCH 095/166] [pallet-revive] set logs_bloom (#6460) Set the logs_bloom in the transaction receipt --------- Co-authored-by: GitHub Action Co-authored-by: Cyrill Leutwiler --- prdoc/pr_6460.prdoc | 9 ++ .../frame/revive/rpc/examples/js/src/lib.ts | 2 +- substrate/frame/revive/rpc/src/client.rs | 20 ++-- substrate/frame/revive/src/evm/api.rs | 2 + .../frame/revive/src/evm/api/rpc_types.rs | 102 +++++++++++++++++- .../frame/revive/src/evm/api/rpc_types_gen.rs | 7 +- 6 files changed, 126 insertions(+), 16 deletions(-) create mode 100644 prdoc/pr_6460.prdoc diff --git a/prdoc/pr_6460.prdoc b/prdoc/pr_6460.prdoc new file mode 100644 index 000000000000..e1fd1a740228 --- /dev/null +++ b/prdoc/pr_6460.prdoc @@ -0,0 +1,9 @@ +title: '[pallet-revive] set logs_bloom' +doc: +- audience: Runtime Dev + description: Set the logs_bloom in the transaction receipt +crates: +- name: pallet-revive-eth-rpc + bump: minor +- name: pallet-revive + bump: minor diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts index 7f6fc19aea75..40f2d6f05824 100644 --- a/substrate/frame/revive/rpc/examples/js/src/lib.ts +++ b/substrate/frame/revive/rpc/examples/js/src/lib.ts @@ -54,7 +54,7 @@ if (geth) { await new Promise((resolve) => setTimeout(resolve, 500)) } -const provider = new JsonRpcProvider( +export const provider = new JsonRpcProvider( westend ? 'https://westend-asset-hub-eth-rpc.polkadot.io' : 'http://localhost:8545' ) diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index bc4f59b5e26e..b7efae15c4aa 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -315,8 +315,8 @@ impl ClientInner { let event = event_details.as_event::().ok()??; Some(Log { - address: Some(event.contract), - topics: Some(event.topics), + address: event.contract, + topics: event.topics, data: Some(event.data.into()), block_number: Some(block_number), transaction_hash, @@ -329,20 +329,20 @@ impl ClientInner { log::debug!(target: LOG_TARGET, "Adding receipt for tx hash: {transaction_hash:?} - block: {block_number:?}"); - let receipt = ReceiptInfo { + let receipt = ReceiptInfo::new( block_hash, block_number, contract_address, from, logs, - to: tx.transaction_legacy_unsigned.to, - effective_gas_price: gas_price, - gas_used: gas_used.into(), - status: Some(if success { U256::one() } else { U256::zero() }), + tx.transaction_legacy_unsigned.to, + gas_price, + gas_used.into(), + success, transaction_hash, - transaction_index: transaction_index.into(), - ..Default::default() - }; + transaction_index.into(), + tx.transaction_legacy_unsigned.r#type.as_byte() + ); Ok::<_, ClientError>((receipt.transaction_hash, (tx.into(), receipt))) }) diff --git a/substrate/frame/revive/src/evm/api.rs b/substrate/frame/revive/src/evm/api.rs index fe18c8735bed..8185a2c8f6f8 100644 --- a/substrate/frame/revive/src/evm/api.rs +++ b/substrate/frame/revive/src/evm/api.rs @@ -25,7 +25,9 @@ pub use rlp; mod type_id; pub use type_id::*; +#[cfg(feature = "std")] mod rpc_types; + mod rpc_types_gen; pub use rpc_types_gen::*; diff --git a/substrate/frame/revive/src/evm/api/rpc_types.rs b/substrate/frame/revive/src/evm/api/rpc_types.rs index 84390563d05a..dd1a2642724d 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. //! Utility impl for the RPC types. -use super::{ReceiptInfo, TransactionInfo, TransactionSigned}; +use super::*; use sp_core::U256; impl TransactionInfo { @@ -33,8 +33,108 @@ impl TransactionInfo { } impl ReceiptInfo { + /// Initialize a new Receipt + pub fn new( + block_hash: H256, + block_number: U256, + contract_address: Option

, + from: Address, + logs: Vec, + to: Option
, + effective_gas_price: U256, + gas_used: U256, + success: bool, + transaction_hash: H256, + transaction_index: U256, + r#type: Byte, + ) -> Self { + let logs_bloom = Self::logs_bloom(&logs); + ReceiptInfo { + block_hash, + block_number, + contract_address, + from, + logs, + logs_bloom, + to, + effective_gas_price, + gas_used, + status: Some(if success { U256::one() } else { U256::zero() }), + transaction_hash, + transaction_index, + r#type: Some(r#type), + ..Default::default() + } + } + /// Returns `true` if the transaction was successful. pub fn is_success(&self) -> bool { self.status.map_or(false, |status| status == U256::one()) } + + /// Calculate receipt logs bloom. + fn logs_bloom(logs: &[Log]) -> Bytes256 { + let mut bloom = [0u8; 256]; + for log in logs { + m3_2048(&mut bloom, &log.address.as_ref()); + for topic in &log.topics { + m3_2048(&mut bloom, topic.as_ref()); + } + } + bloom.into() + } +} +/// Specialised Bloom filter that sets three bits out of 2048, given an +/// arbitrary byte sequence. +/// +/// See Section 4.4.1 "Transaction Receipt" of the [Ethereum Yellow Paper][ref]. +/// +/// [ref]: https://ethereum.github.io/yellowpaper/paper.pdf +fn m3_2048(bloom: &mut [u8; 256], bytes: &[u8]) { + let hash = sp_core::keccak_256(bytes); + for i in [0, 2, 4] { + let bit = (hash[i + 1] as usize + ((hash[i] as usize) << 8)) & 0x7FF; + bloom[256 - 1 - bit / 8] |= 1 << (bit % 8); + } +} + +#[test] +fn logs_bloom_works() { + let receipt: ReceiptInfo = serde_json::from_str( + r#" + { + "blockHash": "0x835ee379aaabf4802a22a93ad8164c02bbdde2cc03d4552d5c642faf4e09d1f3", + "blockNumber": "0x2", + "contractAddress": null, + "cumulativeGasUsed": "0x5d92", + "effectiveGasPrice": "0x2dcd5c2d", + "from": "0xb4f1f9ecfe5a28633a27f57300bda217e99b8969", + "gasUsed": "0x5d92", + "logs": [ + { + "address": "0x82bdb002b9b1f36c42df15fbdc6886abcb2ab31d", + "topics": [ + "0x1585375487296ff2f0370daeec4214074a032b31af827c12622fa9a58c16c7d0", + "0x000000000000000000000000b4f1f9ecfe5a28633a27f57300bda217e99b8969" + ], + "data": "0x00000000000000000000000000000000000000000000000000000000000030390000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b48656c6c6f20776f726c64000000000000000000000000000000000000000000", + "blockNumber": "0x2", + "transactionHash": "0xad0075127962bdf73d787f2944bdb5f351876f23c35e6a48c1f5b6463a100af4", + "transactionIndex": "0x0", + "blockHash": "0x835ee379aaabf4802a22a93ad8164c02bbdde2cc03d4552d5c642faf4e09d1f3", + "logIndex": "0x0", + "removed": false + } + ], + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000008000000000000000000000000000000000000000000000000800000000040000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000004000000000000000800000000000000000080000000000000000000000000000000000000000000", + "status": "0x1", + "to": "0x82bdb002b9b1f36c42df15fbdc6886abcb2ab31d", + "transactionHash": "0xad0075127962bdf73d787f2944bdb5f351876f23c35e6a48c1f5b6463a100af4", + "transactionIndex": "0x0", + "type": "0x2" + } + "#, + ) + .unwrap(); + assert_eq!(receipt.logs_bloom, ReceiptInfo::logs_bloom(&receipt.logs)); } diff --git a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs index 1f391ae846a5..48045a6acc86 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs @@ -375,8 +375,7 @@ impl Default for H256OrTransactionInfo { )] pub struct Log { /// address - #[serde(skip_serializing_if = "Option::is_none")] - pub address: Option
, + pub address: Address, /// block hash #[serde(rename = "blockHash", skip_serializing_if = "Option::is_none")] pub block_hash: Option, @@ -393,8 +392,8 @@ pub struct Log { #[serde(skip_serializing_if = "Option::is_none")] pub removed: Option, /// topics - #[serde(skip_serializing_if = "Option::is_none")] - pub topics: Option>, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub topics: Vec, /// transaction hash #[serde(rename = "transactionHash")] pub transaction_hash: H256, From 5bc571b0f2de67bd650a8c852c0afdd438377f3f Mon Sep 17 00:00:00 2001 From: NingLin-P Date: Fri, 15 Nov 2024 05:30:42 +0800 Subject: [PATCH 096/166] Support more types in TypeWithDefault (#6411) # Description When using `TypeWithDefault` as the default nonce provider to overcome the [replay attack](https://wiki.polkadot.network/docs/transaction-attacks#replay-attack) issue, it fails to compile due to `TypeWithDefault: TryFrom` is not satisfied (which is required by trait `BaseArithmetic`). This is because the blanket implementation `TryFrom for T where U: Into` only impl `TryFrom` and `TryFrom` for `u32` since `u32` only impl `Into` for `u16` and `u8` but not `u64`. This PR fixes the issue by adding `TryFrom` and `From` impl (using macro) for `TypeWithDefault` and removing the blanket impl (otherwise the compiler will complain about conflicting impl), such that `TypeWithDefault: AtLeast8/16/32Bit` is satisfied. ## Integration This PR adds support to more types to be used with `TypeWithDefault`, existing code that used `u64` with `TypeWithDefault` should not be affected, an unit test is added to ensure that. ## Review Notes This PR simply makes `TypeWithDefault: AtLeast8/16/32Bit` satisfied --------- Signed-off-by: linning --- prdoc/pr_6411.prdoc | 10 ++ .../runtime/src/type_with_default.rs | 123 +++++++++++++----- 2 files changed, 103 insertions(+), 30 deletions(-) create mode 100644 prdoc/pr_6411.prdoc diff --git a/prdoc/pr_6411.prdoc b/prdoc/pr_6411.prdoc new file mode 100644 index 000000000000..3d8c2219e90e --- /dev/null +++ b/prdoc/pr_6411.prdoc @@ -0,0 +1,10 @@ +title: "Support more types in TypeWithDefault" + +doc: + - audience: Runtime Dev + description: | + This PR supports more integer types to be used with `TypeWithDefault` and makes `TypeWithDefault: BaseArithmetic` satisfied + +crates: + - name: sp-runtime + bump: patch diff --git a/substrate/primitives/runtime/src/type_with_default.rs b/substrate/primitives/runtime/src/type_with_default.rs index 1465393640dc..5790e3ab6bf6 100644 --- a/substrate/primitives/runtime/src/type_with_default.rs +++ b/substrate/primitives/runtime/src/type_with_default.rs @@ -91,24 +91,6 @@ impl> Default for TypeWithDefault { } } -impl, D: Get> From for TypeWithDefault { - fn from(value: u16) -> Self { - Self::new(value.into()) - } -} - -impl, D: Get> From for TypeWithDefault { - fn from(value: u32) -> Self { - Self::new(value.into()) - } -} - -impl, D: Get> From for TypeWithDefault { - fn from(value: u64) -> Self { - Self::new(value.into()) - } -} - impl> CheckedNeg for TypeWithDefault { fn checked_neg(&self) -> Option { self.0.checked_neg().map(Self::new) @@ -205,24 +187,45 @@ impl> AddAssign for TypeWithDefault { } } -impl, D: Get> From for TypeWithDefault { - fn from(value: u8) -> Self { - Self::new(value.into()) - } -} - impl> Display for TypeWithDefault { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "{}", self.0) } } -impl, D: Get> TryFrom for TypeWithDefault { - type Error = >::Error; - fn try_from(n: u128) -> Result, Self::Error> { - T::try_from(n).map(Self::new) - } -} +macro_rules! impl_from { + ($for_type:ty $(, $from_type:ty)*) => { + $( + impl> From<$from_type> for TypeWithDefault<$for_type, D> { + fn from(value: $from_type) -> Self { + Self::new(value.into()) + } + } + )* + } +} +impl_from!(u128, u128, u64, u32, u16, u8); +impl_from!(u64, u64, u32, u16, u8); +impl_from!(u32, u32, u16, u8); +impl_from!(u16, u16, u8); +impl_from!(u8, u8); + +macro_rules! impl_try_from { + ($for_type:ty $(, $try_from_type:ty)*) => { + $( + impl> TryFrom<$try_from_type> for TypeWithDefault<$for_type, D> { + type Error = <$for_type as TryFrom<$try_from_type>>::Error; + fn try_from(n: $try_from_type) -> Result, Self::Error> { + <$for_type as TryFrom<$try_from_type>>::try_from(n).map(Self::new) + } + } + )* + } +} +impl_try_from!(u8, u16, u32, u64, u128); +impl_try_from!(u16, u32, u64, u128); +impl_try_from!(u32, u64, u128); +impl_try_from!(u64, u128); impl, D: Get> TryFrom for TypeWithDefault { type Error = >::Error; @@ -504,3 +507,63 @@ impl> CompactAs for TypeWithDefault { Ok(Self::new(val)) } } + +#[cfg(test)] +mod tests { + use super::TypeWithDefault; + use sp_arithmetic::traits::{AtLeast16Bit, AtLeast32Bit, AtLeast8Bit}; + use sp_core::Get; + + #[test] + #[allow(dead_code)] + fn test_type_with_default_impl_base_arithmetic() { + trait WrapAtLeast8Bit: AtLeast8Bit {} + trait WrapAtLeast16Bit: AtLeast16Bit {} + trait WrapAtLeast32Bit: AtLeast32Bit {} + + struct Getu8; + impl Get for Getu8 { + fn get() -> u8 { + 0 + } + } + type U8WithDefault = TypeWithDefault; + impl WrapAtLeast8Bit for U8WithDefault {} + + struct Getu16; + impl Get for Getu16 { + fn get() -> u16 { + 0 + } + } + type U16WithDefault = TypeWithDefault; + impl WrapAtLeast16Bit for U16WithDefault {} + + struct Getu32; + impl Get for Getu32 { + fn get() -> u32 { + 0 + } + } + type U32WithDefault = TypeWithDefault; + impl WrapAtLeast32Bit for U32WithDefault {} + + struct Getu64; + impl Get for Getu64 { + fn get() -> u64 { + 0 + } + } + type U64WithDefault = TypeWithDefault; + impl WrapAtLeast32Bit for U64WithDefault {} + + struct Getu128; + impl Get for Getu128 { + fn get() -> u128 { + 0 + } + } + type U128WithDefault = TypeWithDefault; + impl WrapAtLeast32Bit for U128WithDefault {} + } +} From 39eba149960013afabe0d38a570e55897cebc984 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Fri, 15 Nov 2024 09:31:25 +0100 Subject: [PATCH 097/166] [pallet-revive] use evm decimals in call host fn (#6466) This PR update the pallet to use the EVM 18 decimal balance in contracts call and host functions instead of the native balance. It also updates the js example to add the piggy-bank solidity contract that expose the problem --------- Co-authored-by: GitHub Action --- .../assets/asset-hub-westend/src/lib.rs | 17 +- prdoc/pr_6466.prdoc | 12 + substrate/bin/node/runtime/src/lib.rs | 11 +- .../revive/rpc/examples/js/abi/event.json | 34 + .../revive/rpc/examples/js/abi/piggyBank.json | 65 ++ .../revive/rpc/examples/js/abi/revert.json | 14 + .../frame/revive/rpc/examples/js/bun.lockb | Bin 23039 -> 45391 bytes .../rpc/examples/js/contracts/PiggyBank.sol | 32 + .../revive/rpc/examples/js/evm-contracts.json | 56 -- .../frame/revive/rpc/examples/js/index.html | 53 +- .../revive/rpc/examples/js/package-lock.json | 882 +++++++++--------- .../frame/revive/rpc/examples/js/package.json | 9 +- .../revive/rpc/examples/js/pvm-contracts.json | 56 -- .../revive/rpc/examples/js/pvm/event.polkavm | Bin 0 -> 5186 bytes .../rpc/examples/js/pvm/piggyBank.polkavm | Bin 0 -> 12334 bytes .../revive/rpc/examples/js/pvm/revert.polkavm | Bin 0 -> 2490 bytes .../rpc/examples/js/src/build-contracts.ts | 14 +- .../frame/revive/rpc/examples/js/src/event.ts | 4 +- .../frame/revive/rpc/examples/js/src/lib.ts | 24 +- .../revive/rpc/examples/js/src/piggy-bank.ts | 24 + .../revive/rpc/examples/js/src/revert.ts | 4 +- .../revive/rpc/examples/js/src/transfer.ts | 17 + .../revive/rpc/examples/js/tsconfig.json | 38 +- .../js/types/ethers-contracts/Event.ts | 117 +++ .../js/types/ethers-contracts/PiggyBank.ts | 96 ++ .../js/types/ethers-contracts/Revert.ts | 78 ++ .../js/types/ethers-contracts/common.ts | 100 ++ .../factories/Event__factory.ts | 51 + .../factories/PiggyBank__factory.ts | 82 ++ .../factories/Revert__factory.ts | 31 + .../types/ethers-contracts/factories/index.ts | 6 + .../js/types/ethers-contracts/index.ts | 10 + .../frame/revive/rpc/examples/package.json | 1 - .../frame/revive/rpc/revive_chain.metadata | Bin 656635 -> 658056 bytes substrate/frame/revive/rpc/src/client.rs | 36 +- substrate/frame/revive/rpc/src/example.rs | 25 + .../frame/revive/rpc/src/subxt_client.rs | 5 + substrate/frame/revive/rpc/src/tests.rs | 55 +- .../frame/revive/src/benchmarking/mod.rs | 9 +- substrate/frame/revive/src/evm/runtime.rs | 7 +- substrate/frame/revive/src/exec.rs | 163 ++-- substrate/frame/revive/src/lib.rs | 69 +- 42 files changed, 1537 insertions(+), 770 deletions(-) create mode 100644 prdoc/pr_6466.prdoc create mode 100644 substrate/frame/revive/rpc/examples/js/abi/event.json create mode 100644 substrate/frame/revive/rpc/examples/js/abi/piggyBank.json create mode 100644 substrate/frame/revive/rpc/examples/js/abi/revert.json create mode 100644 substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol delete mode 100644 substrate/frame/revive/rpc/examples/js/evm-contracts.json delete mode 100644 substrate/frame/revive/rpc/examples/js/pvm-contracts.json create mode 100644 substrate/frame/revive/rpc/examples/js/pvm/event.polkavm create mode 100644 substrate/frame/revive/rpc/examples/js/pvm/piggyBank.polkavm create mode 100644 substrate/frame/revive/rpc/examples/js/pvm/revert.polkavm create mode 100644 substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/transfer.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts create mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts delete mode 100644 substrate/frame/revive/rpc/examples/package.json 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 e66c4f27fbe8..2206aea78ec2 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -45,10 +45,7 @@ use frame_support::{ ord_parameter_types, parameter_types, traits::{ fungible, fungibles, - tokens::{ - imbalance::ResolveAssetTo, nonfungibles_v2::Inspect, Fortitude::Polite, - Preservation::Expendable, - }, + tokens::{imbalance::ResolveAssetTo, nonfungibles_v2::Inspect}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, InstanceFilter, Nothing, TransformOrigin, }, @@ -68,7 +65,7 @@ use parachains_common::{ NORMAL_DISPATCH_RATIO, }; use sp_api::impl_runtime_apis; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160}; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, U256}; use sp_runtime::{ generic, impl_opaque_keys, traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, Saturating, Verify}, @@ -127,7 +124,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: alloc::borrow::Cow::Borrowed("westmint"), impl_name: alloc::borrow::Cow::Borrowed("westmint"), authoring_version: 1, - spec_version: 1_016_005, + spec_version: 1_016_006, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, @@ -2080,10 +2077,8 @@ impl_runtime_apis! { impl pallet_revive::ReviveApi for Runtime { - fn balance(address: H160) -> Balance { - use frame_support::traits::fungible::Inspect; - let account = ::AddressMapper::to_account_id(&address); - Balances::reducible_balance(&account, Expendable, Polite) + fn balance(address: H160) -> U256 { + Revive::evm_balance(&address) } fn nonce(address: H160) -> Nonce { @@ -2093,7 +2088,7 @@ impl_runtime_apis! { fn eth_transact( from: H160, dest: Option, - value: Balance, + value: U256, input: Vec, gas_limit: Option, storage_deposit_limit: Option, diff --git a/prdoc/pr_6466.prdoc b/prdoc/pr_6466.prdoc new file mode 100644 index 000000000000..0faa6afc8005 --- /dev/null +++ b/prdoc/pr_6466.prdoc @@ -0,0 +1,12 @@ +title: '[pallet-revive] add piggy-bank sol example' +doc: +- audience: Runtime Dev + description: |- + This PR update the pallet to use the EVM 18 decimal balance in contracts call and host functions instead of the native balance. + + It also updates the js example to add the piggy-bank solidity contract that expose the problem +crates: +- name: pallet-revive-eth-rpc + bump: minor +- name: pallet-revive + bump: minor diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 5a2ff3ceb7f6..914b51fb5621 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -54,7 +54,7 @@ use frame_support::{ }, tokens::{ imbalance::ResolveAssetTo, nonfungibles_v2::Inspect, pay::PayAssetFromAccount, - Fortitude::Polite, GetSalary, PayFromAccount, Preservation::Preserve, + GetSalary, PayFromAccount, }, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, Contains, Currency, EitherOfDiverse, EnsureOriginWithArg, EqualPrivilegeOnly, Imbalance, InsideBoth, @@ -86,6 +86,7 @@ use pallet_nis::WithMaximumOf; use pallet_nomination_pools::PoolId; use pallet_revive::{evm::runtime::EthExtra, AddressMapper}; use pallet_session::historical as pallet_session_historical; +use sp_core::U256; // Can't use `FungibleAdapter` here until Treasury pallet migrates to fungibles // use pallet_broker::TaskId; @@ -3205,10 +3206,8 @@ impl_runtime_apis! { impl pallet_revive::ReviveApi for Runtime { - fn balance(address: H160) -> Balance { - use frame_support::traits::fungible::Inspect; - let account = ::AddressMapper::to_account_id(&address); - Balances::reducible_balance(&account, Preserve, Polite) + fn balance(address: H160) -> U256 { + Revive::evm_balance(&address) } fn nonce(address: H160) -> Nonce { @@ -3219,7 +3218,7 @@ impl_runtime_apis! { fn eth_transact( from: H160, dest: Option, - value: Balance, + value: U256, input: Vec, gas_limit: Option, storage_deposit_limit: Option, diff --git a/substrate/frame/revive/rpc/examples/js/abi/event.json b/substrate/frame/revive/rpc/examples/js/abi/event.json new file mode 100644 index 000000000000..d36089fbc84e --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/abi/event.json @@ -0,0 +1,34 @@ +[ + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "string", + "name": "message", + "type": "string" + } + ], + "name": "ExampleEvent", + "type": "event" + }, + { + "inputs": [], + "name": "triggerEvent", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +] diff --git a/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json new file mode 100644 index 000000000000..2c2cfd5f7533 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json @@ -0,0 +1,65 @@ +[ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "payable", + "type": "function" + }, + { + "inputs": [], + "name": "getDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "withdrawAmount", + "type": "uint256" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "remainingBal", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + } +] diff --git a/substrate/frame/revive/rpc/examples/js/abi/revert.json b/substrate/frame/revive/rpc/examples/js/abi/revert.json new file mode 100644 index 000000000000..be2945fcc0a5 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/abi/revert.json @@ -0,0 +1,14 @@ +[ + { + "inputs": [], + "stateMutability": "nonpayable", + "type": "constructor" + }, + { + "inputs": [], + "name": "doRevert", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } +] diff --git a/substrate/frame/revive/rpc/examples/js/bun.lockb b/substrate/frame/revive/rpc/examples/js/bun.lockb index 8bf47d7eb8b82734467165627413c33adede6fd6..700dca51da2ad3f843e890258b59c16fd4df6457 100755 GIT binary patch literal 45391 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 delta 4427 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 - - - - - MetaMask Playground - - - - - + button { + display: block; + margin-bottom: 10px; + } + + + + + - + - - + + - - - + + + diff --git a/substrate/frame/revive/rpc/examples/js/package-lock.json b/substrate/frame/revive/rpc/examples/js/package-lock.json index f1453eae64cc..5c7db0abc936 100644 --- a/substrate/frame/revive/rpc/examples/js/package-lock.json +++ b/substrate/frame/revive/rpc/examples/js/package-lock.json @@ -1,443 +1,443 @@ { - "name": "demo", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "demo", - "version": "0.0.0", - "dependencies": { - "ethers": "^6.13.1", - "solc": "^0.8.28" - }, - "devDependencies": { - "typescript": "^5.5.3", - "vite": "^5.4.8" - } - }, - "node_modules/@adraffy/ens-normalize": { - "version": "1.10.1", - "license": "MIT" - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.21.5", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=12" - } - }, - "node_modules/@noble/curves": { - "version": "1.2.0", - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.3.2" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@noble/hashes": { - "version": "1.3.2", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.24.0", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.24.0", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@types/estree": { - "version": "1.0.6", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "18.15.13", - "license": "MIT" - }, - "node_modules/aes-js": { - "version": "4.0.0-beta.5", - "license": "MIT" - }, - "node_modules/command-exists": { - "version": "1.2.9", - "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz", - "integrity": "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w==", - "license": "MIT" - }, - "node_modules/commander": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", - "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", - "license": "MIT", - "engines": { - "node": ">= 12" - } - }, - "node_modules/esbuild": { - "version": "0.21.5", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=12" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - } - }, - "node_modules/ethers": { - "version": "6.13.3", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/ethers-io/" - }, - { - "type": "individual", - "url": "https://www.buymeacoffee.com/ricmoo" - } - ], - "license": "MIT", - "dependencies": { - "@adraffy/ens-normalize": "1.10.1", - "@noble/curves": "1.2.0", - "@noble/hashes": "1.3.2", - "@types/node": "18.15.13", - "aes-js": "4.0.0-beta.5", - "tslib": "2.4.0", - "ws": "8.17.1" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/follow-redirects": { - "version": "1.15.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", - "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/js-sha3": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", - "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==", - "license": "MIT" - }, - "node_modules/memorystream": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", - "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", - "engines": { - "node": ">= 0.10.0" - } - }, - "node_modules/nanoid": { - "version": "3.3.7", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, - "node_modules/os-tmpdir": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", - "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/picocolors": { - "version": "1.1.0", - "dev": true, - "license": "ISC" - }, - "node_modules/postcss": { - "version": "8.4.47", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/postcss/" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/postcss" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "nanoid": "^3.3.7", - "picocolors": "^1.1.0", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12 || >=14" - } - }, - "node_modules/rollup": { - "version": "4.24.0", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "1.0.6" - }, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" - }, - "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.24.0", - "@rollup/rollup-android-arm64": "4.24.0", - "@rollup/rollup-darwin-arm64": "4.24.0", - "@rollup/rollup-darwin-x64": "4.24.0", - "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", - "@rollup/rollup-linux-arm-musleabihf": "4.24.0", - "@rollup/rollup-linux-arm64-gnu": "4.24.0", - "@rollup/rollup-linux-arm64-musl": "4.24.0", - "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", - "@rollup/rollup-linux-riscv64-gnu": "4.24.0", - "@rollup/rollup-linux-s390x-gnu": "4.24.0", - "@rollup/rollup-linux-x64-gnu": "4.24.0", - "@rollup/rollup-linux-x64-musl": "4.24.0", - "@rollup/rollup-win32-arm64-msvc": "4.24.0", - "@rollup/rollup-win32-ia32-msvc": "4.24.0", - "@rollup/rollup-win32-x64-msvc": "4.24.0", - "fsevents": "~2.3.2" - } - }, - "node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/solc": { - "version": "0.8.28", - "resolved": "https://registry.npmjs.org/solc/-/solc-0.8.28.tgz", - "integrity": "sha512-AFCiJ+b4RosyyNhnfdVH4ZR1+TxiL91iluPjw0EJslIu4LXGM9NYqi2z5y8TqochC4tcH9QsHfwWhOIC9jPDKA==", - "license": "MIT", - "dependencies": { - "command-exists": "^1.2.8", - "commander": "^8.1.0", - "follow-redirects": "^1.12.1", - "js-sha3": "0.8.0", - "memorystream": "^0.3.1", - "semver": "^5.5.0", - "tmp": "0.0.33" - }, - "bin": { - "solcjs": "solc.js" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tmp": { - "version": "0.0.33", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", - "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", - "license": "MIT", - "dependencies": { - "os-tmpdir": "~1.0.2" - }, - "engines": { - "node": ">=0.6.0" - } - }, - "node_modules/tslib": { - "version": "2.4.0", - "license": "0BSD" - }, - "node_modules/typescript": { - "version": "5.6.3", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/vite": { - "version": "5.4.8", - "dev": true, - "license": "MIT", - "dependencies": { - "esbuild": "^0.21.3", - "postcss": "^8.4.43", - "rollup": "^4.20.0" - }, - "bin": { - "vite": "bin/vite.js" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://github.com/vitejs/vite?sponsor=1" - }, - "optionalDependencies": { - "fsevents": "~2.3.3" - }, - "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "sass-embedded": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "less": { - "optional": true - }, - "lightningcss": { - "optional": true - }, - "sass": { - "optional": true - }, - "sass-embedded": { - "optional": true - }, - "stylus": { - "optional": true - }, - "sugarss": { - "optional": true - }, - "terser": { - "optional": true - } - } - }, - "node_modules/ws": { - "version": "8.17.1", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - } - } + "name": "demo", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "demo", + "version": "0.0.0", + "dependencies": { + "ethers": "^6.13.1", + "solc": "^0.8.28" + }, + "devDependencies": { + "typescript": "^5.5.3", + "vite": "^5.4.8" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.10.1", + "license": "MIT" + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.2", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.24.0", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.24.0", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.6", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "18.15.13", + "license": "MIT" + }, + "node_modules/aes-js": { + "version": "4.0.0-beta.5", + "license": "MIT" + }, + "node_modules/command-exists": { + "version": "1.2.9", + "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz", + "integrity": "sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w==", + "license": "MIT" + }, + "node_modules/commander": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz", + "integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/esbuild": { + "version": "0.21.5", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/ethers": { + "version": "6.13.3", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "1.10.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "18.15.13", + "aes-js": "4.0.0-beta.5", + "tslib": "2.4.0", + "ws": "8.17.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.9", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", + "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/js-sha3": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.8.0.tgz", + "integrity": "sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==", + "license": "MIT" + }, + "node_modules/memorystream": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/memorystream/-/memorystream-0.3.1.tgz", + "integrity": "sha512-S3UwM3yj5mtUSEfP41UZmt/0SCoVYUcU1rkXv+BQ5Ig8ndL4sPoJNBUJERafdPb5jjHJGuMgytgKvKIf58XNBw==", + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.7", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/os-tmpdir": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "integrity": "sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.0", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.4.47", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.0", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.24.0", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.6" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.24.0", + "@rollup/rollup-android-arm64": "4.24.0", + "@rollup/rollup-darwin-arm64": "4.24.0", + "@rollup/rollup-darwin-x64": "4.24.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.24.0", + "@rollup/rollup-linux-arm-musleabihf": "4.24.0", + "@rollup/rollup-linux-arm64-gnu": "4.24.0", + "@rollup/rollup-linux-arm64-musl": "4.24.0", + "@rollup/rollup-linux-powerpc64le-gnu": "4.24.0", + "@rollup/rollup-linux-riscv64-gnu": "4.24.0", + "@rollup/rollup-linux-s390x-gnu": "4.24.0", + "@rollup/rollup-linux-x64-gnu": "4.24.0", + "@rollup/rollup-linux-x64-musl": "4.24.0", + "@rollup/rollup-win32-arm64-msvc": "4.24.0", + "@rollup/rollup-win32-ia32-msvc": "4.24.0", + "@rollup/rollup-win32-x64-msvc": "4.24.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/semver": { + "version": "5.7.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", + "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", + "license": "ISC", + "bin": { + "semver": "bin/semver" + } + }, + "node_modules/solc": { + "version": "0.8.28", + "resolved": "https://registry.npmjs.org/solc/-/solc-0.8.28.tgz", + "integrity": "sha512-AFCiJ+b4RosyyNhnfdVH4ZR1+TxiL91iluPjw0EJslIu4LXGM9NYqi2z5y8TqochC4tcH9QsHfwWhOIC9jPDKA==", + "license": "MIT", + "dependencies": { + "command-exists": "^1.2.8", + "commander": "^8.1.0", + "follow-redirects": "^1.12.1", + "js-sha3": "0.8.0", + "memorystream": "^0.3.1", + "semver": "^5.5.0", + "tmp": "0.0.33" + }, + "bin": { + "solcjs": "solc.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tmp": { + "version": "0.0.33", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.0.33.tgz", + "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", + "license": "MIT", + "dependencies": { + "os-tmpdir": "~1.0.2" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/tslib": { + "version": "2.4.0", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "5.6.3", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "5.4.8", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/ws": { + "version": "8.17.1", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } } diff --git a/substrate/frame/revive/rpc/examples/js/package.json b/substrate/frame/revive/rpc/examples/js/package.json index ec05cb74f7d1..3ae1f0fbd799 100644 --- a/substrate/frame/revive/rpc/examples/js/package.json +++ b/substrate/frame/revive/rpc/examples/js/package.json @@ -6,11 +6,14 @@ "scripts": { "dev": "vite", "build": "tsc && vite build", - "preview": "vite preview" + "preview": "vite preview", + "generate-types": "typechain --target=ethers-v6 'abi/*.json'" }, "dependencies": { - "ethers": "^6.13.1", - "solc": "^0.8.28" + "@typechain/ethers-v6": "^0.5.1", + "ethers": "^6.13.4", + "solc": "^0.8.28", + "typechain": "^8.3.2" }, "devDependencies": { "typescript": "^5.5.3", diff --git a/substrate/frame/revive/rpc/examples/js/pvm-contracts.json b/substrate/frame/revive/rpc/examples/js/pvm-contracts.json deleted file mode 100644 index be58e88a9a63..000000000000 --- a/substrate/frame/revive/rpc/examples/js/pvm-contracts.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "event": { - "abi": [ - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "string", - "name": "message", - "type": "string" - } - ], - "name": "ExampleEvent", - "type": "event" - }, - { - "inputs": [], - "name": "triggerEvent", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "bytecode": "50564d00014214000000000000010700c13004c00040045f0600000000060000001300000018000000230000003500000063616c6c65726465706f7369745f6576656e74696e7075747365616c5f72657475726e7365745f696d6d757461626c655f6461746176616c75655f7472616e73666572726564051102912c0463616c6c9133066465706c6f790693b42602913cc8000c0111013001cb010a0327034303570374030c05270530054b055605d505e905f7050b062f06a7075d09e109460a9c0b400c730cdf0c710e800ef70ed20f2610bb10e710131133113b1152790e7a1004070f0a41040a0000012f8a3908890802871f1277e03b370000010a040713000a08000002297814160700000252780407100002088707130004071000020887071300130018875e08970a14a80b099c0128cc29bc1d29873107094a5279110b8b028801029c01109b52c91eacf405350709335279110b8b028801029c01109b52c91eacf4051e07091c027aff0288ff1108980b0bbb029cff089a09109b52c90f0cf113000211e003101c0315180316140215201211e0127601040704080610023dff16070800020d010004040710000352184e0211011726032c040326032804032603240403260320040326031c0403260318040326031404031607100403070607061004090610064b020211c003103c0315380316340215401211e05216040740040820061008d5fe070716020408080002260364000200000080260360000226035c000226035800022603540002260350000226034c000203681826034800020217e01277e003671c52710d171c0d17180d17140d17100d170c0d17080d17040d074e051101681c0182100183018914018a1c018b0c018c040187180188080cba0a0cc9090ca9090c87070c23080c87070c97070f077e0104074004082006100a3afe07077b01016718017450017040017b58017c48017a5401724c0173440e2808128800ff000e29180c9808122900ff000999080922180c92090c980803681c0e3808128800ff000e39180c9808123900ff000999080933180c93090c89030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c89020ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c98080e0908129900ff000e0b180cb909120b00ff0009bb080900180cb00b0cb9090e4b0812bb00ff000e4a180cba0a124b00ff0009bb080944180cb40b0cba0a0ca9090cc8080c98080c3209016a1c0ca9090c98080f086e01681801885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970703671c040806100cfbfc07073c0a080c000207080b04073004034e041101671c040806100edefc07071f01681801671c087808040704094e031104070408061010c2fc0f070400040808000204070104090400124e03110211a003105c0315580316540215601211e004074004082006101491fc0f07040004061004030a0710040303171c0a041404030a031804030a092c04030a082804030a002004030a0c2404032797278a54970a27cb270754cb070c980b54ba070316180a0b1c04032742011a1c1baa041faa0154420a27b2273654b2060cb30b54b60a0cc9090c80080c980854870a0409080002260364000200000080260360000226035c000226035800022603540002260350000226034c00022603480002070a0b010a071000030f47ede48fb7020103191c0d113c0d11380d11340d11300d112c0d11280d11240d11200217204e0511011230011820011934011a3c011b2c011c240116380117280cba0a0cc9090ca9090c67070c28080c87070c97070f07b10001171801721c017318017414017a100178017c0c017604017708028bfc248b0808860b02bbff1c6b09246b0b53980b0278ff08b8092479002489081b7601146c060868081cc80624c8085360081c97070c6707537b0802a7ff0878082478071ba8011484080878092489085377080c4a071b77011473090898082498082473071472070887072d074604070408061016f9fa07076bfe040808000204070104094e0304001805ca00061018c7000407040806101ad5fa070747fe040808000204070104094e0304001c05c80006101cc50004074004082006101eaffa070721fe011b1c01b24c01b34401ba5401b94801bc4001b65001b8580c6c0c0c98080cc8080c3a090c29090c98080e8908129900ff000e8a180ca909098a18128800ff000988080ca8080c98080f08d4fd01b85c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c9707031718040852b606102030fa0707a2fd011818086808040704090400224e03110211fc0310040704080610240efa0f070400040808000204070104090400264e0311021140ff0310bc000315b8000316b4000215c0001211e05216040740040820061028d6f90707e70a04040800020a036400020a084800020a0a6000020a025000020a0c4c00020e8b0812b900ff000e8b180cb909128b00ff0009bb080988180cb8080c98080368780ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c89000ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c890a0e3808128800ff000e39180c9808123900ff000999080933180c93090c890902a801036a6c1baaff0369741b99c0548a090e2808128800ff000e2a180ca808122a00ff0009aa080a0b5400020922180ca20a0c8a020eb808128800ff000eba180ca80812ba00ff0009aa080a0c58000209bb180cba0a0c8a030ec808128800ff000eca180ca80812ca00ff0009aa0803647c0a0b5c000209cc180cca0a0c8a0c0eb808128800ff000eba180ca80812b700ff0009770809bb180cb7070c870a0362680167780c72070360700363640c03080c8707036c60036a5c0cca08036854568903675856790709190904074004082006102a5ef807076f0901677402784003685024780701686c08780903694824890b53770b01675c08b70024700701686008780224820c53770c53bb0c016764087c0c247c0b01676808b70424740853bb0801677008870a247a080163780883030e3708127700ff000e38180c7808123700ff000977080933180c73070c870703674c0ea708127700ff000ea9180c970712a900ff0009990809aa180ca9090c97070367440e4708127700ff000e49180c9707124900ff000999080944180c94090c79040ec708127700ff000ec9180c970712c900ff0009990809cc180cc9090c79030e2708127700ff000e29180c9707122900ff000999080922180c92090c79020e0908129900ff000e0a180ca909120a00ff0009aa080900180ca00a0ca9090167480e7a0812aa00ff000e78180ca808127a00ff0009aa08097c180cca0a0ca8080167500e7a0812aa00ff000e7c180cca0a127b00ff0009bb08097c180ccb0b0cba0a016b7c03ba5c03b85803b95403b25003b34c03b44801674403b74401676c0168680c87070168600169780c98080c870701685c0169700c98080169640c98080c870701684c03b8400f07c80704082001677406102ca8f60707b9070162741b27e01f770101696c279854980701685c2788016a6027a953a8090168545387090167642777016a6827a853a708016c7027c7016b7827ba53b70a0cbc0753780a01675853790a01677c0827080d181c0000000b0d18180d18140d18100d180c0d18080d18040368440d080f0a470702272004082003676006102e24f60707350701687c0167600878080d181c0d18180d18140d18100d180c0d1808726c640d18046f20776f0368340d0848656c6c026780004e0167900003671401678c000367180167880003671c0167840003672001678000036724040740040820061030bff50707d00601677c017250017340017458017048017c54017b4c0179440eb808128800ff000eba180ca80812ba00ff0009aa0809bb180cba0a0ca8080368700e9808128800ff000e9a180ca808129a00ff0009aa080999180ca9090c98080368680ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890b0e0808128800ff000e09180c9808120900ff000999080900180c90090c89000e4808128800ff000e49180c9808124900ff000999080944180c94090c890c0e3808128800ff000e39180c9808123900ff000999080933180c93090c890a0e2808128800ff000e29180c9808122900ff000999080922180c92090c9808036a5c0368540ca808036058036c6c0c0c090c9808036b640169680cb909016a700ca9090c98080f08ae0501687c01885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970704082003677806103269f407077a05016a7c016778087a0a527b0d1a1c000030390d1a180d1a140d1a100d1a0c0d1a080d1a0401686c27891bb7e01f7c0103694854890c01676427780160542704530804016770277801635827325338020169682798016b5c27b753b8070cb9085382070168700c98080cb3090c98080169640c090903694c03644054940c03685003673c54870c036a100d0a0168780f0ce804028720040820036738061034c5f30707d60401677c0168380887070d171c000000400d17180d17140d17100d170c0d17080d17040d0704082001677406103692f30707a3040169781b97c01f770101686c016a48548a0701684c016a40548a07016850016a3c548a070f077b0401674401781c03684801781803687401781403684001781003683c01780c03683801780803683001780403682c017703674402974004082003672806103826f3070737040167781b77a001686c568701684c5687016850568701687c016928089808016c2c038c04016a44038a016b30038b0801643803840c01623c03821001604003801401697403891801694803891c0707e6030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c98080368500ec808128800ff000ec9180c980812c900ff0009990809ca180ca9090c890c0eb808128800ff000eb9180c980812b900ff0009990809ba180ca9090c89030e4808128800ff000e49180c9808124900ff00099908094a180ca9090c89040e2808128800ff000e29180c9808122900ff00099908092a180ca9090c89020e0808128800ff000e09180c9808120900ff00099908090a180ca9090c8900016a740ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c980803684403633c0c38080362300169500c92090c9808036c4003602c0cc0090364380c49090c98080f08dc02016a480ea808128800ff000ea9180c980812a700ff0009770809a9180c97070c780801677802776003674c03687406103a94f10707a50201676001687406103c85f10707960201677801684c247807528b01686c08780903690c24890853770801676408870903692824790701695408790a036a48249a0953770953880901677008790903696024790701685808780903696424890853770801676808780803686c24780703676801677c08b70701683401697406103e58f101684c016974089808016a4401670c08a7070368702498080887021ca20924a20a53980a01682c016928088909016730016c48087c0c24890b08cb0b08a904249409089b031c730c24730b24840753c70b1c84070cc707537a0b01683801676008870724870a01683c016c64088c0c08ac0c1c8c09248c08539a08087b0b247b07087c0024c00953770901675c016a5008a707016a6808a707016a40016c6c08ac0c24ac0a08a70708c80824c80a08a7070889092489080887070cb4080c98080c73070c02090c98080c87070f07530104082001677006104033f00707440101687c0167700878080d181c0d18180d18140d18100d180c0d18080d180401697402971f249709016a4408a909129901127be01bbaa01faa0154990a0d080167780f0aff0002b86003687c061042dfef0707f0000217c01277e052710d171c8c16c7d00d1718622fa9a50d1714af827c120d17104a032b310d170cec4214070d1708f0370dae0d170487296ff20d071585375401681403783c01681803783801681c03783401682003783001682403782c0d17280d17240d1720040802016910016a7c4e01025140ff0110bc000115b8000116b4000211c000130004082004070610444aef07075b01687c0d181c0d18180d18140d18100d180c0d18080d18040d084e487b710407040408200610461eef07072f01687c0d1820000000410d181c0d18180d18140d18100d180c0d18080d18040408240407061048f2ee0f07040004080800020407010409244e03040704004a0581ef040706104a7cef04070106104c74ef00a58424092a241452482549495a52292da994644a2a2549920a21422d8410420821119224290911028410420809494a92243529499224491249882449928424244912929024094948928424244942129224210949929084244992244912929024292424348524a956c890d2244992902124841042a854928492a492244908104208218408014992244993244992244924494a9224499224499224499224499224a9102195840a115249484224499224499290242489242421495221924a53850c298d8888948408218410129290244948429224242149129290244992242421214942121292242421094912929024499224494a91844892244992244992244992242421499290842449421292242109499290842449484292242109499284242449922449922449922449242192a4a49424a5a4942449024992a448122249922408248891482412494224499224242149929084244942129224210949929084244948429224242149922449922491242421499210490a2449929224a5a494949224499224494a2409912490244949882449922489244992244952928448524a4992942449922491908424494212922421094992908424494842922424214992908424499224499244129290244912220991a424499224499224499224499284244992244992244992244992244992244992244992244992248924449224499224499294484224050281402010089224499224498a8888524892244990842490244952c8905452480800" - }, - "revert": { - "abi": [ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "doRevert", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } - ], - "bytecode": "50564d0001ba09000000000000010700c13004c0004004440400000000050000001000000022000000696e7075747365616c5f72657475726e7365745f696d6d757461626c655f6461746176616c75655f7472616e7366657272656405110288020463616c6c8809066465706c6f79068947170288126700aa00af00ce006901a802c502e102f5021303ab04c604cf04eb043d06d50632078f07c907dc07ea070908110852790e7a1004070f0a41040a0000012f8a3908890802871f1277e03b370000010a040713000a0800000229781416070000025278040710000208870713000407100002088707130013000211e003101c0315180316140215201211e0127601040704080610029d16070400020d010004040710000352184e11011726032c040326032804032603240403260320040326031c0403260318040326031404031607100403070607061004090610064b020211c003103c0315380316340215401211e0521604074004082006100837ff07071602040804000226036000020000008026035c000226035800022603540002260350000226034c0002260348000203681826034400020217e01277e003671c52710d171c0d17180d17140d17100d170c0d17080d17040d074e031101681c0182100183018914018a1c018b0c018c040187180188080cba0a0cc9090ca9090c87070c23080c87070c97070f077e0104074004082006100a9cfe07077b01016718017450017040017b58017c48017a5401724c0173440e2808128800ff000e29180c9808122900ff000999080922180c92090c980803681c0e3808128800ff000e39180c9808123900ff000999080933180c93090c89030ea808128800ff000ea9180c980812a900ff0009990809aa180ca9090c89020ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c98080e0908129900ff000e0b180cb909120b00ff0009bb080900180cb00b0cb9090e4b0812bb00ff000e4a180cba0a124b00ff0009bb080944180cb40b0cba0a0ca9090cc8080c98080c3209016a1c0ca9090c98080f086e01681801885c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970703671c040806100c5dfd07073c0a0808000207080b04073004034e021101671c040806100e40fd07071f01681801671c087808040704094e01110407040806101024fd0f070400040804000204070104090400124e011102118003107c031578031674021580001211e0040740040820061014f2fc0f07040004061004030a0710040303173c0a041404030a031804030a092c04030a082804030a002004030a0c2404032797278a54970a27cb270754cb070c980b54ba070316380a0b1c04032742011a3c1baa041faa0154420a27b2273654b2060cb30b54b60a0cc9090c80080c980854870a040904000226036000020000008026035c000226035800022603540002260350000226034c000226034800022603440002070a0b010a071000030f47afc874d2020103193c0d115c0d11580d11540d11500d114c0d11480d11440d11400217404e0311011250011840011954011a5c011b4c011c440116580117480cba0a0cc9090ca9090c67070c28080c87070c97070f07b10001173801721c017318017414017a100178017c0c017604017708028bfc248b0808860b02bbff1c6b09246b0b53980b0278ff08b8092479002489081b7601146c060868081cc80624c8085360081c97070c6707537b0802a7ff0878082478071ba8011484080878092489085377080c4a071b77011473090898082498082473071472070887072d0741040704080610165afb07076bfe040804000204070104094e01040018051e030610181b030407040806101a36fb070747fe040804000204070104094e011104074004082006101c1afb07072bfe01103c010250010340010458010b48010c54010a4c0108440ea608126600ff000ea9180c690912a600ff0009660809aa180c6a0a0ca9090319380e8908129900ff000e8a180ca909128a00ff0009aa080988180ca8080c98080318340ec808128800ff000ec9180c980812c900ff0009990809cc180cc9090c890c0eb808128800ff000eb9180c980812b900ff0009990809bb180cb9090c890a0e4808128800ff000e49180c9808124900ff000999080944180c94090c89040e3808128800ff000e39180c9808123900ff000999080933180c93090c89030e2808128800ff000e29180c9808122900ff000999080922180c92060c860b0c3b080ca4090c98080119340cc9090116380c69090c98080f0818fd52b6031320031a24031c2803142c01085c0e8908129900ff000e8a180ca909128700ff000977080988180c87070c970704082003173006101ec8f90707d9fc011230011a3c082a0a0d0a08c379a00113382737011424274b53470b011c3427c701182027895387090c8c07537b09011b2827b727605367000cb6060cc3070d1a1c0d1a180d1a140d1a100d1a0c0d1a080c8408011b2c27bc0c78081b27fc1f770154bc070316385460075489070d1a040f0764fc031c20031824031028031934031a1c011730027704040820527606102030f9070741fc01173c0867070d171c000000200d17180d17140d17100d170c0d17080d17040118301b88dc1f880101192c011a20549a08011928011a3854a908011934011a2454a9080d070f08f8fb0117300276240408205267061022d3f80707e4fb01173c0867070d171c0000000e0d17180d17140d17100d170c0d17080d17040118301b88bc1f880101192c011a20549a08011928011a3854a908011934011a2454a9080d070f089bfb011730027644040820526706102476f8070787fb01173c0867070d171c0d17180d17140d17100d170c67650d1708657373610d17047274206d0d07726576650408640117300610263cf807074dfb04070104096401181c0400284e01110211fc03100407040806102a1bf80f070400040804000204070104094e01040704002c054bf8040706102c46f804070106102e3ef800a58424092a241452482549928a10a10b21841042488424494a4284002184104242929224494d4a9224499244122249922421094992842424494212922421094992908424494842922424214992244992842424490a09094d2149aa1532a434492249c81012420821542a494249524992240408218410428480244992a449922449922492242549922449922449922449922449925488904a428508a9498824499284242449129290244948429224242149129290240949489284242449922449942449484292242192042925a524a924499224254992449224492192409224499224495224294412489224499224498a24854892240402411222499a2a64489514120200" - } -} \ No newline at end of file diff --git a/substrate/frame/revive/rpc/examples/js/pvm/event.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/event.polkavm new file mode 100644 index 0000000000000000000000000000000000000000..859c1cdf5d3e97c7df8cbad6a0dc0cbd5f8d6388 GIT binary patch literal 5186 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 PI4Am)*gBU=#F+HI@tB`4 literal 0 HcmV?d00001 diff --git a/substrate/frame/revive/rpc/examples/js/pvm/piggyBank.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/piggyBank.polkavm new file mode 100644 index 0000000000000000000000000000000000000000..1a45c15d53f68431b7e5c1dff297c768e1160e97 GIT binary patch literal 12334 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 JpgkTJ{s(-6RoDOk literal 0 HcmV?d00001 diff --git a/substrate/frame/revive/rpc/examples/js/pvm/revert.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/revert.polkavm new file mode 100644 index 0000000000000000000000000000000000000000..7505c402f21b7f8a16914f1f067f94eebb9b3c96 GIT binary patch literal 2490 zcmbtVZ)_V$72h{A-I-nQI_r&NZ|v2@343u80z@Ucrn-P!%c6FYMv=2Z5h`i}ah+b% zQfxO#{|H5pyV&VTRK7#a9Uy_!JDTv};6Ua2=fj~Bkm?XfAU+`7ha&L_z9At6HEnof zn}!3OiiG8TJ3GHOzj-tBdvB&be@uZpn$q|ISAIUk-c?d8!(_(+d@Ou=@Hu_%{Dn%n zFuQP~RH$4iohuhACr+O|d!aJ>rG>(Yx!KC>;_SkO!ih?0_FVZ?p;Ri&9SD&sVPBqI zSg301T;cq}S1zixqft_|i^`Vrmhv0rG~6V=Ab%o%C++ly?3e7f?62%I>L1jD{G0qf z|A7C6Ya%4_7lW59#@qBGOji{6)cRpj6J)K+UV8BSA?(l@Z&!4oD5QTm9O3xRFEef_ zM64mO-)dJ#=mE7{+TqYhm~0DZ~VY$q_W~OokxZO9vV4rG3(P z(j=sDrE#PQGaBI*qg>^x#WdAY#|a6&ORZ7bF+wB5q$7os{rN`yhj5NM9Q_@UGlT`?vcY0|?Atd?$7fg$8{;OuxHKUFh4VzKRj2dQC zm{Df(Ng9HA7rt)6H=q`Vbr-H0@G^rn2dcujqZ{`%V^cHMxbZO|?RDP9zlO_ihNge# zG3S>7iVjq!;Cu=$&%l)|T=Jnb0p(1vPuNvuPYL!r#)h!_v8lZ#v>wN(YuG{O-QY;e z<8Z^{aLePeU!umxNYzntO;RBK2c@@e${vx)2KCBEa|%qmv{A zO)!{3uuIYvU9l`saoQw=n!>ZZM{TIQh9npVrZL4vkc3vKb%k~;(@2GMtSBg>f1OnL zZ@Y~Vs5q)i_0j04&QOZF6s4}AWOad()fH5$ZlG?H*OTl1bv^lhlKby-VZTdZpf{Is5YJNcadwrcz&;NNNpW<~CczoyH$P>}zVWE*`N^GiJy)LsMpG!VG22P{s_UNHitIYfpibf=(Y|$00reZU!PV5Y6sO zx5$mYC(`|~0?`pDxll&MhT)P0%W%bjMFvZPT;27q3h`2a+}(4}Xx^E?^hSUz?}>Lb z@1o+>M0^p#3#ynG?zZY}i|LcXz0QpypS~=}5BBhkyk#E03E@>CmNoRBUJ}L_k1s*E ztceZb;lIqoC5|QL6Z}Z?BqLvV$oZMa`zJXGOmPl8LsiR()22`CIrKUDAs^I1GXvci zVjq7D)+mrEpebN85XgezgFXQw6MR$Hr=*B6flh1on^K3TgoX+9f>bc=9QhBWu1k-t zhEi|JQ>4!D|C41kJ(z7JVXl#cImwST0MqDI%u)8V0`SolL^WOt7|#pihD;%PaFwU$PQRO^}Te{lZCU9g8x<6=NJb@ATC??L-W z@(_f*UsSEc z5XN<67owx0$g!H^Es*%{iVn_Dy!t^`6`*qvVhR6s+?qa!jrf~#k09n@!{lvZ=bK(&&S#&^)z_`>2fA0SbavItjipx=*-qE%Uhdc!ntI0W$<@7XEmvRl zyj = new Map() -let evmContracts: Map = new Map() const input = [ { file: 'Event.sol', contract: 'EventExample', keypath: 'event' }, { file: 'Revert.sol', contract: 'RevertExample', keypath: 'revert' }, + { file: 'PiggyBank.sol', contract: 'PiggyBank', keypath: 'piggyBank' }, ] for (const { keypath, contract, file } of input) { @@ -41,16 +40,17 @@ for (const { keypath, contract, file } of input) { console.log(`Compile with solc ${file}`) const out = JSON.parse(evmCompile(input)) const entry = out.contracts[file][contract] - evmContracts.set(keypath, { abi: entry.abi, bytecode: entry.evm.bytecode.object }) + writeFileSync(join('evm', `${keypath}.bin`), Buffer.from(entry.evm.bytecode.object, 'hex')) + writeFileSync(join('abi', `${keypath}.json`), JSON.stringify(entry.abi, null, 2)) } { console.log(`Compile with revive ${file}`) const out = await compile(input) const entry = out.contracts[file][contract] - pvmContracts.set(keypath, { abi: entry.abi, bytecode: entry.evm.bytecode.object }) + writeFileSync( + join('pvm', `${keypath}.polkavm`), + Buffer.from(entry.evm.bytecode.object, 'hex') + ) } } - -writeFileSync('pvm-contracts.json', JSON.stringify(Object.fromEntries(pvmContracts), null, 2)) -writeFileSync('evm-contracts.json', JSON.stringify(Object.fromEntries(evmContracts), null, 2)) diff --git a/substrate/frame/revive/rpc/examples/js/src/event.ts b/substrate/frame/revive/rpc/examples/js/src/event.ts index 95e630a43461..94cc2560272e 100644 --- a/substrate/frame/revive/rpc/examples/js/src/event.ts +++ b/substrate/frame/revive/rpc/examples/js/src/event.ts @@ -3,8 +3,8 @@ import { call, getContract, deploy } from './lib.ts' try { const { abi, bytecode } = getContract('event') - const address = await deploy(bytecode, abi) - const receipt = await call('triggerEvent', address, abi) + const contract = await deploy(bytecode, abi) + const receipt = await call('triggerEvent', await contract.getAddress(), abi) if (receipt) { for (const log of receipt.logs) { console.log('Event log:', JSON.stringify(log, null, 2)) diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts index 40f2d6f05824..975d8faf15b3 100644 --- a/substrate/frame/revive/rpc/examples/js/src/lib.ts +++ b/substrate/frame/revive/rpc/examples/js/src/lib.ts @@ -10,6 +10,7 @@ import { readFileSync } from 'node:fs' import type { compile } from '@parity/revive' import { spawn } from 'node:child_process' import { parseArgs } from 'node:util' +import { BaseContract } from 'ethers' type CompileOutput = Awaited> type Abi = CompileOutput['contracts'][string][string]['abi'] @@ -41,7 +42,7 @@ if (geth) { '--http.api', 'web3,eth,debug,personal,net', '--http.port', - '8545', + '8546', '--dev', '--verbosity', '0', @@ -55,10 +56,14 @@ if (geth) { } export const provider = new JsonRpcProvider( - westend ? 'https://westend-asset-hub-eth-rpc.polkadot.io' : 'http://localhost:8545' + westend + ? 'https://westend-asset-hub-eth-rpc.polkadot.io' + : geth + ? 'http://localhost:8546' + : 'http://localhost:8545' ) -const signer = privateKey ? new Wallet(privateKey, provider) : await provider.getSigner() +export const signer = privateKey ? new Wallet(privateKey, provider) : await provider.getSigner() console.log(`Signer address: ${await signer.getAddress()}, Nonce: ${await signer.getNonce()}`) /** @@ -66,18 +71,16 @@ console.log(`Signer address: ${await signer.getAddress()}, Nonce: ${await signer * @param name - the contract name */ export function getContract(name: string): { abi: Abi; bytecode: string } { - const file = geth - ? readFileSync('evm-contracts.json', 'utf8') - : readFileSync('pvm-contracts.json', 'utf8') - const contracts = JSON.parse(file) as Record - return contracts[name] + const bytecode = geth ? readFileSync(`evm/${name}.bin`) : readFileSync(`pvm/${name}.polkavm`) + const abi = JSON.parse(readFileSync(`abi/${name}.json`, 'utf8')) as Abi + return { abi, bytecode: Buffer.from(bytecode).toString('hex') } } /** * Deploy a contract * @returns the contract address **/ -export async function deploy(bytecode: string, abi: Abi, args: any[] = []): Promise { +export async function deploy(bytecode: string, abi: Abi, args: any[] = []): Promise { console.log('Deploying contract with', args) const contractFactory = new ContractFactory(abi, bytecode, signer) @@ -85,7 +88,8 @@ export async function deploy(bytecode: string, abi: Abi, args: any[] = []): Prom await contract.waitForDeployment() const address = await contract.getAddress() console.log(`Contract deployed: ${address}`) - return address + + return contract } /** diff --git a/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts b/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts new file mode 100644 index 000000000000..7a8edbde3662 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts @@ -0,0 +1,24 @@ +import { provider, call, getContract, deploy } from './lib.ts' +import { parseEther } from 'ethers' +import { PiggyBank } from '../types/ethers-contracts/PiggyBank' + +try { + const { abi, bytecode } = getContract('piggyBank') + const contract = (await deploy(bytecode, abi)) as PiggyBank + const address = await contract.getAddress() + + let receipt = await call('deposit', address, abi, [], { + value: parseEther('10.0'), + }) + console.log('Deposit receipt:', receipt?.status) + console.log(`Contract balance: ${await provider.getBalance(address)}`) + + console.log('deposit: ', await contract.getDeposit()) + + receipt = await call('withdraw', address, abi, [parseEther('5.0')]) + console.log('Withdraw receipt:', receipt?.status) + console.log(`Contract balance: ${await provider.getBalance(address)}`) + console.log('deposit: ', await contract.getDeposit()) +} catch (err) { + console.error(err) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/revert.ts b/substrate/frame/revive/rpc/examples/js/src/revert.ts index 5fb3ccde6fae..ea1bf4eceeb9 100644 --- a/substrate/frame/revive/rpc/examples/js/src/revert.ts +++ b/substrate/frame/revive/rpc/examples/js/src/revert.ts @@ -3,8 +3,8 @@ import { call, getContract, deploy } from './lib.ts' try { const { abi, bytecode } = getContract('revert') - const address = await deploy(bytecode, abi) - await call('doRevert', address, abi) + const contract = await deploy(bytecode, abi) + await call('doRevert', await contract.getAddress(), abi) } catch (err) { console.error(err) } diff --git a/substrate/frame/revive/rpc/examples/js/src/transfer.ts b/substrate/frame/revive/rpc/examples/js/src/transfer.ts new file mode 100644 index 000000000000..ae2dd50f2af8 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/transfer.ts @@ -0,0 +1,17 @@ +import { parseEther } from 'ethers' +import { provider, signer } from './lib.ts' + +const recipient = '0x75E480dB528101a381Ce68544611C169Ad7EB342' +try { + console.log(`Signer balance: ${await provider.getBalance(signer.address)}`) + console.log(`Recipient balance: ${await provider.getBalance(recipient)}`) + await signer.sendTransaction({ + to: recipient, + value: parseEther('1.0'), + }) + console.log(`Sent: ${parseEther('1.0')}`) + console.log(`Signer balance: ${await provider.getBalance(signer.address)}`) + console.log(`Recipient balance: ${await provider.getBalance(recipient)}`) +} catch (err) { + console.error(err) +} diff --git a/substrate/frame/revive/rpc/examples/js/tsconfig.json b/substrate/frame/revive/rpc/examples/js/tsconfig.json index 0511b9f0e041..55cb8379e886 100644 --- a/substrate/frame/revive/rpc/examples/js/tsconfig.json +++ b/substrate/frame/revive/rpc/examples/js/tsconfig.json @@ -1,23 +1,23 @@ { - "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "module": "ESNext", - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "skipLibCheck": true, + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "module": "ESNext", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "skipLibCheck": true, - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, + /* Bundler mode */ + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, - /* Linting */ - "strict": true, - "noUnusedLocals": true, - "noUnusedParameters": true, - "noFallthroughCasesInSwitch": true - }, - "include": ["src"] + /* Linting */ + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true + }, + "include": ["src"] } diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts new file mode 100644 index 000000000000..d65f953969f0 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts @@ -0,0 +1,117 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +import type { + BaseContract, + BigNumberish, + BytesLike, + FunctionFragment, + Result, + Interface, + EventFragment, + AddressLike, + ContractRunner, + ContractMethod, + Listener, +} from 'ethers' +import type { + TypedContractEvent, + TypedDeferredTopicFilter, + TypedEventLog, + TypedLogDescription, + TypedListener, + TypedContractMethod, +} from './common' + +export interface EventInterface extends Interface { + getFunction(nameOrSignature: 'triggerEvent'): FunctionFragment + + getEvent(nameOrSignatureOrTopic: 'ExampleEvent'): EventFragment + + encodeFunctionData(functionFragment: 'triggerEvent', values?: undefined): string + + decodeFunctionResult(functionFragment: 'triggerEvent', data: BytesLike): Result +} + +export namespace ExampleEventEvent { + export type InputTuple = [sender: AddressLike, value: BigNumberish, message: string] + export type OutputTuple = [sender: string, value: bigint, message: string] + export interface OutputObject { + sender: string + value: bigint + message: string + } + export type Event = TypedContractEvent + export type Filter = TypedDeferredTopicFilter + export type Log = TypedEventLog + export type LogDescription = TypedLogDescription +} + +export interface Event extends BaseContract { + connect(runner?: ContractRunner | null): Event + waitForDeployment(): Promise + + interface: EventInterface + + queryFilter( + event: TCEvent, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + queryFilter( + filter: TypedDeferredTopicFilter, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + + on( + event: TCEvent, + listener: TypedListener + ): Promise + on( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + once( + event: TCEvent, + listener: TypedListener + ): Promise + once( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + listeners( + event: TCEvent + ): Promise>> + listeners(eventName?: string): Promise> + removeAllListeners(event?: TCEvent): Promise + + triggerEvent: TypedContractMethod<[], [void], 'nonpayable'> + + getFunction(key: string | FunctionFragment): T + + getFunction(nameOrSignature: 'triggerEvent'): TypedContractMethod<[], [void], 'nonpayable'> + + getEvent( + key: 'ExampleEvent' + ): TypedContractEvent< + ExampleEventEvent.InputTuple, + ExampleEventEvent.OutputTuple, + ExampleEventEvent.OutputObject + > + + filters: { + 'ExampleEvent(address,uint256,string)': TypedContractEvent< + ExampleEventEvent.InputTuple, + ExampleEventEvent.OutputTuple, + ExampleEventEvent.OutputObject + > + ExampleEvent: TypedContractEvent< + ExampleEventEvent.InputTuple, + ExampleEventEvent.OutputTuple, + ExampleEventEvent.OutputObject + > + } +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts new file mode 100644 index 000000000000..ca137fcc8b30 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts @@ -0,0 +1,96 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +import type { + BaseContract, + BigNumberish, + BytesLike, + FunctionFragment, + Result, + Interface, + ContractRunner, + ContractMethod, + Listener, +} from 'ethers' +import type { + TypedContractEvent, + TypedDeferredTopicFilter, + TypedEventLog, + TypedListener, + TypedContractMethod, +} from './common' + +export interface PiggyBankInterface extends Interface { + getFunction(nameOrSignature: 'deposit' | 'getDeposit' | 'owner' | 'withdraw'): FunctionFragment + + encodeFunctionData(functionFragment: 'deposit', values?: undefined): string + encodeFunctionData(functionFragment: 'getDeposit', values?: undefined): string + encodeFunctionData(functionFragment: 'owner', values?: undefined): string + encodeFunctionData(functionFragment: 'withdraw', values: [BigNumberish]): string + + decodeFunctionResult(functionFragment: 'deposit', data: BytesLike): Result + decodeFunctionResult(functionFragment: 'getDeposit', data: BytesLike): Result + decodeFunctionResult(functionFragment: 'owner', data: BytesLike): Result + decodeFunctionResult(functionFragment: 'withdraw', data: BytesLike): Result +} + +export interface PiggyBank extends BaseContract { + connect(runner?: ContractRunner | null): PiggyBank + waitForDeployment(): Promise + + interface: PiggyBankInterface + + queryFilter( + event: TCEvent, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + queryFilter( + filter: TypedDeferredTopicFilter, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + + on( + event: TCEvent, + listener: TypedListener + ): Promise + on( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + once( + event: TCEvent, + listener: TypedListener + ): Promise + once( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + listeners( + event: TCEvent + ): Promise>> + listeners(eventName?: string): Promise> + removeAllListeners(event?: TCEvent): Promise + + deposit: TypedContractMethod<[], [bigint], 'payable'> + + getDeposit: TypedContractMethod<[], [bigint], 'view'> + + owner: TypedContractMethod<[], [string], 'view'> + + withdraw: TypedContractMethod<[withdrawAmount: BigNumberish], [bigint], 'nonpayable'> + + getFunction(key: string | FunctionFragment): T + + getFunction(nameOrSignature: 'deposit'): TypedContractMethod<[], [bigint], 'payable'> + getFunction(nameOrSignature: 'getDeposit'): TypedContractMethod<[], [bigint], 'view'> + getFunction(nameOrSignature: 'owner'): TypedContractMethod<[], [string], 'view'> + getFunction( + nameOrSignature: 'withdraw' + ): TypedContractMethod<[withdrawAmount: BigNumberish], [bigint], 'nonpayable'> + + filters: {} +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts new file mode 100644 index 000000000000..ad6e23b38a65 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts @@ -0,0 +1,78 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +import type { + BaseContract, + BytesLike, + FunctionFragment, + Result, + Interface, + ContractRunner, + ContractMethod, + Listener, +} from 'ethers' +import type { + TypedContractEvent, + TypedDeferredTopicFilter, + TypedEventLog, + TypedListener, + TypedContractMethod, +} from './common' + +export interface RevertInterface extends Interface { + getFunction(nameOrSignature: 'doRevert'): FunctionFragment + + encodeFunctionData(functionFragment: 'doRevert', values?: undefined): string + + decodeFunctionResult(functionFragment: 'doRevert', data: BytesLike): Result +} + +export interface Revert extends BaseContract { + connect(runner?: ContractRunner | null): Revert + waitForDeployment(): Promise + + interface: RevertInterface + + queryFilter( + event: TCEvent, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + queryFilter( + filter: TypedDeferredTopicFilter, + fromBlockOrBlockhash?: string | number | undefined, + toBlock?: string | number | undefined + ): Promise>> + + on( + event: TCEvent, + listener: TypedListener + ): Promise + on( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + once( + event: TCEvent, + listener: TypedListener + ): Promise + once( + filter: TypedDeferredTopicFilter, + listener: TypedListener + ): Promise + + listeners( + event: TCEvent + ): Promise>> + listeners(eventName?: string): Promise> + removeAllListeners(event?: TCEvent): Promise + + doRevert: TypedContractMethod<[], [void], 'nonpayable'> + + getFunction(key: string | FunctionFragment): T + + getFunction(nameOrSignature: 'doRevert'): TypedContractMethod<[], [void], 'nonpayable'> + + filters: {} +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts new file mode 100644 index 000000000000..247b9468ece2 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts @@ -0,0 +1,100 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +import type { + FunctionFragment, + Typed, + EventFragment, + ContractTransaction, + ContractTransactionResponse, + DeferredTopicFilter, + EventLog, + TransactionRequest, + LogDescription, +} from 'ethers' + +export interface TypedDeferredTopicFilter<_TCEvent extends TypedContractEvent> + extends DeferredTopicFilter {} + +export interface TypedContractEvent< + InputTuple extends Array = any, + OutputTuple extends Array = any, + OutputObject = any, +> { + ( + ...args: Partial + ): TypedDeferredTopicFilter> + name: string + fragment: EventFragment + getFragment(...args: Partial): EventFragment +} + +type __TypechainAOutputTuple = T extends TypedContractEvent ? W : never +type __TypechainOutputObject = + T extends TypedContractEvent ? V : never + +export interface TypedEventLog extends Omit { + args: __TypechainAOutputTuple & __TypechainOutputObject +} + +export interface TypedLogDescription + extends Omit { + args: __TypechainAOutputTuple & __TypechainOutputObject +} + +export type TypedListener = ( + ...listenerArg: [...__TypechainAOutputTuple, TypedEventLog, ...undefined[]] +) => void + +export type MinEthersFactory = { + deploy(...a: ARGS[]): Promise +} + +export type GetContractTypeFromFactory = F extends MinEthersFactory ? C : never +export type GetARGsTypeFromFactory = + F extends MinEthersFactory ? Parameters : never + +export type StateMutability = 'nonpayable' | 'payable' | 'view' + +export type BaseOverrides = Omit +export type NonPayableOverrides = Omit +export type PayableOverrides = Omit +export type ViewOverrides = Omit +export type Overrides = S extends 'nonpayable' + ? NonPayableOverrides + : S extends 'payable' + ? PayableOverrides + : ViewOverrides + +export type PostfixOverrides, S extends StateMutability> = + | A + | [...A, Overrides] +export type ContractMethodArgs, S extends StateMutability> = PostfixOverrides< + { [I in keyof A]-?: A[I] | Typed }, + S +> + +export type DefaultReturnType = R extends Array ? R[0] : R + +// export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> { +export interface TypedContractMethod< + A extends Array = Array, + R = any, + S extends StateMutability = 'payable', +> { + ( + ...args: ContractMethodArgs + ): S extends 'view' ? Promise> : Promise + + name: string + + fragment: FunctionFragment + + getFragment(...args: ContractMethodArgs): FunctionFragment + + populateTransaction(...args: ContractMethodArgs): Promise + staticCall(...args: ContractMethodArgs): Promise> + send(...args: ContractMethodArgs): Promise + estimateGas(...args: ContractMethodArgs): Promise + staticCallResult(...args: ContractMethodArgs): Promise +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts new file mode 100644 index 000000000000..2e16b18a7ed8 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts @@ -0,0 +1,51 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ + +import { Contract, Interface, type ContractRunner } from 'ethers' +import type { Event, EventInterface } from '../Event' + +const _abi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'sender', + type: 'address', + }, + { + indexed: false, + internalType: 'uint256', + name: 'value', + type: 'uint256', + }, + { + indexed: false, + internalType: 'string', + name: 'message', + type: 'string', + }, + ], + name: 'ExampleEvent', + type: 'event', + }, + { + inputs: [], + name: 'triggerEvent', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, +] as const + +export class Event__factory { + static readonly abi = _abi + static createInterface(): EventInterface { + return new Interface(_abi) as EventInterface + } + static connect(address: string, runner?: ContractRunner | null): Event { + return new Contract(address, _abi, runner) as unknown as Event + } +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts new file mode 100644 index 000000000000..0efea80ed2dc --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts @@ -0,0 +1,82 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ + +import { Contract, Interface, type ContractRunner } from 'ethers' +import type { PiggyBank, PiggyBankInterface } from '../PiggyBank' + +const _abi = [ + { + inputs: [], + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + inputs: [], + name: 'deposit', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + ], + stateMutability: 'payable', + type: 'function', + }, + { + inputs: [], + name: 'getDeposit', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + name: 'owner', + outputs: [ + { + internalType: 'address', + name: '', + type: 'address', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [ + { + internalType: 'uint256', + name: 'withdrawAmount', + type: 'uint256', + }, + ], + name: 'withdraw', + outputs: [ + { + internalType: 'uint256', + name: 'remainingBal', + type: 'uint256', + }, + ], + stateMutability: 'nonpayable', + type: 'function', + }, +] as const + +export class PiggyBank__factory { + static readonly abi = _abi + static createInterface(): PiggyBankInterface { + return new Interface(_abi) as PiggyBankInterface + } + static connect(address: string, runner?: ContractRunner | null): PiggyBank { + return new Contract(address, _abi, runner) as unknown as PiggyBank + } +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts new file mode 100644 index 000000000000..ece1c6b5426e --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts @@ -0,0 +1,31 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ + +import { Contract, Interface, type ContractRunner } from 'ethers' +import type { Revert, RevertInterface } from '../Revert' + +const _abi = [ + { + inputs: [], + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + inputs: [], + name: 'doRevert', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, +] as const + +export class Revert__factory { + static readonly abi = _abi + static createInterface(): RevertInterface { + return new Interface(_abi) as RevertInterface + } + static connect(address: string, runner?: ContractRunner | null): Revert { + return new Contract(address, _abi, runner) as unknown as Revert + } +} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts new file mode 100644 index 000000000000..67370dba411c --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts @@ -0,0 +1,6 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +export { Event__factory } from './Event__factory' +export { PiggyBank__factory } from './PiggyBank__factory' +export { Revert__factory } from './Revert__factory' diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts new file mode 100644 index 000000000000..3e324e80dcb1 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts @@ -0,0 +1,10 @@ +/* Autogenerated file. Do not edit manually. */ +/* tslint:disable */ +/* eslint-disable */ +export type { Event } from './Event' +export type { PiggyBank } from './PiggyBank' +export type { Revert } from './Revert' +export * as factories from './factories' +export { Event__factory } from './factories/Event__factory' +export { PiggyBank__factory } from './factories/PiggyBank__factory' +export { Revert__factory } from './factories/Revert__factory' diff --git a/substrate/frame/revive/rpc/examples/package.json b/substrate/frame/revive/rpc/examples/package.json deleted file mode 100644 index 37d819aaa481..000000000000 --- a/substrate/frame/revive/rpc/examples/package.json +++ /dev/null @@ -1 +0,0 @@ -{ "dependencies": { "@parity/revive": "^0.0.5" } } \ No newline at end of file diff --git a/substrate/frame/revive/rpc/revive_chain.metadata b/substrate/frame/revive/rpc/revive_chain.metadata index e5bfa0820b100bce59107541915f9352fce1c99a..3560b3b90407acce7f602ce91ac089843be8dea8 100644 GIT binary patch delta 20100 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 A?*IS* delta 19111 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 diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index b7efae15c4aa..1ca1a6d37c53 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -236,7 +236,6 @@ struct ClientInner { cache: Shared>, chain_id: u64, max_block_weight: Weight, - native_to_evm_ratio: U256, } impl ClientInner { @@ -252,20 +251,10 @@ impl ClientInner { let rpc = LegacyRpcMethods::::new(RpcClient::new(rpc_client.clone())); - let (native_to_evm_ratio, chain_id, max_block_weight) = - tokio::try_join!(native_to_evm_ratio(&api), chain_id(&api), max_block_weight(&api))?; + let (chain_id, max_block_weight) = + tokio::try_join!(chain_id(&api), max_block_weight(&api))?; - Ok(Self { api, rpc_client, rpc, cache, chain_id, max_block_weight, native_to_evm_ratio }) - } - - /// Convert a native balance to an EVM balance. - fn native_to_evm_decimals(&self, value: U256) -> U256 { - value.saturating_mul(self.native_to_evm_ratio) - } - - /// Convert an evm balance to a native balance. - fn evm_to_native_decimals(&self, value: U256) -> U256 { - value / self.native_to_evm_ratio + Ok(Self { api, rpc_client, rpc, cache, chain_id, max_block_weight }) } /// Get the receipt infos from the extrinsics in a block. @@ -368,13 +357,6 @@ async fn max_block_weight(api: &OnlineClient) -> Result) -> Result { - let query = subxt_client::constants().revive().native_to_eth_ratio(); - let ratio = api.constants().at(&query)?; - Ok(U256::from(ratio)) -} - /// Extract the block timestamp. async fn extract_block_timestamp(block: &SubstrateBlock) -> Option { let extrinsics = block.extrinsics().await.ok()?; @@ -607,8 +589,9 @@ impl Client { let runtime_api = self.runtime_api(at).await?; let payload = subxt_client::apis().revive_api().balance(address); - let balance = runtime_api.call(payload).await?.into(); - Ok(self.inner.native_to_evm_decimals(balance)) + let balance = runtime_api.call(payload).await?; + + Ok(*balance) } /// Get the contract storage for the given contract address and key. @@ -659,13 +642,8 @@ impl Client { ) -> Result>, ClientError> { let runtime_api = self.runtime_api(&block).await?; - let value = self - .inner - .evm_to_native_decimals(tx.value.unwrap_or_default()) - .try_into() - .map_err(|_| ClientError::ConversionFailed)?; - // TODO: remove once subxt is updated + let value = subxt::utils::Static(tx.value.unwrap_or_default()); let from = tx.from.map(|v| v.0.into()); let to = tx.to.map(|v| v.0.into()); diff --git a/substrate/frame/revive/rpc/src/example.rs b/substrate/frame/revive/rpc/src/example.rs index d2f9b509f4d2..20f00465b146 100644 --- a/substrate/frame/revive/rpc/src/example.rs +++ b/substrate/frame/revive/rpc/src/example.rs @@ -105,6 +105,30 @@ impl TransactionBuilder { self } + /// Call eth_call to get the result of a view function + pub async fn eth_call( + self, + client: &(impl EthRpcClient + Send + Sync), + ) -> anyhow::Result> { + let TransactionBuilder { signer, value, input, to, .. } = self; + + let from = signer.address(); + let result = client + .call( + GenericTransaction { + from: Some(from), + input: Some(input.clone()), + value: Some(value), + to, + ..Default::default() + }, + None, + ) + .await + .with_context(|| "eth_call failed")?; + Ok(result.0) + } + /// Send the transaction. pub async fn send(self, client: &(impl EthRpcClient + Send + Sync)) -> anyhow::Result { let TransactionBuilder { signer, value, input, to, mutate } = self; @@ -156,6 +180,7 @@ impl TransactionBuilder { Ok(hash) } + /// Send the transaction and wait for the receipt. pub async fn send_and_wait_for_receipt( self, client: &(impl EthRpcClient + Send + Sync), diff --git a/substrate/frame/revive/rpc/src/subxt_client.rs b/substrate/frame/revive/rpc/src/subxt_client.rs index 11a0d51ed03e..a232b231bc7c 100644 --- a/substrate/frame/revive/rpc/src/subxt_client.rs +++ b/substrate/frame/revive/rpc/src/subxt_client.rs @@ -21,6 +21,11 @@ use subxt::config::{signed_extensions, Config, PolkadotConfig}; #[subxt::subxt( runtime_metadata_path = "revive_chain.metadata", + // TODO remove once subxt use the same U256 type + substitute_type( + path = "primitive_types::U256", + with = "::subxt::utils::Static<::sp_core::U256>" + ), substitute_type( path = "pallet_revive::primitives::EthContractResult", with = "::subxt::utils::Static<::pallet_revive::EthContractResult>" diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 3d2cbe42be8e..eb23bd7583a0 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -22,6 +22,7 @@ use crate::{ EthRpcClient, }; use clap::Parser; +use ethabi::Token; use jsonrpsee::ws_client::{WsClient, WsClientBuilder}; use pallet_revive::{ create1, @@ -48,15 +49,12 @@ async fn ws_client_with_retry(url: &str) -> WsClient { } fn get_contract(name: &str) -> anyhow::Result<(Vec, ethabi::Contract)> { - const PVM_CONTRACTS: &str = include_str!("../examples/js/pvm-contracts.json"); - let pvm_contract: serde_json::Value = serde_json::from_str(PVM_CONTRACTS)?; - let pvm_contract = pvm_contract[name].as_object().unwrap(); - let bytecode = pvm_contract["bytecode"].as_str().unwrap(); - let bytecode = hex::decode(bytecode)?; + let pvm_dir: std::path::PathBuf = "./examples/js/pvm".into(); + let abi_dir: std::path::PathBuf = "./examples/js/abi".into(); + let bytecode = std::fs::read(pvm_dir.join(format!("{}.polkavm", name)))?; - let abi = pvm_contract["abi"].clone(); - let abi = serde_json::to_string(&abi)?; - let contract = ethabi::Contract::load(abi.as_bytes())?; + let abi = std::fs::read(abi_dir.join(format!("{}.json", name)))?; + let contract = ethabi::Contract::load(abi.as_slice())?; Ok((bytecode, contract)) } @@ -280,3 +278,44 @@ async fn invalid_transaction() -> anyhow::Result<()> { Ok(()) } + +#[tokio::test] +async fn native_evm_ratio_works() -> anyhow::Result<()> { + let _lock = SHARED_RESOURCES.write(); + let client = SharedResources::client().await; + let (bytecode, contract) = get_contract("piggyBank")?; + let contract_address = TransactionBuilder::default() + .input(bytecode) + .send_and_wait_for_receipt(&client) + .await? + .contract_address + .unwrap(); + + let value = 10_000_000_000_000_000_000u128; // 10 eth + TransactionBuilder::default() + .to(contract_address) + .input(contract.function("deposit")?.encode_input(&[])?.to_vec()) + .value(value.into()) + .send_and_wait_for_receipt(&client) + .await?; + + let contract_value = client.get_balance(contract_address, BlockTag::Latest.into()).await?; + assert_eq!(contract_value, value.into()); + + let withdraw_value = 1_000_000_000_000_000_000u128; // 1 eth + TransactionBuilder::default() + .to(contract_address) + .input( + contract + .function("withdraw")? + .encode_input(&[Token::Uint(withdraw_value.into())])? + .to_vec(), + ) + .send_and_wait_for_receipt(&client) + .await?; + + let contract_value = client.get_balance(contract_address, BlockTag::Latest.into()).await?; + assert_eq!(contract_value, (value - withdraw_value).into()); + + Ok(()) +} diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index 593c16cbb2d8..40ad3a3aed17 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -1516,7 +1516,7 @@ mod benchmarks { let callee_bytes = callee.encode(); let callee_len = callee_bytes.len() as u32; - let value: BalanceOf = t.into(); + let value: BalanceOf = (1_000_000 * t).into(); let value_bytes = Into::::into(value).encode(); let deposit: BalanceOf = (u32::MAX - 100).into(); @@ -1591,7 +1591,7 @@ mod benchmarks { let hash_bytes = hash.encode(); let hash_len = hash_bytes.len() as u32; - let value: BalanceOf = 1u32.into(); + let value: BalanceOf = 1_000_000u32.into(); let value_bytes = Into::::into(value).encode(); let value_len = value_bytes.len() as u32; @@ -1645,7 +1645,10 @@ mod benchmarks { assert_ok!(result); assert!(ContractInfoOf::::get(&addr).is_some()); - assert_eq!(T::Currency::balance(&account_id), Pallet::::min_balance() + value); + assert_eq!( + T::Currency::balance(&account_id), + Pallet::::min_balance() + Pallet::::convert_evm_to_native(value.into()).unwrap() + ); Ok(()) } diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index c27edac93500..21294fdf6baa 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -313,9 +313,10 @@ pub trait EthExtra { return Err(InvalidTransaction::Call); } - let value = (value / U256::from(::NativeToEthRatio::get())) - .try_into() - .map_err(|_| InvalidTransaction::Call)?; + let value = crate::Pallet::::convert_evm_to_native(value).map_err(|err| { + log::debug!(target: LOG_TARGET, "Failed to convert value to native: {err:?}"); + InvalidTransaction::Call + })?; let call = if let Some(dest) = to { crate::Call::call:: { diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 4f90b41b0de5..fdb45f045bbc 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -569,8 +569,8 @@ struct Frame { account_id: T::AccountId, /// The cached in-storage data of the contract. contract_info: CachedContract, - /// The amount of balance transferred by the caller as part of the call. - value_transferred: BalanceOf, + /// The EVM balance transferred by the caller as part of the call. + value_transferred: U256, /// Determines whether this is a call or instantiate frame. entry_point: ExportedFunction, /// The gas meter capped to the supplied gas limit. @@ -757,7 +757,7 @@ where dest: H160, gas_meter: &'a mut GasMeter, storage_meter: &'a mut storage::meter::Meter, - value: BalanceOf, + value: U256, input_data: Vec, debug_message: Option<&'a mut DebugBuffer>, ) -> ExecResult { @@ -791,7 +791,7 @@ where executable: E, gas_meter: &'a mut GasMeter, storage_meter: &'a mut storage::meter::Meter, - value: BalanceOf, + value: U256, input_data: Vec, salt: Option<&[u8; 32]>, debug_message: Option<&'a mut DebugBuffer>, @@ -834,7 +834,7 @@ where origin, gas_meter, storage_meter, - value, + value.into(), debug_message, ) .unwrap() @@ -843,14 +843,14 @@ where /// Create a new call stack. /// - /// Returns `None` when calling a non existant contract. This is not an error case + /// Returns `None` when calling a non existent contract. This is not an error case /// since this will result in a value transfer. fn new( args: FrameArgs, origin: Origin, gas_meter: &'a mut GasMeter, storage_meter: &'a mut storage::meter::Meter, - value: BalanceOf, + value: U256, debug_message: Option<&'a mut DebugBuffer>, ) -> Result, ExecError> { origin.ensure_mapped()?; @@ -890,7 +890,7 @@ where /// not initialized, yet. fn new_frame( frame_args: FrameArgs, - value_transferred: BalanceOf, + value_transferred: U256, gas_meter: &mut GasMeter, gas_limit: Weight, storage_meter: &mut storage::meter::GenericMeter, @@ -975,7 +975,7 @@ where fn push_frame( &mut self, frame_args: FrameArgs, - value_transferred: BalanceOf, + value_transferred: U256, gas_limit: Weight, deposit_limit: BalanceOf, read_only: bool, @@ -1282,8 +1282,9 @@ where origin: &Origin, from: &T::AccountId, to: &T::AccountId, - value: BalanceOf, + value: U256, ) -> ExecResult { + let value = crate::Pallet::::convert_evm_to_native(value)?; if value.is_zero() { return Ok(Default::default()); } @@ -1311,7 +1312,7 @@ where origin: &Origin, from: &Origin, to: &T::AccountId, - value: BalanceOf, + value: U256, ) -> ExecResult { // If the from address is root there is no account to transfer from, and therefore we can't // take any `value` other than 0. @@ -1358,7 +1359,11 @@ where /// Returns the *free* balance of the supplied AccountId. fn account_balance(&self, who: &T::AccountId) -> U256 { - T::Currency::reducible_balance(who, Preservation::Preserve, Fortitude::Polite).into() + crate::Pallet::::convert_native_to_evm(T::Currency::reducible_balance( + who, + Preservation::Preserve, + Fortitude::Polite, + )) } /// Certain APIs, e.g. `{set,get}_immutable_data` behave differently depending @@ -2066,7 +2071,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - value, + value.into(), vec![], None, ), @@ -2086,7 +2091,7 @@ mod tests { set_balance(&BOB, 0); let origin = Origin::from_account_id(ALICE); - MockStack::transfer(&origin, &ALICE, &BOB, 55).unwrap(); + MockStack::transfer(&origin, &ALICE, &BOB, 55u64.into()).unwrap(); let min_balance = ::Currency::minimum_balance(); assert_eq!(get_balance(&ALICE), 45 - min_balance); @@ -2107,7 +2112,12 @@ mod tests { set_balance(&ALICE, ed * 2); set_balance(&BOB, ed + value); - assert_ok!(MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &CHARLIE, value)); + assert_ok!(MockStack::transfer( + &Origin::from_account_id(ALICE), + &BOB, + &CHARLIE, + value.into() + )); assert_eq!(get_balance(&ALICE), ed); assert_eq!(get_balance(&BOB), ed); assert_eq!(get_balance(&CHARLIE), ed + value); @@ -2116,7 +2126,7 @@ mod tests { set_balance(&ALICE, ed); set_balance(&BOB, ed + value); assert_err!( - MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &DJANGO, value), + MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &DJANGO, value.into()), >::TransferFailed ); @@ -2124,7 +2134,7 @@ mod tests { set_balance(&ALICE, ed * 2); set_balance(&BOB, value); assert_err!( - MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &EVE, value), + MockStack::transfer(&Origin::from_account_id(ALICE), &BOB, &EVE, value.into()), >::TransferFailed ); // The ED transfer would work. But it should only be executed with the actual transfer @@ -2153,7 +2163,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - value, + value.into(), vec![], None, ) @@ -2191,7 +2201,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - value, + value.into(), vec![], None, ) @@ -2223,7 +2233,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 55, + 55u64.into(), vec![], None, ) @@ -2246,7 +2256,7 @@ mod tests { ExtBuilder::default().build().execute_with(|| { set_balance(&from, 0); - let result = MockStack::transfer(&origin, &from, &dest, 100); + let result = MockStack::transfer(&origin, &from, &dest, 100u64.into()); assert_eq!(result, Err(Error::::TransferFailed.into())); assert_eq!(get_balance(&from), 0); @@ -2272,7 +2282,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2301,7 +2311,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2330,7 +2340,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![1, 2, 3, 4], None, ); @@ -2365,7 +2375,7 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - min_balance, + min_balance.into(), vec![1, 2, 3, 4], Some(&[0; 32]), None, @@ -2420,7 +2430,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - value, + value.into(), vec![], None, ); @@ -2484,7 +2494,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2549,7 +2559,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2581,7 +2591,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2618,7 +2628,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -2644,7 +2654,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -2688,7 +2698,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -2714,7 +2724,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -2740,7 +2750,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 1, + 1u64.into(), vec![0], None, ); @@ -2784,7 +2794,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -2829,7 +2839,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -2854,7 +2864,7 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - 0, // <- zero value + U256::zero(), // <- zero value vec![], Some(&[0; 32]), None, @@ -2889,8 +2899,7 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - - min_balance, + min_balance.into(), vec![], Some(&[0 ;32]), None, @@ -2945,7 +2954,7 @@ mod tests { &mut gas_meter, &mut storage_meter, - min_balance, + min_balance.into(), vec![], Some(&[0; 32]), None, @@ -3010,7 +3019,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - min_balance * 10, + (min_balance * 10).into(), vec![], None, ), @@ -3090,7 +3099,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ), @@ -3132,7 +3141,7 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - 100, + 100u64.into(), vec![], Some(&[0; 32]), None, @@ -3197,7 +3206,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -3258,7 +3267,7 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - 10, + 10u64.into(), vec![], Some(&[0; 32]), None, @@ -3305,7 +3314,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -3336,7 +3345,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], Some(&mut debug_buffer), ) @@ -3369,7 +3378,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], Some(&mut debug_buffer), ); @@ -3402,7 +3411,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], Some(&mut debug_buf_after), ) @@ -3435,7 +3444,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), CHARLIE_ADDR.as_bytes().to_vec(), None, )); @@ -3447,7 +3456,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), BOB_ADDR.as_bytes().to_vec(), None, ) @@ -3497,7 +3506,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ) @@ -3531,7 +3540,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -3615,7 +3624,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -3740,7 +3749,7 @@ mod tests { fail_executable, &mut gas_meter, &mut storage_meter, - min_balance * 100, + (min_balance * 100).into(), vec![], Some(&[0; 32]), None, @@ -3753,7 +3762,7 @@ mod tests { success_executable, &mut gas_meter, &mut storage_meter, - min_balance * 100, + (min_balance * 100).into(), vec![], Some(&[0; 32]), None, @@ -3765,7 +3774,7 @@ mod tests { succ_fail_executable, &mut gas_meter, &mut storage_meter, - min_balance * 200, + (min_balance * 200).into(), vec![], Some(&[0; 32]), None, @@ -3777,7 +3786,7 @@ mod tests { succ_succ_executable, &mut gas_meter, &mut storage_meter, - min_balance * 200, + (min_balance * 200).into(), vec![], Some(&[0; 32]), None, @@ -3846,7 +3855,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -3957,7 +3966,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -3996,7 +4005,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4035,7 +4044,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4088,7 +4097,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4144,7 +4153,7 @@ mod tests { BOB_ADDR, &mut gas_meter, &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4219,7 +4228,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4289,7 +4298,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -4327,7 +4336,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, )); @@ -4389,7 +4398,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -4422,7 +4431,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -4505,7 +4514,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -4573,7 +4582,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ); @@ -4639,7 +4648,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ); @@ -4690,7 +4699,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -4761,7 +4770,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -4807,7 +4816,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -4851,7 +4860,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![], None, ) @@ -4906,7 +4915,7 @@ mod tests { BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), &mut storage_meter, - 0, + U256::zero(), vec![0], None, ), diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index 5ca0042d929b..caecf07c4071 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -59,6 +59,7 @@ use frame_support::{ pallet_prelude::DispatchClass, traits::{ fungible::{Inspect, Mutate, MutateHold}, + tokens::{Fortitude::Polite, Preservation::Preserve}, ConstU32, ConstU64, Contains, EnsureOrigin, Get, IsType, OriginTrait, Time, }, weights::{Weight, WeightMeter}, @@ -73,7 +74,7 @@ use pallet_transaction_payment::OnChargeTransaction; use scale_info::TypeInfo; use sp_core::{H160, H256, U256}; use sp_runtime::{ - traits::{BadOrigin, Convert, Dispatchable, Saturating}, + traits::{BadOrigin, Convert, Dispatchable, Saturating, Zero}, DispatchError, }; @@ -379,7 +380,7 @@ pub mod pallet { type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>; type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>; type ChainId = ConstU64<0>; - type NativeToEthRatio = ConstU32<1_000_000>; + type NativeToEthRatio = ConstU32<1>; } } @@ -561,6 +562,8 @@ pub mod pallet { ExecutionFailed, /// Failed to convert a U256 to a Balance. BalanceConversionFailed, + /// Failed to convert an EVM balance to a native balance. + DecimalPrecisionLoss, /// Immutable data can only be set during deploys and only be read during calls. /// Additionally, it is only valid to set the data once and it must not be empty. InvalidImmutableAccess, @@ -1115,7 +1118,7 @@ where dest, &mut gas_meter, &mut storage_meter, - value, + Self::convert_native_to_evm(value), data, debug_message.as_mut(), )?; @@ -1180,7 +1183,7 @@ where executable, &mut gas_meter, &mut storage_meter, - value, + Self::convert_native_to_evm(value), data, salt.as_ref(), debug_message.as_mut(), @@ -1214,7 +1217,7 @@ where /// /// - `origin`: The origin of the call. /// - `dest`: The destination address of the call. - /// - `value`: The value to transfer. + /// - `value`: The EVM value to transfer. /// - `input`: The input data. /// - `gas_limit`: The gas limit enforced during contract execution. /// - `storage_deposit_limit`: The maximum balance that can be charged to the caller for storage @@ -1226,7 +1229,7 @@ where pub fn bare_eth_transact( origin: T::AccountId, dest: Option, - value: BalanceOf, + value: U256, input: Vec, gas_limit: Weight, storage_deposit_limit: BalanceOf, @@ -1250,6 +1253,18 @@ where // Get the nonce to encode in the tx. let nonce: T::Nonce = >::account_nonce(&origin); + // Convert the value to the native balance type. + let native_value = match Self::convert_evm_to_native(value) { + Ok(v) => v, + Err(err) => + return EthContractResult { + gas_required: Default::default(), + storage_deposit: Default::default(), + fee: Default::default(), + result: Err(err.into()), + }, + }; + // Dry run the call let (mut result, dispatch_info) = match dest { // A contract call. @@ -1258,13 +1273,14 @@ where let result = crate::Pallet::::bare_call( T::RuntimeOrigin::signed(origin), dest, - value, + native_value, gas_limit, storage_deposit_limit, input.clone(), debug, collect_events, ); + let result = EthContractResult { gas_required: result.gas_required, storage_deposit: result.storage_deposit.charge_or_zero(), @@ -1274,7 +1290,7 @@ where // Get the dispatch info of the call. let dispatch_call: ::RuntimeCall = crate::Call::::call { dest, - value, + value: native_value, gas_limit: result.gas_required, storage_deposit_limit: result.storage_deposit, data: input.clone(), @@ -1300,7 +1316,7 @@ where // Dry run the call. let result = crate::Pallet::::bare_instantiate( T::RuntimeOrigin::signed(origin), - value, + native_value, gas_limit, storage_deposit_limit, Code::Upload(code.to_vec()), @@ -1320,7 +1336,7 @@ where // Get the dispatch info of the call. let dispatch_call: ::RuntimeCall = crate::Call::::instantiate_with_code { - value, + value: native_value, gas_limit: result.gas_required, storage_deposit_limit: result.storage_deposit, code: code.to_vec(), @@ -1333,7 +1349,7 @@ where }; let mut tx = TransactionLegacyUnsigned { - value: value.into().saturating_mul(T::NativeToEthRatio::get().into()), + value, input: input.into(), nonce: nonce.into(), chain_id: Some(T::ChainId::get().into()), @@ -1372,6 +1388,12 @@ where result } + /// Get the balance with EVM decimals of the given `address`. + pub fn evm_balance(address: &H160) -> U256 { + let account = T::AddressMapper::to_account_id(&address); + Self::convert_native_to_evm(T::Currency::reducible_balance(&account, Preserve, Polite)) + } + /// A generalized version of [`Self::upload_code`]. /// /// It is identical to [`Self::upload_code`] and only differs in the information it returns. @@ -1424,6 +1446,25 @@ where .and_then(|r| r) }) } + + /// Convert a native balance to EVM balance. + fn convert_native_to_evm(value: BalanceOf) -> U256 { + value.into().saturating_mul(T::NativeToEthRatio::get().into()) + } + + /// Convert an EVM balance to a native balance. + fn convert_evm_to_native(value: U256) -> Result, Error> { + if value.is_zero() { + return Ok(Zero::zero()) + } + let ratio = T::NativeToEthRatio::get().into(); + let res = value.checked_div(ratio).expect("divisor is non-zero; qed"); + if res.saturating_mul(ratio) == value { + res.try_into().map_err(|_| Error::::BalanceConversionFailed) + } else { + Err(Error::::DecimalPrecisionLoss) + } + } } impl Pallet { @@ -1451,8 +1492,8 @@ sp_api::decl_runtime_apis! { BlockNumber: Codec, EventRecord: Codec, { - /// Returns the free balance of the given `[H160]` address. - fn balance(address: H160) -> Balance; + /// Returns the free balance of the given `[H160]` address, using EVM decimals. + fn balance(address: H160) -> U256; /// Returns the nonce of the given `[H160]` address. fn nonce(address: H160) -> Nonce; @@ -1489,7 +1530,7 @@ sp_api::decl_runtime_apis! { fn eth_transact( origin: H160, dest: Option, - value: Balance, + value: U256, input: Vec, gas_limit: Option, storage_deposit_limit: Option, From 8bea091ef131c8d962f45d89c28e17ece17bc5b2 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Fri, 15 Nov 2024 12:03:24 +0200 Subject: [PATCH 098/166] network/litep2p: Update litep2p network backend to version 0.8.1 (#6484) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR updates the litep2p backend to version 0.8.1 from 0.8.0. - Check the [litep2p updates forum post](https://forum.polkadot.network/t/litep2p-network-backend-updates/9973/3) for performance dashboards. - Check [litep2p release notes](https://github.com/paritytech/litep2p/pull/288) The v0.8.1 release includes key fixes that enhance the stability and performance of the litep2p library. The focus is on long-running stability and improvements to polling mechanisms. ### Long Running Stability Improvements This issue caused long-running nodes to reject all incoming connections, impacting overall stability. Addressed a bug in the connection limits functionality that incorrectly tracked connections due for rejection. This issue caused an artificial increase in inbound peers, which were not being properly removed from the connection limit count. This fix ensures more accurate tracking and management of peer connections [#286](https://github.com/paritytech/litep2p/pull/286). ### Polling implementation fixes This release provides multiple fixes to the polling mechanism, improving how connections and events are processed: - Resolved an overflow issue in TransportContext’s polling index for streams, preventing potential crashes ([#283](https://github.com/paritytech/litep2p/pull/283)). - Fixed a delay in the manager’s poll_next function that prevented immediate polling of newly added futures ([#287](https://github.com/paritytech/litep2p/pull/287)). - Corrected an issue where the listener did not return Poll::Ready(None) when it was closed, ensuring proper signal handling ([#285](https://github.com/paritytech/litep2p/pull/285)). ### Fixed - manager: Fix connection limits tracking of rejected connections ([#286](https://github.com/paritytech/litep2p/pull/286)) - transport: Fix waking up on filtered events from `poll_next` ([#287](https://github.com/paritytech/litep2p/pull/287)) - transports: Fix missing Poll::Ready(None) event from listener ([#285](https://github.com/paritytech/litep2p/pull/285)) - manager: Avoid overflow on stream implementation for `TransportContext` ([#283](https://github.com/paritytech/litep2p/pull/283)) - manager: Log when polling returns Ready(None) ([#284](https://github.com/paritytech/litep2p/pull/284)) ### Testing Done Started kusama nodes running side by side with a higher number of inbound and outbound connections (500). We previously tested with peers bounded at 50. This testing filtered out the fixes included in the latest release. With this high connection testing setup, litep2p outperforms libp2p in almost every domain, from performance to the warnings / errors encountered while operating the nodes. TLDR: this is the version we need to test on kusama validators next - Litep2p Repo | Count | Level | Triage report -|-|-|- polkadot-sdk | 409 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Peer disconnected with inflight after backoffs. Banned, disconnecting. ) litep2p | 128 | warn | Refusing to add known address that corresponds to a different peer ID litep2p | 54 | warn | inbound identify substream opened for peer who doesn't exist polkadot-sdk | 7 | error | 💔 Called `on_validated_block_announce` with a bad peer ID .* polkadot-sdk | 1 | warn | ❌ Error while dialing .*: .* polkadot-sdk | 1 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Invalid justification. Banned, disconnecting. ) - Libp2p Repo | Count | Level | Triage report -|-|-|- polkadot-sdk | 1023 | warn | 💔 Ignored block \(#.* -- .*\) announcement from .* because all validation slots are occupied. polkadot-sdk | 472 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Unsupported protocol. Banned, disconnecting. ) polkadot-sdk | 379 | error | 💔 Called `on_validated_block_announce` with a bad peer ID .* polkadot-sdk | 163 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Invalid justification. Banned, disconnecting. ) polkadot-sdk | 116 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Peer disconnected with inflight after backoffs. Banned, disconnecting. ) polkadot-sdk | 83 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Same block request multiple times. Banned, disconnecting. ) polkadot-sdk | 4 | warn | Re-finalized block #.* \(.*\) in the canonical chain, current best finalized is #.* polkadot-sdk | 2 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Genesis mismatch. Banned, disconnecting. ) polkadot-sdk | 2 | warn | Report .*: .* to .*. Reason: .*. Banned, disconnecting. ( Not requested block data. Banned, disconnecting. ) polkadot-sdk | 2 | warn | Can't listen on .* because: .* polkadot-sdk | 1 | warn | ❌ Error while dialing .*: .* --------- Signed-off-by: Alexandru Vasile --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- prdoc/pr_6484.prdoc | 10 ++++++++++ substrate/client/network/src/litep2p/mod.rs | 8 +++++++- 4 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 prdoc/pr_6484.prdoc diff --git a/Cargo.lock b/Cargo.lock index 775a7fe99e1e..182d8f6bacad 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10194,9 +10194,9 @@ dependencies = [ [[package]] name = "litep2p" -version = "0.8.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7286b1971f85d1d60be40ef49e81c1f3b5a0d8b83cfa02ab53591cdacae22901" +checksum = "5b67484b8ac41e1cfdf012f65fa81e88c2ef5f8a7d6dec0e2678c2d06dc04530" dependencies = [ "async-trait", "bs58", @@ -20402,7 +20402,7 @@ checksum = "f8650aabb6c35b860610e9cff5dc1af886c9e25073b7b1712a68972af4281302" dependencies = [ "bytes", "heck 0.5.0", - "itertools 0.12.1", + "itertools 0.13.0", "log", "multimap", "once_cell", @@ -20448,7 +20448,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acf0c195eebb4af52c752bec4f52f645da98b6e92077a04110c7f349477ae5ac" dependencies = [ "anyhow", - "itertools 0.12.1", + "itertools 0.13.0", "proc-macro2 1.0.86", "quote 1.0.37", "syn 2.0.87", diff --git a/Cargo.toml b/Cargo.toml index b0be2950641d..533ea4c9e878 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -848,7 +848,7 @@ linked-hash-map = { version = "0.5.4" } linked_hash_set = { version = "0.1.4" } linregress = { version = "0.5.1" } lite-json = { version = "0.2.0", default-features = false } -litep2p = { version = "0.8.0", features = ["websocket"] } +litep2p = { version = "0.8.1", features = ["websocket"] } log = { version = "0.4.22", default-features = false } macro_magic = { version = "0.5.1" } maplit = { version = "1.0.2" } diff --git a/prdoc/pr_6484.prdoc b/prdoc/pr_6484.prdoc new file mode 100644 index 000000000000..c212692e6ab4 --- /dev/null +++ b/prdoc/pr_6484.prdoc @@ -0,0 +1,10 @@ +title: Update litep2p network backend to version 0.8.1 + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + Release 0.8.1 of litep2p includes critical fixes to further enhance the stability and performance of the litep2p network backend. + +crates: + - name: sc-network + bump: patch diff --git a/substrate/client/network/src/litep2p/mod.rs b/substrate/client/network/src/litep2p/mod.rs index 15501dab688b..10cf9f4da36d 100644 --- a/substrate/client/network/src/litep2p/mod.rs +++ b/substrate/client/network/src/litep2p/mod.rs @@ -1074,7 +1074,13 @@ impl NetworkBackend for Litep2pNetworkBac metrics.pending_connections_errors_total.with_label_values(&["transport-errors"]).inc(); } } - _ => {} + None => { + log::error!( + target: LOG_TARGET, + "Litep2p backend terminated" + ); + return + } }, } } From a77940bac783108fcae783c553528c8d5328e5b2 Mon Sep 17 00:00:00 2001 From: Tobi Demeco <50408393+TDemeco@users.noreply.github.com> Date: Fri, 15 Nov 2024 07:09:59 -0300 Subject: [PATCH 099/166] sp-trie: minor fix to avoid possible panic during node decoding (#6486) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description This PR is a simple fix consisting of adding a check to the process of decoding nodes of a storage proof to avoid panicking when receiving badly-constructed proofs, returning an error instead. This would close #6485 ## Integration No changes have to be done downstream, and as such the version bump should be minor. --------- Co-authored-by: Bastian Köcher --- prdoc/pr_6486.prdoc | 10 ++++++++++ substrate/primitives/trie/src/node_codec.rs | 8 ++++++++ 2 files changed, 18 insertions(+) create mode 100644 prdoc/pr_6486.prdoc diff --git a/prdoc/pr_6486.prdoc b/prdoc/pr_6486.prdoc new file mode 100644 index 000000000000..e401d3f9a887 --- /dev/null +++ b/prdoc/pr_6486.prdoc @@ -0,0 +1,10 @@ +title: "sp-trie: minor fix to avoid panic on badly-constructed proof" + +doc: + - audience: ["Runtime Dev", "Runtime User"] + description: | + "Added a check when decoding encoded proof nodes in `sp-trie` to avoid panicking when receiving a badly constructed proof, instead erroring out." + +crates: +- name: sp-trie + bump: patch diff --git a/substrate/primitives/trie/src/node_codec.rs b/substrate/primitives/trie/src/node_codec.rs index 78896988ec4c..27da0c6334a2 100644 --- a/substrate/primitives/trie/src/node_codec.rs +++ b/substrate/primitives/trie/src/node_codec.rs @@ -110,6 +110,10 @@ where NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; + // data should be at least the size of the offset + if data.len() < input.offset { + return Err(Error::BadFormat) + } // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(Error::BadFormat) @@ -154,6 +158,10 @@ where }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; + // data should be at least the size of the offset + if data.len() < input.offset { + return Err(Error::BadFormat) + } // check that the padding is valid (if any) if padding && nibble_ops::pad_left(data[input.offset]) != 0 { return Err(Error::BadFormat) From 4df94333119b507e79032af613824b1ddfcd55ed Mon Sep 17 00:00:00 2001 From: clangenb <37865735+clangenb@users.noreply.github.com> Date: Fri, 15 Nov 2024 16:59:44 +0100 Subject: [PATCH 100/166] migrate pallet-nomination-pool-benchmarking to benchmarking syntax v2 (#6302) Migrates pallet-nomination-pool-benchmarking to benchmarking syntax v2. Part of: * #6202 --------- Co-authored-by: GitHub Action Co-authored-by: Guillaume Thiolliere Co-authored-by: Giuseppe Re --- prdoc/pr_6302.prdoc | 8 + .../benchmarking/src/inner.rs | 687 +++++++++++------- 2 files changed, 433 insertions(+), 262 deletions(-) create mode 100644 prdoc/pr_6302.prdoc diff --git a/prdoc/pr_6302.prdoc b/prdoc/pr_6302.prdoc new file mode 100644 index 000000000000..8b3e0964b6a6 --- /dev/null +++ b/prdoc/pr_6302.prdoc @@ -0,0 +1,8 @@ +title: migrate pallet-nomination-pool-benchmarking to benchmarking syntax v2 +doc: +- audience: Runtime Dev + description: |- + migrate pallet-nomination-pool-benchmarking to benchmarking syntax v2 +crates: +- name: pallet-nomination-pools-benchmarking + bump: patch diff --git a/substrate/frame/nomination-pools/benchmarking/src/inner.rs b/substrate/frame/nomination-pools/benchmarking/src/inner.rs index b0c8f3655a50..7ddb78cca3f9 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/inner.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/inner.rs @@ -18,7 +18,7 @@ //! Benchmarks for the nomination pools coupled with the staking and bags list pallets. use alloc::{vec, vec::Vec}; -use frame_benchmarking::v1::{account, whitelist_account}; +use frame_benchmarking::v2::*; use frame_election_provider_support::SortedListProvider; use frame_support::{ assert_ok, ensure, @@ -270,19 +270,21 @@ impl ListScenario { } } -frame_benchmarking::benchmarks! { - where_clause { - where - T: pallet_staking::Config, - pallet_staking::BalanceOf: From, - BalanceOf: Into, - } - - join { +#[benchmarks( + where + T: pallet_staking::Config, + pallet_staking::BalanceOf: From, + BalanceOf: Into, +)] +mod benchmarks { + use super::*; + + #[benchmark] + fn join() { let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); // setup the worst case list scenario. - let scenario = ListScenario::::new(origin_weight, true)?; + let scenario = ListScenario::::new(origin_weight, true).unwrap(); assert_eq!( T::StakeAdapter::active_stake(Pool::from(scenario.origin1.clone())), origin_weight @@ -291,12 +293,13 @@ frame_benchmarking::benchmarks! { let max_additional = scenario.dest_weight - origin_weight; let joiner_free = CurrencyOf::::minimum_balance() + max_additional; - let joiner: T::AccountId - = create_funded_user_with_balance::("joiner", 0, joiner_free); + let joiner: T::AccountId = create_funded_user_with_balance::("joiner", 0, joiner_free); whitelist_account!(joiner); - }: _(RuntimeOrigin::Signed(joiner.clone()), max_additional, 1) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(joiner.clone()), max_additional, 1); + assert_eq!(CurrencyOf::::balance(&joiner), joiner_free - max_additional); assert_eq!( T::StakeAdapter::active_stake(Pool::from(scenario.origin1)), @@ -304,51 +307,64 @@ frame_benchmarking::benchmarks! { ); } - bond_extra_transfer { + #[benchmark] + fn bond_extra_transfer() { let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); - let scenario = ListScenario::::new(origin_weight, true)?; + let scenario = ListScenario::::new(origin_weight, true).unwrap(); let extra = scenario.dest_weight - origin_weight; // creator of the src pool will bond-extra, bumping itself to dest bag. - }: bond_extra(RuntimeOrigin::Signed(scenario.creator1.clone()), BondExtra::FreeBalance(extra)) - verify { + #[extrinsic_call] + bond_extra(RuntimeOrigin::Signed(scenario.creator1.clone()), BondExtra::FreeBalance(extra)); + assert!( - T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) >= - scenario.dest_weight + T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) >= scenario.dest_weight ); } - bond_extra_other { + #[benchmark] + fn bond_extra_other() { let claimer: T::AccountId = account("claimer", USER_SEED + 4, 0); let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); - let scenario = ListScenario::::new(origin_weight, true)?; + let scenario = ListScenario::::new(origin_weight, true).unwrap(); let extra = (scenario.dest_weight - origin_weight).max(CurrencyOf::::minimum_balance()); - // set claim preferences to `PermissionlessAll` to any account to bond extra on member's behalf. - let _ = Pools::::set_claim_permission(RuntimeOrigin::Signed(scenario.creator1.clone()).into(), ClaimPermission::PermissionlessAll); + // set claim preferences to `PermissionlessAll` to any account to bond extra on member's + // behalf. + let _ = Pools::::set_claim_permission( + RuntimeOrigin::Signed(scenario.creator1.clone()).into(), + ClaimPermission::PermissionlessAll, + ); // transfer exactly `extra` to the depositor of the src pool (1), let reward_account1 = Pools::::generate_reward_account(1); assert!(extra >= CurrencyOf::::minimum_balance()); let _ = CurrencyOf::::mint_into(&reward_account1, extra); - }: _(RuntimeOrigin::Signed(claimer), T::Lookup::unlookup(scenario.creator1.clone()), BondExtra::Rewards) - verify { - // commission of 50% deducted here. + #[extrinsic_call] + _( + RuntimeOrigin::Signed(claimer), + T::Lookup::unlookup(scenario.creator1.clone()), + BondExtra::Rewards, + ); + + // commission of 50% deducted here. assert!( T::StakeAdapter::active_stake(Pool::from(scenario.origin1)) >= - scenario.dest_weight / 2u32.into() + scenario.dest_weight / 2u32.into() ); } - claim_payout { + #[benchmark] + fn claim_payout() { let claimer: T::AccountId = account("claimer", USER_SEED + 4, 0); let commission = Perbill::from_percent(50); let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); let ed = CurrencyOf::::minimum_balance(); - let (depositor, pool_account) = create_pool_account::(0, origin_weight, Some(commission)); + let (depositor, _pool_account) = + create_pool_account::(0, origin_weight, Some(commission)); let reward_account = Pools::::generate_reward_account(1); // Send funds to the reward account of the pool @@ -356,33 +372,32 @@ frame_benchmarking::benchmarks! { // set claim preferences to `PermissionlessAll` so any account can claim rewards on member's // behalf. - let _ = Pools::::set_claim_permission(RuntimeOrigin::Signed(depositor.clone()).into(), ClaimPermission::PermissionlessAll); + let _ = Pools::::set_claim_permission( + RuntimeOrigin::Signed(depositor.clone()).into(), + ClaimPermission::PermissionlessAll, + ); // Sanity check - assert_eq!( - CurrencyOf::::balance(&depositor), - origin_weight - ); + assert_eq!(CurrencyOf::::balance(&depositor), origin_weight); whitelist_account!(depositor); - }:claim_payout_other(RuntimeOrigin::Signed(claimer), depositor.clone()) - verify { + + #[extrinsic_call] + claim_payout_other(RuntimeOrigin::Signed(claimer), depositor.clone()); + assert_eq!( CurrencyOf::::balance(&depositor), origin_weight + commission * origin_weight ); - assert_eq!( - CurrencyOf::::balance(&reward_account), - ed + commission * origin_weight - ); + assert_eq!(CurrencyOf::::balance(&reward_account), ed + commission * origin_weight); } - - unbond { + #[benchmark] + fn unbond() { // The weight the nominator will start at. The value used here is expected to be // significantly higher than the first position in a list (e.g. the first bag threshold). let origin_weight = Pools::::depositor_min_bond() * 200u32.into(); - let scenario = ListScenario::::new(origin_weight, false)?; + let scenario = ListScenario::::new(origin_weight, false).unwrap(); let amount = origin_weight - scenario.dest_weight; let scenario = scenario.add_joiner(amount); @@ -390,36 +405,30 @@ frame_benchmarking::benchmarks! { let member_id_lookup = T::Lookup::unlookup(member_id.clone()); let all_points = PoolMembers::::get(&member_id).unwrap().points; whitelist_account!(member_id); - }: _(RuntimeOrigin::Signed(member_id.clone()), member_id_lookup, all_points) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(member_id.clone()), member_id_lookup, all_points); + let bonded_after = T::StakeAdapter::active_stake(Pool::from(scenario.origin1)); // We at least went down to the destination bag assert!(bonded_after <= scenario.dest_weight); - let member = PoolMembers::::get( - &member_id - ) - .unwrap(); + let member = PoolMembers::::get(&member_id).unwrap(); assert_eq!( member.unbonding_eras.keys().cloned().collect::>(), vec![0 + T::StakeAdapter::bonding_duration()] ); - assert_eq!( - member.unbonding_eras.values().cloned().collect::>(), - vec![all_points] - ); + assert_eq!(member.unbonding_eras.values().cloned().collect::>(), vec![all_points]); } - pool_withdraw_unbonded { - let s in 0 .. MAX_SPANS; - + #[benchmark] + fn pool_withdraw_unbonded(s: Linear<0, MAX_SPANS>) { let min_create_bond = Pools::::depositor_min_bond(); - let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); + let (_depositor, pool_account) = create_pool_account::(0, min_create_bond, None); // Add a new member let min_join_bond = MinJoinBond::::get().max(CurrencyOf::::minimum_balance()); let joiner = create_funded_user_with_balance::("joiner", 0, min_join_bond * 2u32.into()); - Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1) - .unwrap(); + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1).unwrap(); // Sanity check join worked assert_eq!( @@ -429,7 +438,8 @@ frame_benchmarking::benchmarks! { assert_eq!(CurrencyOf::::balance(&joiner), min_join_bond); // Unbond the new member - Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); + Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()) + .unwrap(); // Sanity check that unbond worked assert_eq!( @@ -443,26 +453,26 @@ frame_benchmarking::benchmarks! { // Add `s` count of slashing spans to storage. pallet_staking::benchmarking::add_slashing_spans::(&pool_account, s); whitelist_account!(pool_account); - }: _(RuntimeOrigin::Signed(pool_account.clone()), 1, s) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(pool_account.clone()), 1, s); + // The joiners funds didn't change assert_eq!(CurrencyOf::::balance(&joiner), min_join_bond); // The unlocking chunk was removed assert_eq!(pallet_staking::Ledger::::get(pool_account).unwrap().unlocking.len(), 0); } - withdraw_unbonded_update { - let s in 0 .. MAX_SPANS; - + #[benchmark] + fn withdraw_unbonded_update(s: Linear<0, MAX_SPANS>) { let min_create_bond = Pools::::depositor_min_bond(); - let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); + let (_depositor, pool_account) = create_pool_account::(0, min_create_bond, None); // Add a new member let min_join_bond = MinJoinBond::::get().max(CurrencyOf::::minimum_balance()); let joiner = create_funded_user_with_balance::("joiner", 0, min_join_bond * 2u32.into()); let joiner_lookup = T::Lookup::unlookup(joiner.clone()); - Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1) - .unwrap(); + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1).unwrap(); // Sanity check join worked assert_eq!( @@ -473,7 +483,8 @@ frame_benchmarking::benchmarks! { // Unbond the new member pallet_staking::CurrentEra::::put(0); - Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()).unwrap(); + Pools::::fully_unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner.clone()) + .unwrap(); // Sanity check that unbond worked assert_eq!( @@ -487,18 +498,17 @@ frame_benchmarking::benchmarks! { pallet_staking::benchmarking::add_slashing_spans::(&pool_account, s); whitelist_account!(joiner); - }: withdraw_unbonded(RuntimeOrigin::Signed(joiner.clone()), joiner_lookup, s) - verify { - assert_eq!( - CurrencyOf::::balance(&joiner), min_join_bond * 2u32.into() - ); + + #[extrinsic_call] + withdraw_unbonded(RuntimeOrigin::Signed(joiner.clone()), joiner_lookup, s); + + assert_eq!(CurrencyOf::::balance(&joiner), min_join_bond * 2u32.into()); // The unlocking chunk was removed assert_eq!(pallet_staking::Ledger::::get(&pool_account).unwrap().unlocking.len(), 0); } - withdraw_unbonded_kill { - let s in 0 .. MAX_SPANS; - + #[benchmark] + fn withdraw_unbonded_kill(s: Linear<0, MAX_SPANS>) { let min_create_bond = Pools::::depositor_min_bond(); let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); @@ -519,13 +529,14 @@ frame_benchmarking::benchmarks! { // up when unbonding. let reward_account = Pools::::generate_reward_account(1); assert!(frame_system::Account::::contains_key(&reward_account)); - Pools::::fully_unbond(RuntimeOrigin::Signed(depositor.clone()).into(), depositor.clone()).unwrap(); + Pools::::fully_unbond( + RuntimeOrigin::Signed(depositor.clone()).into(), + depositor.clone(), + ) + .unwrap(); // Sanity check that unbond worked - assert_eq!( - T::StakeAdapter::active_stake(Pool::from(pool_account.clone())), - Zero::zero() - ); + assert_eq!(T::StakeAdapter::active_stake(Pool::from(pool_account.clone())), Zero::zero()); assert_eq!( T::StakeAdapter::total_balance(Pool::from(pool_account.clone())), Some(min_create_bond) @@ -544,8 +555,10 @@ frame_benchmarking::benchmarks! { assert!(frame_system::Account::::contains_key(&reward_account)); whitelist_account!(depositor); - }: withdraw_unbonded(RuntimeOrigin::Signed(depositor.clone()), depositor_lookup, s) - verify { + + #[extrinsic_call] + withdraw_unbonded(RuntimeOrigin::Signed(depositor.clone()), depositor_lookup, s); + // Pool removal worked assert!(!pallet_staking::Ledger::::contains_key(&pool_account)); assert!(!BondedPools::::contains_key(&1)); @@ -563,27 +576,34 @@ frame_benchmarking::benchmarks! { ); } - create { + #[benchmark] + fn create() { let min_create_bond = Pools::::depositor_min_bond(); let depositor: T::AccountId = account("depositor", USER_SEED, 0); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); // Give the depositor some balance to bond - // it needs to transfer min balance to reward account as well so give additional min balance. - CurrencyOf::::set_balance(&depositor, min_create_bond + CurrencyOf::::minimum_balance() * 2u32.into()); + // it needs to transfer min balance to reward account as well so give additional min + // balance. + CurrencyOf::::set_balance( + &depositor, + min_create_bond + CurrencyOf::::minimum_balance() * 2u32.into(), + ); // Make sure no Pools exist at a pre-condition for our verify checks assert_eq!(RewardPools::::count(), 0); assert_eq!(BondedPools::::count(), 0); whitelist_account!(depositor); - }: _( + + #[extrinsic_call] + _( RuntimeOrigin::Signed(depositor.clone()), min_create_bond, depositor_lookup.clone(), depositor_lookup.clone(), - depositor_lookup - ) - verify { + depositor_lookup, + ); + assert_eq!(RewardPools::::count(), 1); assert_eq!(BondedPools::::count(), 1); let (_, new_pool) = BondedPools::::iter().next().unwrap(); @@ -608,22 +628,21 @@ frame_benchmarking::benchmarks! { ); } - nominate { - let n in 1 .. MaxNominationsOf::::get(); - + #[benchmark] + fn nominate(n: Linear<1, { MaxNominationsOf::::get() }>) { // Create a pool let min_create_bond = Pools::::depositor_min_bond() * 2u32.into(); - let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); + let (depositor, _pool_account) = create_pool_account::(0, min_create_bond, None); // Create some accounts to nominate. For the sake of benchmarking they don't need to be // actual validators - let validators: Vec<_> = (0..n) - .map(|i| account("stash", USER_SEED, i)) - .collect(); + let validators: Vec<_> = (0..n).map(|i| account("stash", USER_SEED, i)).collect(); whitelist_account!(depositor); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1, validators) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor.clone()), 1, validators); + assert_eq!(RewardPools::::count(), 1); assert_eq!(BondedPools::::count(), 1); let (_, new_pool) = BondedPools::::iter().next().unwrap(); @@ -648,10 +667,12 @@ frame_benchmarking::benchmarks! { ); } - set_state { + #[benchmark] + fn set_state() { // Create a pool let min_create_bond = Pools::::depositor_min_bond(); - let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); + // Don't need the accounts, but the pool. + let _ = create_pool_account::(0, min_create_bond, None); BondedPools::::mutate(&1, |maybe_pool| { // Force the pool into an invalid state maybe_pool.as_mut().map(|pool| pool.points = min_create_bond * 10u32.into()); @@ -659,36 +680,44 @@ frame_benchmarking::benchmarks! { let caller = account("caller", 0, USER_SEED); whitelist_account!(caller); - }:_(RuntimeOrigin::Signed(caller), 1, PoolState::Destroying) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(caller), 1, PoolState::Destroying); + assert_eq!(BondedPools::::get(1).unwrap().state, PoolState::Destroying); } - set_metadata { - let n in 1 .. ::MaxMetadataLen::get(); - + #[benchmark] + fn set_metadata( + n: Linear<1, { ::MaxMetadataLen::get() }>, + ) { // Create a pool - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + let (depositor, _pool_account) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); // Create metadata of the max possible size let metadata: Vec = (0..n).map(|_| 42).collect(); whitelist_account!(depositor); - }:_(RuntimeOrigin::Signed(depositor), 1, metadata.clone()) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor), 1, metadata.clone()); assert_eq!(Metadata::::get(&1), metadata); } - set_configs { - }:_( - RuntimeOrigin::Root, - ConfigOp::Set(BalanceOf::::max_value()), - ConfigOp::Set(BalanceOf::::max_value()), - ConfigOp::Set(u32::MAX), - ConfigOp::Set(u32::MAX), - ConfigOp::Set(u32::MAX), - ConfigOp::Set(Perbill::max_value()) - ) verify { + #[benchmark] + fn set_configs() { + #[extrinsic_call] + _( + RuntimeOrigin::Root, + ConfigOp::Set(BalanceOf::::max_value()), + ConfigOp::Set(BalanceOf::::max_value()), + ConfigOp::Set(u32::MAX), + ConfigOp::Set(u32::MAX), + ConfigOp::Set(u32::MAX), + ConfigOp::Set(Perbill::max_value()), + ); + assert_eq!(MinJoinBond::::get(), BalanceOf::::max_value()); assert_eq!(MinCreateBond::::get(), BalanceOf::::max_value()); assert_eq!(MaxPools::::get(), Some(u32::MAX)); @@ -697,17 +726,22 @@ frame_benchmarking::benchmarks! { assert_eq!(GlobalMaxCommission::::get(), Some(Perbill::max_value())); } - update_roles { + #[benchmark] + fn update_roles() { let first_id = pallet_nomination_pools::LastPoolId::::get() + 1; - let (root, _) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); - let random: T::AccountId = account("but is anything really random in computers..?", 0, USER_SEED); - }:_( - RuntimeOrigin::Signed(root.clone()), - first_id, - ConfigOp::Set(random.clone()), - ConfigOp::Set(random.clone()), - ConfigOp::Set(random.clone()) - ) verify { + let (root, _) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + let random: T::AccountId = + account("but is anything really random in computers..?", 0, USER_SEED); + + #[extrinsic_call] + _( + RuntimeOrigin::Signed(root.clone()), + first_id, + ConfigOp::Set(random.clone()), + ConfigOp::Set(random.clone()), + ConfigOp::Set(random.clone()), + ); assert_eq!( pallet_nomination_pools::BondedPools::::get(first_id).unwrap().roles, pallet_nomination_pools::PoolRoles { @@ -719,12 +753,14 @@ frame_benchmarking::benchmarks! { ) } - chill { + #[benchmark] + fn chill() { // Create a pool - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + let (depositor, pool_account) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); // Nominate with the pool. - let validators: Vec<_> = (0..MaxNominationsOf::::get()) + let validators: Vec<_> = (0..MaxNominationsOf::::get()) .map(|i| account("stash", USER_SEED, i)) .collect(); @@ -732,121 +768,176 @@ frame_benchmarking::benchmarks! { assert!(T::StakeAdapter::nominations(Pool::from(pool_account.clone())).is_some()); whitelist_account!(depositor); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor.clone()), 1); + assert!(T::StakeAdapter::nominations(Pool::from(pool_account.clone())).is_none()); } - set_commission { + #[benchmark] + fn set_commission() { // Create a pool - do not set a commission yet. - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + let (depositor, _pool_account) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); // set a max commission - Pools::::set_commission_max(RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into(), Perbill::from_percent(50)).unwrap(); + Pools::::set_commission_max( + RuntimeOrigin::Signed(depositor.clone()).into(), + 1u32.into(), + Perbill::from_percent(50), + ) + .unwrap(); // set a change rate - Pools::::set_commission_change_rate(RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into(), CommissionChangeRate { - max_increase: Perbill::from_percent(20), - min_delay: 0u32.into(), - }).unwrap(); + Pools::::set_commission_change_rate( + RuntimeOrigin::Signed(depositor.clone()).into(), + 1u32.into(), + CommissionChangeRate { + max_increase: Perbill::from_percent(20), + min_delay: 0u32.into(), + }, + ) + .unwrap(); // set a claim permission to an account. Pools::::set_commission_claim_permission( RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into(), - Some(CommissionClaimPermission::Account(depositor.clone())) - ).unwrap(); - - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Some((Perbill::from_percent(20), depositor.clone()))) - verify { - assert_eq!(BondedPools::::get(1).unwrap().commission, Commission { - current: Some((Perbill::from_percent(20), depositor.clone())), - max: Some(Perbill::from_percent(50)), - change_rate: Some(CommissionChangeRate { + Some(CommissionClaimPermission::Account(depositor.clone())), + ) + .unwrap(); + + #[extrinsic_call] + _( + RuntimeOrigin::Signed(depositor.clone()), + 1u32.into(), + Some((Perbill::from_percent(20), depositor.clone())), + ); + + assert_eq!( + BondedPools::::get(1).unwrap().commission, + Commission { + current: Some((Perbill::from_percent(20), depositor.clone())), + max: Some(Perbill::from_percent(50)), + change_rate: Some(CommissionChangeRate { max_increase: Perbill::from_percent(20), min_delay: 0u32.into() - }), - throttle_from: Some(1u32.into()), - claim_permission: Some(CommissionClaimPermission::Account(depositor)), - }); + }), + throttle_from: Some(1u32.into()), + claim_permission: Some(CommissionClaimPermission::Account(depositor)), + } + ); } - set_commission_max { + #[benchmark] + fn set_commission_max() { // Create a pool, setting a commission that will update when max commission is set. - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), Some(Perbill::from_percent(50))); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Perbill::from_percent(50)) - verify { + let (depositor, _pool_account) = create_pool_account::( + 0, + Pools::::depositor_min_bond() * 2u32.into(), + Some(Perbill::from_percent(50)), + ); + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Perbill::from_percent(50)); + assert_eq!( - BondedPools::::get(1).unwrap().commission, Commission { - current: Some((Perbill::from_percent(50), depositor)), - max: Some(Perbill::from_percent(50)), - change_rate: None, - throttle_from: Some(0u32.into()), - claim_permission: None, - }); + BondedPools::::get(1).unwrap().commission, + Commission { + current: Some((Perbill::from_percent(50), depositor)), + max: Some(Perbill::from_percent(50)), + change_rate: None, + throttle_from: Some(0u32.into()), + claim_permission: None, + } + ); } - set_commission_change_rate { + #[benchmark] + fn set_commission_change_rate() { // Create a pool - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), CommissionChangeRate { - max_increase: Perbill::from_percent(50), - min_delay: 1000u32.into(), - }) - verify { - assert_eq!( - BondedPools::::get(1).unwrap().commission, Commission { - current: None, - max: None, - change_rate: Some(CommissionChangeRate { + let (depositor, _pool_account) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + + #[extrinsic_call] + _( + RuntimeOrigin::Signed(depositor.clone()), + 1u32.into(), + CommissionChangeRate { max_increase: Perbill::from_percent(50), min_delay: 1000u32.into(), - }), - throttle_from: Some(1_u32.into()), - claim_permission: None, - }); - } + }, + ); + + assert_eq!( + BondedPools::::get(1).unwrap().commission, + Commission { + current: None, + max: None, + change_rate: Some(CommissionChangeRate { + max_increase: Perbill::from_percent(50), + min_delay: 1000u32.into(), + }), + throttle_from: Some(1_u32.into()), + claim_permission: None, + } + ); + } - set_commission_claim_permission { + #[benchmark] + fn set_commission_claim_permission() { // Create a pool. - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Some(CommissionClaimPermission::Account(depositor.clone()))) - verify { + let (depositor, _pool_account) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + + #[extrinsic_call] + _( + RuntimeOrigin::Signed(depositor.clone()), + 1u32.into(), + Some(CommissionClaimPermission::Account(depositor.clone())), + ); + assert_eq!( - BondedPools::::get(1).unwrap().commission, Commission { - current: None, - max: None, - change_rate: None, - throttle_from: None, - claim_permission: Some(CommissionClaimPermission::Account(depositor)), - }); + BondedPools::::get(1).unwrap().commission, + Commission { + current: None, + max: None, + change_rate: None, + throttle_from: None, + claim_permission: Some(CommissionClaimPermission::Account(depositor)), + } + ); } - set_claim_permission { + #[benchmark] + fn set_claim_permission() { // Create a pool let min_create_bond = Pools::::depositor_min_bond(); - let (depositor, pool_account) = create_pool_account::(0, min_create_bond, None); + let (_depositor, pool_account) = create_pool_account::(0, min_create_bond, None); // Join pool let min_join_bond = MinJoinBond::::get().max(CurrencyOf::::minimum_balance()); let joiner = create_funded_user_with_balance::("joiner", 0, min_join_bond * 4u32.into()); - let joiner_lookup = T::Lookup::unlookup(joiner.clone()); - Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1) - .unwrap(); + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), min_join_bond, 1).unwrap(); // Sanity check join worked assert_eq!( T::StakeAdapter::active_stake(Pool::from(pool_account.clone())), min_create_bond + min_join_bond ); - }:_(RuntimeOrigin::Signed(joiner.clone()), ClaimPermission::Permissioned) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(joiner.clone()), ClaimPermission::Permissioned); + assert_eq!(ClaimPermissions::::get(joiner), ClaimPermission::Permissioned); } - claim_commission { + #[benchmark] + fn claim_commission() { let claimer: T::AccountId = account("claimer_member", USER_SEED + 4, 0); let commission = Perbill::from_percent(50); let origin_weight = Pools::::depositor_min_bond() * 2u32.into(); let ed = CurrencyOf::::minimum_balance(); - let (depositor, pool_account) = create_pool_account::(0, origin_weight, Some(commission)); + let (depositor, _pool_account) = + create_pool_account::(0, origin_weight, Some(commission)); let reward_account = Pools::::generate_reward_account(1); CurrencyOf::::set_balance(&reward_account, ed + origin_weight); @@ -856,52 +947,60 @@ frame_benchmarking::benchmarks! { let _ = Pools::::set_commission_claim_permission( RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into(), - Some(CommissionClaimPermission::Account(claimer)) + Some(CommissionClaimPermission::Account(claimer)), ); whitelist_account!(depositor); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into()) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor.clone()), 1u32.into()); + assert_eq!( CurrencyOf::::balance(&depositor), origin_weight + commission * origin_weight ); - assert_eq!( - CurrencyOf::::balance(&reward_account), - ed + commission * origin_weight - ); + assert_eq!(CurrencyOf::::balance(&reward_account), ed + commission * origin_weight); } - adjust_pool_deposit { + #[benchmark] + fn adjust_pool_deposit() { // Create a pool - let (depositor, _) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); + let (depositor, _) = + create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); // Remove ed freeze to create a scenario where the ed deposit needs to be adjusted. let _ = Pools::::unfreeze_pool_deposit(&Pools::::generate_reward_account(1)); assert!(&Pools::::check_ed_imbalance().is_err()); whitelist_account!(depositor); - }:_(RuntimeOrigin::Signed(depositor), 1) - verify { + + #[extrinsic_call] + _(RuntimeOrigin::Signed(depositor), 1); + assert!(&Pools::::check_ed_imbalance().is_ok()); } - apply_slash { + #[benchmark] + fn apply_slash() { // Note: With older `TransferStake` strategy, slashing is greedy and apply_slash should // always fail. // We want to fill member's unbonding pools. So let's bond with big enough amount. - let deposit_amount = Pools::::depositor_min_bond() * T::MaxUnbonding::get().into() * 4u32.into(); + let deposit_amount = + Pools::::depositor_min_bond() * T::MaxUnbonding::get().into() * 4u32.into(); let (depositor, pool_account) = create_pool_account::(0, deposit_amount, None); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); // verify user balance in the pool. assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount); // verify delegated balance. - assert_if_delegate::(T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == Some(deposit_amount)); + assert_if_delegate::( + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == + Some(deposit_amount), + ); // ugly type conversion between balances of pallet staking and pools (which really are same // type). Maybe there is a better way? - let slash_amount: u128 = deposit_amount.into()/2; + let slash_amount: u128 = deposit_amount.into() / 2; // slash pool by half pallet_staking::slashing::do_slash::( @@ -909,49 +1008,75 @@ frame_benchmarking::benchmarks! { slash_amount.into(), &mut pallet_staking::BalanceOf::::zero(), &mut pallet_staking::NegativeImbalanceOf::::zero(), - EraIndex::zero() + EraIndex::zero(), ); // verify user balance is slashed in the pool. - assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount/2u32.into()); + assert_eq!( + PoolMembers::::get(&depositor).unwrap().total_balance(), + deposit_amount / 2u32.into() + ); // verify delegated balance are not yet slashed. - assert_if_delegate::(T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == Some(deposit_amount)); + assert_if_delegate::( + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == + Some(deposit_amount), + ); // Fill member's sub pools for the worst case. for i in 1..(T::MaxUnbonding::get() + 1) { pallet_staking::CurrentEra::::put(i); - assert!(Pools::::unbond(RuntimeOrigin::Signed(depositor.clone()).into(), depositor_lookup.clone(), Pools::::depositor_min_bond()).is_ok()); + assert!(Pools::::unbond( + RuntimeOrigin::Signed(depositor.clone()).into(), + depositor_lookup.clone(), + Pools::::depositor_min_bond() + ) + .is_ok()); } pallet_staking::CurrentEra::::put(T::MaxUnbonding::get() + 2); - let slash_reporter = create_funded_user_with_balance::("slasher", 0, CurrencyOf::::minimum_balance()); + let slash_reporter = + create_funded_user_with_balance::("slasher", 0, CurrencyOf::::minimum_balance()); whitelist_account!(depositor); - }: - { - assert_if_delegate::(Pools::::apply_slash(RuntimeOrigin::Signed(slash_reporter.clone()).into(), depositor_lookup.clone()).is_ok()); - } - verify { + + #[block] + { + assert_if_delegate::( + Pools::::apply_slash( + RuntimeOrigin::Signed(slash_reporter.clone()).into(), + depositor_lookup.clone(), + ) + .is_ok(), + ); + } + // verify balances are correct and slash applied. - assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount/2u32.into()); - assert_if_delegate::(T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == Some(deposit_amount/2u32.into())); + assert_eq!( + PoolMembers::::get(&depositor).unwrap().total_balance(), + deposit_amount / 2u32.into() + ); + assert_if_delegate::( + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == + Some(deposit_amount / 2u32.into()), + ); } - apply_slash_fail { + #[benchmark] + fn apply_slash_fail() { // Bench the scenario where pool has some unapplied slash but the member does not have any // slash to be applied. let deposit_amount = Pools::::depositor_min_bond() * 10u32.into(); // Create pool. - let (depositor, pool_account) = create_pool_account::(0, deposit_amount, None); + let (_depositor, pool_account) = create_pool_account::(0, deposit_amount, None); // slash pool by half - let slash_amount: u128 = deposit_amount.into()/2; + let slash_amount: u128 = deposit_amount.into() / 2; pallet_staking::slashing::do_slash::( &pool_account, slash_amount.into(), &mut pallet_staking::BalanceOf::::zero(), &mut pallet_staking::NegativeImbalanceOf::::zero(), - EraIndex::zero() + EraIndex::zero(), ); pallet_staking::CurrentEra::::put(1); @@ -961,68 +1086,106 @@ frame_benchmarking::benchmarks! { let join_amount = min_join_bond * T::MaxUnbonding::get().into() * 2u32.into(); let joiner = create_funded_user_with_balance::("joiner", 0, join_amount * 2u32.into()); let joiner_lookup = T::Lookup::unlookup(joiner.clone()); - assert!(Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), join_amount, 1).is_ok()); + assert!( + Pools::::join(RuntimeOrigin::Signed(joiner.clone()).into(), join_amount, 1).is_ok() + ); // Fill member's sub pools for the worst case. for i in 0..T::MaxUnbonding::get() { pallet_staking::CurrentEra::::put(i + 2); // +2 because we already set the current era to 1. - assert!(Pools::::unbond(RuntimeOrigin::Signed(joiner.clone()).into(), joiner_lookup.clone(), min_join_bond).is_ok()); + assert!(Pools::::unbond( + RuntimeOrigin::Signed(joiner.clone()).into(), + joiner_lookup.clone(), + min_join_bond + ) + .is_ok()); } pallet_staking::CurrentEra::::put(T::MaxUnbonding::get() + 3); whitelist_account!(joiner); - }: { - // Since the StakeAdapter can be different based on the runtime config, the errors could be different as well. - assert!(Pools::::apply_slash(RuntimeOrigin::Signed(joiner.clone()).into(), joiner_lookup.clone()).is_err()); + // Since the StakeAdapter can be different based on the runtime config, the errors could be + // different as well. + #[block] + { + assert!(Pools::::apply_slash( + RuntimeOrigin::Signed(joiner.clone()).into(), + joiner_lookup.clone() + ) + .is_err()); + } } - - pool_migrate { + #[benchmark] + fn pool_migrate() { // create a pool. let deposit_amount = Pools::::depositor_min_bond() * 2u32.into(); let (depositor, pool_account) = create_pool_account::(0, deposit_amount, None); // migrate pool to transfer stake. let _ = migrate_to_transfer_stake::(1); - }: { - assert_if_delegate::(Pools::::migrate_pool_to_delegate_stake(RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into()).is_ok()); - } - verify { + #[block] + { + assert_if_delegate::( + Pools::::migrate_pool_to_delegate_stake( + RuntimeOrigin::Signed(depositor.clone()).into(), + 1u32.into(), + ) + .is_ok(), + ); + } // this queries agent balance if `DelegateStake` strategy. - assert!(T::StakeAdapter::total_balance(Pool::from(pool_account.clone())) == Some(deposit_amount)); + assert_eq!( + T::StakeAdapter::total_balance(Pool::from(pool_account.clone())), + Some(deposit_amount) + ); } - migrate_delegation { + #[benchmark] + fn migrate_delegation() { // create a pool. let deposit_amount = Pools::::depositor_min_bond() * 2u32.into(); - let (depositor, pool_account) = create_pool_account::(0, deposit_amount, None); + let (depositor, _pool_account) = create_pool_account::(0, deposit_amount, None); let depositor_lookup = T::Lookup::unlookup(depositor.clone()); // migrate pool to transfer stake. let _ = migrate_to_transfer_stake::(1); // Now migrate pool to delegate stake keeping delegators unmigrated. - assert_if_delegate::(Pools::::migrate_pool_to_delegate_stake(RuntimeOrigin::Signed(depositor.clone()).into(), 1u32.into()).is_ok()); + assert_if_delegate::( + Pools::::migrate_pool_to_delegate_stake( + RuntimeOrigin::Signed(depositor.clone()).into(), + 1u32.into(), + ) + .is_ok(), + ); // delegation does not exist. - assert!(T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())).is_none()); + assert!( + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())).is_none() + ); // contribution exists in the pool. assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount); whitelist_account!(depositor); - }: { - assert_if_delegate::(Pools::::migrate_delegation(RuntimeOrigin::Signed(depositor.clone()).into(), depositor_lookup.clone()).is_ok()); - } - verify { + + #[block] + { + assert_if_delegate::( + Pools::::migrate_delegation( + RuntimeOrigin::Signed(depositor.clone()).into(), + depositor_lookup.clone(), + ) + .is_ok(), + ); + } // verify balances once more. - assert_if_delegate::(T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == Some(deposit_amount)); + assert_if_delegate::( + T::StakeAdapter::member_delegation_balance(Member::from(depositor.clone())) == + Some(deposit_amount), + ); assert_eq!(PoolMembers::::get(&depositor).unwrap().total_balance(), deposit_amount); } - impl_benchmark_test_suite!( - Pallet, - crate::mock::new_test_ext(), - crate::mock::Runtime - ); + impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Runtime); } From 603a392b6799d6ea3e13dabc411242f821c30215 Mon Sep 17 00:00:00 2001 From: Joseph Zhao <65984904+programskillforverification@users.noreply.github.com> Date: Mon, 18 Nov 2024 10:09:15 +0800 Subject: [PATCH 101/166] Migrate some pallets to benchmark v2 (#6311) Part of #6202 --------- Co-authored-by: Guillaume Thiolliere Co-authored-by: Giuseppe Re --- prdoc/pr_6311.prdoc | 13 ++ substrate/frame/babe/src/benchmarking.rs | 27 ++-- .../frame/fast-unstake/src/benchmarking.rs | 116 +++++++++--------- 3 files changed, 88 insertions(+), 68 deletions(-) create mode 100644 prdoc/pr_6311.prdoc diff --git a/prdoc/pr_6311.prdoc b/prdoc/pr_6311.prdoc new file mode 100644 index 000000000000..a63876f4e4ac --- /dev/null +++ b/prdoc/pr_6311.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Migrate pallet-fast-unstake and pallet-babe benchmark to v2 +doc: +- audience: Runtime Dev + description: |- + Migrate pallet-fast-unstake and pallet-babe benchmark to v2 +crates: +- name: pallet-babe + bump: patch +- name: pallet-fast-unstake + bump: patch diff --git a/substrate/frame/babe/src/benchmarking.rs b/substrate/frame/babe/src/benchmarking.rs index 6b0e31e84718..33e275fcb5e3 100644 --- a/substrate/frame/babe/src/benchmarking.rs +++ b/substrate/frame/babe/src/benchmarking.rs @@ -20,14 +20,16 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; -use frame_benchmarking::v1::benchmarks; +use frame_benchmarking::v2::*; type Header = sp_runtime::generic::Header; -benchmarks! { - check_equivocation_proof { - let x in 0 .. 1; +#[benchmarks] +mod benchmarks { + use super::*; + #[benchmark] + fn check_equivocation_proof(x: Linear<0, 1>) { // NOTE: generated with the test below `test_generate_equivocation_report_blob`. // the output is not deterministic since keys are generated randomly (and therefore // signature content changes). it should not affect the benchmark. @@ -53,22 +55,21 @@ benchmarks! { 124, 11, 167, 227, 103, 88, 78, 23, 228, 33, 96, 41, 207, 183, 227, 189, 114, 70, 254, 30, 128, 243, 233, 83, 214, 45, 74, 182, 120, 119, 64, 243, 219, 119, 63, 240, 205, 123, 231, 82, 205, 174, 143, 70, 2, 86, 182, 20, 16, 141, 145, 91, 116, 195, 58, 223, - 175, 145, 255, 7, 121, 133 + 175, 145, 255, 7, 121, 133, ]; let equivocation_proof1: sp_consensus_babe::EquivocationProof
= Decode::decode(&mut &EQUIVOCATION_PROOF_BLOB[..]).unwrap(); let equivocation_proof2 = equivocation_proof1.clone(); - }: { - sp_consensus_babe::check_equivocation_proof::
(equivocation_proof1); - } verify { + + #[block] + { + sp_consensus_babe::check_equivocation_proof::
(equivocation_proof1); + } + assert!(sp_consensus_babe::check_equivocation_proof::
(equivocation_proof2)); } - impl_benchmark_test_suite!( - Pallet, - crate::mock::new_test_ext(3), - crate::mock::Test, - ) + impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(3), crate::mock::Test,); } diff --git a/substrate/frame/fast-unstake/src/benchmarking.rs b/substrate/frame/fast-unstake/src/benchmarking.rs index d01ff715ca4f..750f348c4596 100644 --- a/substrate/frame/fast-unstake/src/benchmarking.rs +++ b/substrate/frame/fast-unstake/src/benchmarking.rs @@ -19,9 +19,9 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::{types::*, Pallet as FastUnstake, *}; +use crate::{types::*, *}; use alloc::{vec, vec::Vec}; -use frame_benchmarking::v1::{benchmarks, whitelist_account, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::{ assert_ok, traits::{Currency, EnsureOrigin, Get, Hooks}, @@ -89,22 +89,21 @@ fn setup_staking(v: u32, until: EraIndex) { fn on_idle_full_block() { let remaining_weight = ::BlockWeights::get().max_block; - FastUnstake::::on_idle(Zero::zero(), remaining_weight); + Pallet::::on_idle(Zero::zero(), remaining_weight); } -benchmarks! { +#[benchmarks] +mod benchmarks { + use super::*; // on_idle, we don't check anyone, but fully unbond them. - on_idle_unstake { - let b in 1 .. T::BatchSize::get(); - + #[benchmark] + fn on_idle_unstake(b: Linear<1, { T::BatchSize::get() }>) { ErasToCheckPerBlock::::put(1); for who in create_unexposed_batch::(b).into_iter() { - assert_ok!(FastUnstake::::register_fast_unstake( - RawOrigin::Signed(who.clone()).into(), - )); + assert_ok!(Pallet::::register_fast_unstake(RawOrigin::Signed(who.clone()).into(),)); } - // run on_idle once. This will check era 0. + // Run on_idle once. This will check era 0. assert_eq!(Head::::get(), None); on_idle_full_block::(); @@ -116,21 +115,19 @@ benchmarks! { .. }) if checked.len() == 1 && stashes.len() as u32 == b )); + + #[block] + { + on_idle_full_block::(); + } + + assert_eq!(fast_unstake_events::().last(), Some(&Event::BatchFinished { size: b })); } - : { - on_idle_full_block::(); - } - verify { - assert!(matches!( - fast_unstake_events::().last(), - Some(Event::BatchFinished { size: b }) - )); - } - // on_idle, when we check some number of eras and the queue is already set. - on_idle_check { - let v in 1 .. 256; - let b in 1 .. T::BatchSize::get(); + #[benchmark] + fn on_idle_check(v: Linear<1, 256>, b: Linear<1, { T::BatchSize::get() }>) { + // on_idle: When we check some number of eras and the queue is already set. + let u = T::MaxErasToCheckPerBlock::get().min(T::Staking::bonding_duration()); ErasToCheckPerBlock::::put(u); @@ -139,64 +136,73 @@ benchmarks! { // setup staking with v validators and u eras of data (0..=u+1) setup_staking::(v, u); - let stashes = create_unexposed_batch::(b).into_iter().map(|s| { - assert_ok!(FastUnstake::::register_fast_unstake( - RawOrigin::Signed(s.clone()).into(), - )); - (s, T::Deposit::get()) - }).collect::>(); + let stashes = create_unexposed_batch::(b) + .into_iter() + .map(|s| { + assert_ok!( + Pallet::::register_fast_unstake(RawOrigin::Signed(s.clone()).into(),) + ); + (s, T::Deposit::get()) + }) + .collect::>(); // no one is queued thus far. assert_eq!(Head::::get(), None); - Head::::put(UnstakeRequest { stashes: stashes.clone().try_into().unwrap(), checked: Default::default() }); - } - : { - on_idle_full_block::(); - } - verify { + Head::::put(UnstakeRequest { + stashes: stashes.clone().try_into().unwrap(), + checked: Default::default(), + }); + + #[block] + { + on_idle_full_block::(); + } + let checked = (1..=u).rev().collect::>(); let request = Head::::get().unwrap(); assert_eq!(checked, request.checked.into_inner()); - assert!(matches!( - fast_unstake_events::().last(), - Some(Event::BatchChecked { .. }) - )); + assert!(matches!(fast_unstake_events::().last(), Some(Event::BatchChecked { .. }))); assert!(stashes.iter().all(|(s, _)| request.stashes.iter().any(|(ss, _)| ss == s))); } - register_fast_unstake { + #[benchmark] + fn register_fast_unstake() { ErasToCheckPerBlock::::put(1); let who = create_unexposed_batch::(1).get(0).cloned().unwrap(); whitelist_account!(who); assert_eq!(Queue::::count(), 0); - } - :_(RawOrigin::Signed(who.clone())) - verify { + #[extrinsic_call] + _(RawOrigin::Signed(who.clone())); + assert_eq!(Queue::::count(), 1); } - deregister { + #[benchmark] + fn deregister() { ErasToCheckPerBlock::::put(1); let who = create_unexposed_batch::(1).get(0).cloned().unwrap(); - assert_ok!(FastUnstake::::register_fast_unstake( - RawOrigin::Signed(who.clone()).into(), - )); + assert_ok!(Pallet::::register_fast_unstake(RawOrigin::Signed(who.clone()).into(),)); assert_eq!(Queue::::count(), 1); whitelist_account!(who); - } - :_(RawOrigin::Signed(who.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(who.clone())); + assert_eq!(Queue::::count(), 0); } - control { + #[benchmark] + fn control() -> Result<(), BenchmarkError> { let origin = ::ControlOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, T::MaxErasToCheckPerBlock::get()); + + Ok(()) } - : _(origin, T::MaxErasToCheckPerBlock::get()) - verify {} - impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Runtime) + impl_benchmark_test_suite!(Pallet, mock::ExtBuilder::default().build(), mock::Runtime); } From 95be9c18904a2079cbbfd59df9396846fa8fede8 Mon Sep 17 00:00:00 2001 From: Guillaume Thiolliere Date: Mon, 18 Nov 2024 15:53:12 +0900 Subject: [PATCH 102/166] Mention that account might still be required in doc for feeless if. (#6490) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Bastian Köcher --- substrate/frame/support/src/lib.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 6d8b772d9d4a..c64987b17d35 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -1883,11 +1883,16 @@ pub mod pallet_macros { /// } /// ``` /// - /// Please note that this only works for signed dispatchables and requires a signed + /// Please note that this only works for signed dispatchables and requires a transaction /// extension such as [`pallet_skip_feeless_payment::SkipCheckIfFeeless`] to wrap the /// existing payment extension. Else, this is completely ignored and the dispatchable is /// still charged. /// + /// Also this will not allow accountless caller to send a transaction if some transaction + /// extension such as `frame_system::CheckNonce` is used. + /// Extensions such as `frame_system::CheckNonce` require a funded account to validate + /// the transaction. + /// /// ### Macro expansion /// /// The macro implements the [`pallet_skip_feeless_payment::CheckIfFeeless`] trait on the From 06a68bec30dd56395fb8ae03e80e0fdadc682ed9 Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Mon, 18 Nov 2024 16:41:05 +0800 Subject: [PATCH 103/166] Pure state sync refactoring (part-1) (#6249) This pure refactoring of state sync is preparing for https://github.com/paritytech/polkadot-sdk/issues/4. As the rough plan in https://github.com/paritytech/polkadot-sdk/issues/4#issuecomment-2439588876, there will be two PRs for the state sync refactoring. This first PR focuses on isolating the function `process_state_key_values()` as the central point for storing received state data in memory. This function will later be adapted to forward the state data directly to the DB layer for persistent sync. A follow-up PR will handle the encapsulation of `StateSyncMetadata` to support this persistent storage. Although there are many commits in this PR, each commit is small and intentionally incremental to facilitate a smoother review, please review them commit by commit. Each commit should represent an equivalent rewrite of the existing logic, with one exception https://github.com/paritytech/polkadot-sdk/commit/bb447b2daa01fecf3bf0ca20c451ac6147f3f8c7, which has a slight deviation from the original but is correct IMHO. Please give this commit special attention during the review. --- prdoc/pr_6249.prdoc | 10 ++ .../network/sync/src/strategy/state_sync.rs | 165 +++++++++--------- 2 files changed, 88 insertions(+), 87 deletions(-) create mode 100644 prdoc/pr_6249.prdoc diff --git a/prdoc/pr_6249.prdoc b/prdoc/pr_6249.prdoc new file mode 100644 index 000000000000..52fa10b22627 --- /dev/null +++ b/prdoc/pr_6249.prdoc @@ -0,0 +1,10 @@ +title: Pure state sync refactoring (part-1) + +doc: +- audience: Node Dev + description: | + The pure refactoring of state sync is preparing for https://github.com/paritytech/polkadot-sdk/issues/4. This is the first part, focusing on isolating the function `process_state_key_values()` as the central point for storing received state data in memory. This function will later be adapted to forward the state data directly to the DB layer to resolve the OOM issue and support persistent state sync. + +crates: +- name: sc-network-sync + bump: none diff --git a/substrate/client/network/sync/src/strategy/state_sync.rs b/substrate/client/network/sync/src/strategy/state_sync.rs index 1ed1de7c8efa..7a0cc1191609 100644 --- a/substrate/client/network/sync/src/strategy/state_sync.rs +++ b/substrate/client/network/sync/src/strategy/state_sync.rs @@ -19,12 +19,12 @@ //! State sync support. use crate::{ - schema::v1::{StateEntry, StateRequest, StateResponse}, + schema::v1::{KeyValueStateEntry, StateEntry, StateRequest, StateResponse}, LOG_TARGET, }; use codec::{Decode, Encode}; use log::debug; -use sc_client_api::{CompactProof, ProofProvider}; +use sc_client_api::{CompactProof, KeyValueStates, ProofProvider}; use sc_consensus::ImportedState; use smallvec::SmallVec; use sp_core::storage::well_known_keys; @@ -132,6 +132,80 @@ where skip_proof, } } + + fn process_state_key_values( + &mut self, + state_root: Vec, + key_values: impl IntoIterator, Vec)>, + ) { + let is_top = state_root.is_empty(); + + let entry = self.state.entry(state_root).or_default(); + + if entry.0.len() > 0 && entry.1.len() > 1 { + // Already imported child_trie with same root. + // Warning this will not work with parallel download. + return; + } + + let mut child_storage_roots = Vec::new(); + + for (key, value) in key_values { + // Skip all child key root (will be recalculated on import) + if is_top && well_known_keys::is_child_storage_key(key.as_slice()) { + child_storage_roots.push((value, key)); + } else { + self.imported_bytes += key.len() as u64; + entry.0.push((key, value)); + } + } + + for (root, storage_key) in child_storage_roots { + self.state.entry(root).or_default().1.push(storage_key); + } + } + + fn process_state_verified(&mut self, values: KeyValueStates) { + for values in values.0 { + self.process_state_key_values(values.state_root, values.key_values); + } + } + + fn process_state_unverified(&mut self, response: StateResponse) -> bool { + let mut complete = true; + // if the trie is a child trie and one of its parent trie is empty, + // the parent cursor stays valid. + // Empty parent trie content only happens when all the response content + // is part of a single child trie. + if self.last_key.len() == 2 && response.entries[0].entries.is_empty() { + // Do not remove the parent trie position. + self.last_key.pop(); + } else { + self.last_key.clear(); + } + for state in response.entries { + debug!( + target: LOG_TARGET, + "Importing state from {:?} to {:?}", + state.entries.last().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)), + state.entries.first().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)), + ); + + if !state.complete { + if let Some(e) = state.entries.last() { + self.last_key.push(e.key.clone()); + } + complete = false; + } + + let KeyValueStateEntry { state_root, entries, complete: _ } = state; + self.process_state_key_values( + state_root, + entries.into_iter().map(|StateEntry { key, value }| (key, value)), + ); + } + complete + } } impl StateSyncProvider for StateSync @@ -181,94 +255,11 @@ where debug!(target: LOG_TARGET, "Error updating key cursor, depth: {}", completed); }; - for values in values.0 { - let key_values = if values.state_root.is_empty() { - // Read child trie roots. - values - .key_values - .into_iter() - .filter(|key_value| { - if well_known_keys::is_child_storage_key(key_value.0.as_slice()) { - self.state - .entry(key_value.1.clone()) - .or_default() - .1 - .push(key_value.0.clone()); - false - } else { - true - } - }) - .collect() - } else { - values.key_values - }; - let entry = self.state.entry(values.state_root).or_default(); - if entry.0.len() > 0 && entry.1.len() > 1 { - // Already imported child_trie with same root. - // Warning this will not work with parallel download. - } else if entry.0.is_empty() { - for (key, _value) in key_values.iter() { - self.imported_bytes += key.len() as u64; - } - - entry.0 = key_values; - } else { - for (key, value) in key_values { - self.imported_bytes += key.len() as u64; - entry.0.push((key, value)) - } - } - } + self.process_state_verified(values); self.imported_bytes += proof_size; complete } else { - let mut complete = true; - // if the trie is a child trie and one of its parent trie is empty, - // the parent cursor stays valid. - // Empty parent trie content only happens when all the response content - // is part of a single child trie. - if self.last_key.len() == 2 && response.entries[0].entries.is_empty() { - // Do not remove the parent trie position. - self.last_key.pop(); - } else { - self.last_key.clear(); - } - for state in response.entries { - debug!( - target: LOG_TARGET, - "Importing state from {:?} to {:?}", - state.entries.last().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)), - state.entries.first().map(|e| sp_core::hexdisplay::HexDisplay::from(&e.key)), - ); - - if !state.complete { - if let Some(e) = state.entries.last() { - self.last_key.push(e.key.clone()); - } - complete = false; - } - let is_top = state.state_root.is_empty(); - let entry = self.state.entry(state.state_root).or_default(); - if entry.0.len() > 0 && entry.1.len() > 1 { - // Already imported child trie with same root. - } else { - let mut child_roots = Vec::new(); - for StateEntry { key, value } in state.entries { - // Skip all child key root (will be recalculated on import). - if is_top && well_known_keys::is_child_storage_key(key.as_slice()) { - child_roots.push((value, key)); - } else { - self.imported_bytes += key.len() as u64; - entry.0.push((key, value)) - } - } - for (root, storage_key) in child_roots { - self.state.entry(root).or_default().1.push(storage_key); - } - } - } - complete + self.process_state_unverified(response) }; if complete { self.complete = true; From e98c1ac6994766411f96bd7c14e8049cc5284396 Mon Sep 17 00:00:00 2001 From: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Date: Mon, 18 Nov 2024 11:00:28 +0100 Subject: [PATCH 104/166] [WIP][ci] Add worfklow stopper (#4551) PR to implements workflow stopper - a custom solution to stop all workflows if one of a required jobs failed. Previously we had the same solution in GitLab and it saved a lot of compute. Because GitHub doesn't have one united pipeline and instead it has multiple workflows something like this has to be implemented. cc https://github.com/paritytech/ci_cd/issues/939 --- .github/actions/workflow-stopper/action.yml | 28 +++++++++++++++++++ .github/workflows/build-misc.yml | 15 +++++++++- .../workflows/check-frame-omni-bencher.yml | 15 ++++++++++ .github/workflows/check-runtime-migration.yml | 13 +++++++-- .github/workflows/checks-quick.yml | 7 +++++ .github/workflows/checks.yml | 23 +++++++++++++++ .github/workflows/docs.yml | 14 ++++++++++ .github/workflows/tests-linux-stable.yml | 28 +++++++++++++++++++ 8 files changed, 140 insertions(+), 3 deletions(-) create mode 100644 .github/actions/workflow-stopper/action.yml diff --git a/.github/actions/workflow-stopper/action.yml b/.github/actions/workflow-stopper/action.yml new file mode 100644 index 000000000000..0bd9382fdb30 --- /dev/null +++ b/.github/actions/workflow-stopper/action.yml @@ -0,0 +1,28 @@ +name: "stop all workflows" +description: "Action stops all workflows in a PR to save compute resources." +inputs: + app-id: + description: "App id" + required: true + app-key: + description: "App token" + required: true +runs: + using: "composite" + steps: + - name: Worfklow stopper - Generate token + uses: actions/create-github-app-token@v1 + id: app-token + with: + app-id: ${{ inputs.app-id }} + private-key: ${{ inputs.app-key }} + owner: "paritytech" + repositories: "workflow-stopper" + - name: Workflow stopper - Stop all workflows + uses: octokit/request-action@v2.x + with: + route: POST /repos/paritytech/workflow-stopper/actions/workflows/stopper.yml/dispatches + ref: main + inputs: '${{ format(''{{ "github_sha": "{0}", "github_repository": "{1}", "github_ref_name": "{2}", "github_workflow_id": "{3}", "github_job_name": "{4}" }}'', github.event.pull_request.head.sha, github.repository, github.ref_name, github.run_id, github.job) }}' + env: + GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} diff --git a/.github/workflows/build-misc.yml b/.github/workflows/build-misc.yml index 2a8e81b97878..a9b433a94b64 100644 --- a/.github/workflows/build-misc.yml +++ b/.github/workflows/build-misc.yml @@ -16,7 +16,6 @@ permissions: contents: read jobs: - preflight: uses: ./.github/workflows/reusable-preflight.yml @@ -38,11 +37,18 @@ jobs: - name: Build env: SUBSTRATE_RUNTIME_TARGET: riscv + id: required run: | forklift cargo check -p minimal-template-runtime forklift cargo check -p westend-runtime forklift cargo check -p rococo-runtime forklift cargo check -p polkadot-test-runtime + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} build-subkey: timeout-minutes: 20 @@ -62,9 +68,16 @@ jobs: - name: Build env: SKIP_WASM_BUILD: 1 + id: required run: | cd ./substrate/bin/utils/subkey forklift cargo build --locked --release + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} confirm-required-build-misc-jobs-passed: runs-on: ubuntu-latest diff --git a/.github/workflows/check-frame-omni-bencher.yml b/.github/workflows/check-frame-omni-bencher.yml index 924a8b7f712f..b47c9d49feaf 100644 --- a/.github/workflows/check-frame-omni-bencher.yml +++ b/.github/workflows/check-frame-omni-bencher.yml @@ -36,9 +36,16 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: script + id: required run: | forklift cargo build --locked --quiet --release -p asset-hub-westend-runtime --features runtime-benchmarks forklift cargo run --locked --release -p frame-omni-bencher --quiet -- v1 benchmark pallet --runtime target/release/wbuild/asset-hub-westend-runtime/asset_hub_westend_runtime.compact.compressed.wasm --all --steps 2 --repeat 1 --quiet + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} runtime-matrix: runs-on: ubuntu-latest @@ -80,6 +87,7 @@ jobs: uses: actions/checkout@v4 - name: script + id: required run: | RUNTIME_BLOB_NAME=$(echo $PACKAGE_NAME | sed 's/-/_/g').compact.compressed.wasm RUNTIME_BLOB_PATH=./target/release/wbuild/$PACKAGE_NAME/$RUNTIME_BLOB_NAME @@ -90,6 +98,13 @@ jobs: cmd="./target/release/frame-omni-bencher v1 benchmark pallet --runtime $RUNTIME_BLOB_PATH --all --steps 2 --repeat 1 $FLAGS" echo "Running command: $cmd" eval "$cmd" + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} + confirm-frame-omni-benchers-passed: runs-on: ubuntu-latest name: All benchmarks passed diff --git a/.github/workflows/check-runtime-migration.yml b/.github/workflows/check-runtime-migration.yml index 758de0e7b433..9866ae18b98a 100644 --- a/.github/workflows/check-runtime-migration.yml +++ b/.github/workflows/check-runtime-migration.yml @@ -101,20 +101,29 @@ jobs: ./try-runtime create-snapshot --uri ${{ matrix.uri }} snapshot.raw - name: Build Runtime + id: required1 run: | echo "---------- Building ${{ matrix.package }} runtime ----------" - time forklift cargo build --release --locked -p ${{ matrix.package }} --features try-runtime -q + forklift cargo build --release --locked -p ${{ matrix.package }} --features try-runtime -q - name: Run Check + id: required2 run: | echo "Running ${{ matrix.network }} runtime migration check" export RUST_LOG=remote-ext=debug,runtime=debug echo "---------- Executing on-runtime-upgrade for ${{ matrix.network }} ----------" - time ./try-runtime ${{ matrix.command_extra_args }} \ + ./try-runtime ${{ matrix.command_extra_args }} \ --runtime ./target/release/wbuild/${{ matrix.package }}/${{ matrix.wasm }} \ on-runtime-upgrade --disable-spec-version-check --checks=all ${{ matrix.subcommand_extra_args }} snap -p snapshot.raw sleep 5 + - name: Stop all workflows if failed + if: ${{ failure() && (steps.required1.conclusion == 'failure' || steps.required2.conclusion == 'failure') }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} + # name of this job must be unique across all workflows # otherwise GitHub will mark all these jobs as required confirm-required-checks-passed: diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index 28f5bf932e2c..4fcaf80c83fc 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -27,7 +27,14 @@ jobs: steps: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: Cargo fmt + id: required run: cargo +nightly fmt --all -- --check + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} check-dependency-rules: runs-on: ubuntu-latest timeout-minutes: 20 diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 8ec3660307d4..c240504fa1e7 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -31,9 +31,17 @@ jobs: steps: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: script + id: required run: | cargo clippy --all-targets --locked --workspace --quiet cargo clippy --all-targets --all-features --locked --workspace --quiet + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} + check-try-runtime: runs-on: ${{ needs.preflight.outputs.RUNNER }} needs: [preflight] @@ -44,6 +52,7 @@ jobs: steps: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: script + id: required run: | forklift cargo check --locked --all --features try-runtime --quiet # this is taken from cumulus @@ -52,6 +61,13 @@ jobs: # add after https://github.com/paritytech/substrate/pull/14502 is merged # experimental code may rely on try-runtime and vice-versa forklift cargo check --locked --all --features try-runtime,experimental --quiet + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} + # check-core-crypto-features works fast without forklift check-core-crypto-features: runs-on: ${{ needs.preflight.outputs.RUNNER }} @@ -63,6 +79,7 @@ jobs: steps: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.7 - name: script + id: required run: | cd substrate/primitives/core ./check-features-variants.sh @@ -73,6 +90,12 @@ jobs: cd substrate/primitives/keyring ./check-features-variants.sh cd - + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} # name of this job must be unique across all workflows # otherwise GitHub will mark all these jobs as required confirm-required-checks-passed: diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a257c8229598..cc84e7f9ad3b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -25,8 +25,15 @@ jobs: steps: - uses: actions/checkout@v4 - run: forklift cargo test --doc --workspace + id: required env: RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings" + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} build-rustdoc: runs-on: ${{ needs.preflight.outputs.RUNNER }} @@ -38,6 +45,7 @@ jobs: steps: - uses: actions/checkout@v4 - run: forklift cargo doc --all-features --workspace --no-deps + id: required env: SKIP_WASM_BUILD: 1 RUSTDOCFLAGS: "-Dwarnings --default-theme=ayu --html-in-header ./docs/sdk/assets/header.html --extend-css ./docs/sdk/assets/theme.css --html-after-content ./docs/sdk/assets/after-content.html" @@ -60,6 +68,12 @@ jobs: path: ./crate-docs/ retention-days: 1 if-no-files-found: error + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} build-implementers-guide: runs-on: ubuntu-latest diff --git a/.github/workflows/tests-linux-stable.yml b/.github/workflows/tests-linux-stable.yml index 24b96219738a..b9d0605b2495 100644 --- a/.github/workflows/tests-linux-stable.yml +++ b/.github/workflows/tests-linux-stable.yml @@ -34,7 +34,14 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: script + id: required run: WASM_BUILD_NO_COLOR=1 forklift cargo test -p staging-node-cli --release --locked -- --ignored + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} # https://github.com/paritytech/ci_cd/issues/864 test-linux-stable-runtime-benchmarks: @@ -53,7 +60,14 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: script + id: required run: forklift cargo nextest run --workspace --features runtime-benchmarks benchmark --locked --cargo-profile testnet --cargo-quiet + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} test-linux-stable: needs: [preflight] @@ -82,6 +96,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: script + id: required run: | # Fixes "detected dubious ownership" error in the ci git config --global --add safe.directory '*' @@ -97,6 +112,12 @@ jobs: - name: runtime-api tests if: ${{ matrix.partition == '1/3' }} run: forklift cargo nextest run -p sp-api-test --features enable-staging-api --cargo-quiet + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} # some tests do not run with `try-runtime` feature enabled # https://github.com/paritytech/polkadot-sdk/pull/4251#discussion_r1624282143 @@ -123,6 +144,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: script + id: required run: | forklift cargo nextest run --workspace \ --locked \ @@ -132,6 +154,12 @@ jobs: --features experimental,ci-only-tests \ --filter-expr " !test(/all_security_features_work/) - test(/nonexistent_cache_dir/)" \ --partition count:${{ matrix.partition }} \ + - name: Stop all workflows if failed + if: ${{ failure() && steps.required.conclusion == 'failure' }} + uses: ./.github/actions/workflow-stopper + with: + app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} + app-key: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_KEY }} confirm-required-jobs-passed: runs-on: ubuntu-latest From 7d5d72027eee124451f9c7d10d7cab5167f2f57e Mon Sep 17 00:00:00 2001 From: Tsvetomir Dimitrov Date: Mon, 18 Nov 2024 19:42:45 +0200 Subject: [PATCH 105/166] Remove `ProspectiveParachainsMode` usage in backing subsystem (#6215) Since async backing parameters runtime api is released on all networks the code in backing subsystem can be simplified by removing the usages of `ProspectiveParachainsMode` and keeping only the branches of the code under `ProspectiveParachainsMode::Enabled`. The PR does that and reworks the tests in mod.rs to use async backing. It's a preparation for https://github.com/paritytech/polkadot-sdk/issues/5079 --------- Co-authored-by: Alin Dima Co-authored-by: command-bot <> --- polkadot/node/core/backing/src/lib.rs | 399 +-- polkadot/node/core/backing/src/tests/mod.rs | 2522 ++++++++++++----- .../src/tests/prospective_parachains.rs | 1745 ------------ .../src/backing_implicit_view.rs | 17 +- .../src/node/utility/provisioner.md | 5 +- .../src/types/overseer-protocol.md | 10 - polkadot/statement-table/src/generic.rs | 112 +- polkadot/statement-table/src/lib.rs | 2 +- prdoc/pr_6215.prdoc | 16 + 9 files changed, 2004 insertions(+), 2824 deletions(-) delete mode 100644 polkadot/node/core/backing/src/tests/prospective_parachains.rs create mode 100644 prdoc/pr_6215.prdoc diff --git a/polkadot/node/core/backing/src/lib.rs b/polkadot/node/core/backing/src/lib.rs index 250013c6541a..8b54a8b5907b 100644 --- a/polkadot/node/core/backing/src/lib.rs +++ b/polkadot/node/core/backing/src/lib.rs @@ -98,13 +98,10 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_util::{ self as util, - backing_implicit_view::{FetchError as ImplicitViewFetchError, View as ImplicitView}, - request_from_runtime, request_session_executor_params, request_session_index_for_child, - request_validator_groups, request_validators, - runtime::{ - self, fetch_claim_queue, prospective_parachains_mode, request_min_backing_votes, - ClaimQueueSnapshot, ProspectiveParachainsMode, - }, + backing_implicit_view::View as ImplicitView, + request_claim_queue, request_disabled_validators, request_session_executor_params, + request_session_index_for_child, request_validator_groups, request_validators, + runtime::{self, request_min_backing_votes, ClaimQueueSnapshot}, Validator, }; use polkadot_parachain_primitives::primitives::IsSystem; @@ -112,7 +109,7 @@ use polkadot_primitives::{ node_features::FeatureIndex, vstaging::{ BackedCandidate, CandidateReceiptV2 as CandidateReceipt, - CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CoreState, + CommittedCandidateReceiptV2 as CommittedCandidateReceipt, }, CandidateCommitments, CandidateHash, CoreIndex, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, Id as ParaId, IndexedVec, NodeFeatures, PersistedValidationData, SessionIndex, @@ -125,10 +122,10 @@ use polkadot_statement_table::{ SignedStatement as TableSignedStatement, Statement as TableStatement, Summary as TableSummary, }, - Config as TableConfig, Context as TableContextTrait, Table, + Context as TableContextTrait, Table, }; use sp_keystore::KeystorePtr; -use util::runtime::{get_disabled_validators_with_fallback, request_node_features}; +use util::runtime::request_node_features; mod error; @@ -215,7 +212,6 @@ where } struct PerRelayParentState { - prospective_parachains_mode: ProspectiveParachainsMode, /// The hash of the relay parent on top of which this job is doing it's work. parent: Hash, /// The node features. @@ -258,43 +254,6 @@ struct PerCandidateState { relay_parent: Hash, } -enum ActiveLeafState { - // If prospective-parachains is disabled, one validator may only back one candidate per - // paraid. - ProspectiveParachainsDisabled { seconded: HashSet }, - ProspectiveParachainsEnabled { max_candidate_depth: usize, allowed_ancestry_len: usize }, -} - -impl ActiveLeafState { - fn new(mode: ProspectiveParachainsMode) -> Self { - match mode { - ProspectiveParachainsMode::Disabled => - Self::ProspectiveParachainsDisabled { seconded: HashSet::new() }, - ProspectiveParachainsMode::Enabled { max_candidate_depth, allowed_ancestry_len } => - Self::ProspectiveParachainsEnabled { max_candidate_depth, allowed_ancestry_len }, - } - } - - fn add_seconded_candidate(&mut self, para_id: ParaId) { - if let Self::ProspectiveParachainsDisabled { seconded } = self { - seconded.insert(para_id); - } - } -} - -impl From<&ActiveLeafState> for ProspectiveParachainsMode { - fn from(state: &ActiveLeafState) -> Self { - match *state { - ActiveLeafState::ProspectiveParachainsDisabled { .. } => - ProspectiveParachainsMode::Disabled, - ActiveLeafState::ProspectiveParachainsEnabled { - max_candidate_depth, - allowed_ancestry_len, - } => ProspectiveParachainsMode::Enabled { max_candidate_depth, allowed_ancestry_len }, - } - } -} - /// A cache for storing data per-session to reduce repeated /// runtime API calls and avoid redundant computations. struct PerSessionCache { @@ -470,27 +429,9 @@ impl PerSessionCache { /// The state of the subsystem. struct State { /// The utility for managing the implicit and explicit views in a consistent way. - /// - /// We only feed leaves which have prospective parachains enabled to this view. implicit_view: ImplicitView, - /// State tracked for all active leaves, whether or not they have prospective parachains - /// enabled. - per_leaf: HashMap, /// State tracked for all relay-parents backing work is ongoing for. This includes /// all active leaves. - /// - /// relay-parents fall into one of 3 categories. - /// 1. active leaves which do support prospective parachains - /// 2. active leaves which do not support prospective parachains - /// 3. relay-chain blocks which are ancestors of an active leaf and do support prospective - /// parachains. - /// - /// Relay-chain blocks which don't support prospective parachains are - /// never included in the fragment chains of active leaves which do. - /// - /// While it would be technically possible to support such leaves in - /// fragment chains, it only benefits the transition period when asynchronous - /// backing is being enabled and complicates code. per_relay_parent: HashMap, /// State tracked for all candidates relevant to the implicit view. /// @@ -514,7 +455,6 @@ impl State { ) -> Self { State { implicit_view: ImplicitView::default(), - per_leaf: HashMap::default(), per_relay_parent: HashMap::default(), per_candidate: HashMap::new(), per_session_cache: PerSessionCache::default(), @@ -1022,87 +962,42 @@ async fn handle_active_leaves_update( update: ActiveLeavesUpdate, state: &mut State, ) -> Result<(), Error> { - enum LeafHasProspectiveParachains { - Enabled(Result), - Disabled, - } - // Activate in implicit view before deactivate, per the docs // on ImplicitView, this is more efficient. let res = if let Some(leaf) = update.activated { - // Only activate in implicit view if prospective - // parachains are enabled. - let mode = prospective_parachains_mode(ctx.sender(), leaf.hash).await?; - let leaf_hash = leaf.hash; - Some(( - leaf, - match mode { - ProspectiveParachainsMode::Disabled => LeafHasProspectiveParachains::Disabled, - ProspectiveParachainsMode::Enabled { .. } => LeafHasProspectiveParachains::Enabled( - state.implicit_view.activate_leaf(ctx.sender(), leaf_hash).await.map(|_| mode), - ), - }, - )) + Some((leaf, state.implicit_view.activate_leaf(ctx.sender(), leaf_hash).await.map(|_| ()))) } else { None }; for deactivated in update.deactivated { - state.per_leaf.remove(&deactivated); state.implicit_view.deactivate_leaf(deactivated); } // clean up `per_relay_parent` according to ancestry // of leaves. we do this so we can clean up candidates right after // as a result. - // - // when prospective parachains are disabled, the implicit view is empty, - // which means we'll clean up everything that's not a leaf - the expected behavior - // for pre-asynchronous backing. { - let remaining: HashSet<_> = state - .per_leaf - .keys() - .chain(state.implicit_view.all_allowed_relay_parents()) - .collect(); + let remaining: HashSet<_> = state.implicit_view.all_allowed_relay_parents().collect(); state.per_relay_parent.retain(|r, _| remaining.contains(&r)); } // clean up `per_candidate` according to which relay-parents // are known. - // - // when prospective parachains are disabled, we clean up all candidates - // because we've cleaned up all relay parents. this is correct. state .per_candidate .retain(|_, pc| state.per_relay_parent.contains_key(&pc.relay_parent)); // Get relay parents which might be fresh but might be known already // that are explicit or implicit from the new active leaf. - let (fresh_relay_parents, leaf_mode) = match res { + let fresh_relay_parents = match res { None => return Ok(()), - Some((leaf, LeafHasProspectiveParachains::Disabled)) => { - // defensive in this case - for enabled, this manifests as an error. - if state.per_leaf.contains_key(&leaf.hash) { - return Ok(()) - } - - state - .per_leaf - .insert(leaf.hash, ActiveLeafState::new(ProspectiveParachainsMode::Disabled)); - - (vec![leaf.hash], ProspectiveParachainsMode::Disabled) - }, - Some((leaf, LeafHasProspectiveParachains::Enabled(Ok(prospective_parachains_mode)))) => { + Some((leaf, Ok(_))) => { let fresh_relay_parents = state.implicit_view.known_allowed_relay_parents_under(&leaf.hash, None); - let active_leaf_state = ActiveLeafState::new(prospective_parachains_mode); - - state.per_leaf.insert(leaf.hash, active_leaf_state); - let fresh_relay_parent = match fresh_relay_parents { Some(f) => f.to_vec(), None => { @@ -1115,9 +1010,9 @@ async fn handle_active_leaves_update( vec![leaf.hash] }, }; - (fresh_relay_parent, prospective_parachains_mode) + fresh_relay_parent }, - Some((leaf, LeafHasProspectiveParachains::Enabled(Err(e)))) => { + Some((leaf, Err(e))) => { gum::debug!( target: LOG_TARGET, leaf_hash = ?leaf.hash, @@ -1135,18 +1030,6 @@ async fn handle_active_leaves_update( continue } - let mode = match state.per_leaf.get(&maybe_new) { - None => { - // If the relay-parent isn't a leaf itself, - // then it is guaranteed by the prospective parachains - // subsystem that it is an ancestor of a leaf which - // has prospective parachains enabled and that the - // block itself did. - leaf_mode - }, - Some(l) => l.into(), - }; - // construct a `PerRelayParent` from the runtime API // and insert it. let per = construct_per_relay_parent_state( @@ -1154,7 +1037,6 @@ async fn handle_active_leaves_update( maybe_new, &state.keystore, &mut state.per_session_cache, - mode, ) .await?; @@ -1254,17 +1136,14 @@ async fn construct_per_relay_parent_state( relay_parent: Hash, keystore: &KeystorePtr, per_session_cache: &mut PerSessionCache, - mode: ProspectiveParachainsMode, ) -> Result, Error> { let parent = relay_parent; - let (session_index, groups, cores) = futures::try_join!( + let (session_index, groups, claim_queue, disabled_validators) = futures::try_join!( request_session_index_for_child(parent, ctx.sender()).await, request_validator_groups(parent, ctx.sender()).await, - request_from_runtime(parent, ctx.sender(), |tx| { - RuntimeApiRequest::AvailabilityCores(tx) - },) - .await, + request_claim_queue(parent, ctx.sender()).await, + request_disabled_validators(parent, ctx.sender()).await, ) .map_err(Error::JoinMultiple)?; @@ -1290,23 +1169,13 @@ async fn construct_per_relay_parent_state( gum::debug!(target: LOG_TARGET, inject_core_index, ?parent, "New state"); let (validator_groups, group_rotation_info) = try_runtime_api!(groups); - let cores = try_runtime_api!(cores); let minimum_backing_votes = per_session_cache .minimum_backing_votes(session_index, parent, ctx.sender()) .await; let minimum_backing_votes = try_runtime_api!(minimum_backing_votes); - - // TODO: https://github.com/paritytech/polkadot-sdk/issues/1940 - // Once runtime ver `DISABLED_VALIDATORS_RUNTIME_REQUIREMENT` is released remove this call to - // `get_disabled_validators_with_fallback`, add `request_disabled_validators` call to the - // `try_join!` above and use `try_runtime_api!` to get `disabled_validators` - let disabled_validators = - get_disabled_validators_with_fallback(ctx.sender(), parent).await.map_err(|e| { - Error::UtilError(TryFrom::try_from(e).expect("the conversion is infallible; qed")) - })?; - - let maybe_claim_queue = try_runtime_api!(fetch_claim_queue(ctx.sender(), parent).await); + let claim_queue = try_runtime_api!(claim_queue); + let disabled_validators = try_runtime_api!(disabled_validators); let signing_context = SigningContext { parent_hash: parent, session_index }; let validator = match Validator::construct( @@ -1328,33 +1197,15 @@ async fn construct_per_relay_parent_state( }, }; - let n_cores = cores.len(); + let n_cores = validator_groups.len(); let mut groups = HashMap::>::new(); let mut assigned_core = None; - let has_claim_queue = maybe_claim_queue.is_some(); - let mut claim_queue = maybe_claim_queue.unwrap_or_default().0; - - for (idx, core) in cores.iter().enumerate() { + for idx in 0..n_cores { let core_index = CoreIndex(idx as _); - if !has_claim_queue { - match core { - CoreState::Scheduled(scheduled) => - claim_queue.insert(core_index, [scheduled.para_id].into_iter().collect()), - CoreState::Occupied(occupied) if mode.is_enabled() => { - // Async backing makes it legal to build on top of - // occupied core. - if let Some(next) = &occupied.next_up_on_available { - claim_queue.insert(core_index, [next.para_id].into_iter().collect()) - } else { - continue - } - }, - _ => continue, - }; - } else if !claim_queue.contains_key(&core_index) { + if !claim_queue.contains_key(&core_index) { continue } @@ -1373,28 +1224,21 @@ async fn construct_per_relay_parent_state( let table_context = TableContext { validator, groups, validators: validators.to_vec(), disabled_validators }; - let table_config = TableConfig { - allow_multiple_seconded: match mode { - ProspectiveParachainsMode::Enabled { .. } => true, - ProspectiveParachainsMode::Disabled => false, - }, - }; Ok(Some(PerRelayParentState { - prospective_parachains_mode: mode, parent, node_features, executor_params, assigned_core, backed: HashSet::new(), - table: Table::new(table_config), + table: Table::new(), table_context, issued_statements: HashSet::new(), awaiting_validation: HashSet::new(), fallbacks: HashMap::new(), minimum_backing_votes, inject_core_index, - n_cores: cores.len() as u32, + n_cores: validator_groups.len() as u32, claim_queue: ClaimQueueSnapshot::from(claim_queue), validator_to_group, group_rotation_info, @@ -1412,7 +1256,6 @@ enum SecondingAllowed { #[overseer::contextbounds(CandidateBacking, prefix = self::overseer)] async fn seconding_sanity_check( ctx: &mut Context, - active_leaves: &HashMap, implicit_view: &ImplicitView, hypothetical_candidate: HypotheticalCandidate, ) -> SecondingAllowed { @@ -1423,49 +1266,36 @@ async fn seconding_sanity_check( let candidate_relay_parent = hypothetical_candidate.relay_parent(); let candidate_hash = hypothetical_candidate.candidate_hash(); - for (head, leaf_state) in active_leaves { - if ProspectiveParachainsMode::from(leaf_state).is_enabled() { - // Check that the candidate relay parent is allowed for para, skip the - // leaf otherwise. - let allowed_parents_for_para = - implicit_view.known_allowed_relay_parents_under(head, Some(candidate_para)); - if !allowed_parents_for_para.unwrap_or_default().contains(&candidate_relay_parent) { - continue - } - - let (tx, rx) = oneshot::channel(); - ctx.send_message(ProspectiveParachainsMessage::GetHypotheticalMembership( - HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(*head), - }, - tx, - )) - .await; - let response = rx.map_ok(move |candidate_memberships| { - let is_member_or_potential = candidate_memberships - .into_iter() - .find_map(|(candidate, leaves)| { - (candidate.candidate_hash() == candidate_hash).then_some(leaves) - }) - .and_then(|leaves| leaves.into_iter().find(|leaf| leaf == head)) - .is_some(); - - (is_member_or_potential, head) - }); - responses.push_back(response.boxed()); - } else { - if *head == candidate_relay_parent { - if let ActiveLeafState::ProspectiveParachainsDisabled { seconded } = leaf_state { - if seconded.contains(&candidate_para) { - // The leaf is already occupied. For non-prospective parachains, we only - // second one candidate. - return SecondingAllowed::No - } - } - responses.push_back(futures::future::ok((true, head)).boxed()); - } + for head in implicit_view.leaves() { + // Check that the candidate relay parent is allowed for para, skip the + // leaf otherwise. + let allowed_parents_for_para = + implicit_view.known_allowed_relay_parents_under(head, Some(candidate_para)); + if !allowed_parents_for_para.unwrap_or_default().contains(&candidate_relay_parent) { + continue } + + let (tx, rx) = oneshot::channel(); + ctx.send_message(ProspectiveParachainsMessage::GetHypotheticalMembership( + HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(*head), + }, + tx, + )) + .await; + let response = rx.map_ok(move |candidate_memberships| { + let is_member_or_potential = candidate_memberships + .into_iter() + .find_map(|(candidate, leaves)| { + (candidate.candidate_hash() == candidate_hash).then_some(leaves) + }) + .and_then(|leaves| leaves.into_iter().find(|leaf| leaf == head)) + .is_some(); + + (is_member_or_potential, head) + }); + responses.push_back(response.boxed()); } if responses.is_empty() { @@ -1514,11 +1344,7 @@ async fn handle_can_second_request( tx: oneshot::Sender, ) { let relay_parent = request.candidate_relay_parent; - let response = if state - .per_relay_parent - .get(&relay_parent) - .map_or(false, |pr_state| pr_state.prospective_parachains_mode.is_enabled()) - { + let response = if state.per_relay_parent.get(&relay_parent).is_some() { let hypothetical_candidate = HypotheticalCandidate::Incomplete { candidate_hash: request.candidate_hash, candidate_para: request.candidate_para_id, @@ -1526,13 +1352,8 @@ async fn handle_can_second_request( candidate_relay_parent: relay_parent, }; - let result = seconding_sanity_check( - ctx, - &state.per_leaf, - &state.implicit_view, - hypothetical_candidate, - ) - .await; + let result = + seconding_sanity_check(ctx, &state.implicit_view, hypothetical_candidate).await; match result { SecondingAllowed::No => false, @@ -1585,16 +1406,14 @@ async fn handle_validated_candidate_command( // sanity check that we're allowed to second the candidate // and that it doesn't conflict with other candidates we've // seconded. - let hypothetical_membership = match seconding_sanity_check( + if let SecondingAllowed::No = seconding_sanity_check( ctx, - &state.per_leaf, &state.implicit_view, hypothetical_candidate, ) .await { - SecondingAllowed::No => return Ok(()), - SecondingAllowed::Yes(membership) => membership, + return Ok(()) }; let statement = @@ -1644,24 +1463,6 @@ async fn handle_validated_candidate_command( Some(p) => p.seconded_locally = true, } - // record seconded candidates for non-prospective-parachains mode. - for leaf in hypothetical_membership { - let leaf_data = match state.per_leaf.get_mut(&leaf) { - None => { - gum::warn!( - target: LOG_TARGET, - leaf_hash = ?leaf, - "Missing `per_leaf` for known active leaf." - ); - - continue - }, - Some(d) => d, - }; - - leaf_data.add_seconded_candidate(candidate.descriptor().para_id()); - } - rp_state.issued_statements.insert(candidate_hash); metrics.on_candidate_seconded(); @@ -1765,13 +1566,11 @@ fn sign_statement( /// Import a statement into the statement table and return the summary of the import. /// -/// This will fail with `Error::RejectedByProspectiveParachains` if the message type -/// is seconded, the candidate is fresh, -/// and any of the following are true: +/// This will fail with `Error::RejectedByProspectiveParachains` if the message type is seconded, +/// the candidate is fresh, and any of the following are true: /// 1. There is no `PersistedValidationData` attached. -/// 2. Prospective parachains are enabled for the relay parent and the prospective parachains -/// subsystem returned an empty `HypotheticalMembership` i.e. did not recognize the candidate as -/// being applicable to any of the active leaves. +/// 2. Prospective parachains subsystem returned an empty `HypotheticalMembership` i.e. did not +/// recognize the candidate as being applicable to any of the active leaves. #[overseer::contextbounds(CandidateBacking, prefix = self::overseer)] async fn import_statement( ctx: &mut Context, @@ -1792,8 +1591,7 @@ async fn import_statement( // If this is a new candidate (statement is 'seconded' and candidate is unknown), // we need to create an entry in the `PerCandidateState` map. // - // If the relay parent supports prospective parachains, we also need - // to inform the prospective parachains subsystem of the seconded candidate. + // We also need to inform the prospective parachains subsystem of the seconded candidate. // If `ProspectiveParachainsMessage::Second` fails, then we return // Error::RejectedByProspectiveParachains. // @@ -1804,30 +1602,28 @@ async fn import_statement( // our active leaves. if let StatementWithPVD::Seconded(candidate, pvd) = statement.payload() { if !per_candidate.contains_key(&candidate_hash) { - if rp_state.prospective_parachains_mode.is_enabled() { - let (tx, rx) = oneshot::channel(); - ctx.send_message(ProspectiveParachainsMessage::IntroduceSecondedCandidate( - IntroduceSecondedCandidateRequest { - candidate_para: candidate.descriptor.para_id(), - candidate_receipt: candidate.clone(), - persisted_validation_data: pvd.clone(), - }, - tx, - )) - .await; + let (tx, rx) = oneshot::channel(); + ctx.send_message(ProspectiveParachainsMessage::IntroduceSecondedCandidate( + IntroduceSecondedCandidateRequest { + candidate_para: candidate.descriptor.para_id(), + candidate_receipt: candidate.clone(), + persisted_validation_data: pvd.clone(), + }, + tx, + )) + .await; - match rx.await { - Err(oneshot::Canceled) => { - gum::warn!( - target: LOG_TARGET, - "Could not reach the Prospective Parachains subsystem." - ); + match rx.await { + Err(oneshot::Canceled) => { + gum::warn!( + target: LOG_TARGET, + "Could not reach the Prospective Parachains subsystem." + ); - return Err(Error::RejectedByProspectiveParachains) - }, - Ok(false) => return Err(Error::RejectedByProspectiveParachains), - Ok(true) => {}, - } + return Err(Error::RejectedByProspectiveParachains) + }, + Ok(false) => return Err(Error::RejectedByProspectiveParachains), + Ok(true) => {}, } // Only save the candidate if it was approved by prospective parachains. @@ -1890,28 +1686,15 @@ async fn post_import_statement_actions( "Candidate backed", ); - if rp_state.prospective_parachains_mode.is_enabled() { - // Inform the prospective parachains subsystem - // that the candidate is now backed. - ctx.send_message(ProspectiveParachainsMessage::CandidateBacked( - para_id, - candidate_hash, - )) - .await; - // Notify statement distribution of backed candidate. - ctx.send_message(StatementDistributionMessage::Backed(candidate_hash)).await; - } else { - // The provisioner waits on candidate-backing, which means - // that we need to send unbounded messages to avoid cycles. - // - // Backed candidates are bounded by the number of validators, - // parachains, and the block production rate of the relay chain. - let message = ProvisionerMessage::ProvisionableData( - rp_state.parent, - ProvisionableData::BackedCandidate(backed.receipt()), - ); - ctx.send_unbounded_message(message); - } + // Inform the prospective parachains subsystem + // that the candidate is now backed. + ctx.send_message(ProspectiveParachainsMessage::CandidateBacked( + para_id, + candidate_hash, + )) + .await; + // Notify statement distribution of backed candidate. + ctx.send_message(StatementDistributionMessage::Backed(candidate_hash)).await; } else { gum::debug!(target: LOG_TARGET, ?candidate_hash, "Cannot get BackedCandidate"); } diff --git a/polkadot/node/core/backing/src/tests/mod.rs b/polkadot/node/core/backing/src/tests/mod.rs index 5e3d50373870..1a5fbeda100c 100644 --- a/polkadot/node/core/backing/src/tests/mod.rs +++ b/polkadot/node/core/backing/src/tests/mod.rs @@ -14,23 +14,23 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use self::test_helpers::mock::new_leaf; use super::*; use assert_matches::assert_matches; use futures::{future, Future}; use polkadot_node_primitives::{BlockData, InvalidCandidate, SignedFullStatement, Statement}; use polkadot_node_subsystem::{ - errors::RuntimeApiError, messages::{ - AllMessages, CollatorProtocolMessage, PvfExecKind, RuntimeApiMessage, RuntimeApiRequest, - ValidationFailed, + AllMessages, ChainApiMessage, CollatorProtocolMessage, HypotheticalMembership, PvfExecKind, + RuntimeApiMessage, RuntimeApiRequest, ValidationFailed, }, - ActiveLeavesUpdate, FromOrchestra, OverseerSignal, TimeoutExt, + ActivatedLeaf, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, TimeoutExt, }; -use polkadot_node_subsystem_test_helpers as test_helpers; +use polkadot_node_subsystem_test_helpers::mock::new_leaf; use polkadot_primitives::{ - node_features, vstaging::MutateDescriptorV2, CandidateDescriptor, GroupRotationInfo, HeadData, - PersistedValidationData, ScheduledCore, SessionIndex, LEGACY_MIN_BACKING_VOTES, + node_features, + vstaging::{CoreState, MutateDescriptorV2, OccupiedCore}, + BlockNumber, CandidateDescriptor, GroupRotationInfo, HeadData, Header, PersistedValidationData, + ScheduledCore, SessionIndex, LEGACY_MIN_BACKING_VOTES, }; use polkadot_primitives_test_helpers::{ dummy_candidate_receipt_bad_sig, dummy_collator, dummy_collator_signature, @@ -47,10 +47,10 @@ use std::{ time::Duration, }; -mod prospective_parachains; - -const ASYNC_BACKING_DISABLED_ERROR: RuntimeApiError = - RuntimeApiError::NotSupported { runtime_api_name: "test-runtime" }; +struct TestLeaf { + activated: ActivatedLeaf, + min_relay_parents: Vec<(ParaId, u32)>, +} fn table_statement_to_primitive(statement: TableStatement) -> Statement { match statement { @@ -190,6 +190,8 @@ fn test_harness>( keystore: KeystorePtr, test: impl FnOnce(VirtualOverseer) -> T, ) { + sp_tracing::init_for_tests(); + let pool = sp_core::testing::TaskExecutor::new(); let (context, virtual_overseer) = @@ -260,171 +262,349 @@ impl TestCandidateBuilder { } } -// Tests that the subsystem performs actions that are required on startup. -async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &mut TestState) { - // Start work on some new parent. - virtual_overseer - .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves(ActiveLeavesUpdate::start_work( - new_leaf(test_state.relay_parent, 1), - )))) - .await; - +async fn assert_validation_request( + virtual_overseer: &mut VirtualOverseer, + validation_code: ValidationCode, +) { assert_matches!( virtual_overseer.recv().await, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Err(ASYNC_BACKING_DISABLED_ERROR)).unwrap(); + RuntimeApiMessage::Request(_, RuntimeApiRequest::ValidationCodeByHash(hash, tx)) + ) if hash == validation_code.hash() => { + tx.send(Ok(Some(validation_code))).unwrap(); } ); +} - // Check that subsystem job issues a request for the session index for child. +async fn assert_validate_from_exhaustive( + virtual_overseer: &mut VirtualOverseer, + assert_pvd: &PersistedValidationData, + assert_pov: &PoV, + assert_validation_code: &ValidationCode, + assert_candidate: &CommittedCandidateReceipt, + expected_head_data: &HeadData, + result_validation_data: PersistedValidationData, +) { assert_matches!( virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.signing_context.session_index)).unwrap(); + AllMessages::CandidateValidation( + CandidateValidationMessage::ValidateFromExhaustive { + pov, + validation_data, + validation_code, + candidate_receipt, + exec_kind, + response_sender, + .. + }, + ) if validation_data == *assert_pvd && + validation_code == *assert_validation_code && + *pov == *assert_pov && candidate_receipt.descriptor == assert_candidate.descriptor && + matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && + candidate_receipt.commitments_hash == assert_candidate.commitments.hash() => + { + response_sender.send(Ok(ValidationResult::Valid( + CandidateCommitments { + head_data: expected_head_data.clone(), + horizontal_messages: Default::default(), + upward_messages: Default::default(), + new_validation_code: None, + processed_downward_messages: 0, + hrmp_watermark: 0, + }, + result_validation_data, + ))) + .unwrap(); } ); +} + +// Activates the initial leaf and returns the `ParaId` used. This function is a prerequisite for all +// tests. +async fn activate_initial_leaf( + virtual_overseer: &mut VirtualOverseer, + test_state: &mut TestState, +) -> ParaId { + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + let activated = new_leaf(test_state.relay_parent, LEAF_A_BLOCK_NUMBER - 1); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(virtual_overseer, test_leaf_a, test_state).await; + para_id +} - // Check that subsystem job issues a request for the validator groups. +async fn assert_candidate_is_shared_and_seconded( + virtual_overseer: &mut VirtualOverseer, + relay_parent: &Hash, +) { assert_matches!( virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::ValidatorGroups(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.validator_groups.clone())).unwrap(); + AllMessages::StatementDistribution( + StatementDistributionMessage::Share( + parent_hash, + _signed_statement, + ) + ) if parent_hash == *relay_parent => {} + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { + assert_eq!(*relay_parent, hash); + assert_matches!(statement.payload(), Statement::Seconded(_)); } ); +} - // Check that subsystem job issues a request for the availability cores. +async fn assert_candidate_is_shared_and_backed( + virtual_overseer: &mut VirtualOverseer, + relay_parent: &Hash, + expected_para_id: &ParaId, + expected_candidate_hash: &CandidateHash, +) { assert_matches!( virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AvailabilityCores(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.availability_cores.clone())).unwrap(); + AllMessages::StatementDistribution( + StatementDistributionMessage::Share(hash, _stmt) + ) => { + assert_eq!(*relay_parent, hash); } ); - if !test_state.per_session_cache_state.has_cached_validators { - // Check that subsystem job issues a request for a validator set. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked( + candidate_para_id, candidate_hash + ), + ) if *expected_candidate_hash == candidate_hash && candidate_para_id == *expected_para_id + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::StatementDistribution(StatementDistributionMessage::Backed ( + candidate_hash + )) if *expected_candidate_hash == candidate_hash + ); +} + +fn get_parent_hash(hash: Hash) -> Hash { + Hash::from_low_u64_be(hash.to_low_u64_be() + 1) +} + +async fn activate_leaf( + virtual_overseer: &mut VirtualOverseer, + leaf: TestLeaf, + test_state: &mut TestState, +) { + let TestLeaf { activated, min_relay_parents } = leaf; + let leaf_hash = activated.hash; + let leaf_number = activated.number; + // Start work on some new parent. + virtual_overseer + .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves(ActiveLeavesUpdate::start_work( + activated, + )))) + .await; + + let min_min = *min_relay_parents + .iter() + .map(|(_, block_num)| block_num) + .min() + .unwrap_or(&leaf_number); + + let ancestry_len = leaf_number + 1 - min_min; + + let ancestry_hashes = std::iter::successors(Some(leaf_hash), |h| Some(get_parent_hash(*h))) + .take(ancestry_len as usize); + let ancestry_numbers = (min_min..=leaf_number).rev(); + let ancestry_iter = ancestry_hashes.zip(ancestry_numbers).peekable(); + + let mut next_overseer_message = None; + // How many blocks were actually requested. + let mut requested_len = 0; + { + let mut ancestry_iter = ancestry_iter.clone(); + while let Some((hash, number)) = ancestry_iter.next() { + // May be `None` for the last element. + let parent_hash = + ancestry_iter.peek().map(|(h, _)| *h).unwrap_or_else(|| get_parent_hash(hash)); + + let msg = virtual_overseer.recv().await; + // It may happen that some blocks were cached by implicit view, + // reuse the message. + if !matches!(&msg, AllMessages::ChainApi(ChainApiMessage::BlockHeader(..))) { + next_overseer_message.replace(msg); + break + } + + assert_matches!( + msg, + AllMessages::ChainApi( + ChainApiMessage::BlockHeader(_hash, tx) + ) if _hash == hash => { + let header = Header { + parent_hash, + number, + state_root: Hash::zero(), + extrinsics_root: Hash::zero(), + digest: Default::default(), + }; + + tx.send(Ok(Some(header))).unwrap(); + } + ); + + if requested_len == 0 { + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::GetMinimumRelayParents(parent, tx) + ) if parent == leaf_hash => { + tx.send(min_relay_parents.clone()).unwrap(); + } + ); + } + + requested_len += 1; + } + } + + for (hash, number) in ancestry_iter.take(requested_len) { + let msg = match next_overseer_message.take() { + Some(msg) => msg, + None => virtual_overseer.recv().await, + }; + + // Check that subsystem job issues a request for the session index for child. assert_matches!( - virtual_overseer.recv().await, + msg, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.validator_public.clone())).unwrap(); + RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx)) + ) if parent == hash => { + tx.send(Ok(test_state.signing_context.session_index)).unwrap(); } ); - test_state.per_session_cache_state.has_cached_validators = true; - } - if !test_state.per_session_cache_state.has_cached_node_features { - // Node features request from runtime: all features are disabled. + // Check that subsystem job issues a request for the validator groups. assert_matches!( virtual_overseer.recv().await, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) - ) => { - tx.send(Ok(test_state.node_features.clone())).unwrap(); + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ValidatorGroups(tx)) + ) if parent == hash => { + let (validator_groups, mut group_rotation_info) = test_state.validator_groups.clone(); + group_rotation_info.now = number; + tx.send(Ok((validator_groups, group_rotation_info))).unwrap(); } ); - test_state.per_session_cache_state.has_cached_node_features = true; - } - if !test_state.per_session_cache_state.has_cached_executor_params { - // Check if subsystem job issues a request for the executor parameters. assert_matches!( virtual_overseer.recv().await, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_parent, RuntimeApiRequest::SessionExecutorParams(_session_index, tx)) - ) => { - tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) + ) if parent == hash => { + tx.send(Ok( + test_state.claim_queue.clone() + )).unwrap(); } ); - test_state.per_session_cache_state.has_cached_executor_params = true; - } - if !test_state.per_session_cache_state.has_cached_minimum_backing_votes { - // Check if subsystem job issues a request for the minimum backing votes. + // Check that the subsystem job issues a request for the disabled validators. assert_matches!( virtual_overseer.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::MinimumBackingVotes(session_index, tx), - )) if parent == test_state.relay_parent && session_index == test_state.signing_context.session_index => { - tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::DisabledValidators(tx)) + ) if parent == hash => { + tx.send(Ok(test_state.disabled_validators.clone())).unwrap(); } ); - test_state.per_session_cache_state.has_cached_minimum_backing_votes = true; - } - // Check that subsystem job issues a request for the runtime version. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(RuntimeApiRequest::DISABLED_VALIDATORS_RUNTIME_REQUIREMENT)).unwrap(); - } - ); - - // Check that subsystem job issues a request for the disabled validators. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::DisabledValidators(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(test_state.disabled_validators.clone())).unwrap(); + if !test_state.per_session_cache_state.has_cached_validators { + // Check that subsystem job issues a request for a validator set. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) + ) if parent == hash => { + tx.send(Ok(test_state.validator_public.clone())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_validators = true; } - ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); + if !test_state.per_session_cache_state.has_cached_node_features { + // Node features request from runtime: all features are disabled. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) + ) if parent == hash => { + tx.send(Ok(test_state.node_features.clone())).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_node_features = true; } - ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) - ) if parent == test_state.relay_parent => { - tx.send(Ok( - test_state.claim_queue.clone() - )).unwrap(); + if !test_state.per_session_cache_state.has_cached_executor_params { + // Check if subsystem job issues a request for the executor parameters. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionExecutorParams(_session_index, tx)) + ) if parent == hash => { + tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_executor_params = true; } - ); -} -async fn assert_validation_requests( - virtual_overseer: &mut VirtualOverseer, - validation_code: ValidationCode, -) { - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::ValidationCodeByHash(hash, tx)) - ) if hash == validation_code.hash() => { - tx.send(Ok(Some(validation_code))).unwrap(); + if !test_state.per_session_cache_state.has_cached_minimum_backing_votes { + // Check if subsystem job issues a request for the minimum backing votes. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::MinimumBackingVotes(session_index, tx), + )) if parent == hash && session_index == test_state.signing_context.session_index => { + tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); + } + ); + test_state.per_session_cache_state.has_cached_minimum_backing_votes = true; } - ); + } } -async fn assert_validate_from_exhaustive( +async fn assert_validate_seconded_candidate( virtual_overseer: &mut VirtualOverseer, - assert_pvd: &PersistedValidationData, + relay_parent: Hash, + candidate: &CommittedCandidateReceipt, assert_pov: &PoV, + assert_pvd: &PersistedValidationData, assert_validation_code: &ValidationCode, - assert_candidate: &CommittedCandidateReceipt, expected_head_data: &HeadData, - result_validation_data: PersistedValidationData, + fetch_pov: bool, ) { + assert_validation_request(virtual_overseer, assert_validation_code.clone()).await; + + if fetch_pov { + assert_matches!( + virtual_overseer.recv().await, + AllMessages::AvailabilityDistribution( + AvailabilityDistributionMessage::FetchPoV { + relay_parent: hash, + tx, + .. + } + ) if hash == relay_parent => { + tx.send(assert_pov.clone()).unwrap(); + } + ); + } + assert_matches!( virtual_overseer.recv().await, AllMessages::CandidateValidation( @@ -439,9 +619,9 @@ async fn assert_validate_from_exhaustive( }, ) if validation_data == *assert_pvd && validation_code == *assert_validation_code && - *pov == *assert_pov && candidate_receipt.descriptor == assert_candidate.descriptor && + *pov == *assert_pov && candidate_receipt.descriptor == candidate.descriptor && matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate_receipt.commitments_hash == assert_candidate.commitments.hash() => + candidate_receipt.commitments_hash == candidate.commitments.hash() => { response_sender.send(Ok(ValidationResult::Valid( CandidateCommitments { @@ -452,30 +632,79 @@ async fn assert_validate_from_exhaustive( processed_downward_messages: 0, hrmp_watermark: 0, }, - result_validation_data, + assert_pvd.clone(), ))) .unwrap(); } ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::AvailabilityStore( + AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } + ) if candidate_hash == candidate.hash() => { + tx.send(Ok(())).unwrap(); + } + ); +} + +pub(crate) async fn assert_hypothetical_membership_requests( + virtual_overseer: &mut VirtualOverseer, + mut expected_requests: Vec<( + HypotheticalMembershipRequest, + Vec<(HypotheticalCandidate, HypotheticalMembership)>, + )>, +) { + // Requests come with no particular order. + let requests_num = expected_requests.len(); + + for _ in 0..requests_num { + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::GetHypotheticalMembership(request, tx), + ) => { + let idx = match expected_requests.iter().position(|r| r.0 == request) { + Some(idx) => idx, + None => + panic!( + "unexpected hypothetical membership request, no match found for {:?}", + request + ), + }; + let resp = std::mem::take(&mut expected_requests[idx].1); + tx.send(resp).unwrap(); + + expected_requests.remove(idx); + } + ); + } } -// Test that a `CandidateBackingMessage::Second` issues validation work -// and in case validation is successful issues a `StatementDistributionMessage`. +pub(crate) fn make_hypothetical_membership_response( + hypothetical_candidate: HypotheticalCandidate, + relay_parent_hash: Hash, +) -> Vec<(HypotheticalCandidate, HypotheticalMembership)> { + vec![(hypothetical_candidate, vec![relay_parent_hash])] +} + +// Test that a `CandidateBackingMessage::Second` issues validation work and in case validation is +// successful issues correct messages. #[test] fn backing_second_works() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); let validation_code = ValidationCode(vec![1, 2, 3]); - let expected_head_data = test_state.head_data.get(&test_state.chain_ids[0]).unwrap(); + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); let pov_hash = pov.hash(); let candidate = TestCandidateBuilder { - para_id: test_state.chain_ids[0], + para_id, relay_parent: test_state.relay_parent, pov_hash, head_data: expected_head_data.clone(), @@ -494,46 +723,53 @@ fn backing_second_works() { virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - assert_validation_requests(&mut virtual_overseer, validation_code.clone()).await; - - assert_validate_from_exhaustive( + assert_validate_seconded_candidate( &mut virtual_overseer, - &pvd, + test_state.relay_parent, + &candidate, &pov, + &pvd, &validation_code, - &candidate, expected_head_data, - test_state.validation_data.clone(), + false, ) .await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate.hash() => { - tx.send(Ok(())).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == test_state.relay_parent => {} - ); + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(test_state.relay_parent), + }; + let expected_response = + make_hypothetical_membership_response(hypothetical_candidate, test_state.relay_parent); + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![(expected_request, expected_response)], + ) + .await; assert_matches!( virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(test_state.relay_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &test_state.relay_parent) + .await; + virtual_overseer .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves( ActiveLeavesUpdate::stop_work(test_state.relay_parent), @@ -559,7 +795,7 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { } test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_ab = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd_ab = dummy_pvd(); @@ -567,10 +803,10 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { let pov_hash = pov_ab.hash(); - let expected_head_data = test_state.head_data.get(&test_state.chain_ids[0]).unwrap(); + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); let candidate_a = TestCandidateBuilder { - para_id: test_state.chain_ids[0], + para_id, relay_parent: test_state.relay_parent, pov_hash, head_data: expected_head_data.clone(), @@ -581,7 +817,6 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { .build(); let candidate_a_hash = candidate_a.hash(); - let candidate_a_commitments_hash = candidate_a.commitments.hash(); let public1 = Keystore::sr25519_generate_new( &*test_state.keystore, @@ -623,85 +858,40 @@ fn backing_works(#[case] elastic_scaling_mvp: bool) { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_ab.clone()).await; - - // Sending a `Statement::Seconded` for our assignment will start - // validation process. The first thing requested is the PoV. assert_matches!( virtual_overseer.recv().await, - AllMessages::AvailabilityDistribution( - AvailabilityDistributionMessage::FetchPoV { - relay_parent, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, tx, - .. - } - ) if relay_parent == test_state.relay_parent => { - tx.send(pov_ab.clone()).unwrap(); + ), + ) if + req.candidate_receipt == candidate_a + && req.candidate_para == para_id + && pvd_ab == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); - // The next step is the actual request to Validation subsystem - // to validate the `Seconded` candidate. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { - validation_data, - validation_code, - candidate_receipt, - pov, - exec_kind, - response_sender, - .. - }, - ) if validation_data == pvd_ab && - validation_code == validation_code_ab && - *pov == pov_ab && candidate_receipt.descriptor == candidate_a.descriptor && - matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate_receipt.commitments_hash == candidate_a_commitments_hash => - { - response_sender.send(Ok( - ValidationResult::Valid(CandidateCommitments { - head_data: expected_head_data.clone(), - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, test_state.validation_data.clone()), - )).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate_a.hash() => { - tx.send(Ok(())).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share(hash, _stmt) - ) => { - assert_eq!(test_state.relay_parent, hash); - } - ); + assert_validate_seconded_candidate( + &mut virtual_overseer, + candidate_a.descriptor.relay_parent(), + &candidate_a, + &pov_ab, + &pvd_ab, + &validation_code_ab, + expected_head_data, + true, + ) + .await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(candidate_receipt) - ) - ) => { - assert_eq!(candidate_receipt, candidate_a.to_plain()); - } - ); + assert_candidate_is_shared_and_backed( + &mut virtual_overseer, + &test_state.relay_parent, + ¶_id, + &candidate_a_hash, + ) + .await; let statement = CandidateBackingMessage::Statement(test_state.relay_parent, signed_b.clone()); @@ -777,7 +967,7 @@ fn get_backed_candidate_preserves_order() { .insert(CoreIndex(2), [test_state.chain_ids[1]].into_iter().collect()); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pov_b = PoV { block_data: BlockData(vec![3, 4, 5]) }; @@ -886,17 +1076,37 @@ fn get_backed_candidate_preserves_order() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; + // Prospective parachains are notified about candidate seconded first. assert_matches!( virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(candidate_receipt) - ) - ) => { - assert_eq!(candidate_receipt, candidate.to_plain()); + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == candidate.descriptor.para_id() + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked( + candidate_para_id, candidate_hash + ), + ) if candidate.hash() == candidate_hash && candidate_para_id == candidate.descriptor.para_id() + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::StatementDistribution(StatementDistributionMessage::Backed ( + candidate_hash + )) if candidate.hash() == candidate_hash + ); } // Happy case, all candidates should be present. @@ -1178,7 +1388,7 @@ fn extract_core_index_from_statement_works() { fn backing_works_while_validation_ongoing() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_abc = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd_abc = dummy_pvd(); @@ -1258,7 +1468,22 @@ fn backing_works_while_validation_ongoing() { CandidateBackingMessage::Statement(test_state.relay_parent, signed_a.clone()); virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_abc.clone()).await; + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate_a + && req.candidate_para == para_id + && pvd_abc == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_validation_request(&mut virtual_overseer, validation_code_abc.clone()).await; // Sending a `Statement::Seconded` for our assignment will start // validation process. The first thing requested is PoV from the @@ -1310,15 +1535,11 @@ fn backing_works_while_validation_ongoing() { // Candidate gets backed entirely by other votes. assert_matches!( virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(CandidateReceipt { - descriptor, - .. - }) - ) - ) if descriptor == candidate_a.descriptor + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked( + candidate_para_id, candidate_hash + ), + ) if candidate_a_hash == candidate_hash && candidate_para_id == para_id ); let statement = @@ -1367,13 +1588,12 @@ fn backing_works_while_validation_ongoing() { }); } -// Issuing conflicting statements on the same candidate should -// be a misbehavior. +// Issuing conflicting statements on the same candidate should be a misbehavior. #[test] fn backing_misbehavior_works() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![1, 2, 3]) }; @@ -1395,8 +1615,6 @@ fn backing_misbehavior_works() { .build(); let candidate_a_hash = candidate_a.hash(); - let candidate_a_commitments_hash = candidate_a.commitments.hash(); - let public2 = Keystore::sr25519_generate_new( &*test_state.keystore, ValidatorId::ID, @@ -1430,85 +1648,41 @@ fn backing_misbehavior_works() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; - + // Prospective parachains are notified about candidate seconded first. assert_matches!( virtual_overseer.recv().await, - AllMessages::AvailabilityDistribution( - AvailabilityDistributionMessage::FetchPoV { - relay_parent, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, tx, - .. - } - ) if relay_parent == test_state.relay_parent => { - tx.send(pov_a.clone()).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { - validation_data, - validation_code, - candidate_receipt, - pov, - exec_kind, - response_sender, - .. - }, - ) if validation_data == pvd_a && - validation_code == validation_code_a && - *pov == pov_a && candidate_receipt.descriptor == candidate_a.descriptor && - matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate_a_commitments_hash == candidate_receipt.commitments_hash => - { - response_sender.send(Ok( - ValidationResult::Valid(CandidateCommitments { - head_data: expected_head_data.clone(), - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, test_state.validation_data.clone()), - )).unwrap(); + ), + ) if + req.candidate_receipt == candidate_a + && req.candidate_para == para_id + && pvd_a == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate_a.hash() => { - tx.send(Ok(())).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - relay_parent, - signed_statement, - ) - ) if relay_parent == test_state.relay_parent => { - assert_eq!(*signed_statement.payload(), StatementWithPVD::Valid(candidate_a_hash)); - } - ); + assert_validate_seconded_candidate( + &mut virtual_overseer, + test_state.relay_parent, + &candidate_a, + &pov_a, + &pvd_a, + &validation_code_a, + expected_head_data, + true, + ) + .await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(CandidateReceipt { - descriptor, - .. - }) - ) - ) if descriptor == candidate_a.descriptor - ); + assert_candidate_is_shared_and_backed( + &mut virtual_overseer, + &test_state.relay_parent, + ¶_id, + &candidate_a_hash, + ) + .await; // This `Valid` statement is redundant after the `Seconded` statement already sent. let statement = @@ -1553,13 +1727,13 @@ fn backing_misbehavior_works() { }); } -// Test that if we are asked to second an invalid candidate we -// can still second a valid one afterwards. +// Test that if we are asked to second an invalid candidate we can still second a valid one +// afterwards. #[test] -fn backing_dont_second_invalid() { +fn backing_doesnt_second_invalid() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_block_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -1610,7 +1784,7 @@ fn backing_dont_second_invalid() { virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; + assert_validation_request(&mut virtual_overseer, validation_code_a.clone()).await; assert_matches!( virtual_overseer.recv().await, @@ -1650,38 +1824,18 @@ fn backing_dont_second_invalid() { virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_b.clone()).await; + assert_validation_request(&mut virtual_overseer, validation_code_b.clone()).await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { - validation_data, - validation_code, - candidate_receipt, - pov, - exec_kind, - response_sender, - .. - }, - ) if validation_data == pvd_b && - validation_code == validation_code_b && - *pov == pov_block_b && candidate_receipt.descriptor == candidate_b.descriptor && - matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate_b.commitments.hash() == candidate_receipt.commitments_hash => - { - response_sender.send(Ok( - ValidationResult::Valid(CandidateCommitments { - head_data: expected_head_data.clone(), - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, pvd_b.clone()), - )).unwrap(); - } - ); + assert_validate_from_exhaustive( + &mut virtual_overseer, + &pvd_b, + &pov_block_b, + &validation_code_b, + &candidate_b, + expected_head_data, + test_state.validation_data.clone(), + ) + .await; assert_matches!( virtual_overseer.recv().await, @@ -1692,15 +1846,42 @@ fn backing_dont_second_invalid() { } ); + let hypothetical_candidate_b = HypotheticalCandidate::Complete { + candidate_hash: candidate_b.hash(), + receipt: Arc::new(candidate_b.clone()), + persisted_validation_data: pvd_a.clone(), // ??? + }; + let expected_request_b = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate_b.clone()], + fragment_chain_relay_parent: Some(test_state.relay_parent), + }; + let expected_response_b = make_hypothetical_membership_response( + hypothetical_candidate_b.clone(), + test_state.relay_parent, + ); + + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![ + // (expected_request_a, expected_response_a), + (expected_request_b, expected_response_b), + ], + ) + .await; + + // Prospective parachains are notified. assert_matches!( virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - signed_statement, - ) - ) if parent_hash == test_state.relay_parent => { - assert_eq!(*signed_statement.payload(), StatementWithPVD::Seconded(candidate_b, pvd_b.clone())); + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) => { + assert_eq!(req.candidate_receipt, candidate_b); + assert_eq!(req.candidate_para, para_id); + assert_eq!(pvd_a, req.persisted_validation_data); // ??? + tx.send(true).unwrap(); } ); @@ -1713,13 +1894,13 @@ fn backing_dont_second_invalid() { }); } -// Test that if we have already issued a statement (in this case `Invalid`) about a -// candidate we will not be issuing a `Seconded` statement on it. +// Test that if we have already issued a statement (in this case `Invalid`) about a candidate we +// will not be issuing a `Seconded` statement on it. #[test] fn backing_second_after_first_fails_works() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -1762,7 +1943,22 @@ fn backing_second_after_first_fails_works() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd_a == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_validation_request(&mut virtual_overseer, validation_code_a.clone()).await; // Subsystem requests PoV and requests validation. assert_matches!( @@ -1845,7 +2041,7 @@ fn backing_second_after_first_fails_works() { // triggered on the prev step. virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_to_second.clone()).await; + assert_validation_request(&mut virtual_overseer, validation_code_to_second.clone()).await; assert_matches!( virtual_overseer.recv().await, @@ -1859,13 +2055,13 @@ fn backing_second_after_first_fails_works() { }); } -// That that if the validation of the candidate has failed this does not stop -// the work of this subsystem and so it is not fatal to the node. +// Test that if the validation of the candidate has failed this does not stop the work of this +// subsystem and so it is not fatal to the node. #[test] fn backing_works_after_failed_validation() { let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); @@ -1906,7 +2102,22 @@ fn backing_works_after_failed_validation() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd_a == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_validation_request(&mut virtual_overseer, validation_code_a.clone()).await; // Subsystem requests PoV and requests validation. assert_matches!( @@ -2041,16 +2252,16 @@ fn candidate_backing_reorders_votes() { // Test whether we retry on failed PoV fetching. #[test] fn retry_works() { - // sp_tracing::try_init_simple(); let mut test_state = TestState::default(); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd_a = dummy_pvd(); let validation_code_a = ValidationCode(vec![1, 2, 3]); let pov_hash = pov_a.hash(); + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); let candidate = TestCandidateBuilder { para_id: test_state.chain_ids[0], @@ -2059,7 +2270,7 @@ fn retry_works() { erasure_root: make_erasure_root(&test_state, pov_a.clone(), pvd_a.clone()), persisted_validation_data_hash: pvd_a.hash(), validation_code: validation_code_a.0.clone(), - ..Default::default() + head_data: expected_head_data.clone(), } .build(); @@ -2117,7 +2328,22 @@ fn retry_works() { CandidateBackingMessage::Statement(test_state.relay_parent, signed_a.clone()); virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd_a == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_validation_request(&mut virtual_overseer, validation_code_a.clone()).await; // Subsystem requests PoV and requests validation. // We cancel - should mean retry on next backing statement. @@ -2141,17 +2367,23 @@ fn retry_works() { // Not deterministic which message comes first: for _ in 0u32..3 { match virtual_overseer.recv().await { - AllMessages::Provisioner(ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(CandidateReceipt { descriptor, .. }), - )) => { - assert_eq!(descriptor, candidate.descriptor); + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked( + candidate_para_id, + candidate_hash, + ), + ) if candidate_hash == candidate_hash && candidate_para_id == para_id => { + assert_eq!(candidate_para_id, para_id); + assert_eq!(candidate_hash, candidate.hash()); }, AllMessages::AvailabilityDistribution( AvailabilityDistributionMessage::FetchPoV { relay_parent, tx, .. }, ) if relay_parent == test_state.relay_parent => { std::mem::drop(tx); }, + AllMessages::StatementDistribution(StatementDistributionMessage::Backed( + candidate_hash, + )) if candidate_hash == candidate.hash() => {}, AllMessages::RuntimeApi(RuntimeApiMessage::Request( _, RuntimeApiRequest::ValidationCodeByHash(hash, tx), @@ -2168,8 +2400,6 @@ fn retry_works() { CandidateBackingMessage::Statement(test_state.relay_parent, signed_c.clone()); virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - assert_validation_requests(&mut virtual_overseer, validation_code_a.clone()).await; - assert_matches!( virtual_overseer.recv().await, AllMessages::AvailabilityDistribution( @@ -2211,7 +2441,7 @@ fn observes_backing_even_if_not_validator() { let mut test_state = TestState::default(); let empty_keystore = Arc::new(sc_keystore::LocalKeystore::in_memory()); test_harness(empty_keystore, |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![1, 2, 3]) }; let pvd = dummy_pvd(); @@ -2292,6 +2522,22 @@ fn observes_backing_even_if_not_validator() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; + // Prospective parachains are notified about candidate seconded first. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate_a + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + let statement = CandidateBackingMessage::Statement(test_state.relay_parent, signed_b.clone()); @@ -2299,14 +2545,11 @@ fn observes_backing_even_if_not_validator() { assert_matches!( virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(candidate_receipt) - ) - ) => { - assert_eq!(candidate_receipt, candidate_a.to_plain()); - } + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked( + candidate_para_id, candidate_hash + ), + ) if candidate_a_hash == candidate_hash && candidate_para_id == para_id ); let statement = @@ -2323,13 +2566,29 @@ fn observes_backing_even_if_not_validator() { }); } -// Tests that it's impossible to second multiple candidates per relay parent -// without prospective parachains. #[test] -fn cannot_second_multiple_candidates_per_parent() { +fn new_leaf_view_doesnt_clobber_old() { let mut test_state = TestState::default(); + let relay_parent_2 = Hash::repeat_byte(1); + assert_ne!(test_state.relay_parent, relay_parent_2); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; + + // New leaf that doesn't clobber old. + { + let old_relay_parent = test_state.relay_parent; + test_state.relay_parent = relay_parent_2; + + const LEAF_B_BLOCK_NUMBER: BlockNumber = 101; + const LEAF_B_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + let activated = new_leaf(test_state.relay_parent, LEAF_B_BLOCK_NUMBER - 1); + let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; + let test_leaf_b = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; + test_state.relay_parent = old_relay_parent; + } let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2338,7 +2597,7 @@ fn cannot_second_multiple_candidates_per_parent() { let expected_head_data = test_state.head_data.get(&test_state.chain_ids[0]).unwrap(); let pov_hash = pov.hash(); - let candidate_builder = TestCandidateBuilder { + let candidate = TestCandidateBuilder { para_id: test_state.chain_ids[0], relay_parent: test_state.relay_parent, pov_hash, @@ -2346,8 +2605,8 @@ fn cannot_second_multiple_candidates_per_parent() { erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), persisted_validation_data_hash: pvd.hash(), validation_code: validation_code.0.clone(), - }; - let candidate = candidate_builder.clone().build(); + } + .build(); let second = CandidateBackingMessage::Second( test_state.relay_parent, @@ -2358,173 +2617,29 @@ fn cannot_second_multiple_candidates_per_parent() { virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - assert_validation_requests(&mut virtual_overseer, validation_code.clone()).await; + // If the old leaf was clobbered by the first, the seconded candidate + // would be ignored. + assert!( + virtual_overseer + .recv() + .timeout(std::time::Duration::from_millis(500)) + .await + .is_some(), + "first leaf appears to be inactive" + ); - assert_validate_from_exhaustive( - &mut virtual_overseer, - &pvd, - &pov, - &validation_code, - &candidate, - expected_head_data, - test_state.validation_data.clone(), - ) - .await; + virtual_overseer + }); +} - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate.hash() => { - tx.send(Ok(())).unwrap(); - } - ); +// Test that a disabled local validator doesn't do any work on `CandidateBackingMessage::Second` +#[test] +fn disabled_validator_doesnt_distribute_statement_on_receiving_second() { + let mut test_state = TestState::default(); + test_state.disabled_validators.push(ValidatorIndex(0)); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == test_state.relay_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(test_state.relay_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - // Try to second candidate with the same relay parent again. - - // Make sure the candidate hash is different. - let validation_code = ValidationCode(vec![4, 5, 6]); - let mut candidate_builder = candidate_builder; - candidate_builder.validation_code = validation_code.0.clone(); - let candidate = candidate_builder.build(); - - let second = CandidateBackingMessage::Second( - test_state.relay_parent, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - // The validation is still requested. - assert_validation_requests(&mut virtual_overseer, validation_code.clone()).await; - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { response_sender, .. }, - ) => { - response_sender.send(Ok(ValidationResult::Valid( - CandidateCommitments { - head_data: expected_head_data.clone(), - horizontal_messages: Default::default(), - upward_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, - test_state.validation_data.clone(), - ))) - .unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate.hash() => { - tx.send(Ok(())).unwrap(); - } - ); - - // Validation done, but the candidate is rejected cause of 0-depth being already occupied. - - assert!(virtual_overseer - .recv() - .timeout(std::time::Duration::from_millis(50)) - .await - .is_none()); - - virtual_overseer - }); -} - -#[test] -fn new_leaf_view_doesnt_clobber_old() { - let mut test_state = TestState::default(); - let relay_parent_2 = Hash::repeat_byte(1); - assert_ne!(test_state.relay_parent, relay_parent_2); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; - - // New leaf that doesn't clobber old. - { - let old_relay_parent = test_state.relay_parent; - test_state.relay_parent = relay_parent_2; - test_startup(&mut virtual_overseer, &mut test_state).await; - test_state.relay_parent = old_relay_parent; - } - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(&test_state.chain_ids[0]).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id: test_state.chain_ids[0], - relay_parent: test_state.relay_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - test_state.relay_parent, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - // If the old leaf was clobbered by the first, the seconded candidate - // would be ignored. - assert!( - virtual_overseer - .recv() - .timeout(std::time::Duration::from_millis(500)) - .await - .is_some(), - "first leaf appears to be inactive" - ); - - virtual_overseer - }); -} - -// Test that a disabled local validator doesn't do any work on `CandidateBackingMessage::Second` -#[test] -fn disabled_validator_doesnt_distribute_statement_on_receiving_second() { - let mut test_state = TestState::default(); - test_state.disabled_validators.push(ValidatorIndex(0)); - - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2572,7 +2687,7 @@ fn disabled_validator_doesnt_distribute_statement_on_receiving_statement() { test_state.disabled_validators.push(ValidatorIndex(0)); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2614,6 +2729,21 @@ fn disabled_validator_doesnt_distribute_statement_on_receiving_statement() { virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + // Ensure backing subsystem is not doing any work assert_matches!(virtual_overseer.recv().timeout(Duration::from_secs(1)).await, None); @@ -2634,7 +2764,7 @@ fn validator_ignores_statements_from_disabled_validators() { test_state.disabled_validators.push(ValidatorIndex(2)); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - test_startup(&mut virtual_overseer, &mut test_state).await; + let para_id = activate_initial_leaf(&mut virtual_overseer, &mut test_state).await; let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; let pvd = dummy_pvd(); @@ -2653,7 +2783,6 @@ fn validator_ignores_statements_from_disabled_validators() { validation_code: validation_code.0.clone(), } .build(); - let candidate_commitments_hash = candidate.commitments.hash(); let public2 = Keystore::sr25519_generate_new( &*test_state.keystore, @@ -2705,93 +2834,1198 @@ fn validator_ignores_statements_from_disabled_validators() { virtual_overseer.send(FromOrchestra::Communication { msg: statement_3 }).await; - assert_validation_requests(&mut virtual_overseer, validation_code.clone()).await; - - // Sending a `Statement::Seconded` for our assignment will start - // validation process. The first thing requested is the PoV. + // Prospective parachains are notified about candidate seconded first. assert_matches!( virtual_overseer.recv().await, - AllMessages::AvailabilityDistribution( - AvailabilityDistributionMessage::FetchPoV { - relay_parent, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, tx, - .. - } - ) if relay_parent == test_state.relay_parent => { - tx.send(pov.clone()).unwrap(); + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); - // The next step is the actual request to Validation subsystem - // to validate the `Seconded` candidate. - let expected_pov = pov; - let expected_validation_code = validation_code; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { - validation_data, - validation_code, - candidate_receipt, - pov, - executor_params: _, - exec_kind, - response_sender, - } - ) if validation_data == pvd && - validation_code == expected_validation_code && - *pov == expected_pov && candidate_receipt.descriptor == candidate.descriptor && - matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate_commitments_hash == candidate_receipt.commitments_hash => - { - response_sender.send(Ok( - ValidationResult::Valid(CandidateCommitments { - head_data: expected_head_data.clone(), - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, test_state.validation_data.clone()), - )).unwrap(); - } - ); + assert_validate_seconded_candidate( + &mut virtual_overseer, + test_state.relay_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + true, + ) + .await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate.hash() => { - tx.send(Ok(())).unwrap(); - } - ); + assert_candidate_is_shared_and_backed( + &mut virtual_overseer, + &test_state.relay_parent, + ¶_id, + &candidate.hash(), + ) + .await; - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share(hash, _stmt) - ) => { - assert_eq!(test_state.relay_parent, hash); - } + virtual_overseer + .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves( + ActiveLeavesUpdate::stop_work(test_state.relay_parent), + ))) + .await; + virtual_overseer + }); +} + +// Test that `seconding_sanity_check` works when a candidate is allowed +// for all leaves. +#[test] +fn seconding_sanity_check_allowed_on_all() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate is seconded in a parent of the activated `leaf_a`. + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + // `a` is grandparent of `b`. + let leaf_a_hash = Hash::from_low_u64_be(130); + let leaf_a_parent = get_parent_hash(leaf_a_hash); + let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; + const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; + + let leaf_b_hash = Hash::from_low_u64_be(128); + let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; + let test_leaf_b = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); + + let pov_hash = pov.hash(); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), ); + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }; + let expected_response_a = + make_hypothetical_membership_response(hypothetical_candidate.clone(), leaf_a_hash); + let expected_request_b = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_b_hash), + }; + let expected_response_b = + make_hypothetical_membership_response(hypothetical_candidate, leaf_b_hash); + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![ + (expected_request_a, expected_response_a), + (expected_request_b, expected_response_b), + ], + ) + .await; + // Prospective parachains are notified. assert_matches!( virtual_overseer.recv().await, - AllMessages::Provisioner( - ProvisionerMessage::ProvisionableData( - _, - ProvisionableData::BackedCandidate(candidate_receipt) - ) - ) => { - assert_eq!(candidate_receipt, candidate.to_plain()); + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); } ); + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &leaf_a_parent).await; + virtual_overseer - .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves( - ActiveLeavesUpdate::stop_work(test_state.relay_parent), - ))) - .await; + }); +} + +// Test that `seconding_sanity_check` disallows seconding when a candidate is disallowed +// for all leaves. +#[test] +fn seconding_sanity_check_disallowed() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate is seconded in a parent of the activated `leaf_a`. + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + let leaf_b_hash = Hash::from_low_u64_be(128); + // `a` is grandparent of `b`. + let leaf_a_hash = Hash::from_low_u64_be(130); + let leaf_a_parent = get_parent_hash(leaf_a_hash); + let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; + const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; + + let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; + let test_leaf_b = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap().clone(); + + let pov_hash = pov.hash(); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + &expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }; + let expected_response_a = + make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash); + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![(expected_request_a, expected_response_a)], + ) + .await; + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &leaf_a_parent).await; + + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; + let leaf_a_grandparent = get_parent_hash(leaf_a_parent); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_grandparent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_grandparent, + &candidate, + &pov, + &pvd, + &validation_code, + &expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate), + persisted_validation_data: pvd, + }; + let expected_request_a = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }; + let expected_empty_response = vec![(hypothetical_candidate.clone(), vec![])]; + let expected_request_b = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_b_hash), + }; + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![ + (expected_request_a, expected_empty_response.clone()), + (expected_request_b, expected_empty_response), + ], + ) + .await; + + assert!(virtual_overseer + .recv() + .timeout(std::time::Duration::from_millis(50)) + .await + .is_none()); + + virtual_overseer + }); +} + +// Test that `seconding_sanity_check` allows seconding a candidate when it's allowed on at least one +// leaf. +#[test] +fn seconding_sanity_check_allowed_on_at_least_one_leaf() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate is seconded in a parent of the activated `leaf_a`. + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + // `a` is grandparent of `b`. + let leaf_a_hash = Hash::from_low_u64_be(130); + let leaf_a_parent = get_parent_hash(leaf_a_hash); + let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; + const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; + + let leaf_b_hash = Hash::from_low_u64_be(128); + let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; + let test_leaf_b = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); + + let pov_hash = pov.hash(); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }; + let expected_response_a = + make_hypothetical_membership_response(hypothetical_candidate.clone(), leaf_a_hash); + let expected_request_b = HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_b_hash), + }; + let expected_response_b = vec![(hypothetical_candidate.clone(), vec![])]; + assert_hypothetical_membership_requests( + &mut virtual_overseer, + vec![ + (expected_request_a, expected_response_a), + (expected_request_b, expected_response_b), + ], + ) + .await; + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &leaf_a_parent).await; + + virtual_overseer + }); +} + +// Test that a seconded candidate which is not approved by prospective parachains +// subsystem doesn't change the view. +#[test] +fn prospective_parachains_reject_candidate() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate is seconded in a parent of the activated `leaf_a`. + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + let leaf_a_hash = Hash::from_low_u64_be(130); + let leaf_a_parent = get_parent_hash(leaf_a_hash); + let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); + + let pov_hash = pov.hash(); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = vec![( + HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }, + make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash), + )]; + assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request_a.clone()) + .await; + + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + // Reject it. + tx.send(false).unwrap(); + } + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::CollatorProtocol(CollatorProtocolMessage::Invalid( + relay_parent, + candidate_receipt, + )) if candidate_receipt.descriptor() == &candidate.descriptor && + candidate_receipt.commitments_hash == candidate.commitments.hash() && + relay_parent == leaf_a_parent + ); + + // Try seconding the same candidate. + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request_a).await; + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &leaf_a_parent).await; + + virtual_overseer + }); +} + +// Test that a validator can second multiple candidates per single relay parent. +#[test] +fn second_multiple_candidates_per_relay_parent() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate `a` is seconded in a parent of the activated `leaf`. + const LEAF_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + let leaf_hash = Hash::from_low_u64_be(130); + let leaf_parent = get_parent_hash(leaf_hash); + let leaf_grandparent = get_parent_hash(leaf_parent); + let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); + + let pov_hash = pov.hash(); + let candidate_a = TestCandidateBuilder { + para_id, + relay_parent: leaf_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + }; + let mut candidate_b = candidate_a.clone(); + candidate_b.relay_parent = leaf_grandparent; + + let candidate_a = candidate_a.build(); + let candidate_b = candidate_b.build(); + + for candidate in &[candidate_a, candidate_b] { + let second = CandidateBackingMessage::Second( + leaf_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + candidate.descriptor.relay_parent(), + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = vec![( + HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_hash), + }, + make_hypothetical_membership_response(hypothetical_candidate, leaf_hash), + )]; + assert_hypothetical_membership_requests( + &mut virtual_overseer, + expected_request_a.clone(), + ) + .await; + + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + &req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data + => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded( + &mut virtual_overseer, + &candidate.descriptor.relay_parent(), + ) + .await; + } + + virtual_overseer + }); +} + +// Tests that validators start work on consecutive prospective parachain blocks. +#[test] +fn concurrent_dependent_candidates() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate `a` is seconded in a grandparent of the activated `leaf`, + // candidate `b` -- in parent. + const LEAF_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + + let leaf_hash = Hash::from_low_u64_be(130); + let leaf_parent = get_parent_hash(leaf_hash); + let leaf_grandparent = get_parent_hash(leaf_parent); + let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let head_data = &[ + HeadData(vec![10, 20, 30]), // Before `a`. + HeadData(vec![11, 21, 31]), // After `a`. + HeadData(vec![12, 22]), // After `b`. + ]; + + let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd_a = PersistedValidationData { + parent_head: head_data[0].clone(), + relay_parent_number: LEAF_BLOCK_NUMBER - 2, + relay_parent_storage_root: Hash::zero(), + max_pov_size: 1024, + }; + + let pov_b = PoV { block_data: BlockData(vec![22, 14, 100]) }; + let pvd_b = PersistedValidationData { + parent_head: head_data[1].clone(), + relay_parent_number: LEAF_BLOCK_NUMBER - 1, + relay_parent_storage_root: Hash::zero(), + max_pov_size: 1024, + }; + let validation_code = ValidationCode(vec![1, 2, 3]); + + let candidate_a = TestCandidateBuilder { + para_id, + relay_parent: leaf_grandparent, + pov_hash: pov_a.hash(), + head_data: head_data[1].clone(), + erasure_root: make_erasure_root(&test_state, pov_a.clone(), pvd_a.clone()), + persisted_validation_data_hash: pvd_a.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + let candidate_b = TestCandidateBuilder { + para_id, + relay_parent: leaf_parent, + pov_hash: pov_b.hash(), + head_data: head_data[2].clone(), + erasure_root: make_erasure_root(&test_state, pov_b.clone(), pvd_b.clone()), + persisted_validation_data_hash: pvd_b.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + let candidate_a_hash = candidate_a.hash(); + let candidate_b_hash = candidate_b.hash(); + + let public1 = Keystore::sr25519_generate_new( + &*test_state.keystore, + ValidatorId::ID, + Some(&test_state.validators[5].to_seed()), + ) + .expect("Insert key into keystore"); + let public2 = Keystore::sr25519_generate_new( + &*test_state.keystore, + ValidatorId::ID, + Some(&test_state.validators[2].to_seed()), + ) + .expect("Insert key into keystore"); + + // Signing context should have a parent hash candidate is based on. + let signing_context = + SigningContext { parent_hash: leaf_grandparent, session_index: test_state.session() }; + let signed_a = SignedFullStatementWithPVD::sign( + &test_state.keystore, + StatementWithPVD::Seconded(candidate_a.clone(), pvd_a.clone()), + &signing_context, + ValidatorIndex(2), + &public2.into(), + ) + .ok() + .flatten() + .expect("should be signed"); + + let signing_context = + SigningContext { parent_hash: leaf_parent, session_index: test_state.session() }; + let signed_b = SignedFullStatementWithPVD::sign( + &test_state.keystore, + StatementWithPVD::Seconded(candidate_b.clone(), pvd_b.clone()), + &signing_context, + ValidatorIndex(5), + &public1.into(), + ) + .ok() + .flatten() + .expect("should be signed"); + + let statement_a = CandidateBackingMessage::Statement(leaf_grandparent, signed_a.clone()); + let statement_b = CandidateBackingMessage::Statement(leaf_parent, signed_b.clone()); + + virtual_overseer.send(FromOrchestra::Communication { msg: statement_a }).await; + + // At this point the subsystem waits for response, the previous message is received, + // send a second one without blocking. + let _ = virtual_overseer + .tx + .start_send_unpin(FromOrchestra::Communication { msg: statement_b }); + + let mut valid_statements = HashSet::new(); + let mut backed_statements = HashSet::new(); + + loop { + let msg = virtual_overseer + .recv() + .timeout(std::time::Duration::from_secs(1)) + .await + .expect("overseer recv timed out"); + + // Order is not guaranteed since we have 2 statements being handled concurrently. + match msg { + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate(_, tx), + ) => { + tx.send(true).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::ValidationCodeByHash(_, tx), + )) => { + tx.send(Ok(Some(validation_code.clone()))).unwrap(); + }, + AllMessages::AvailabilityDistribution( + AvailabilityDistributionMessage::FetchPoV { candidate_hash, tx, .. }, + ) => { + let pov = if candidate_hash == candidate_a_hash { + &pov_a + } else if candidate_hash == candidate_b_hash { + &pov_b + } else { + panic!("unknown candidate hash") + }; + tx.send(pov.clone()).unwrap(); + }, + AllMessages::CandidateValidation( + CandidateValidationMessage::ValidateFromExhaustive { + candidate_receipt, + response_sender, + .. + }, + ) => { + let candidate_hash = candidate_receipt.hash(); + let (head_data, pvd) = if candidate_hash == candidate_a_hash { + (&head_data[1], &pvd_a) + } else if candidate_hash == candidate_b_hash { + (&head_data[2], &pvd_b) + } else { + panic!("unknown candidate hash") + }; + response_sender + .send(Ok(ValidationResult::Valid( + CandidateCommitments { + head_data: head_data.clone(), + horizontal_messages: Default::default(), + upward_messages: Default::default(), + new_validation_code: None, + processed_downward_messages: 0, + hrmp_watermark: 0, + }, + pvd.clone(), + ))) + .unwrap(); + }, + AllMessages::AvailabilityStore(AvailabilityStoreMessage::StoreAvailableData { + tx, + .. + }) => { + tx.send(Ok(())).unwrap(); + }, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::CandidateBacked(..), + ) => {}, + AllMessages::StatementDistribution(StatementDistributionMessage::Share( + _, + statement, + )) => { + assert_eq!(statement.validator_index(), ValidatorIndex(0)); + let payload = statement.payload(); + assert_matches!( + payload.clone(), + StatementWithPVD::Valid(hash) + if hash == candidate_a_hash || hash == candidate_b_hash => + { + assert!(valid_statements.insert(hash)); + } + ); + }, + AllMessages::StatementDistribution(StatementDistributionMessage::Backed(hash)) => { + // Ensure that `Share` was received first for the candidate. + assert!(valid_statements.contains(&hash)); + backed_statements.insert(hash); + + if backed_statements.len() == 2 { + break + } + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::SessionIndexForChild(tx), + )) => { + tx.send(Ok(1u32.into())).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::SessionExecutorParams(sess_idx, tx), + )) => { + assert_eq!(sess_idx, 1); + tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _parent, + RuntimeApiRequest::ValidatorGroups(tx), + )) => { + tx.send(Ok(test_state.validator_groups.clone())).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::NodeFeatures(sess_idx, tx), + )) => { + assert_eq!(sess_idx, 1); + tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); + }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _parent, + RuntimeApiRequest::AvailabilityCores(tx), + )) => { + tx.send(Ok(test_state.availability_cores.clone())).unwrap(); + }, + _ => panic!("unexpected message received from overseer: {:?}", msg), + } + } + + assert!(valid_statements.contains(&candidate_a_hash)); + assert!(valid_statements.contains(&candidate_b_hash)); + assert!(backed_statements.contains(&candidate_a_hash)); + assert!(backed_statements.contains(&candidate_b_hash)); + + virtual_overseer + }); +} + +// Test that multiple candidates from different paras can occupy the same depth +// in a given relay parent. +#[test] +fn seconding_sanity_check_occupy_same_depth() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate `a` is seconded in a parent of the activated `leaf`. + const LEAF_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_ANCESTRY_LEN: BlockNumber = 3; + + let para_id_a = test_state.chain_ids[0]; + let para_id_b = test_state.chain_ids[1]; + + let leaf_hash = Hash::from_low_u64_be(130); + let leaf_parent = get_parent_hash(leaf_hash); + + let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); + let min_block_number = LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN; + let min_relay_parents = vec![(para_id_a, min_block_number), (para_id_b, min_block_number)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data_a = test_state.head_data.get(¶_id_a).unwrap(); + let expected_head_data_b = test_state.head_data.get(¶_id_b).unwrap(); + + let pov_hash = pov.hash(); + let candidate_a = TestCandidateBuilder { + para_id: para_id_a, + relay_parent: leaf_parent, + pov_hash, + head_data: expected_head_data_a.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + }; + + let mut candidate_b = candidate_a.clone(); + candidate_b.para_id = para_id_b; + candidate_b.head_data = expected_head_data_b.clone(); + // A rotation happens, test validator is assigned to second para here. + candidate_b.relay_parent = leaf_hash; + + let candidate_a = (candidate_a.build(), expected_head_data_a, para_id_a); + let candidate_b = (candidate_b.build(), expected_head_data_b, para_id_b); + + for candidate in &[candidate_a, candidate_b] { + let (candidate, expected_head_data, para_id) = candidate; + let second = CandidateBackingMessage::Second( + leaf_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + candidate.descriptor.relay_parent(), + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request_a = vec![( + HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_hash), + }, + // Send the same membership for both candidates. + make_hypothetical_membership_response(hypothetical_candidate, leaf_hash), + )]; + + assert_hypothetical_membership_requests( + &mut virtual_overseer, + expected_request_a.clone(), + ) + .await; + + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + &req.candidate_receipt == candidate + && &req.candidate_para == para_id + && pvd == req.persisted_validation_data + => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded( + &mut virtual_overseer, + &candidate.descriptor.relay_parent(), + ) + .await; + } + + virtual_overseer + }); +} + +// Test that the subsystem doesn't skip occupied cores assignments. +#[test] +fn occupied_core_assignment() { + let mut test_state = TestState::default(); + test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { + // Candidate is seconded in a parent of the activated `leaf_a`. + const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; + const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; + let para_id = test_state.chain_ids[0]; + let previous_para_id = test_state.chain_ids[1]; + + // Set the core state to occupied. + let mut candidate_descriptor = + polkadot_primitives_test_helpers::dummy_candidate_descriptor(Hash::zero()); + candidate_descriptor.para_id = previous_para_id; + test_state.availability_cores[0] = CoreState::Occupied(OccupiedCore { + group_responsible: Default::default(), + next_up_on_available: Some(ScheduledCore { para_id, collator: None }), + occupied_since: 100_u32, + time_out_at: 200_u32, + next_up_on_time_out: None, + availability: Default::default(), + candidate_descriptor: candidate_descriptor.into(), + candidate_hash: Default::default(), + }); + + let leaf_a_hash = Hash::from_low_u64_be(130); + let leaf_a_parent = get_parent_hash(leaf_a_hash); + let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); + let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; + let test_leaf_a = TestLeaf { activated, min_relay_parents }; + + activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; + + let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; + let pvd = dummy_pvd(); + let validation_code = ValidationCode(vec![1, 2, 3]); + + let expected_head_data = test_state.head_data.get(¶_id).unwrap(); + + let pov_hash = pov.hash(); + let candidate = TestCandidateBuilder { + para_id, + relay_parent: leaf_a_parent, + pov_hash, + head_data: expected_head_data.clone(), + erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), + persisted_validation_data_hash: pvd.hash(), + validation_code: validation_code.0.clone(), + } + .build(); + + let second = CandidateBackingMessage::Second( + leaf_a_hash, + candidate.to_plain(), + pvd.clone(), + pov.clone(), + ); + + virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; + + assert_validate_seconded_candidate( + &mut virtual_overseer, + leaf_a_parent, + &candidate, + &pov, + &pvd, + &validation_code, + expected_head_data, + false, + ) + .await; + + // `seconding_sanity_check` + let hypothetical_candidate = HypotheticalCandidate::Complete { + candidate_hash: candidate.hash(), + receipt: Arc::new(candidate.clone()), + persisted_validation_data: pvd.clone(), + }; + let expected_request = vec![( + HypotheticalMembershipRequest { + candidates: vec![hypothetical_candidate.clone()], + fragment_chain_relay_parent: Some(leaf_a_hash), + }, + make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash), + )]; + assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request).await; + // Prospective parachains are notified. + assert_matches!( + virtual_overseer.recv().await, + AllMessages::ProspectiveParachains( + ProspectiveParachainsMessage::IntroduceSecondedCandidate( + req, + tx, + ), + ) if + req.candidate_receipt == candidate + && req.candidate_para == para_id + && pvd == req.persisted_validation_data + => { + tx.send(true).unwrap(); + } + ); + + assert_candidate_is_shared_and_seconded(&mut virtual_overseer, &leaf_a_parent).await; + virtual_overseer }); } diff --git a/polkadot/node/core/backing/src/tests/prospective_parachains.rs b/polkadot/node/core/backing/src/tests/prospective_parachains.rs deleted file mode 100644 index a05408eff85d..000000000000 --- a/polkadot/node/core/backing/src/tests/prospective_parachains.rs +++ /dev/null @@ -1,1745 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Polkadot. - -// Polkadot 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. - -// Polkadot 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 Polkadot. If not, see . - -//! Tests for the backing subsystem with enabled prospective parachains. - -use polkadot_node_subsystem::{ - messages::{ChainApiMessage, HypotheticalMembership}, - ActivatedLeaf, TimeoutExt, -}; -use polkadot_primitives::{vstaging::OccupiedCore, AsyncBackingParams, BlockNumber, Header}; - -use super::*; - -const ASYNC_BACKING_PARAMETERS: AsyncBackingParams = - AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 }; - -struct TestLeaf { - activated: ActivatedLeaf, - min_relay_parents: Vec<(ParaId, u32)>, -} - -fn get_parent_hash(hash: Hash) -> Hash { - Hash::from_low_u64_be(hash.to_low_u64_be() + 1) -} - -async fn activate_leaf( - virtual_overseer: &mut VirtualOverseer, - leaf: TestLeaf, - test_state: &mut TestState, -) { - let TestLeaf { activated, min_relay_parents } = leaf; - let leaf_hash = activated.hash; - let leaf_number = activated.number; - // Start work on some new parent. - virtual_overseer - .send(FromOrchestra::Signal(OverseerSignal::ActiveLeaves(ActiveLeavesUpdate::start_work( - activated, - )))) - .await; - - // Prospective parachains mode is temporarily defined by the Runtime API version. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx)) - ) if parent == leaf_hash => { - tx.send(Ok(ASYNC_BACKING_PARAMETERS)).unwrap(); - } - ); - - let min_min = *min_relay_parents - .iter() - .map(|(_, block_num)| block_num) - .min() - .unwrap_or(&leaf_number); - - let ancestry_len = leaf_number + 1 - min_min; - - let ancestry_hashes = std::iter::successors(Some(leaf_hash), |h| Some(get_parent_hash(*h))) - .take(ancestry_len as usize); - let ancestry_numbers = (min_min..=leaf_number).rev(); - let ancestry_iter = ancestry_hashes.zip(ancestry_numbers).peekable(); - - let mut next_overseer_message = None; - // How many blocks were actually requested. - let mut requested_len = 0; - { - let mut ancestry_iter = ancestry_iter.clone(); - while let Some((hash, number)) = ancestry_iter.next() { - // May be `None` for the last element. - let parent_hash = - ancestry_iter.peek().map(|(h, _)| *h).unwrap_or_else(|| get_parent_hash(hash)); - - let msg = virtual_overseer.recv().await; - // It may happen that some blocks were cached by implicit view, - // reuse the message. - if !matches!(&msg, AllMessages::ChainApi(ChainApiMessage::BlockHeader(..))) { - next_overseer_message.replace(msg); - break - } - - assert_matches!( - msg, - AllMessages::ChainApi( - ChainApiMessage::BlockHeader(_hash, tx) - ) if _hash == hash => { - let header = Header { - parent_hash, - number, - state_root: Hash::zero(), - extrinsics_root: Hash::zero(), - digest: Default::default(), - }; - - tx.send(Ok(Some(header))).unwrap(); - } - ); - - if requested_len == 0 { - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::GetMinimumRelayParents(parent, tx) - ) if parent == leaf_hash => { - tx.send(min_relay_parents.clone()).unwrap(); - } - ); - } - - requested_len += 1; - } - } - - for (hash, number) in ancestry_iter.take(requested_len) { - let msg = match next_overseer_message.take() { - Some(msg) => msg, - None => virtual_overseer.recv().await, - }; - - // Check that subsystem job issues a request for the session index for child. - assert_matches!( - msg, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionIndexForChild(tx)) - ) if parent == hash => { - tx.send(Ok(test_state.signing_context.session_index)).unwrap(); - } - ); - - // Check that subsystem job issues a request for the validator groups. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::ValidatorGroups(tx)) - ) if parent == hash => { - let (validator_groups, mut group_rotation_info) = test_state.validator_groups.clone(); - group_rotation_info.now = number; - tx.send(Ok((validator_groups, group_rotation_info))).unwrap(); - } - ); - - // Check that subsystem job issues a request for the availability cores. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AvailabilityCores(tx)) - ) if parent == hash => { - tx.send(Ok(test_state.availability_cores.clone())).unwrap(); - } - ); - - if !test_state.per_session_cache_state.has_cached_validators { - // Check that subsystem job issues a request for a validator set. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Validators(tx)) - ) if parent == hash => { - tx.send(Ok(test_state.validator_public.clone())).unwrap(); - } - ); - test_state.per_session_cache_state.has_cached_validators = true; - } - - if !test_state.per_session_cache_state.has_cached_node_features { - // Node features request from runtime: all features are disabled. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::NodeFeatures(_session_index, tx)) - ) if parent == hash => { - tx.send(Ok(Default::default())).unwrap(); - } - ); - test_state.per_session_cache_state.has_cached_node_features = true; - } - - if !test_state.per_session_cache_state.has_cached_executor_params { - // Check if subsystem job issues a request for the executor parameters. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::SessionExecutorParams(_session_index, tx)) - ) if parent == hash => { - tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); - } - ); - test_state.per_session_cache_state.has_cached_executor_params = true; - } - - if !test_state.per_session_cache_state.has_cached_minimum_backing_votes { - // Check if subsystem job issues a request for the minimum backing votes. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - parent, - RuntimeApiRequest::MinimumBackingVotes(session_index, tx), - )) if parent == hash && session_index == test_state.signing_context.session_index => { - tx.send(Ok(test_state.minimum_backing_votes)).unwrap(); - } - ); - test_state.per_session_cache_state.has_cached_minimum_backing_votes = true; - } - - // Check that subsystem job issues a request for the runtime version. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) - ) if parent == hash => { - tx.send(Ok(RuntimeApiRequest::DISABLED_VALIDATORS_RUNTIME_REQUIREMENT)).unwrap(); - } - ); - - // Check that the subsystem job issues a request for the disabled validators. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::DisabledValidators(tx)) - ) if parent == hash => { - tx.send(Ok(Vec::new())).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) - ) if parent == hash => { - tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) - ) if parent == hash => { - tx.send(Ok( - test_state.claim_queue.clone() - )).unwrap(); - } - ); - } -} - -async fn assert_validate_seconded_candidate( - virtual_overseer: &mut VirtualOverseer, - relay_parent: Hash, - candidate: &CommittedCandidateReceipt, - assert_pov: &PoV, - assert_pvd: &PersistedValidationData, - assert_validation_code: &ValidationCode, - expected_head_data: &HeadData, - fetch_pov: bool, -) { - assert_validation_requests(virtual_overseer, assert_validation_code.clone()).await; - - if fetch_pov { - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityDistribution( - AvailabilityDistributionMessage::FetchPoV { - relay_parent: hash, - tx, - .. - } - ) if hash == relay_parent => { - tx.send(assert_pov.clone()).unwrap(); - } - ); - } - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CandidateValidation(CandidateValidationMessage::ValidateFromExhaustive { - validation_data, - validation_code, - candidate_receipt, - pov, - exec_kind, - response_sender, - .. - }) if &validation_data == assert_pvd && - &validation_code == assert_validation_code && - &*pov == assert_pov && - candidate_receipt.descriptor == candidate.descriptor && - matches!(exec_kind, PvfExecKind::BackingSystemParas(_)) && - candidate.commitments.hash() == candidate_receipt.commitments_hash => - { - response_sender.send(Ok(ValidationResult::Valid( - CandidateCommitments { - head_data: expected_head_data.clone(), - horizontal_messages: Default::default(), - upward_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, - assert_pvd.clone(), - ))) - .unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::AvailabilityStore( - AvailabilityStoreMessage::StoreAvailableData { candidate_hash, tx, .. } - ) if candidate_hash == candidate.hash() => { - tx.send(Ok(())).unwrap(); - } - ); -} - -async fn assert_hypothetical_membership_requests( - virtual_overseer: &mut VirtualOverseer, - mut expected_requests: Vec<( - HypotheticalMembershipRequest, - Vec<(HypotheticalCandidate, HypotheticalMembership)>, - )>, -) { - // Requests come with no particular order. - let requests_num = expected_requests.len(); - - for _ in 0..requests_num { - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::GetHypotheticalMembership(request, tx), - ) => { - let idx = match expected_requests.iter().position(|r| r.0 == request) { - Some(idx) => idx, - None => - panic!( - "unexpected hypothetical membership request, no match found for {:?}", - request - ), - }; - let resp = std::mem::take(&mut expected_requests[idx].1); - tx.send(resp).unwrap(); - - expected_requests.remove(idx); - } - ); - } -} - -fn make_hypothetical_membership_response( - hypothetical_candidate: HypotheticalCandidate, - relay_parent_hash: Hash, -) -> Vec<(HypotheticalCandidate, HypotheticalMembership)> { - vec![(hypothetical_candidate, vec![relay_parent_hash])] -} - -// Test that `seconding_sanity_check` works when a candidate is allowed -// for all leaves. -#[test] -fn seconding_sanity_check_allowed_on_all() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate is seconded in a parent of the activated `leaf_a`. - const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - // `a` is grandparent of `b`. - let leaf_a_hash = Hash::from_low_u64_be(130); - let leaf_a_parent = get_parent_hash(leaf_a_hash); - let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; - const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; - - let leaf_b_hash = Hash::from_low_u64_be(128); - let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; - let test_leaf_b = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }; - let expected_response_a = - make_hypothetical_membership_response(hypothetical_candidate.clone(), leaf_a_hash); - let expected_request_b = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_b_hash), - }; - let expected_response_b = - make_hypothetical_membership_response(hypothetical_candidate, leaf_b_hash); - assert_hypothetical_membership_requests( - &mut virtual_overseer, - vec![ - (expected_request_a, expected_response_a), - (expected_request_b, expected_response_b), - ], - ) - .await; - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == leaf_a_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(leaf_a_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - virtual_overseer - }); -} - -// Test that `seconding_sanity_check` disallows seconding when a candidate is disallowed -// for all leaves. -#[test] -fn seconding_sanity_check_disallowed() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate is seconded in a parent of the activated `leaf_a`. - const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - let leaf_b_hash = Hash::from_low_u64_be(128); - // `a` is grandparent of `b`. - let leaf_a_hash = Hash::from_low_u64_be(130); - let leaf_a_parent = get_parent_hash(leaf_a_hash); - let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; - const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; - - let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; - let test_leaf_b = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }; - let expected_response_a = - make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash); - assert_hypothetical_membership_requests( - &mut virtual_overseer, - vec![(expected_request_a, expected_response_a)], - ) - .await; - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == leaf_a_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(leaf_a_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; - let leaf_a_grandparent = get_parent_hash(leaf_a_parent); - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_grandparent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_grandparent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate), - persisted_validation_data: pvd, - }; - let expected_request_a = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }; - let expected_empty_response = vec![(hypothetical_candidate.clone(), vec![])]; - let expected_request_b = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_b_hash), - }; - assert_hypothetical_membership_requests( - &mut virtual_overseer, - vec![ - (expected_request_a, expected_empty_response.clone()), - (expected_request_b, expected_empty_response), - ], - ) - .await; - - assert!(virtual_overseer - .recv() - .timeout(std::time::Duration::from_millis(50)) - .await - .is_none()); - - virtual_overseer - }); -} - -// Test that `seconding_sanity_check` allows seconding a candidate when it's allowed on at least one -// leaf. -#[test] -fn seconding_sanity_check_allowed_on_at_least_one_leaf() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate is seconded in a parent of the activated `leaf_a`. - const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - // `a` is grandparent of `b`. - let leaf_a_hash = Hash::from_low_u64_be(130); - let leaf_a_parent = get_parent_hash(leaf_a_hash); - let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - const LEAF_B_BLOCK_NUMBER: BlockNumber = LEAF_A_BLOCK_NUMBER + 2; - const LEAF_B_ANCESTRY_LEN: BlockNumber = 4; - - let leaf_b_hash = Hash::from_low_u64_be(128); - let activated = new_leaf(leaf_b_hash, LEAF_B_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_B_BLOCK_NUMBER - LEAF_B_ANCESTRY_LEN)]; - let test_leaf_b = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - activate_leaf(&mut virtual_overseer, test_leaf_b, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }; - let expected_response_a = - make_hypothetical_membership_response(hypothetical_candidate.clone(), leaf_a_hash); - let expected_request_b = HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_b_hash), - }; - let expected_response_b = vec![(hypothetical_candidate.clone(), vec![])]; - assert_hypothetical_membership_requests( - &mut virtual_overseer, - vec![ - (expected_request_a, expected_response_a), - (expected_request_b, expected_response_b), - ], - ) - .await; - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == leaf_a_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(leaf_a_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - virtual_overseer - }); -} - -// Test that a seconded candidate which is not approved by prospective parachains -// subsystem doesn't change the view. -#[test] -fn prospective_parachains_reject_candidate() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate is seconded in a parent of the activated `leaf_a`. - const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - let leaf_a_hash = Hash::from_low_u64_be(130); - let leaf_a_parent = get_parent_hash(leaf_a_hash); - let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = vec![( - HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }, - make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash), - )]; - assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request_a.clone()) - .await; - - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - // Reject it. - tx.send(false).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Invalid( - relay_parent, - candidate_receipt, - )) if candidate_receipt.descriptor == candidate.descriptor && - candidate_receipt.commitments_hash == candidate.commitments.hash() && - relay_parent == leaf_a_parent - ); - - // Try seconding the same candidate. - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request_a).await; - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == leaf_a_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(leaf_a_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - virtual_overseer - }); -} - -// Test that a validator can second multiple candidates per single relay parent. -#[test] -fn second_multiple_candidates_per_relay_parent() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate `a` is seconded in a parent of the activated `leaf`. - const LEAF_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - let leaf_hash = Hash::from_low_u64_be(130); - let leaf_parent = get_parent_hash(leaf_hash); - let leaf_grandparent = get_parent_hash(leaf_parent); - let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate_a = TestCandidateBuilder { - para_id, - relay_parent: leaf_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - }; - let mut candidate_b = candidate_a.clone(); - candidate_b.relay_parent = leaf_grandparent; - - let candidate_a = candidate_a.build(); - let candidate_b = candidate_b.build(); - - for candidate in &[candidate_a, candidate_b] { - let second = CandidateBackingMessage::Second( - leaf_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - candidate.descriptor.relay_parent(), - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = vec![( - HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_hash), - }, - make_hypothetical_membership_response(hypothetical_candidate, leaf_hash), - )]; - assert_hypothetical_membership_requests( - &mut virtual_overseer, - expected_request_a.clone(), - ) - .await; - - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - &req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data - => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == candidate.descriptor.relay_parent() => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(candidate.descriptor.relay_parent(), hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - } - - virtual_overseer - }); -} - -// Test that the candidate reaches quorum successfully. -#[test] -fn backing_works() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate `a` is seconded in a parent of the activated `leaf`. - const LEAF_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - let leaf_hash = Hash::from_low_u64_be(130); - let leaf_parent = get_parent_hash(leaf_hash); - let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - - let candidate_a = TestCandidateBuilder { - para_id, - relay_parent: leaf_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - validation_code: validation_code.0.clone(), - persisted_validation_data_hash: pvd.hash(), - } - .build(); - - let candidate_a_hash = candidate_a.hash(); - - let public1 = Keystore::sr25519_generate_new( - &*test_state.keystore, - ValidatorId::ID, - Some(&test_state.validators[5].to_seed()), - ) - .expect("Insert key into keystore"); - let public2 = Keystore::sr25519_generate_new( - &*test_state.keystore, - ValidatorId::ID, - Some(&test_state.validators[2].to_seed()), - ) - .expect("Insert key into keystore"); - - // Signing context should have a parent hash candidate is based on. - let signing_context = - SigningContext { parent_hash: leaf_parent, session_index: test_state.session() }; - let signed_a = SignedFullStatementWithPVD::sign( - &test_state.keystore, - StatementWithPVD::Seconded(candidate_a.clone(), pvd.clone()), - &signing_context, - ValidatorIndex(2), - &public2.into(), - ) - .ok() - .flatten() - .expect("should be signed"); - - let signed_b = SignedFullStatementWithPVD::sign( - &test_state.keystore, - StatementWithPVD::Valid(candidate_a_hash), - &signing_context, - ValidatorIndex(5), - &public1.into(), - ) - .ok() - .flatten() - .expect("should be signed"); - - let statement = CandidateBackingMessage::Statement(leaf_parent, signed_a.clone()); - - virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - - // Prospective parachains are notified about candidate seconded first. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate_a - && req.candidate_para == para_id - && pvd == req.persisted_validation_data => { - tx.send(true).unwrap(); - } - ); - - assert_validate_seconded_candidate( - &mut virtual_overseer, - candidate_a.descriptor.relay_parent(), - &candidate_a, - &pov, - &pvd, - &validation_code, - expected_head_data, - true, - ) - .await; - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share(hash, _stmt) - ) => { - assert_eq!(leaf_parent, hash); - } - ); - - // Prospective parachains and collator protocol are notified about candidate backed. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::CandidateBacked( - candidate_para_id, candidate_hash - ), - ) if candidate_a_hash == candidate_hash && candidate_para_id == para_id - ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution(StatementDistributionMessage::Backed ( - candidate_hash - )) if candidate_a_hash == candidate_hash - ); - - let statement = CandidateBackingMessage::Statement(leaf_parent, signed_b.clone()); - - virtual_overseer.send(FromOrchestra::Communication { msg: statement }).await; - - virtual_overseer - }); -} - -// Tests that validators start work on consecutive prospective parachain blocks. -#[test] -fn concurrent_dependent_candidates() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate `a` is seconded in a grandparent of the activated `leaf`, - // candidate `b` -- in parent. - const LEAF_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - - let leaf_hash = Hash::from_low_u64_be(130); - let leaf_parent = get_parent_hash(leaf_hash); - let leaf_grandparent = get_parent_hash(leaf_parent); - let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let head_data = &[ - HeadData(vec![10, 20, 30]), // Before `a`. - HeadData(vec![11, 21, 31]), // After `a`. - HeadData(vec![12, 22]), // After `b`. - ]; - - let pov_a = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd_a = PersistedValidationData { - parent_head: head_data[0].clone(), - relay_parent_number: LEAF_BLOCK_NUMBER - 2, - relay_parent_storage_root: Hash::zero(), - max_pov_size: 1024, - }; - - let pov_b = PoV { block_data: BlockData(vec![22, 14, 100]) }; - let pvd_b = PersistedValidationData { - parent_head: head_data[1].clone(), - relay_parent_number: LEAF_BLOCK_NUMBER - 1, - relay_parent_storage_root: Hash::zero(), - max_pov_size: 1024, - }; - let validation_code = ValidationCode(vec![1, 2, 3]); - - let candidate_a = TestCandidateBuilder { - para_id, - relay_parent: leaf_grandparent, - pov_hash: pov_a.hash(), - head_data: head_data[1].clone(), - erasure_root: make_erasure_root(&test_state, pov_a.clone(), pvd_a.clone()), - persisted_validation_data_hash: pvd_a.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - let candidate_b = TestCandidateBuilder { - para_id, - relay_parent: leaf_parent, - pov_hash: pov_b.hash(), - head_data: head_data[2].clone(), - erasure_root: make_erasure_root(&test_state, pov_b.clone(), pvd_b.clone()), - persisted_validation_data_hash: pvd_b.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - let candidate_a_hash = candidate_a.hash(); - let candidate_b_hash = candidate_b.hash(); - - let public1 = Keystore::sr25519_generate_new( - &*test_state.keystore, - ValidatorId::ID, - Some(&test_state.validators[5].to_seed()), - ) - .expect("Insert key into keystore"); - let public2 = Keystore::sr25519_generate_new( - &*test_state.keystore, - ValidatorId::ID, - Some(&test_state.validators[2].to_seed()), - ) - .expect("Insert key into keystore"); - - // Signing context should have a parent hash candidate is based on. - let signing_context = - SigningContext { parent_hash: leaf_grandparent, session_index: test_state.session() }; - let signed_a = SignedFullStatementWithPVD::sign( - &test_state.keystore, - StatementWithPVD::Seconded(candidate_a.clone(), pvd_a.clone()), - &signing_context, - ValidatorIndex(2), - &public2.into(), - ) - .ok() - .flatten() - .expect("should be signed"); - - let signing_context = - SigningContext { parent_hash: leaf_parent, session_index: test_state.session() }; - let signed_b = SignedFullStatementWithPVD::sign( - &test_state.keystore, - StatementWithPVD::Seconded(candidate_b.clone(), pvd_b.clone()), - &signing_context, - ValidatorIndex(5), - &public1.into(), - ) - .ok() - .flatten() - .expect("should be signed"); - - let statement_a = CandidateBackingMessage::Statement(leaf_grandparent, signed_a.clone()); - let statement_b = CandidateBackingMessage::Statement(leaf_parent, signed_b.clone()); - - virtual_overseer.send(FromOrchestra::Communication { msg: statement_a }).await; - - // At this point the subsystem waits for response, the previous message is received, - // send a second one without blocking. - let _ = virtual_overseer - .tx - .start_send_unpin(FromOrchestra::Communication { msg: statement_b }); - - let mut valid_statements = HashSet::new(); - let mut backed_statements = HashSet::new(); - - loop { - let msg = virtual_overseer - .recv() - .timeout(std::time::Duration::from_secs(1)) - .await - .expect("overseer recv timed out"); - - // Order is not guaranteed since we have 2 statements being handled concurrently. - match msg { - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate(_, tx), - ) => { - tx.send(true).unwrap(); - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::ValidationCodeByHash(_, tx), - )) => { - tx.send(Ok(Some(validation_code.clone()))).unwrap(); - }, - AllMessages::AvailabilityDistribution( - AvailabilityDistributionMessage::FetchPoV { candidate_hash, tx, .. }, - ) => { - let pov = if candidate_hash == candidate_a_hash { - &pov_a - } else if candidate_hash == candidate_b_hash { - &pov_b - } else { - panic!("unknown candidate hash") - }; - tx.send(pov.clone()).unwrap(); - }, - AllMessages::CandidateValidation( - CandidateValidationMessage::ValidateFromExhaustive { - candidate_receipt, - response_sender, - .. - }, - ) => { - let candidate_hash = candidate_receipt.hash(); - let (head_data, pvd) = if candidate_hash == candidate_a_hash { - (&head_data[1], &pvd_a) - } else if candidate_hash == candidate_b_hash { - (&head_data[2], &pvd_b) - } else { - panic!("unknown candidate hash") - }; - response_sender - .send(Ok(ValidationResult::Valid( - CandidateCommitments { - head_data: head_data.clone(), - horizontal_messages: Default::default(), - upward_messages: Default::default(), - new_validation_code: None, - processed_downward_messages: 0, - hrmp_watermark: 0, - }, - pvd.clone(), - ))) - .unwrap(); - }, - AllMessages::AvailabilityStore(AvailabilityStoreMessage::StoreAvailableData { - tx, - .. - }) => { - tx.send(Ok(())).unwrap(); - }, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::CandidateBacked(..), - ) => {}, - AllMessages::StatementDistribution(StatementDistributionMessage::Share( - _, - statement, - )) => { - assert_eq!(statement.validator_index(), ValidatorIndex(0)); - let payload = statement.payload(); - assert_matches!( - payload.clone(), - StatementWithPVD::Valid(hash) - if hash == candidate_a_hash || hash == candidate_b_hash => - { - assert!(valid_statements.insert(hash)); - } - ); - }, - AllMessages::StatementDistribution(StatementDistributionMessage::Backed(hash)) => { - // Ensure that `Share` was received first for the candidate. - assert!(valid_statements.contains(&hash)); - backed_statements.insert(hash); - - if backed_statements.len() == 2 { - break - } - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _parent, - RuntimeApiRequest::ValidatorGroups(tx), - )) => { - tx.send(Ok(test_state.validator_groups.clone())).unwrap(); - }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _parent, - RuntimeApiRequest::AvailabilityCores(tx), - )) => { - tx.send(Ok(test_state.availability_cores.clone())).unwrap(); - }, - _ => panic!("unexpected message received from overseer: {:?}", msg), - } - } - - assert!(valid_statements.contains(&candidate_a_hash)); - assert!(valid_statements.contains(&candidate_b_hash)); - assert!(backed_statements.contains(&candidate_a_hash)); - assert!(backed_statements.contains(&candidate_b_hash)); - - virtual_overseer - }); -} - -// Test that multiple candidates from different paras can occupy the same depth -// in a given relay parent. -#[test] -fn seconding_sanity_check_occupy_same_depth() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate `a` is seconded in a parent of the activated `leaf`. - const LEAF_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_ANCESTRY_LEN: BlockNumber = 3; - - let para_id_a = test_state.chain_ids[0]; - let para_id_b = test_state.chain_ids[1]; - - let leaf_hash = Hash::from_low_u64_be(130); - let leaf_parent = get_parent_hash(leaf_hash); - - let activated = new_leaf(leaf_hash, LEAF_BLOCK_NUMBER); - let min_block_number = LEAF_BLOCK_NUMBER - LEAF_ANCESTRY_LEN; - let min_relay_parents = vec![(para_id_a, min_block_number), (para_id_b, min_block_number)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data_a = test_state.head_data.get(¶_id_a).unwrap(); - let expected_head_data_b = test_state.head_data.get(¶_id_b).unwrap(); - - let pov_hash = pov.hash(); - let candidate_a = TestCandidateBuilder { - para_id: para_id_a, - relay_parent: leaf_parent, - pov_hash, - head_data: expected_head_data_a.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - }; - - let mut candidate_b = candidate_a.clone(); - candidate_b.para_id = para_id_b; - candidate_b.head_data = expected_head_data_b.clone(); - // A rotation happens, test validator is assigned to second para here. - candidate_b.relay_parent = leaf_hash; - - let candidate_a = (candidate_a.build(), expected_head_data_a, para_id_a); - let candidate_b = (candidate_b.build(), expected_head_data_b, para_id_b); - - for candidate in &[candidate_a, candidate_b] { - let (candidate, expected_head_data, para_id) = candidate; - let second = CandidateBackingMessage::Second( - leaf_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - candidate.descriptor.relay_parent(), - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request_a = vec![( - HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_hash), - }, - // Send the same membership for both candidates. - make_hypothetical_membership_response(hypothetical_candidate, leaf_hash), - )]; - - assert_hypothetical_membership_requests( - &mut virtual_overseer, - expected_request_a.clone(), - ) - .await; - - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - &req.candidate_receipt == candidate - && &req.candidate_para == para_id - && pvd == req.persisted_validation_data - => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == candidate.descriptor.relay_parent() => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(candidate.descriptor.relay_parent(), hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - } - - virtual_overseer - }); -} - -// Test that the subsystem doesn't skip occupied cores assignments. -#[test] -fn occupied_core_assignment() { - let mut test_state = TestState::default(); - test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { - // Candidate is seconded in a parent of the activated `leaf_a`. - const LEAF_A_BLOCK_NUMBER: BlockNumber = 100; - const LEAF_A_ANCESTRY_LEN: BlockNumber = 3; - let para_id = test_state.chain_ids[0]; - let previous_para_id = test_state.chain_ids[1]; - - // Set the core state to occupied. - let mut candidate_descriptor = - polkadot_primitives_test_helpers::dummy_candidate_descriptor(Hash::zero()); - candidate_descriptor.para_id = previous_para_id; - test_state.availability_cores[0] = CoreState::Occupied(OccupiedCore { - group_responsible: Default::default(), - next_up_on_available: Some(ScheduledCore { para_id, collator: None }), - occupied_since: 100_u32, - time_out_at: 200_u32, - next_up_on_time_out: None, - availability: Default::default(), - candidate_descriptor: candidate_descriptor.into(), - candidate_hash: Default::default(), - }); - - let leaf_a_hash = Hash::from_low_u64_be(130); - let leaf_a_parent = get_parent_hash(leaf_a_hash); - let activated = new_leaf(leaf_a_hash, LEAF_A_BLOCK_NUMBER); - let min_relay_parents = vec![(para_id, LEAF_A_BLOCK_NUMBER - LEAF_A_ANCESTRY_LEN)]; - let test_leaf_a = TestLeaf { activated, min_relay_parents }; - - activate_leaf(&mut virtual_overseer, test_leaf_a, &mut test_state).await; - - let pov = PoV { block_data: BlockData(vec![42, 43, 44]) }; - let pvd = dummy_pvd(); - let validation_code = ValidationCode(vec![1, 2, 3]); - - let expected_head_data = test_state.head_data.get(¶_id).unwrap(); - - let pov_hash = pov.hash(); - let candidate = TestCandidateBuilder { - para_id, - relay_parent: leaf_a_parent, - pov_hash, - head_data: expected_head_data.clone(), - erasure_root: make_erasure_root(&test_state, pov.clone(), pvd.clone()), - persisted_validation_data_hash: pvd.hash(), - validation_code: validation_code.0.clone(), - } - .build(); - - let second = CandidateBackingMessage::Second( - leaf_a_hash, - candidate.to_plain(), - pvd.clone(), - pov.clone(), - ); - - virtual_overseer.send(FromOrchestra::Communication { msg: second }).await; - - assert_validate_seconded_candidate( - &mut virtual_overseer, - leaf_a_parent, - &candidate, - &pov, - &pvd, - &validation_code, - expected_head_data, - false, - ) - .await; - - // `seconding_sanity_check` - let hypothetical_candidate = HypotheticalCandidate::Complete { - candidate_hash: candidate.hash(), - receipt: Arc::new(candidate.clone()), - persisted_validation_data: pvd.clone(), - }; - let expected_request = vec![( - HypotheticalMembershipRequest { - candidates: vec![hypothetical_candidate.clone()], - fragment_chain_relay_parent: Some(leaf_a_hash), - }, - make_hypothetical_membership_response(hypothetical_candidate, leaf_a_hash), - )]; - assert_hypothetical_membership_requests(&mut virtual_overseer, expected_request).await; - // Prospective parachains are notified. - assert_matches!( - virtual_overseer.recv().await, - AllMessages::ProspectiveParachains( - ProspectiveParachainsMessage::IntroduceSecondedCandidate( - req, - tx, - ), - ) if - req.candidate_receipt == candidate - && req.candidate_para == para_id - && pvd == req.persisted_validation_data - => { - tx.send(true).unwrap(); - } - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::StatementDistribution( - StatementDistributionMessage::Share( - parent_hash, - _signed_statement, - ) - ) if parent_hash == leaf_a_parent => {} - ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::CollatorProtocol(CollatorProtocolMessage::Seconded(hash, statement)) => { - assert_eq!(leaf_a_parent, hash); - assert_matches!(statement.payload(), Statement::Seconded(_)); - } - ); - - virtual_overseer - }); -} diff --git a/polkadot/node/subsystem-util/src/backing_implicit_view.rs b/polkadot/node/subsystem-util/src/backing_implicit_view.rs index a805ef8165e5..6f2191e7add2 100644 --- a/polkadot/node/subsystem-util/src/backing_implicit_view.rs +++ b/polkadot/node/subsystem-util/src/backing_implicit_view.rs @@ -20,14 +20,14 @@ use polkadot_node_subsystem::{ messages::{ChainApiMessage, ProspectiveParachainsMessage, RuntimeApiMessage}, SubsystemSender, }; -use polkadot_primitives::{BlockNumber, Hash, Id as ParaId}; +use polkadot_primitives::{AsyncBackingParams, BlockNumber, Hash, Id as ParaId}; use std::collections::HashMap; use crate::{ inclusion_emulator::RelayChainBlockInfo, - request_session_index_for_child, - runtime::{self, prospective_parachains_mode, recv_runtime, ProspectiveParachainsMode}, + request_async_backing_params, request_session_index_for_child, + runtime::{self, recv_runtime}, }; // Always aim to retain 1 block before the active leaves. @@ -396,13 +396,8 @@ where + SubsystemSender + SubsystemSender, { - let Ok(ProspectiveParachainsMode::Enabled { allowed_ancestry_len, .. }) = - prospective_parachains_mode(sender, leaf_hash).await - else { - // This should never happen, leaves that don't have prospective parachains mode enabled - // should not use implicit view. - return Ok(None) - }; + let AsyncBackingParams { allowed_ancestry_len, .. } = + recv_runtime(request_async_backing_params(leaf_hash, sender).await).await?; // Fetch the session of the leaf. We must make sure that we stop at the ancestor which has a // different session index. @@ -416,7 +411,7 @@ where sender .send_message(ChainApiMessage::Ancestors { hash: leaf_hash, - k: allowed_ancestry_len, + k: allowed_ancestry_len as usize, response_channel: tx, }) .await; diff --git a/polkadot/roadmap/implementers-guide/src/node/utility/provisioner.md b/polkadot/roadmap/implementers-guide/src/node/utility/provisioner.md index 64727d39fabe..0fe7fdd13653 100644 --- a/polkadot/roadmap/implementers-guide/src/node/utility/provisioner.md +++ b/polkadot/roadmap/implementers-guide/src/node/utility/provisioner.md @@ -74,9 +74,8 @@ Subsystem](../disputes/dispute-coordinator.md). Misbehavior reports are currentl subsystem](../backing/candidate-backing.md) and contain the following misbehaviors: 1. `Misbehavior::ValidityDoubleVote` -2. `Misbehavior::MultipleCandidates` -3. `Misbehavior::UnauthorizedStatement` -4. `Misbehavior::DoubleSign` +2. `Misbehavior::UnauthorizedStatement` +3. `Misbehavior::DoubleSign` But we choose not to punish these forms of misbehavior for the time being. Risks from misbehavior are sufficiently mitigated at the protocol level via reputation changes. Punitive actions here may become desirable enough to dedicate diff --git a/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md b/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md index 6e24d969dde4..85415e42a11c 100644 --- a/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md +++ b/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md @@ -697,14 +697,6 @@ mod generic { Invalidity(Digest, Signature, Signature), } - /// Misbehavior: declaring multiple candidates. - pub struct MultipleCandidates { - /// The first candidate seen. - pub first: (Candidate, Signature), - /// The second candidate seen. - pub second: (Candidate, Signature), - } - /// Misbehavior: submitted statement for wrong group. pub struct UnauthorizedStatement { /// A signed statement which was submitted without proper authority. @@ -714,8 +706,6 @@ mod generic { pub enum Misbehavior { /// Voted invalid and valid on validity. ValidityDoubleVote(ValidityDoubleVote), - /// Submitted multiple candidates. - MultipleCandidates(MultipleCandidates), /// Submitted a message that was unauthorized. UnauthorizedStatement(UnauthorizedStatement), /// Submitted two valid signatures for the same message. diff --git a/polkadot/statement-table/src/generic.rs b/polkadot/statement-table/src/generic.rs index e3c470fcdeec..4ab6e27d2c74 100644 --- a/polkadot/statement-table/src/generic.rs +++ b/polkadot/statement-table/src/generic.rs @@ -62,14 +62,6 @@ pub trait Context { fn get_group_size(&self, group: &Self::GroupId) -> Option; } -/// Table configuration. -pub struct Config { - /// When this is true, the table will allow multiple seconded candidates - /// per authority. This flag means that higher-level code is responsible for - /// bounding the number of candidates. - pub allow_multiple_seconded: bool, -} - /// Statements circulated among peers. #[derive(PartialEq, Eq, Debug, Clone, Encode, Decode)] pub enum Statement { @@ -143,15 +135,6 @@ impl DoubleSign { } } -/// Misbehavior: declaring multiple candidates. -#[derive(PartialEq, Eq, Debug, Clone)] -pub struct MultipleCandidates { - /// The first candidate seen. - pub first: (Candidate, Signature), - /// The second candidate seen. - pub second: (Candidate, Signature), -} - /// Misbehavior: submitted statement for wrong group. #[derive(PartialEq, Eq, Debug, Clone)] pub struct UnauthorizedStatement { @@ -165,8 +148,6 @@ pub struct UnauthorizedStatement { pub enum Misbehavior { /// Voted invalid and valid on validity. ValidityDoubleVote(ValidityDoubleVote), - /// Submitted multiple candidates. - MultipleCandidates(MultipleCandidates), /// Submitted a message that was unauthorized. UnauthorizedStatement(UnauthorizedStatement), /// Submitted two valid signatures for the same message. @@ -300,17 +281,14 @@ pub struct Table { authority_data: HashMap>, detected_misbehavior: HashMap>>, candidate_votes: HashMap>, - config: Config, } impl Table { - /// Create a new `Table` from a `Config`. - pub fn new(config: Config) -> Self { + pub fn new() -> Self { Table { authority_data: HashMap::default(), detected_misbehavior: HashMap::default(), candidate_votes: HashMap::default(), - config, } } @@ -408,33 +386,7 @@ impl Table { // if digest is different, fetch candidate and // note misbehavior. let existing = occ.get_mut(); - - if !self.config.allow_multiple_seconded && existing.proposals.len() == 1 { - let (old_digest, old_sig) = &existing.proposals[0]; - - if old_digest != &digest { - const EXISTENCE_PROOF: &str = - "when proposal first received from authority, candidate \ - votes entry is created. proposal here is `Some`, therefore \ - candidate votes entry exists; qed"; - - let old_candidate = self - .candidate_votes - .get(old_digest) - .expect(EXISTENCE_PROOF) - .candidate - .clone(); - - return Err(Misbehavior::MultipleCandidates(MultipleCandidates { - first: (old_candidate, old_sig.clone()), - second: (candidate, signature.clone()), - })) - } - - false - } else if self.config.allow_multiple_seconded && - existing.proposals.iter().any(|(ref od, _)| od == &digest) - { + if existing.proposals.iter().any(|(ref od, _)| od == &digest) { false } else { existing.proposals.push((digest.clone(), signature.clone())); @@ -591,14 +543,6 @@ mod tests { use super::*; use std::collections::HashMap; - fn create_single_seconded() -> Table { - Table::new(Config { allow_multiple_seconded: false }) - } - - fn create_many_seconded() -> Table { - Table::new(Config { allow_multiple_seconded: true }) - } - #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] struct AuthorityId(usize); @@ -646,42 +590,6 @@ mod tests { } } - #[test] - fn submitting_two_candidates_can_be_misbehavior() { - let context = TestContext { - authorities: { - let mut map = HashMap::new(); - map.insert(AuthorityId(1), GroupId(2)); - map - }, - }; - - let mut table = create_single_seconded(); - let statement_a = SignedStatement { - statement: Statement::Seconded(Candidate(2, 100)), - signature: Signature(1), - sender: AuthorityId(1), - }; - - let statement_b = SignedStatement { - statement: Statement::Seconded(Candidate(2, 999)), - signature: Signature(1), - sender: AuthorityId(1), - }; - - table.import_statement(&context, GroupId(2), statement_a); - assert!(!table.detected_misbehavior.contains_key(&AuthorityId(1))); - - table.import_statement(&context, GroupId(2), statement_b); - assert_eq!( - table.detected_misbehavior[&AuthorityId(1)][0], - Misbehavior::MultipleCandidates(MultipleCandidates { - first: (Candidate(2, 100), Signature(1)), - second: (Candidate(2, 999), Signature(1)), - }) - ); - } - #[test] fn submitting_two_candidates_can_be_allowed() { let context = TestContext { @@ -692,7 +600,7 @@ mod tests { }, }; - let mut table = create_many_seconded(); + let mut table = Table::new(); let statement_a = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -722,7 +630,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -754,7 +662,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let candidate_a = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), @@ -798,7 +706,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -828,7 +736,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -896,7 +804,7 @@ mod tests { }; // have 2/3 validity guarantors note validity. - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -930,7 +838,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), @@ -957,7 +865,7 @@ mod tests { }, }; - let mut table = create_single_seconded(); + let mut table = Table::new(); let statement = SignedStatement { statement: Statement::Seconded(Candidate(2, 100)), signature: Signature(1), diff --git a/polkadot/statement-table/src/lib.rs b/polkadot/statement-table/src/lib.rs index 68febf76feb3..c8ad28437f88 100644 --- a/polkadot/statement-table/src/lib.rs +++ b/polkadot/statement-table/src/lib.rs @@ -29,7 +29,7 @@ pub mod generic; -pub use generic::{Config, Context, Table}; +pub use generic::{Context, Table}; /// Concrete instantiations suitable for v2 primitives. pub mod v2 { diff --git a/prdoc/pr_6215.prdoc b/prdoc/pr_6215.prdoc new file mode 100644 index 000000000000..3726a2fc5788 --- /dev/null +++ b/prdoc/pr_6215.prdoc @@ -0,0 +1,16 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Remove `ProspectiveParachainsMode` from backing subsystem +doc: + - audience: "Node Dev" + description: | + Removes `ProspectiveParachainsMode` usage from the backing subsystem and assumes + `async_backing_params` runtime api is always available. Since the runtime api v7 is released on + all networks it should always be true. + +crates: + - name: polkadot-node-core-backing + bump: patch + - name: polkadot-statement-table + bump: major From b71bd53f5fde0624c828461432a6b0f223c585c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Mon, 18 Nov 2024 20:56:54 +0000 Subject: [PATCH 106/166] sp-runtime: Be a little bit more functional :D (#6526) Co-authored-by: GitHub Action --- prdoc/pr_6526.prdoc | 8 +++ .../primitives/runtime/src/generic/digest.rs | 55 ++++++------------- 2 files changed, 25 insertions(+), 38 deletions(-) create mode 100644 prdoc/pr_6526.prdoc diff --git a/prdoc/pr_6526.prdoc b/prdoc/pr_6526.prdoc new file mode 100644 index 000000000000..9ea1368ab10c --- /dev/null +++ b/prdoc/pr_6526.prdoc @@ -0,0 +1,8 @@ +title: 'sp-runtime: Be a little bit more functional :D' +doc: +- audience: Runtime Dev + description: + Some internal refactorings in the `Digest` code. +crates: +- name: sp-runtime + bump: patch diff --git a/substrate/primitives/runtime/src/generic/digest.rs b/substrate/primitives/runtime/src/generic/digest.rs index c639576a2867..5ed0c7075cae 100644 --- a/substrate/primitives/runtime/src/generic/digest.rs +++ b/substrate/primitives/runtime/src/generic/digest.rs @@ -20,6 +20,7 @@ #[cfg(all(not(feature = "std"), feature = "serde"))] use alloc::format; use alloc::vec::Vec; +use codec::DecodeAll; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; @@ -256,8 +257,7 @@ impl DigestItem { self.dref().try_as_raw(id) } - /// Returns the data contained in the item if `Some` if this entry has the id given, decoded - /// to the type provided `T`. + /// Returns the data decoded as `T`, if the `id` is matching. pub fn try_to(&self, id: OpaqueDigestItemId) -> Option { self.dref().try_to::(id) } @@ -367,17 +367,16 @@ impl<'a> DigestItemRef<'a> { /// Try to match this digest item to the given opaque item identifier; if it matches, then /// try to cast to the given data type; if that works, return it. pub fn try_to(&self, id: OpaqueDigestItemId) -> Option { - self.try_as_raw(id).and_then(|mut x| Decode::decode(&mut x).ok()) + self.try_as_raw(id).and_then(|mut x| DecodeAll::decode_all(&mut x).ok()) } /// Try to match this to a `Self::Seal`, check `id` matches and decode it. /// /// Returns `None` if this isn't a seal item, the `id` doesn't match or when the decoding fails. pub fn seal_try_to(&self, id: &ConsensusEngineId) -> Option { - match self { - Self::Seal(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(), - _ => None, - } + self.as_seal() + .filter(|s| s.0 == *id) + .and_then(|mut d| DecodeAll::decode_all(&mut d.1).ok()) } /// Try to match this to a `Self::Consensus`, check `id` matches and decode it. @@ -385,10 +384,9 @@ impl<'a> DigestItemRef<'a> { /// Returns `None` if this isn't a consensus item, the `id` doesn't match or /// when the decoding fails. pub fn consensus_try_to(&self, id: &ConsensusEngineId) -> Option { - match self { - Self::Consensus(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(), - _ => None, - } + self.as_consensus() + .filter(|s| s.0 == *id) + .and_then(|mut d| DecodeAll::decode_all(&mut d.1).ok()) } /// Try to match this to a `Self::PreRuntime`, check `id` matches and decode it. @@ -396,40 +394,21 @@ impl<'a> DigestItemRef<'a> { /// Returns `None` if this isn't a pre-runtime item, the `id` doesn't match or /// when the decoding fails. pub fn pre_runtime_try_to(&self, id: &ConsensusEngineId) -> Option { - match self { - Self::PreRuntime(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(), - _ => None, - } + self.as_pre_runtime() + .filter(|s| s.0 == *id) + .and_then(|mut d| DecodeAll::decode_all(&mut d.1).ok()) } } impl<'a> Encode for DigestItemRef<'a> { fn encode(&self) -> Vec { - let mut v = Vec::new(); - match *self { - Self::Consensus(val, data) => { - DigestItemType::Consensus.encode_to(&mut v); - (val, data).encode_to(&mut v); - }, - Self::Seal(val, sig) => { - DigestItemType::Seal.encode_to(&mut v); - (val, sig).encode_to(&mut v); - }, - Self::PreRuntime(val, data) => { - DigestItemType::PreRuntime.encode_to(&mut v); - (val, data).encode_to(&mut v); - }, - Self::Other(val) => { - DigestItemType::Other.encode_to(&mut v); - val.encode_to(&mut v); - }, - Self::RuntimeEnvironmentUpdated => { - DigestItemType::RuntimeEnvironmentUpdated.encode_to(&mut v); - }, + Self::Consensus(val, data) => (DigestItemType::Consensus, val, data).encode(), + Self::Seal(val, sig) => (DigestItemType::Seal, val, sig).encode(), + Self::PreRuntime(val, data) => (DigestItemType::PreRuntime, val, data).encode(), + Self::Other(val) => (DigestItemType::Other, val).encode(), + Self::RuntimeEnvironmentUpdated => DigestItemType::RuntimeEnvironmentUpdated.encode(), } - - v } } From 5721e5569e10453588e3869162f0f4740b828a17 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Tue, 19 Nov 2024 10:12:17 +0100 Subject: [PATCH 107/166] `TransactionPool` API uses `async_trait` (#6528) This PR refactors `TransactionPool` API to use `async_trait`, replacing the` Pin>` pattern. This should improve readability and maintainability. The change is not altering any functionality. --------- Co-authored-by: GitHub Action --- Cargo.lock | 2 + prdoc/pr_6528.prdoc | 18 ++ substrate/bin/node/bench/Cargo.toml | 1 + substrate/bin/node/bench/src/construct.rs | 48 ++--- substrate/client/rpc-spec-v2/Cargo.toml | 1 + .../src/transaction/tests/middleware_pool.rs | 96 ++++----- substrate/client/rpc/src/author/mod.rs | 17 +- substrate/client/service/src/lib.rs | 16 +- .../client/transaction-pool/api/src/lib.rs | 55 ++---- .../fork_aware_txpool/fork_aware_txpool.rs | 184 ++++++++---------- .../src/fork_aware_txpool/mod.rs | 12 +- substrate/client/transaction-pool/src/lib.rs | 4 +- .../single_state_txpool.rs | 95 ++++----- .../src/transaction_pool_wrapper.rs | 52 ++--- 14 files changed, 268 insertions(+), 333 deletions(-) create mode 100644 prdoc/pr_6528.prdoc diff --git a/Cargo.lock b/Cargo.lock index 182d8f6bacad..02d7da8f7657 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11086,6 +11086,7 @@ name = "node-bench" version = "0.9.0-dev" dependencies = [ "array-bytes", + "async-trait", "clap 4.5.13", "derive_more 0.99.17", "fs_extra", @@ -23245,6 +23246,7 @@ version = "0.34.0" dependencies = [ "array-bytes", "assert_matches", + "async-trait", "futures", "futures-util", "hex", diff --git a/prdoc/pr_6528.prdoc b/prdoc/pr_6528.prdoc new file mode 100644 index 000000000000..477ad76c947f --- /dev/null +++ b/prdoc/pr_6528.prdoc @@ -0,0 +1,18 @@ +title: 'TransactionPool API uses async_trait' +doc: +- audience: Node Dev + description: |- + This PR refactors `TransactionPool` API to use `async_trait`, replacing the` Pin>` pattern. This should improve readability and maintainability. + + The change is not altering any functionality. +crates: +- name: sc-rpc-spec-v2 + bump: minor +- name: sc-service + bump: minor +- name: sc-transaction-pool-api + bump: major +- name: sc-transaction-pool + bump: major +- name: sc-rpc + bump: minor diff --git a/substrate/bin/node/bench/Cargo.toml b/substrate/bin/node/bench/Cargo.toml index 8c6556da682c..447f947107c1 100644 --- a/substrate/bin/node/bench/Cargo.toml +++ b/substrate/bin/node/bench/Cargo.toml @@ -15,6 +15,7 @@ workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +async-trait = { workspace = true } array-bytes = { workspace = true, default-features = true } clap = { features = ["derive"], workspace = true } log = { workspace = true, default-features = true } diff --git a/substrate/bin/node/bench/src/construct.rs b/substrate/bin/node/bench/src/construct.rs index bed6e3d914c2..22129c6a1d69 100644 --- a/substrate/bin/node/bench/src/construct.rs +++ b/substrate/bin/node/bench/src/construct.rs @@ -24,14 +24,14 @@ //! DO NOT depend on user input). Thus transaction generation should be //! based on randomized data. -use futures::Future; use std::{borrow::Cow, collections::HashMap, pin::Pin, sync::Arc}; +use async_trait::async_trait; use node_primitives::Block; use node_testing::bench::{BenchDb, BlockType, DatabaseType, KeyTypes}; use sc_transaction_pool_api::{ - ImportNotificationStream, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, - TransactionSource, TransactionStatusStreamFor, TxHash, + ImportNotificationStream, PoolStatus, ReadyTransactions, TransactionFor, TransactionSource, + TransactionStatusStreamFor, TxHash, }; use sp_consensus::{Environment, Proposer}; use sp_inherents::InherentDataProvider; @@ -224,54 +224,47 @@ impl ReadyTransactions for TransactionsIterator { fn report_invalid(&mut self, _tx: &Self::Item) {} } +#[async_trait] impl sc_transaction_pool_api::TransactionPool for Transactions { type Block = Block; type Hash = node_primitives::Hash; type InPoolTransaction = PoolTransaction; type Error = sc_transaction_pool_api::error::Error; - /// Returns a future that imports a bunch of unverified transactions to the pool. - fn submit_at( + /// Asynchronously imports a bunch of unverified transactions to the pool. + async fn submit_at( &self, _at: Self::Hash, _source: TransactionSource, _xts: Vec>, - ) -> PoolFuture>, Self::Error> { + ) -> Result>, Self::Error> { unimplemented!() } - /// Returns a future that imports one unverified transaction to the pool. - fn submit_one( + /// Asynchronously imports one unverified transaction to the pool. + async fn submit_one( &self, _at: Self::Hash, _source: TransactionSource, _xt: TransactionFor, - ) -> PoolFuture, Self::Error> { + ) -> Result, Self::Error> { unimplemented!() } - fn submit_and_watch( + async fn submit_and_watch( &self, _at: Self::Hash, _source: TransactionSource, _xt: TransactionFor, - ) -> PoolFuture>>, Self::Error> { + ) -> Result>>, Self::Error> { unimplemented!() } - fn ready_at( + async fn ready_at( &self, _at: Self::Hash, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send, - >, - > { - let iter: Box> + Send> = - Box::new(TransactionsIterator(self.0.clone().into_iter())); - Box::pin(futures::future::ready(iter)) + ) -> Box> + Send> { + Box::new(TransactionsIterator(self.0.clone().into_iter())) } fn ready(&self) -> Box> + Send> { @@ -306,18 +299,11 @@ impl sc_transaction_pool_api::TransactionPool for Transactions { unimplemented!() } - fn ready_at_with_timeout( + async fn ready_at_with_timeout( &self, _at: Self::Hash, _timeout: std::time::Duration, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send - + '_, - >, - > { + ) -> Box> + Send> { unimplemented!() } } diff --git a/substrate/client/rpc-spec-v2/Cargo.toml b/substrate/client/rpc-spec-v2/Cargo.toml index 58dd8b830beb..daa805912fb9 100644 --- a/substrate/client/rpc-spec-v2/Cargo.toml +++ b/substrate/client/rpc-spec-v2/Cargo.toml @@ -44,6 +44,7 @@ rand = { workspace = true, default-features = true } schnellru = { workspace = true } [dev-dependencies] +async-trait = { workspace = true } jsonrpsee = { workspace = true, features = ["server", "ws-client"] } serde_json = { workspace = true, default-features = true } tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/substrate/client/rpc-spec-v2/src/transaction/tests/middleware_pool.rs b/substrate/client/rpc-spec-v2/src/transaction/tests/middleware_pool.rs index adcc987f9c39..a543969a89b8 100644 --- a/substrate/client/rpc-spec-v2/src/transaction/tests/middleware_pool.rs +++ b/substrate/client/rpc-spec-v2/src/transaction/tests/middleware_pool.rs @@ -16,16 +16,16 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . +use async_trait::async_trait; use codec::Encode; -use futures::Future; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{ - ImportNotificationStream, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, - TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, + ImportNotificationStream, PoolStatus, ReadyTransactions, TransactionFor, TransactionPool, + TransactionSource, TransactionStatusStreamFor, TxHash, }; use crate::hex_string; -use futures::{FutureExt, StreamExt}; +use futures::StreamExt; use sp_runtime::traits::Block as BlockT; use std::{collections::HashMap, pin::Pin, sync::Arc}; @@ -77,67 +77,64 @@ impl MiddlewarePool { } } +#[async_trait] impl TransactionPool for MiddlewarePool { type Block = as TransactionPool>::Block; type Hash = as TransactionPool>::Hash; type InPoolTransaction = as TransactionPool>::InPoolTransaction; type Error = as TransactionPool>::Error; - fn submit_at( + async fn submit_at( &self, at: ::Hash, source: TransactionSource, xts: Vec>, - ) -> PoolFuture, Self::Error>>, Self::Error> { - self.inner_pool.submit_at(at, source, xts) + ) -> Result, Self::Error>>, Self::Error> { + self.inner_pool.submit_at(at, source, xts).await } - fn submit_one( + async fn submit_one( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture, Self::Error> { - self.inner_pool.submit_one(at, source, xt) + ) -> Result, Self::Error> { + self.inner_pool.submit_one(at, source, xt).await } - fn submit_and_watch( + async fn submit_and_watch( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture>>, Self::Error> { - let pool = self.inner_pool.clone(); - let sender = self.sender.clone(); + ) -> Result>>, Self::Error> { let transaction = hex_string(&xt.encode()); + let sender = self.sender.clone(); - async move { - let watcher = match pool.submit_and_watch(at, source, xt).await { - Ok(watcher) => watcher, - Err(err) => { - let _ = sender.send(MiddlewarePoolEvent::PoolError { - transaction: transaction.clone(), - err: err.to_string(), - }); - return Err(err); - }, - }; - - let watcher = watcher.map(move |status| { - let sender = sender.clone(); - let transaction = transaction.clone(); - - let _ = sender.send(MiddlewarePoolEvent::TransactionStatus { - transaction, - status: status.clone(), + let watcher = match self.inner_pool.submit_and_watch(at, source, xt).await { + Ok(watcher) => watcher, + Err(err) => { + let _ = sender.send(MiddlewarePoolEvent::PoolError { + transaction: transaction.clone(), + err: err.to_string(), }); + return Err(err); + }, + }; + + let watcher = watcher.map(move |status| { + let sender = sender.clone(); + let transaction = transaction.clone(); - status + let _ = sender.send(MiddlewarePoolEvent::TransactionStatus { + transaction, + status: status.clone(), }); - Ok(watcher.boxed()) - } - .boxed() + status + }); + + Ok(watcher.boxed()) } fn remove_invalid(&self, hashes: &[TxHash]) -> Vec> { @@ -164,17 +161,11 @@ impl TransactionPool for MiddlewarePool { self.inner_pool.ready_transaction(hash) } - fn ready_at( + async fn ready_at( &self, at: ::Hash, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send, - >, - > { - self.inner_pool.ready_at(at) + ) -> Box> + Send> { + self.inner_pool.ready_at(at).await } fn ready(&self) -> Box> + Send> { @@ -185,18 +176,11 @@ impl TransactionPool for MiddlewarePool { self.inner_pool.futures() } - fn ready_at_with_timeout( + async fn ready_at_with_timeout( &self, at: ::Hash, _timeout: std::time::Duration, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send - + '_, - >, - > { - self.inner_pool.ready_at(at) + ) -> Box> + Send> { + self.inner_pool.ready_at(at).await } } diff --git a/substrate/client/rpc/src/author/mod.rs b/substrate/client/rpc/src/author/mod.rs index 731f4df2f6f3..6afc871e565a 100644 --- a/substrate/client/rpc/src/author/mod.rs +++ b/substrate/client/rpc/src/author/mod.rs @@ -29,7 +29,6 @@ use crate::{ }; use codec::{Decode, Encode}; -use futures::TryFutureExt; use jsonrpsee::{core::async_trait, types::ErrorObject, Extensions, PendingSubscriptionSink}; use sc_rpc_api::check_if_safe; use sc_transaction_pool_api::{ @@ -191,14 +190,16 @@ where }, }; - let submit = self.pool.submit_and_watch(best_block_hash, TX_SOURCE, dxt).map_err(|e| { - e.into_pool_error() - .map(error::Error::from) - .unwrap_or_else(|e| error::Error::Verification(Box::new(e))) - }); - + let pool = self.pool.clone(); let fut = async move { - let stream = match submit.await { + let submit = + pool.submit_and_watch(best_block_hash, TX_SOURCE, dxt).await.map_err(|e| { + e.into_pool_error() + .map(error::Error::from) + .unwrap_or_else(|e| error::Error::Verification(Box::new(e))) + }); + + let stream = match submit { Ok(stream) => stream, Err(err) => { let _ = pending.reject(ErrorObject::from(err)).await; diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 5cfd80cef910..9c01d7288a81 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -528,13 +528,17 @@ where }; let start = std::time::Instant::now(); - let import_future = self.pool.submit_one( - self.client.info().best_hash, - sc_transaction_pool_api::TransactionSource::External, - uxt, - ); + let pool = self.pool.clone(); + let client = self.client.clone(); Box::pin(async move { - match import_future.await { + match pool + .submit_one( + client.info().best_hash, + sc_transaction_pool_api::TransactionSource::External, + uxt, + ) + .await + { Ok(_) => { let elapsed = start.elapsed(); debug!(target: sc_transaction_pool::LOG_TARGET, "import transaction: {elapsed:?}"); diff --git a/substrate/client/transaction-pool/api/src/lib.rs b/substrate/client/transaction-pool/api/src/lib.rs index 3ac1a79a0c28..6f771e9479bd 100644 --- a/substrate/client/transaction-pool/api/src/lib.rs +++ b/substrate/client/transaction-pool/api/src/lib.rs @@ -23,7 +23,7 @@ pub mod error; use async_trait::async_trait; use codec::Codec; -use futures::{Future, Stream}; +use futures::Stream; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use sp_core::offchain::TransactionPoolExt; use sp_runtime::traits::{Block as BlockT, Member}; @@ -208,9 +208,6 @@ pub type LocalTransactionFor

= <

::Block as BlockT> /// Transaction's index within the block in which it was included. pub type TxIndex = usize; -/// Typical future type used in transaction pool api. -pub type PoolFuture = std::pin::Pin> + Send>>; - /// In-pool transaction interface. /// /// The pool is container of transactions that are implementing this trait. @@ -238,6 +235,7 @@ pub trait InPoolTransaction { } /// Transaction pool interface. +#[async_trait] pub trait TransactionPool: Send + Sync { /// Block type. type Block: BlockT; @@ -253,46 +251,40 @@ pub trait TransactionPool: Send + Sync { // *** RPC - /// Returns a future that imports a bunch of unverified transactions to the pool. - fn submit_at( + /// Asynchronously imports a bunch of unverified transactions to the pool. + async fn submit_at( &self, at: ::Hash, source: TransactionSource, xts: Vec>, - ) -> PoolFuture, Self::Error>>, Self::Error>; + ) -> Result, Self::Error>>, Self::Error>; - /// Returns a future that imports one unverified transaction to the pool. - fn submit_one( + /// Asynchronously imports one unverified transaction to the pool. + async fn submit_one( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture, Self::Error>; + ) -> Result, Self::Error>; - /// Returns a future that imports a single transaction and starts to watch their progress in the + /// Asynchronously imports a single transaction and starts to watch their progress in the /// pool. - fn submit_and_watch( + async fn submit_and_watch( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture>>, Self::Error>; + ) -> Result>>, Self::Error>; // *** Block production / Networking /// Get an iterator for ready transactions ordered by priority. /// - /// Guarantees to return only when transaction pool got updated at `at` block. - /// Guarantees to return immediately when `None` is passed. - fn ready_at( + /// Guaranteed to resolve only when transaction pool got updated at `at` block. + /// Guaranteed to resolve immediately when `None` is passed. + async fn ready_at( &self, at: ::Hash, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send, - >, - >; + ) -> Box> + Send>; /// Get an iterator for ready transactions ordered by priority. fn ready(&self) -> Box> + Send>; @@ -322,22 +314,15 @@ pub trait TransactionPool: Send + Sync { /// Return specific ready transaction by hash, if there is one. fn ready_transaction(&self, hash: &TxHash) -> Option>; - /// Returns set of ready transaction at given block within given timeout. + /// Asynchronously returns a set of ready transaction at given block within given timeout. /// - /// If the timeout is hit during method execution then the best effort set of ready transactions - /// for given block, without executing full maintain process is returned. - fn ready_at_with_timeout( + /// If the timeout is hit during method execution, then the best effort (without executing full + /// maintain process) set of ready transactions for given block is returned. + async fn ready_at_with_timeout( &self, at: ::Hash, timeout: std::time::Duration, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send - + '_, - >, - >; + ) -> Box> + Send>; } /// An iterator of ready transactions. diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs index a342d35b2844..065d0cb3a274 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/fork_aware_txpool.rs @@ -33,7 +33,7 @@ use crate::{ enactment_state::{EnactmentAction, EnactmentState}, fork_aware_txpool::revalidation_worker, graph::{self, base_pool::Transaction, ExtrinsicFor, ExtrinsicHash, IsValidator, Options}, - PolledIterator, ReadyIteratorFor, LOG_TARGET, + ReadyIteratorFor, LOG_TARGET, }; use async_trait::async_trait; use futures::{ @@ -45,8 +45,8 @@ use futures::{ use parking_lot::Mutex; use prometheus_endpoint::Registry as PrometheusRegistry; use sc_transaction_pool_api::{ - ChainEvent, ImportNotificationStream, MaintainedTransactionPool, PoolFuture, PoolStatus, - TransactionFor, TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, + ChainEvent, ImportNotificationStream, MaintainedTransactionPool, PoolStatus, TransactionFor, + TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, }; use sp_blockchain::{HashAndNumber, TreeRoute}; use sp_core::traits::SpawnEssentialNamed; @@ -375,14 +375,13 @@ where /// /// Pruning is just rebuilding the underlying transactions graph, no validations are executed, /// so this process shall be fast. - pub fn ready_at_light(&self, at: Block::Hash) -> PolledIterator { + pub async fn ready_at_light(&self, at: Block::Hash) -> ReadyIteratorFor { let start = Instant::now(); let api = self.api.clone(); log::trace!(target: LOG_TARGET, "fatp::ready_at_light {:?}", at); let Ok(block_number) = self.api.resolve_block_number(at) else { - let empty: ReadyIteratorFor = Box::new(std::iter::empty()); - return Box::pin(async { empty }) + return Box::new(std::iter::empty()) }; let best_result = { @@ -401,57 +400,53 @@ where ) }; - Box::pin(async move { - if let Ok((Some(best_tree_route), Some(best_view))) = best_result { - let tmp_view: View = View::new_from_other( - &best_view, - &HashAndNumber { hash: at, number: block_number }, - ); - - let mut all_extrinsics = vec![]; + if let Ok((Some(best_tree_route), Some(best_view))) = best_result { + let tmp_view: View = + View::new_from_other(&best_view, &HashAndNumber { hash: at, number: block_number }); - for h in best_tree_route.enacted() { - let extrinsics = api - .block_body(h.hash) - .await - .unwrap_or_else(|e| { - log::warn!(target: LOG_TARGET, "Compute ready light transactions: error request: {}", e); - None - }) - .unwrap_or_default() - .into_iter() - .map(|t| api.hash_and_length(&t).0); - all_extrinsics.extend(extrinsics); - } + let mut all_extrinsics = vec![]; - let before_count = tmp_view.pool.validated_pool().status().ready; - let tags = tmp_view - .pool - .validated_pool() - .extrinsics_tags(&all_extrinsics) + for h in best_tree_route.enacted() { + let extrinsics = api + .block_body(h.hash) + .await + .unwrap_or_else(|e| { + log::warn!(target: LOG_TARGET, "Compute ready light transactions: error request: {}", e); + None + }) + .unwrap_or_default() .into_iter() - .flatten() - .flatten() - .collect::>(); - let _ = tmp_view.pool.validated_pool().prune_tags(tags); - - let after_count = tmp_view.pool.validated_pool().status().ready; - log::debug!(target: LOG_TARGET, - "fatp::ready_at_light {} from {} before: {} to be removed: {} after: {} took:{:?}", - at, - best_view.at.hash, - before_count, - all_extrinsics.len(), - after_count, - start.elapsed() - ); - Box::new(tmp_view.pool.validated_pool().ready()) - } else { - let empty: ReadyIteratorFor = Box::new(std::iter::empty()); - log::debug!(target: LOG_TARGET, "fatp::ready_at_light {} -> empty, took:{:?}", at, start.elapsed()); - empty + .map(|t| api.hash_and_length(&t).0); + all_extrinsics.extend(extrinsics); } - }) + + let before_count = tmp_view.pool.validated_pool().status().ready; + let tags = tmp_view + .pool + .validated_pool() + .extrinsics_tags(&all_extrinsics) + .into_iter() + .flatten() + .flatten() + .collect::>(); + let _ = tmp_view.pool.validated_pool().prune_tags(tags); + + let after_count = tmp_view.pool.validated_pool().status().ready; + log::debug!(target: LOG_TARGET, + "fatp::ready_at_light {} from {} before: {} to be removed: {} after: {} took:{:?}", + at, + best_view.at.hash, + before_count, + all_extrinsics.len(), + after_count, + start.elapsed() + ); + Box::new(tmp_view.pool.validated_pool().ready()) + } else { + let empty: ReadyIteratorFor = Box::new(std::iter::empty()); + log::debug!(target: LOG_TARGET, "fatp::ready_at_light {} -> empty, took:{:?}", at, start.elapsed()); + empty + } } /// Waits for the set of ready transactions for a given block up to a specified timeout. @@ -464,18 +459,18 @@ where /// maintain. /// /// Returns a future resolving to a ready iterator of transactions. - fn ready_at_with_timeout_internal( + async fn ready_at_with_timeout_internal( &self, at: Block::Hash, timeout: std::time::Duration, - ) -> PolledIterator { + ) -> ReadyIteratorFor { log::debug!(target: LOG_TARGET, "fatp::ready_at_with_timeout at {:?} allowed delay: {:?}", at, timeout); let timeout = futures_timer::Delay::new(timeout); let (view_already_exists, ready_at) = self.ready_at_internal(at); if view_already_exists { - return ready_at; + return ready_at.await; } let maybe_ready = async move { @@ -493,18 +488,19 @@ where }; let fall_back_ready = self.ready_at_light(at); - Box::pin(async { - let (maybe_ready, fall_back_ready) = - futures::future::join(maybe_ready.boxed(), fall_back_ready.boxed()).await; - maybe_ready.unwrap_or(fall_back_ready) - }) + let (maybe_ready, fall_back_ready) = + futures::future::join(maybe_ready, fall_back_ready).await; + maybe_ready.unwrap_or(fall_back_ready) } - fn ready_at_internal(&self, at: Block::Hash) -> (bool, PolledIterator) { + fn ready_at_internal( + &self, + at: Block::Hash, + ) -> (bool, Pin> + Send>>) { let mut ready_poll = self.ready_poll.lock(); if let Some((view, inactive)) = self.view_store.get_view_at(at, true) { - log::debug!(target: LOG_TARGET, "fatp::ready_at {at:?} (inactive:{inactive:?})"); + log::debug!(target: LOG_TARGET, "fatp::ready_at_internal {at:?} (inactive:{inactive:?})"); let iterator: ReadyIteratorFor = Box::new(view.pool.validated_pool().ready()); return (true, async move { iterator }.boxed()); } @@ -519,7 +515,7 @@ where }) .boxed(); log::debug!(target: LOG_TARGET, - "fatp::ready_at {at:?} pending keys: {:?}", + "fatp::ready_at_internal {at:?} pending keys: {:?}", ready_poll.pollers.keys() ); (false, pending) @@ -573,6 +569,7 @@ fn reduce_multiview_result(input: HashMap>>) -> Vec TransactionPool for ForkAwareTxPool where Block: BlockT, @@ -590,12 +587,12 @@ where /// /// The internal limits of the pool are checked. The results of submissions to individual views /// are reduced to single result. Refer to `reduce_multiview_result` for more details. - fn submit_at( + async fn submit_at( &self, _: ::Hash, source: TransactionSource, xts: Vec>, - ) -> PoolFuture, Self::Error>>, Self::Error> { + ) -> Result, Self::Error>>, Self::Error> { let view_store = self.view_store.clone(); log::debug!(target: LOG_TARGET, "fatp::submit_at count:{} views:{}", xts.len(), self.active_views_count()); log_xt_trace!(target: LOG_TARGET, xts.iter().map(|xt| self.tx_hash(xt)), "[{:?}] fatp::submit_at"); @@ -603,7 +600,7 @@ where let mempool_results = self.mempool.extend_unwatched(source, &xts); if view_store.is_empty() { - return future::ready(Ok(mempool_results)).boxed() + return Ok(mempool_results) } let to_be_submitted = mempool_results @@ -616,11 +613,10 @@ where .report(|metrics| metrics.submitted_transactions.inc_by(to_be_submitted.len() as _)); let mempool = self.mempool.clone(); - async move { - let results_map = view_store.submit(source, to_be_submitted.into_iter()).await; - let mut submission_results = reduce_multiview_result(results_map).into_iter(); + let results_map = view_store.submit(source, to_be_submitted.into_iter()).await; + let mut submission_results = reduce_multiview_result(results_map).into_iter(); - Ok(mempool_results + Ok(mempool_results .into_iter() .map(|result| { result.and_then(|xt_hash| { @@ -633,60 +629,50 @@ where }) }) .collect::>()) - } - .boxed() } /// Submits a single transaction and returns a future resolving to the submission results. /// /// Actual transaction submission process is delegated to the `submit_at` function. - fn submit_one( + async fn submit_one( &self, _at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture, Self::Error> { + ) -> Result, Self::Error> { log::trace!(target: LOG_TARGET, "[{:?}] fatp::submit_one views:{}", self.tx_hash(&xt), self.active_views_count()); - let result_future = self.submit_at(_at, source, vec![xt]); - async move { - let result = result_future.await; - match result { - Ok(mut v) => - v.pop().expect("There is exactly one element in result of submit_at. qed."), - Err(e) => Err(e), - } + match self.submit_at(_at, source, vec![xt]).await { + Ok(mut v) => + v.pop().expect("There is exactly one element in result of submit_at. qed."), + Err(e) => Err(e), } - .boxed() } /// Submits a transaction and starts to watch its progress in the pool, returning a stream of /// status updates. /// /// Actual transaction submission process is delegated to the `ViewStore` internal instance. - fn submit_and_watch( + async fn submit_and_watch( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture>>, Self::Error> { + ) -> Result>>, Self::Error> { log::trace!(target: LOG_TARGET, "[{:?}] fatp::submit_and_watch views:{}", self.tx_hash(&xt), self.active_views_count()); let xt = Arc::from(xt); let xt_hash = match self.mempool.push_watched(source, xt.clone()) { Ok(xt_hash) => xt_hash, - Err(e) => return future::ready(Err(e)).boxed(), + Err(e) => return Err(e), }; self.metrics.report(|metrics| metrics.submitted_transactions.inc()); let view_store = self.view_store.clone(); let mempool = self.mempool.clone(); - async move { - view_store - .submit_and_watch(at, source, xt) - .await - .inspect_err(|_| mempool.remove(xt_hash)) - } - .boxed() + view_store + .submit_and_watch(at, source, xt) + .await + .inspect_err(|_| mempool.remove(xt_hash)) } /// Intended to remove transactions identified by the given hashes, and any dependent @@ -757,9 +743,9 @@ where } /// Returns an iterator for ready transactions at a specific block, ordered by priority. - fn ready_at(&self, at: ::Hash) -> PolledIterator { + async fn ready_at(&self, at: ::Hash) -> ReadyIteratorFor { let (_, result) = self.ready_at_internal(at); - result + result.await } /// Returns an iterator for ready transactions, ordered by priority. @@ -782,12 +768,12 @@ where /// /// If the timeout expires before the maintain process is accomplished, a best-effort /// set of transactions is returned (refer to `ready_at_light`). - fn ready_at_with_timeout( + async fn ready_at_with_timeout( &self, at: ::Hash, timeout: std::time::Duration, - ) -> PolledIterator { - self.ready_at_with_timeout_internal(at, timeout) + ) -> ReadyIteratorFor { + self.ready_at_with_timeout_internal(at, timeout).await } } diff --git a/substrate/client/transaction-pool/src/fork_aware_txpool/mod.rs b/substrate/client/transaction-pool/src/fork_aware_txpool/mod.rs index 9f979e216b6d..5f7294a24fd7 100644 --- a/substrate/client/transaction-pool/src/fork_aware_txpool/mod.rs +++ b/substrate/client/transaction-pool/src/fork_aware_txpool/mod.rs @@ -201,12 +201,12 @@ //! required to accomplish it. //! //! ### Providing ready transactions: `ready_at` -//! The [`ready_at`] function returns a [future][`crate::PolledIterator`] that resolves to the -//! [ready transactions iterator][`ReadyTransactions`]. The block builder shall wait either for the -//! future to be resolved or for timeout to be hit. To avoid building empty blocks in case of -//! timeout, the waiting for timeout functionality was moved into the transaction pool, and new API -//! function was added: [`ready_at_with_timeout`]. This function also provides a fall back ready -//! iterator which is result of [light maintain](#light-maintain). +//! The asynchronous [`ready_at`] function resolves to the [ready transactions +//! iterator][`ReadyTransactions`]. The block builder shall wait either for the future to be +//! resolved or for timeout to be hit. To avoid building empty blocks in case of timeout, the +//! waiting for timeout functionality was moved into the transaction pool, and new API function was +//! added: [`ready_at_with_timeout`]. This function also provides a fall back ready iterator which +//! is result of [light maintain](#light-maintain). //! //! New function internally waits either for [maintain](#maintain) process triggered for requested //! block to be accomplished or for the timeout. If timeout hits then the result of [light diff --git a/substrate/client/transaction-pool/src/lib.rs b/substrate/client/transaction-pool/src/lib.rs index 888d25d3a0d2..3d3d596c291f 100644 --- a/substrate/client/transaction-pool/src/lib.rs +++ b/substrate/client/transaction-pool/src/lib.rs @@ -30,7 +30,7 @@ mod single_state_txpool; mod transaction_pool_wrapper; use common::{api, enactment_state}; -use std::{future::Future, pin::Pin, sync::Arc}; +use std::sync::Arc; pub use api::FullChainApi; pub use builder::{Builder, TransactionPoolHandle, TransactionPoolOptions, TransactionPoolType}; @@ -50,8 +50,6 @@ type BoxedReadyIterator = Box< type ReadyIteratorFor = BoxedReadyIterator, graph::ExtrinsicFor>; -type PolledIterator = Pin> + Send>>; - /// Log target for transaction pool. /// /// It can be used by other components for logging functionality strictly related to txpool (e.g. diff --git a/substrate/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs b/substrate/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs index 0826b95cf070..b29630b563bb 100644 --- a/substrate/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs +++ b/substrate/client/transaction-pool/src/single_state_txpool/single_state_txpool.rs @@ -29,9 +29,8 @@ use crate::{ error, log_xt::log_xt_trace, }, - graph, - graph::{ExtrinsicHash, IsValidator}, - PolledIterator, ReadyIteratorFor, LOG_TARGET, + graph::{self, ExtrinsicHash, IsValidator}, + ReadyIteratorFor, LOG_TARGET, }; use async_trait::async_trait; use futures::{channel::oneshot, future, prelude::*, Future, FutureExt}; @@ -39,8 +38,8 @@ use parking_lot::Mutex; use prometheus_endpoint::Registry as PrometheusRegistry; use sc_transaction_pool_api::{ error::Error as TxPoolError, ChainEvent, ImportNotificationStream, MaintainedTransactionPool, - PoolFuture, PoolStatus, TransactionFor, TransactionPool, TransactionSource, - TransactionStatusStreamFor, TxHash, + PoolStatus, TransactionFor, TransactionPool, TransactionSource, TransactionStatusStreamFor, + TxHash, }; use sp_blockchain::{HashAndNumber, TreeRoute}; use sp_core::traits::SpawnEssentialNamed; @@ -224,26 +223,19 @@ where &self.api } - fn ready_at_with_timeout_internal( + async fn ready_at_with_timeout_internal( &self, at: Block::Hash, timeout: std::time::Duration, - ) -> PolledIterator { - let timeout = futures_timer::Delay::new(timeout); - let ready_maintained = self.ready_at(at); - let ready_current = self.ready(); - - let ready = async { - select! { - ready = ready_maintained => ready, - _ = timeout => ready_current - } - }; - - Box::pin(ready) + ) -> ReadyIteratorFor { + select! { + ready = self.ready_at(at)=> ready, + _ = futures_timer::Delay::new(timeout)=> self.ready() + } } } +#[async_trait] impl TransactionPool for BasicPool where Block: BlockT, @@ -255,12 +247,12 @@ where graph::base_pool::Transaction, graph::ExtrinsicFor>; type Error = PoolApi::Error; - fn submit_at( + async fn submit_at( &self, at: ::Hash, source: TransactionSource, xts: Vec>, - ) -> PoolFuture, Self::Error>>, Self::Error> { + ) -> Result, Self::Error>>, Self::Error> { let pool = self.pool.clone(); let xts = xts.into_iter().map(Arc::from).collect::>(); @@ -268,38 +260,32 @@ where .report(|metrics| metrics.submitted_transactions.inc_by(xts.len() as u64)); let number = self.api.resolve_block_number(at); - async move { - let at = HashAndNumber { hash: at, number: number? }; - Ok(pool.submit_at(&at, source, xts).await) - } - .boxed() + let at = HashAndNumber { hash: at, number: number? }; + Ok(pool.submit_at(&at, source, xts).await) } - fn submit_one( + async fn submit_one( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture, Self::Error> { + ) -> Result, Self::Error> { let pool = self.pool.clone(); let xt = Arc::from(xt); self.metrics.report(|metrics| metrics.submitted_transactions.inc()); let number = self.api.resolve_block_number(at); - async move { - let at = HashAndNumber { hash: at, number: number? }; - pool.submit_one(&at, source, xt).await - } - .boxed() + let at = HashAndNumber { hash: at, number: number? }; + pool.submit_one(&at, source, xt).await } - fn submit_and_watch( + async fn submit_and_watch( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture>>, Self::Error> { + ) -> Result>>, Self::Error> { let pool = self.pool.clone(); let xt = Arc::from(xt); @@ -307,13 +293,10 @@ where let number = self.api.resolve_block_number(at); - async move { - let at = HashAndNumber { hash: at, number: number? }; - let watcher = pool.submit_and_watch(&at, source, xt).await?; + let at = HashAndNumber { hash: at, number: number? }; + let watcher = pool.submit_and_watch(&at, source, xt).await?; - Ok(watcher.into_stream().boxed()) - } - .boxed() + Ok(watcher.into_stream().boxed()) } fn remove_invalid(&self, hashes: &[TxHash]) -> Vec> { @@ -343,9 +326,9 @@ where self.pool.validated_pool().ready_by_hash(hash) } - fn ready_at(&self, at: ::Hash) -> PolledIterator { + async fn ready_at(&self, at: ::Hash) -> ReadyIteratorFor { let Ok(at) = self.api.resolve_block_number(at) else { - return async { Box::new(std::iter::empty()) as Box<_> }.boxed() + return Box::new(std::iter::empty()) as Box<_> }; let status = self.status(); @@ -354,25 +337,23 @@ where // There could be transaction being added because of some re-org happening at the relevant // block, but this is relative unlikely. if status.ready == 0 && status.future == 0 { - return async { Box::new(std::iter::empty()) as Box<_> }.boxed() + return Box::new(std::iter::empty()) as Box<_> } if self.ready_poll.lock().updated_at() >= at { log::trace!(target: LOG_TARGET, "Transaction pool already processed block #{}", at); let iterator: ReadyIteratorFor = Box::new(self.pool.validated_pool().ready()); - return async move { iterator }.boxed() + return iterator } - self.ready_poll - .lock() - .add(at) - .map(|received| { - received.unwrap_or_else(|e| { - log::warn!(target: LOG_TARGET, "Error receiving pending set: {:?}", e); - Box::new(std::iter::empty()) - }) + let result = self.ready_poll.lock().add(at).map(|received| { + received.unwrap_or_else(|e| { + log::warn!(target: LOG_TARGET, "Error receiving pending set: {:?}", e); + Box::new(std::iter::empty()) }) - .boxed() + }); + + result.await } fn ready(&self) -> ReadyIteratorFor { @@ -384,12 +365,12 @@ where pool.futures().cloned().collect::>() } - fn ready_at_with_timeout( + async fn ready_at_with_timeout( &self, at: ::Hash, timeout: std::time::Duration, - ) -> PolledIterator { - self.ready_at_with_timeout_internal(at, timeout) + ) -> ReadyIteratorFor { + self.ready_at_with_timeout_internal(at, timeout).await } } diff --git a/substrate/client/transaction-pool/src/transaction_pool_wrapper.rs b/substrate/client/transaction-pool/src/transaction_pool_wrapper.rs index 4e1b53833b8f..e373c0278d80 100644 --- a/substrate/client/transaction-pool/src/transaction_pool_wrapper.rs +++ b/substrate/client/transaction-pool/src/transaction_pool_wrapper.rs @@ -22,16 +22,16 @@ use crate::{ builder::FullClientTransactionPool, graph::{base_pool::Transaction, ExtrinsicFor, ExtrinsicHash}, - ChainApi, FullChainApi, + ChainApi, FullChainApi, ReadyIteratorFor, }; use async_trait::async_trait; use sc_transaction_pool_api::{ ChainEvent, ImportNotificationStream, LocalTransactionFor, LocalTransactionPool, - MaintainedTransactionPool, PoolFuture, PoolStatus, ReadyTransactions, TransactionFor, - TransactionPool, TransactionSource, TransactionStatusStreamFor, TxHash, + MaintainedTransactionPool, PoolStatus, ReadyTransactions, TransactionFor, TransactionPool, + TransactionSource, TransactionStatusStreamFor, TxHash, }; use sp_runtime::traits::Block as BlockT; -use std::{collections::HashMap, future::Future, pin::Pin, sync::Arc}; +use std::{collections::HashMap, pin::Pin, sync::Arc}; /// The wrapper for actual object providing implementation of TransactionPool. /// @@ -49,6 +49,7 @@ where + 'static, Client::Api: sp_transaction_pool::runtime_api::TaggedTransactionQueue; +#[async_trait] impl TransactionPool for TransactionPoolWrapper where Block: BlockT, @@ -68,44 +69,38 @@ where >; type Error = as ChainApi>::Error; - fn submit_at( + async fn submit_at( &self, at: ::Hash, source: TransactionSource, xts: Vec>, - ) -> PoolFuture, Self::Error>>, Self::Error> { - self.0.submit_at(at, source, xts) + ) -> Result, Self::Error>>, Self::Error> { + self.0.submit_at(at, source, xts).await } - fn submit_one( + async fn submit_one( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture, Self::Error> { - self.0.submit_one(at, source, xt) + ) -> Result, Self::Error> { + self.0.submit_one(at, source, xt).await } - fn submit_and_watch( + async fn submit_and_watch( &self, at: ::Hash, source: TransactionSource, xt: TransactionFor, - ) -> PoolFuture>>, Self::Error> { - self.0.submit_and_watch(at, source, xt) + ) -> Result>>, Self::Error> { + self.0.submit_and_watch(at, source, xt).await } - fn ready_at( + async fn ready_at( &self, at: ::Hash, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send, - >, - > { - self.0.ready_at(at) + ) -> ReadyIteratorFor> { + self.0.ready_at(at).await } fn ready(&self) -> Box> + Send> { @@ -140,19 +135,12 @@ where self.0.ready_transaction(hash) } - fn ready_at_with_timeout( + async fn ready_at_with_timeout( &self, at: ::Hash, timeout: std::time::Duration, - ) -> Pin< - Box< - dyn Future< - Output = Box> + Send>, - > + Send - + '_, - >, - > { - self.0.ready_at_with_timeout(at, timeout) + ) -> ReadyIteratorFor> { + self.0.ready_at_with_timeout(at, timeout).await } } From 5e8348f03f49cc32ad48912e186c04b0f1212b16 Mon Sep 17 00:00:00 2001 From: Tobi Demeco <50408393+TDemeco@users.noreply.github.com> Date: Tue, 19 Nov 2024 06:29:15 -0300 Subject: [PATCH 108/166] sp-trie: correctly avoid panicking when decoding bad compact proofs (#6502) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Opening another PR because I added a test to check for my fix pushed in #6486 and realized that for some reason I completely forgot how to code and did not fix the underlying issue, since out-of-bounds indexing could still happen even with the check I added. This one should fix that and, as an added bonus, has a simple test used as an integrity check to make sure future changes don't accidently revert this fix. Now `sp-trie` should definitely not panic when faced with bad `CompactProof`s. Sorry about that 😅 This, like #6486, is related to issue #6485 ## Integration No changes have to be done downstream, and as such the version bump should be minor. --------- Co-authored-by: Bastian Köcher --- prdoc/pr_6502.prdoc | 10 ++++++++++ substrate/primitives/trie/src/node_codec.rs | 8 ++++---- substrate/primitives/trie/src/storage_proof.rs | 10 +++++++++- 3 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 prdoc/pr_6502.prdoc diff --git a/prdoc/pr_6502.prdoc b/prdoc/pr_6502.prdoc new file mode 100644 index 000000000000..3e2467ed5524 --- /dev/null +++ b/prdoc/pr_6502.prdoc @@ -0,0 +1,10 @@ +title: "sp-trie: correctly avoid panicking when decoding bad compact proofs" + +doc: + - audience: "Runtime Dev" + description: | + "Fixed the check introduced in [PR #6486](https://github.com/paritytech/polkadot-sdk/pull/6486). Now `sp-trie` correctly avoids panicking when decoding bad compact proofs." + +crates: +- name: sp-trie + bump: patch diff --git a/substrate/primitives/trie/src/node_codec.rs b/substrate/primitives/trie/src/node_codec.rs index 27da0c6334a2..400f57f3b1bf 100644 --- a/substrate/primitives/trie/src/node_codec.rs +++ b/substrate/primitives/trie/src/node_codec.rs @@ -110,8 +110,8 @@ where NodeHeader::Null => Ok(NodePlan::Empty), NodeHeader::HashedValueBranch(nibble_count) | NodeHeader::Branch(_, nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; - // data should be at least the size of the offset - if data.len() < input.offset { + // data should be at least of size offset + 1 + if data.len() < input.offset + 1 { return Err(Error::BadFormat) } // check that the padding is valid (if any) @@ -158,8 +158,8 @@ where }, NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => { let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0; - // data should be at least the size of the offset - if data.len() < input.offset { + // data should be at least of size offset + 1 + if data.len() < input.offset + 1 { return Err(Error::BadFormat) } // check that the padding is valid (if any) diff --git a/substrate/primitives/trie/src/storage_proof.rs b/substrate/primitives/trie/src/storage_proof.rs index a9f6298742f6..bf0dc72e650b 100644 --- a/substrate/primitives/trie/src/storage_proof.rs +++ b/substrate/primitives/trie/src/storage_proof.rs @@ -232,7 +232,8 @@ pub mod tests { use super::*; use crate::{tests::create_storage_proof, StorageProof}; - type Layout = crate::LayoutV1; + type Hasher = sp_core::Blake2Hasher; + type Layout = crate::LayoutV1; const TEST_DATA: &[(&[u8], &[u8])] = &[(b"key1", &[1; 64]), (b"key2", &[2; 64]), (b"key3", &[3; 64]), (b"key11", &[4; 64])]; @@ -245,4 +246,11 @@ pub mod tests { Err(StorageProofError::DuplicateNodes) )); } + + #[test] + fn invalid_compact_proof_does_not_panic_when_decoding() { + let invalid_proof = CompactProof { encoded_nodes: vec![vec![135]] }; + let result = invalid_proof.to_memory_db::(None); + assert!(result.is_err()); + } } From 293d4a59a9c39e69e083724d45d3cec34ca7b6f2 Mon Sep 17 00:00:00 2001 From: Ermal Kaleci Date: Tue, 19 Nov 2024 10:34:03 +0100 Subject: [PATCH 109/166] [pallet-revive] Update delegate_call to accept address and weight (#6111) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enhance the `delegate_call` function to accept an `address` target parameter instead of a `code_hash`. This allows direct identification of the target contract using the provided address. Additionally, introduce parameters for specifying a customizable `ref_time` limit and `proof_size` limit, thereby improving flexibility and control during contract interactions. --------- Co-authored-by: Alexander Theißen --- prdoc/pr_6111.prdoc | 17 ++ .../fixtures/contracts/delegate_call.rs | 8 +- .../contracts/delegate_call_deposit_limit.rs | 46 +++++ .../contracts/delegate_call_simple.rs | 6 +- .../contracts/locking_delegate_dependency.rs | 3 +- .../frame/revive/src/benchmarking/mod.rs | 25 ++- substrate/frame/revive/src/exec.rs | 172 +++++++++++++----- substrate/frame/revive/src/tests.rs | 112 +++++++++++- substrate/frame/revive/src/wasm/runtime.rs | 50 ++--- substrate/frame/revive/uapi/src/host.rs | 13 +- .../frame/revive/uapi/src/host/riscv32.rs | 51 ++++-- 11 files changed, 391 insertions(+), 112 deletions(-) create mode 100644 prdoc/pr_6111.prdoc create mode 100644 substrate/frame/revive/fixtures/contracts/delegate_call_deposit_limit.rs diff --git a/prdoc/pr_6111.prdoc b/prdoc/pr_6111.prdoc new file mode 100644 index 000000000000..4ada3031c805 --- /dev/null +++ b/prdoc/pr_6111.prdoc @@ -0,0 +1,17 @@ +title: "[pallet-revive] Update delegate_call to accept address and weight" + +doc: + - audience: Runtime Dev + description: | + Enhance the `delegate_call` function to accept an `address` target parameter instead of a `code_hash`. + This allows direct identification of the target contract using the provided address. + Additionally, introduce parameters for specifying a customizable `ref_time` limit and `proof_size` limit, + thereby improving flexibility and control during contract interactions. + +crates: + - name: pallet-revive + bump: major + - name: pallet-revive-fixtures + bump: patch + - name: pallet-revive-uapi + bump: major diff --git a/substrate/frame/revive/fixtures/contracts/delegate_call.rs b/substrate/frame/revive/fixtures/contracts/delegate_call.rs index 9fd155408af3..3cf74acf1321 100644 --- a/substrate/frame/revive/fixtures/contracts/delegate_call.rs +++ b/substrate/frame/revive/fixtures/contracts/delegate_call.rs @@ -28,7 +28,11 @@ pub extern "C" fn deploy() {} #[no_mangle] #[polkavm_derive::polkavm_export] pub extern "C" fn call() { - input!(code_hash: &[u8; 32],); + input!( + address: &[u8; 20], + ref_time: u64, + proof_size: u64, + ); let mut key = [0u8; 32]; key[0] = 1u8; @@ -42,7 +46,7 @@ pub extern "C" fn call() { assert!(value[0] == 2u8); let input = [0u8; 0]; - api::delegate_call(uapi::CallFlags::empty(), code_hash, &input, None).unwrap(); + api::delegate_call(uapi::CallFlags::empty(), address, ref_time, proof_size, None, &input, None).unwrap(); api::get_storage(StorageFlags::empty(), &key, value).unwrap(); assert!(value[0] == 1u8); diff --git a/substrate/frame/revive/fixtures/contracts/delegate_call_deposit_limit.rs b/substrate/frame/revive/fixtures/contracts/delegate_call_deposit_limit.rs new file mode 100644 index 000000000000..55203d534c9b --- /dev/null +++ b/substrate/frame/revive/fixtures/contracts/delegate_call_deposit_limit.rs @@ -0,0 +1,46 @@ +// 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] + +use common::{input, u256_bytes}; +use uapi::{HostFn, HostFnImpl as api, StorageFlags}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + address: &[u8; 20], + deposit_limit: u64, + ); + + let input = [0u8; 0]; + api::delegate_call(uapi::CallFlags::empty(), address, 0, 0, Some(&u256_bytes(deposit_limit)), &input, None).unwrap(); + + let mut key = [0u8; 32]; + key[0] = 1u8; + + let mut value = [0u8; 32]; + + api::get_storage(StorageFlags::empty(), &key, &mut &mut value[..]).unwrap(); + assert!(value[0] == 1u8); +} diff --git a/substrate/frame/revive/fixtures/contracts/delegate_call_simple.rs b/substrate/frame/revive/fixtures/contracts/delegate_call_simple.rs index 20f8ec3364ee..a8501dad4692 100644 --- a/substrate/frame/revive/fixtures/contracts/delegate_call_simple.rs +++ b/substrate/frame/revive/fixtures/contracts/delegate_call_simple.rs @@ -28,9 +28,9 @@ pub extern "C" fn deploy() {} #[no_mangle] #[polkavm_derive::polkavm_export] pub extern "C" fn call() { - input!(code_hash: &[u8; 32],); + input!(address: &[u8; 20],); - // Delegate call into passed code hash. + // Delegate call into passed address. let input = [0u8; 0]; - api::delegate_call(uapi::CallFlags::empty(), code_hash, &input, None).unwrap(); + api::delegate_call(uapi::CallFlags::empty(), address, 0, 0, None, &input, None).unwrap(); } diff --git a/substrate/frame/revive/fixtures/contracts/locking_delegate_dependency.rs b/substrate/frame/revive/fixtures/contracts/locking_delegate_dependency.rs index 54c7c7f3d5e2..3d7702c6537a 100644 --- a/substrate/frame/revive/fixtures/contracts/locking_delegate_dependency.rs +++ b/substrate/frame/revive/fixtures/contracts/locking_delegate_dependency.rs @@ -30,6 +30,7 @@ const ALICE_FALLBACK: [u8; 20] = [1u8; 20]; fn load_input(delegate_call: bool) { input!( action: u32, + address: &[u8; 20], code_hash: &[u8; 32], ); @@ -51,7 +52,7 @@ fn load_input(delegate_call: bool) { } if delegate_call { - api::delegate_call(uapi::CallFlags::empty(), code_hash, &[], None).unwrap(); + api::delegate_call(uapi::CallFlags::empty(), address, 0, 0, None, &[], None).unwrap(); } } diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index 40ad3a3aed17..9c4d817a07de 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -1555,25 +1555,36 @@ mod benchmarks { #[benchmark(pov_mode = Measured)] fn seal_delegate_call() -> Result<(), BenchmarkError> { - let hash = Contract::::with_index(1, WasmModule::dummy(), vec![])?.info()?.code_hash; + let Contract { account_id: address, .. } = + Contract::::with_index(1, WasmModule::dummy(), vec![]).unwrap(); + + let address_bytes = address.encode(); + let address_len = address_bytes.len() as u32; + + let deposit: BalanceOf = (u32::MAX - 100).into(); + let deposit_bytes = Into::::into(deposit).encode(); let mut setup = CallSetup::::default(); + setup.set_storage_deposit_limit(deposit); setup.set_origin(Origin::from_account_id(setup.contract().account_id.clone())); let (mut ext, _) = setup.ext(); let mut runtime = crate::wasm::Runtime::<_, [u8]>::new(&mut ext, vec![]); - let mut memory = memory!(hash.encode(),); + let mut memory = memory!(address_bytes, deposit_bytes,); let result; #[block] { result = runtime.bench_delegate_call( memory.as_mut_slice(), - 0, // flags - 0, // code_hash_ptr - 0, // input_data_ptr - 0, // input_data_len - SENTINEL, // output_ptr + 0, // flags + 0, // address_ptr + 0, // ref_time_limit + 0, // proof_size_limit + address_len, // deposit_ptr + 0, // input_data_ptr + 0, // input_data_len + SENTINEL, // output_ptr 0, ); } diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index fdb45f045bbc..49c08166483e 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -210,7 +210,13 @@ pub trait Ext: sealing::Sealed { /// Execute code in the current frame. /// /// Returns the code size of the called contract. - fn delegate_call(&mut self, code: H256, input_data: Vec) -> Result<(), ExecError>; + fn delegate_call( + &mut self, + gas_limit: Weight, + deposit_limit: U256, + address: H160, + input_data: Vec, + ) -> Result<(), ExecError>; /// Instantiate a contract from the given code. /// @@ -581,18 +587,30 @@ struct Frame { allows_reentry: bool, /// If `true` subsequent calls cannot modify storage. read_only: bool, - /// The caller of the currently executing frame which was spawned by `delegate_call`. - delegate_caller: Option>, + /// The delegate call info of the currently executing frame which was spawned by + /// `delegate_call`. + delegate: Option>, /// The output of the last executed call frame. last_frame_output: ExecReturnValue, } +/// This structure is used to represent the arguments in a delegate call frame in order to +/// distinguish who delegated the call and where it was delegated to. +struct DelegateInfo { + /// The caller of the contract. + pub caller: Origin, + /// The address of the contract the call was delegated to. + pub callee: H160, +} + /// Used in a delegate call frame arguments in order to override the executable and caller. struct DelegatedCall { /// The executable which is run instead of the contracts own `executable`. executable: E, /// The caller of the contract. caller: Origin, + /// The address of the contract the call was delegated to. + callee: H160, } /// Parameter passed in when creating a new `Frame`. @@ -898,8 +916,7 @@ where read_only: bool, origin_is_caller: bool, ) -> Result, E)>, ExecError> { - let (account_id, contract_info, executable, delegate_caller, entry_point) = match frame_args - { + let (account_id, contract_info, executable, delegate, entry_point) = match frame_args { FrameArgs::Call { dest, cached_info, delegated_call } => { let contract = if let Some(contract) = cached_info { contract @@ -914,8 +931,8 @@ where }; let (executable, delegate_caller) = - if let Some(DelegatedCall { executable, caller }) = delegated_call { - (executable, Some(caller)) + if let Some(DelegatedCall { executable, caller, callee }) = delegated_call { + (executable, Some(DelegateInfo { caller, callee })) } else { (E::from_storage(contract.code_hash, gas_meter)?, None) }; @@ -931,8 +948,8 @@ where use sp_runtime::Saturating; address::create1( &deployer, - // the Nonce from the origin has been incremented pre-dispatch, so we need - // to subtract 1 to get the nonce at the time of the call. + // the Nonce from the origin has been incremented pre-dispatch, so we + // need to subtract 1 to get the nonce at the time of the call. if origin_is_caller { account_nonce.saturating_sub(1u32.into()).saturated_into() } else { @@ -956,7 +973,7 @@ where }; let frame = Frame { - delegate_caller, + delegate, value_transferred, contract_info: CachedContract::Cached(contract_info), account_id, @@ -1025,7 +1042,7 @@ where let frame = self.top_frame(); let entry_point = frame.entry_point; let delegated_code_hash = - if frame.delegate_caller.is_some() { Some(*executable.code_hash()) } else { None }; + if frame.delegate.is_some() { Some(*executable.code_hash()) } else { None }; // The output of the caller frame will be replaced by the output of this run. // It is also not accessible from nested frames. @@ -1103,7 +1120,13 @@ where frame.nested_storage.enforce_limit(contract)?; } - let frame = self.top_frame(); + let frame = self.top_frame_mut(); + + // If a special limit was set for the sub-call, we enforce it here. + // The sub-call will be rolled back in case the limit is exhausted. + let contract = frame.contract_info.as_contract(); + frame.nested_storage.enforce_subcall_limit(contract)?; + let account_id = T::AddressMapper::to_address(&frame.account_id); match (entry_point, delegated_code_hash) { (ExportedFunction::Constructor, _) => { @@ -1112,15 +1135,7 @@ where return Err(Error::::TerminatedInConstructor.into()); } - // If a special limit was set for the sub-call, we enforce it here. - // This is needed because contract constructor might write to storage. - // The sub-call will be rolled back in case the limit is exhausted. - let frame = self.top_frame_mut(); - let contract = frame.contract_info.as_contract(); - frame.nested_storage.enforce_subcall_limit(contract)?; - let caller = T::AddressMapper::to_address(self.caller().account_id()?); - // Deposit an instantiation event. Contracts::::deposit_event(Event::Instantiated { deployer: caller, @@ -1134,12 +1149,6 @@ where }); }, (ExportedFunction::Call, None) => { - // If a special limit was set for the sub-call, we enforce it here. - // The sub-call will be rolled back in case the limit is exhausted. - let frame = self.top_frame_mut(); - let contract = frame.contract_info.as_contract(); - frame.nested_storage.enforce_subcall_limit(contract)?; - let caller = self.caller(); Contracts::::deposit_event(Event::Called { caller: caller.clone(), @@ -1468,11 +1477,20 @@ where result } - fn delegate_call(&mut self, code_hash: H256, input_data: Vec) -> Result<(), ExecError> { + fn delegate_call( + &mut self, + gas_limit: Weight, + deposit_limit: U256, + address: H160, + input_data: Vec, + ) -> Result<(), ExecError> { // We reset the return data now, so it is cleared out even if no new frame was executed. // This is for example the case for unknown code hashes or creating the frame fails. *self.last_frame_output_mut() = Default::default(); + let code_hash = ContractInfoOf::::get(&address) + .ok_or(Error::::CodeNotFound) + .map(|c| c.code_hash)?; let executable = E::from_storage(code_hash, self.gas_meter_mut())?; let top_frame = self.top_frame_mut(); let contract_info = top_frame.contract_info().clone(); @@ -1482,11 +1500,15 @@ where FrameArgs::Call { dest: account_id, cached_info: Some(contract_info), - delegated_call: Some(DelegatedCall { executable, caller: self.caller().clone() }), + delegated_call: Some(DelegatedCall { + executable, + caller: self.caller().clone(), + callee: address, + }), }, value, - Weight::zero(), - BalanceOf::::zero(), + gas_limit, + deposit_limit.try_into().map_err(|_| Error::::BalanceConversionFailed)?, self.is_read_only(), )?; self.run(executable.expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE), input_data) @@ -1601,7 +1623,7 @@ where } fn caller(&self) -> Origin { - if let Some(caller) = &self.top_frame().delegate_caller { + if let Some(DelegateInfo { caller, .. }) = &self.top_frame().delegate { caller.clone() } else { self.frames() @@ -1655,7 +1677,13 @@ where return Err(Error::::InvalidImmutableAccess.into()); } - let address = T::AddressMapper::to_address(self.account_id()); + // Immutable is read from contract code being executed + let address = self + .top_frame() + .delegate + .as_ref() + .map(|d| d.callee) + .unwrap_or(T::AddressMapper::to_address(self.account_id())); Ok(>::get(address).ok_or_else(|| Error::::InvalidImmutableAccess)?) } @@ -1917,7 +1945,7 @@ mod tests { AddressMapper, Error, }; use assert_matches::assert_matches; - use frame_support::{assert_err, assert_ok, parameter_types}; + use frame_support::{assert_err, assert_noop, assert_ok, parameter_types}; use frame_system::{AccountInfo, EventRecord, Phase}; use pallet_revive_uapi::ReturnFlags; use pretty_assertions::assert_eq; @@ -2185,18 +2213,20 @@ mod tests { let delegate_ch = MockLoader::insert(Call, move |ctx, _| { assert_eq!(ctx.ext.value_transferred(), U256::from(value)); - let _ = ctx.ext.delegate_call(success_ch, Vec::new())?; + let _ = + ctx.ext.delegate_call(Weight::zero(), U256::zero(), CHARLIE_ADDR, Vec::new())?; Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) }); ExtBuilder::default().build().execute_with(|| { place_contract(&BOB, delegate_ch); + place_contract(&CHARLIE, success_ch); set_balance(&ALICE, 100); let balance = get_balance(&BOB_FALLBACK); let origin = Origin::from_account_id(ALICE); let mut storage_meter = storage::meter::Meter::new(&origin, 0, 55).unwrap(); - let _ = MockStack::run_call( + assert_ok!(MockStack::run_call( origin, BOB_ADDR, &mut GasMeter::::new(GAS_LIMIT), @@ -2204,14 +2234,63 @@ mod tests { value.into(), vec![], None, - ) - .unwrap(); + )); assert_eq!(get_balance(&ALICE), 100 - value); assert_eq!(get_balance(&BOB_FALLBACK), balance + value); }); } + #[test] + fn delegate_call_missing_contract() { + let missing_ch = MockLoader::insert(Call, move |_ctx, _| { + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }); + + let delegate_ch = MockLoader::insert(Call, move |ctx, _| { + let _ = + ctx.ext.delegate_call(Weight::zero(), U256::zero(), CHARLIE_ADDR, Vec::new())?; + Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }) + }); + + ExtBuilder::default().build().execute_with(|| { + place_contract(&BOB, delegate_ch); + set_balance(&ALICE, 100); + + let origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&origin, 0, 55).unwrap(); + + // contract code missing + assert_noop!( + MockStack::run_call( + origin.clone(), + BOB_ADDR, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + U256::zero(), + vec![], + None, + ), + ExecError { + error: Error::::CodeNotFound.into(), + origin: ErrorOrigin::Callee, + } + ); + + // add missing contract code + place_contract(&CHARLIE, missing_ch); + assert_ok!(MockStack::run_call( + origin, + BOB_ADDR, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + U256::zero(), + vec![], + None, + )); + }); + } + #[test] fn changes_are_reverted_on_failing_call() { // This test verifies that changes are reverted on a call which fails (or equally, returns @@ -4615,7 +4694,12 @@ mod tests { // An unknown code hash to fail the delegate_call on the first condition. *ctx.ext.last_frame_output_mut() = output_revert(); assert_eq!( - ctx.ext.delegate_call(invalid_code_hash, Default::default()), + ctx.ext.delegate_call( + Weight::zero(), + U256::zero(), + H160([0xff; 20]), + Default::default() + ), Err(Error::::CodeNotFound.into()) ); assert_eq!(ctx.ext.last_frame_output(), &Default::default()); @@ -4732,14 +4816,12 @@ mod tests { Ok(vec![2]), ); - // In a delegate call, we should witness the caller immutable data + // Also in a delegate call, we should witness the callee immutable data assert_eq!( - ctx.ext.delegate_call(charlie_ch, Vec::new()).map(|_| ctx - .ext - .last_frame_output() - .data - .clone()), - Ok(vec![1]) + ctx.ext + .delegate_call(Weight::zero(), U256::zero(), CHARLIE_ADDR, Vec::new()) + .map(|_| ctx.ext.last_frame_output().data.clone()), + Ok(vec![2]) ); exec_success() diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index a35e4d908601..177b8dff706b 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -1127,7 +1127,7 @@ fn deploy_and_call_other_contract() { #[test] fn delegate_call() { let (caller_wasm, _caller_code_hash) = compile_module("delegate_call").unwrap(); - let (callee_wasm, callee_code_hash) = compile_module("delegate_call_lib").unwrap(); + let (callee_wasm, _callee_code_hash) = compile_module("delegate_call_lib").unwrap(); ExtBuilder::default().existential_deposit(500).build().execute_with(|| { let _ = ::Currency::set_balance(&ALICE, 1_000_000); @@ -1137,12 +1137,91 @@ fn delegate_call() { builder::bare_instantiate(Code::Upload(caller_wasm)) .value(300_000) .build_and_unwrap_contract(); - // Only upload 'callee' code - assert_ok!(Contracts::upload_code(RuntimeOrigin::signed(ALICE), callee_wasm, 100_000,)); + + // Instantiate the 'callee' + let Contract { addr: callee_addr, .. } = + builder::bare_instantiate(Code::Upload(callee_wasm)) + .value(100_000) + .build_and_unwrap_contract(); assert_ok!(builder::call(caller_addr) .value(1337) - .data(callee_code_hash.as_ref().to_vec()) + .data((callee_addr, 0u64, 0u64).encode()) + .build()); + }); +} + +#[test] +fn delegate_call_with_weight_limit() { + let (caller_wasm, _caller_code_hash) = compile_module("delegate_call").unwrap(); + let (callee_wasm, _callee_code_hash) = compile_module("delegate_call_lib").unwrap(); + + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the 'caller' + let Contract { addr: caller_addr, .. } = + builder::bare_instantiate(Code::Upload(caller_wasm)) + .value(300_000) + .build_and_unwrap_contract(); + + // Instantiate the 'callee' + let Contract { addr: callee_addr, .. } = + builder::bare_instantiate(Code::Upload(callee_wasm)) + .value(100_000) + .build_and_unwrap_contract(); + + // fails, not enough weight + assert_err!( + builder::bare_call(caller_addr) + .value(1337) + .data((callee_addr, 100u64, 100u64).encode()) + .build() + .result, + Error::::ContractTrapped, + ); + + assert_ok!(builder::call(caller_addr) + .value(1337) + .data((callee_addr, 500_000_000u64, 100_000u64).encode()) + .build()); + }); +} + +#[test] +fn delegate_call_with_deposit_limit() { + let (caller_pvm, _caller_code_hash) = compile_module("delegate_call_deposit_limit").unwrap(); + let (callee_pvm, _callee_code_hash) = compile_module("delegate_call_lib").unwrap(); + + ExtBuilder::default().existential_deposit(500).build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + + // Instantiate the 'caller' + let Contract { addr: caller_addr, .. } = + builder::bare_instantiate(Code::Upload(caller_pvm)) + .value(300_000) + .build_and_unwrap_contract(); + + // Instantiate the 'callee' + let Contract { addr: callee_addr, .. } = + builder::bare_instantiate(Code::Upload(callee_pvm)) + .value(100_000) + .build_and_unwrap_contract(); + + // Delegate call will write 1 storage and deposit of 2 (1 item) + 32 (bytes) is required. + // Fails, not enough deposit + assert_err!( + builder::bare_call(caller_addr) + .value(1337) + .data((callee_addr, 33u64).encode()) + .build() + .result, + Error::::StorageDepositLimitExhausted, + ); + + assert_ok!(builder::call(caller_addr) + .value(1337) + .data((callee_addr, 34u64).encode()) .build()); }); } @@ -3666,6 +3745,12 @@ fn locking_delegate_dependency_works() { .map(|c| sp_core::H256(sp_io::hashing::keccak_256(c))) .collect(); + let hash2addr = |code_hash: &H256| { + let mut addr = H160::zero(); + addr.as_bytes_mut().copy_from_slice(&code_hash.as_ref()[..20]); + addr + }; + // Define inputs with various actions to test locking / unlocking delegate_dependencies. // See the contract for more details. let noop_input = (0u32, callee_hashes[0]); @@ -3675,17 +3760,19 @@ fn locking_delegate_dependency_works() { // Instantiate the caller contract with the given input. let instantiate = |input: &(u32, H256)| { + let (action, code_hash) = input; builder::bare_instantiate(Code::Upload(wasm_caller.clone())) .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) - .data(input.encode()) + .data((action, hash2addr(code_hash), code_hash).encode()) .build() }; // Call contract with the given input. let call = |addr_caller: &H160, input: &(u32, H256)| { + let (action, code_hash) = input; builder::bare_call(*addr_caller) .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) - .data(input.encode()) + .data((action, hash2addr(code_hash), code_hash).encode()) .build() }; const ED: u64 = 2000; @@ -3702,7 +3789,7 @@ fn locking_delegate_dependency_works() { // Upload all the delegated codes (they all have the same size) let mut deposit = Default::default(); for code in callee_codes.iter() { - let CodeUploadReturnValue { deposit: deposit_per_code, .. } = + let CodeUploadReturnValue { deposit: deposit_per_code, code_hash } = Contracts::bare_upload_code( RuntimeOrigin::signed(ALICE_FALLBACK), code.clone(), @@ -3710,6 +3797,9 @@ fn locking_delegate_dependency_works() { ) .unwrap(); deposit = deposit_per_code; + // Mock contract info by using first 20 bytes of code_hash as address. + let addr = hash2addr(&code_hash); + ContractInfoOf::::set(&addr, ContractInfo::new(&addr, 0, code_hash).ok()); } // Instantiate should now work. @@ -3746,7 +3836,11 @@ fn locking_delegate_dependency_works() { // Locking self should fail. assert_err!( - call(&addr_caller, &(1u32, self_code_hash)).result, + builder::bare_call(addr_caller) + .origin(RuntimeOrigin::signed(ALICE_FALLBACK)) + .data((1u32, &addr_caller, self_code_hash).encode()) + .build() + .result, Error::::CannotAddSelfAsDelegateDependency ); @@ -3785,7 +3879,7 @@ fn locking_delegate_dependency_works() { assert_err!( builder::bare_call(addr_caller) .storage_deposit_limit(dependency_deposit - 1) - .data(lock_delegate_dependency_input.encode()) + .data((1u32, hash2addr(&callee_hashes[0]), callee_hashes[0]).encode()) .build() .result, Error::::StorageDepositLimitExhausted diff --git a/substrate/frame/revive/src/wasm/runtime.rs b/substrate/frame/revive/src/wasm/runtime.rs index 8310fe701013..3e2c83db1ebd 100644 --- a/substrate/frame/revive/src/wasm/runtime.rs +++ b/substrate/frame/revive/src/wasm/runtime.rs @@ -536,16 +536,17 @@ macro_rules! charge_gas { /// The kind of call that should be performed. enum CallType { /// Execute another instantiated contract - Call { callee_ptr: u32, value_ptr: u32, deposit_ptr: u32, weight: Weight }, - /// Execute deployed code in the context (storage, account ID, value) of the caller contract - DelegateCall { code_hash_ptr: u32 }, + Call { value_ptr: u32 }, + /// Execute another contract code in the context (storage, account ID, value) of the caller + /// contract + DelegateCall, } impl CallType { fn cost(&self) -> RuntimeCosts { match self { CallType::Call { .. } => RuntimeCosts::CallBase, - CallType::DelegateCall { .. } => RuntimeCosts::DelegateCallBase, + CallType::DelegateCall => RuntimeCosts::DelegateCallBase, } } } @@ -987,6 +988,9 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { memory: &mut M, flags: CallFlags, call_type: CallType, + callee_ptr: u32, + deposit_ptr: u32, + weight: Weight, input_data_ptr: u32, input_data_len: u32, output_ptr: u32, @@ -994,6 +998,10 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { ) -> Result { self.charge_gas(call_type.cost())?; + let callee = memory.read_h160(callee_ptr)?; + let deposit_limit = + if deposit_ptr == SENTINEL { U256::zero() } else { memory.read_u256(deposit_ptr)? }; + let input_data = if flags.contains(CallFlags::CLONE_INPUT) { let input = self.input_data.as_ref().ok_or(Error::::InputForwarded)?; charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?; @@ -1006,13 +1014,7 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { }; let call_outcome = match call_type { - CallType::Call { callee_ptr, value_ptr, deposit_ptr, weight } => { - let callee = memory.read_h160(callee_ptr)?; - let deposit_limit = if deposit_ptr == SENTINEL { - U256::zero() - } else { - memory.read_u256(deposit_ptr)? - }; + CallType::Call { value_ptr } => { let read_only = flags.contains(CallFlags::READ_ONLY); let value = memory.read_u256(value_ptr)?; if value > 0u32.into() { @@ -1033,13 +1035,11 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { read_only, ) }, - CallType::DelegateCall { code_hash_ptr } => { + CallType::DelegateCall => { if flags.intersects(CallFlags::ALLOW_REENTRY | CallFlags::READ_ONLY) { return Err(Error::::InvalidCallFlags.into()); } - - let code_hash = memory.read_h256(code_hash_ptr)?; - self.ext.delegate_call(code_hash, input_data) + self.ext.delegate_call(weight, deposit_limit, callee, input_data) }, }; @@ -1252,12 +1252,10 @@ pub mod env { self.call( memory, CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, - CallType::Call { - callee_ptr, - value_ptr, - deposit_ptr, - weight: Weight::from_parts(ref_time_limit, proof_size_limit), - }, + CallType::Call { value_ptr }, + callee_ptr, + deposit_ptr, + Weight::from_parts(ref_time_limit, proof_size_limit), input_data_ptr, input_data_len, output_ptr, @@ -1272,7 +1270,10 @@ pub mod env { &mut self, memory: &mut M, flags: u32, - code_hash_ptr: u32, + address_ptr: u32, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_ptr: u32, input_data_ptr: u32, input_data_len: u32, output_ptr: u32, @@ -1281,7 +1282,10 @@ pub mod env { self.call( memory, CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, - CallType::DelegateCall { code_hash_ptr }, + CallType::DelegateCall, + address_ptr, + deposit_ptr, + Weight::from_parts(ref_time_limit, proof_size_limit), input_data_ptr, input_data_len, output_ptr, diff --git a/substrate/frame/revive/uapi/src/host.rs b/substrate/frame/revive/uapi/src/host.rs index cb52cf93540b..6b3a8b07f040 100644 --- a/substrate/frame/revive/uapi/src/host.rs +++ b/substrate/frame/revive/uapi/src/host.rs @@ -323,7 +323,13 @@ pub trait HostFn: private::Sealed { /// # Parameters /// /// - `flags`: See [`CallFlags`] for a documentation of the supported flags. - /// - `code_hash`: The hash of the code to be executed. + /// - `address`: The address of the code to be executed. Should be decodable as an + /// `T::AccountId`. Traps otherwise. + /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. + /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. + /// - `deposit_limit`: The storage deposit limit for delegate call. Passing `None` means setting + /// no specific limit for the call, which implies storage usage up to the limit of the parent + /// call. /// - `input`: The input data buffer used to call the contract. /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` /// is provided then the output buffer is not copied. @@ -338,7 +344,10 @@ pub trait HostFn: private::Sealed { /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] fn delegate_call( flags: CallFlags, - code_hash: &[u8; 32], + address: &[u8; 20], + ref_time_limit: u64, + proof_size_limit: u64, + deposit_limit: Option<&[u8; 32]>, input_data: &[u8], output: Option<&mut &mut [u8]>, ) -> Result; diff --git a/substrate/frame/revive/uapi/src/host/riscv32.rs b/substrate/frame/revive/uapi/src/host/riscv32.rs index 199a0abc3ddc..e8b27057ed18 100644 --- a/substrate/frame/revive/uapi/src/host/riscv32.rs +++ b/substrate/frame/revive/uapi/src/host/riscv32.rs @@ -59,14 +59,7 @@ mod sys { out_len_ptr: *mut u32, ) -> ReturnCode; pub fn call(ptr: *const u8) -> ReturnCode; - pub fn delegate_call( - flags: u32, - code_hash_ptr: *const u8, - input_data_ptr: *const u8, - input_data_len: u32, - out_ptr: *mut u8, - out_len_ptr: *mut u32, - ) -> ReturnCode; + pub fn delegate_call(ptr: *const u8) -> ReturnCode; pub fn instantiate(ptr: *const u8) -> ReturnCode; pub fn terminate(beneficiary_ptr: *const u8); pub fn input(out_ptr: *mut u8, out_len_ptr: *mut u32); @@ -306,24 +299,42 @@ impl HostFn for HostFnImpl { fn delegate_call( flags: CallFlags, - code_hash: &[u8; 32], + address: &[u8; 20], + ref_time_limit: u64, + proof_size_limit: u64, + deposit_limit: Option<&[u8; 32]>, input: &[u8], mut output: Option<&mut &mut [u8]>, ) -> Result { let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let ret_code = { - unsafe { - sys::delegate_call( - flags.bits(), - code_hash.as_ptr(), - input.as_ptr(), - input.len() as u32, - output_ptr, - &mut output_len, - ) - } + let deposit_limit_ptr = ptr_or_sentinel(&deposit_limit); + #[repr(packed)] + #[allow(dead_code)] + struct Args { + flags: u32, + address: *const u8, + ref_time_limit: u64, + proof_size_limit: u64, + deposit_limit: *const u8, + input: *const u8, + input_len: u32, + output: *mut u8, + output_len: *mut u32, + } + let args = Args { + flags: flags.bits(), + address: address.as_ptr(), + ref_time_limit, + proof_size_limit, + deposit_limit: deposit_limit_ptr, + input: input.as_ptr(), + input_len: input.len() as _, + output: output_ptr, + output_len: &mut output_len as *mut _, }; + let ret_code = { unsafe { sys::delegate_call(&args as *const Args as *const _) } }; + if let Some(ref mut output) = output { extract_from_slice(output, output_len as usize); } From 0449b214accd0f0fbf7ea3e8f3a8d8b7f99445e4 Mon Sep 17 00:00:00 2001 From: tmpolaczyk <44604217+tmpolaczyk@users.noreply.github.com> Date: Tue, 19 Nov 2024 10:43:09 +0100 Subject: [PATCH 110/166] Fix metrics not shutting down if there are open connections (#6220) Fix prometheus metrics not shutting down if there are open connections. I fixed the same issue in the past but it broke again after a dependecy upgrade. See also: https://github.com/paritytech/polkadot-sdk/pull/1637 --- prdoc/pr_6220.prdoc | 10 ++++++++++ substrate/utils/prometheus/Cargo.toml | 2 +- substrate/utils/prometheus/src/lib.rs | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 prdoc/pr_6220.prdoc diff --git a/prdoc/pr_6220.prdoc b/prdoc/pr_6220.prdoc new file mode 100644 index 000000000000..6a5ee4fa59be --- /dev/null +++ b/prdoc/pr_6220.prdoc @@ -0,0 +1,10 @@ +title: Fix metrics not shutting down if there are open connections + +doc: + - audience: Runtime Dev + description: | + Fix prometheus metrics not shutting down if there are open connections + +crates: +- name: substrate-prometheus-endpoint + bump: patch diff --git a/substrate/utils/prometheus/Cargo.toml b/substrate/utils/prometheus/Cargo.toml index 9bdec3cb8183..b8dfd6fb2bee 100644 --- a/substrate/utils/prometheus/Cargo.toml +++ b/substrate/utils/prometheus/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] http-body-util = { workspace = true } hyper = { features = ["http1", "server"], workspace = true } -hyper-util = { features = ["server-auto", "tokio"], workspace = true } +hyper-util = { features = ["server-auto", "server-graceful", "tokio"], workspace = true } log = { workspace = true, default-features = true } prometheus = { workspace = true } thiserror = { workspace = true } diff --git a/substrate/utils/prometheus/src/lib.rs b/substrate/utils/prometheus/src/lib.rs index 35597cad03d8..5edac2e6650f 100644 --- a/substrate/utils/prometheus/src/lib.rs +++ b/substrate/utils/prometheus/src/lib.rs @@ -102,6 +102,7 @@ async fn init_prometheus_with_listener( log::info!(target: "prometheus", "〽️ Prometheus exporter started at {}", listener.local_addr()?); let server = hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new()); + let graceful = hyper_util::server::graceful::GracefulShutdown::new(); loop { let io = match listener.accept().await { @@ -120,6 +121,7 @@ async fn init_prometheus_with_listener( hyper::service::service_fn(move |req| request_metrics(req, registry.clone())), ) .into_owned(); + let conn = graceful.watch(conn); tokio::spawn(async move { if let Err(err) = conn.await { From 8d4138f77106a6af49920ad84f3283f696f3f905 Mon Sep 17 00:00:00 2001 From: Maciej Date: Tue, 19 Nov 2024 14:40:25 +0000 Subject: [PATCH 111/166] Validator Re-Enabling (#5724) Aims to implement Stage 3 of Validator Disbling as outlined here: https://github.com/paritytech/polkadot-sdk/issues/4359 Features: - [x] New Disabling Strategy (Staking level) - [x] Re-enabling logic (Session level) - [x] More generic disabling decision output - [x] New Disabling Events Testing & Security: - [x] Unit tests - [x] Mock tests - [x] Try-runtime checks - [x] Try-runtime tested on westend snap - [x] Try-runtime CI tests - [ ] Re-enabling Zombienet Test (?) - [ ] SRLabs Audit Closes #4745 Closes #2418 --------- Co-authored-by: ordian Co-authored-by: Ankan <10196091+Ank4n@users.noreply.github.com> Co-authored-by: Tsvetomir Dimitrov --- .../src/validate_block/trie_cache.rs | 5 +- .../src/validate_block/trie_recorder.rs | 5 +- polkadot/runtime/test-runtime/src/lib.rs | 2 +- polkadot/runtime/westend/src/lib.rs | 3 +- prdoc/pr_5724.prdoc | 37 ++ substrate/bin/node/runtime/src/lib.rs | 2 +- .../test-staking-e2e/src/lib.rs | 27 +- .../test-staking-e2e/src/mock.rs | 3 +- substrate/frame/session/src/lib.rs | 21 +- substrate/frame/staking/CHANGELOG.md | 12 + substrate/frame/staking/src/lib.rs | 175 ++++++- substrate/frame/staking/src/migrations.rs | 76 +++ substrate/frame/staking/src/mock.rs | 6 +- substrate/frame/staking/src/pallet/impls.rs | 17 +- substrate/frame/staking/src/pallet/mod.rs | 17 +- substrate/frame/staking/src/slashing.rs | 51 +- substrate/frame/staking/src/tests.rs | 442 +++++++++++++++++- substrate/primitives/staking/src/offence.rs | 25 + .../state-machine/src/trie_backend.rs | 20 +- substrate/primitives/trie/src/recorder.rs | 5 +- 20 files changed, 864 insertions(+), 87 deletions(-) create mode 100644 prdoc/pr_5724.prdoc diff --git a/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs b/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs index 035541fb17b1..36efd3decf77 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs @@ -85,7 +85,10 @@ impl CacheProvider { } impl TrieCacheProvider for CacheProvider { - type Cache<'a> = TrieCache<'a, H> where H: 'a; + type Cache<'a> + = TrieCache<'a, H> + where + H: 'a; fn as_trie_db_cache(&self, storage_root: ::Out) -> Self::Cache<'_> { TrieCache { diff --git a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs b/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs index 4a478d047f1b..8dc2f20dd390 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs @@ -115,7 +115,10 @@ impl SizeOnlyRecorderProvider { } impl sp_trie::TrieRecorderProvider for SizeOnlyRecorderProvider { - type Recorder<'a> = SizeOnlyRecorder<'a, H> where H: 'a; + type Recorder<'a> + = SizeOnlyRecorder<'a, H> + where + H: 'a; fn drain_storage_proof(self) -> Option { None diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index d2ed5abb6ed1..69ce187dce40 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -395,7 +395,7 @@ impl pallet_staking::Config for Runtime { type BenchmarkingConfig = polkadot_runtime_common::StakingBenchmarkingConfig; type EventListeners = (); type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type DisablingStrategy = pallet_staking::UpToLimitWithReEnablingDisablingStrategy; } parameter_types! { diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 993010cbce66..7a5562cc98c1 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -755,7 +755,7 @@ impl pallet_staking::Config for Runtime { type BenchmarkingConfig = polkadot_runtime_common::StakingBenchmarkingConfig; type EventListeners = (NominationPools, DelegatedStaking); type WeightInfo = weights::pallet_staking::WeightInfo; - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type DisablingStrategy = pallet_staking::UpToLimitWithReEnablingDisablingStrategy; } impl pallet_fast_unstake::Config for Runtime { @@ -1836,6 +1836,7 @@ pub mod migrations { >, parachains_shared::migration::MigrateToV1, parachains_scheduler::migration::MigrateV2ToV3, + pallet_staking::migrations::v16::MigrateV15ToV16, // permanent pallet_xcm::migration::MigrateToLatestXcmVersion, ); diff --git a/prdoc/pr_5724.prdoc b/prdoc/pr_5724.prdoc new file mode 100644 index 000000000000..be9d21c214a8 --- /dev/null +++ b/prdoc/pr_5724.prdoc @@ -0,0 +1,37 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Validator Re-Enabling (master PR) + +doc: + - audience: Runtime Dev + description: | + Implementation of the Stage 3 for the New Disabling Strategy: https://github.com/paritytech/polkadot-sdk/issues/4359 + + This PR changes when an active validator node gets disabled for comitting offences. + When Byzantine Threshold Validators (1/3) are already disabled instead of no longer + disabling the highest offenders will be disabled potentially re-enabling low offenders. + + - audience: Node Operator + description: | + Implementation of the Stage 3 for the New Disabling Strategy: https://github.com/paritytech/polkadot-sdk/issues/4359 + + This PR changes when an active validator node gets disabled within parachain consensus (reduced responsibilities and + reduced rewards) for comitting offences. This should not affect active validators on a day-to-day basis and will only + be relevant when the network is under attack or there is a wide spread malfunction causing slashes. In that case + lowest offenders might get eventually re-enabled (back to normal responsibilities and normal rewards). + +migrations: + db: [] + runtime: + - reference: pallet-staking + description: | + Migrating `DisabledValidators` from `Vec` to `Vec<(u32, PerBill)>` where the PerBill represents the severity + of the offence in terms of the % slash. + +crates: + - name: pallet-staking + bump: minor + + - name: pallet-session + bump: minor diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 914b51fb5621..e68e04840776 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -742,7 +742,7 @@ impl pallet_staking::Config for Runtime { type EventListeners = NominationPools; type WeightInfo = pallet_staking::weights::SubstrateWeight; type BenchmarkingConfig = StakingBenchmarkingConfig; - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type DisablingStrategy = pallet_staking::UpToLimitWithReEnablingDisablingStrategy; } impl pallet_fast_unstake::Config for Runtime { diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs index 41928905ed95..26a6345e145f 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs @@ -147,30 +147,35 @@ fn mass_slash_doesnt_enter_emergency_phase() { let active_set_size_before_slash = Session::validators().len(); - // Slash more than 1/3 of the active validators - let mut slashed = slash_half_the_active_set(); + // assuming half is above the disabling limit (default 1/3), otherwise test will break + let slashed = slash_half_the_active_set(); let active_set_size_after_slash = Session::validators().len(); // active set should stay the same before and after the slash assert_eq!(active_set_size_before_slash, active_set_size_after_slash); - // Slashed validators are disabled up to a limit - slashed.truncate( - pallet_staking::UpToLimitDisablingStrategy::::disable_limit( - active_set_size_after_slash, - ), - ); - // Find the indices of the disabled validators let active_set = Session::validators(); - let expected_disabled = slashed + let potentially_disabled = slashed .into_iter() .map(|d| active_set.iter().position(|a| *a == d).unwrap() as u32) .collect::>(); + // Ensure that every actually disabled validator is also in the potentially disabled set + // (not necessarily the other way around) + let disabled = Session::disabled_validators(); + for d in disabled.iter() { + assert!(potentially_disabled.contains(d)); + } + + // Ensure no more than disabling limit of validators (default 1/3) is disabled + let disabling_limit = pallet_staking::UpToLimitWithReEnablingDisablingStrategy::< + SLASHING_DISABLING_FACTOR, + >::disable_limit(active_set_size_before_slash); + assert!(disabled.len() == disabling_limit); + assert_eq!(pallet_staking::ForceEra::::get(), pallet_staking::Forcing::NotForcing); - assert_eq!(Session::disabled_validators(), expected_disabled); }); } diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index b182ddec77ab..eaab848c1694 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -304,7 +304,8 @@ impl pallet_staking::Config for Runtime { type MaxUnlockingChunks = MaxUnlockingChunks; type EventListeners = Pools; type WeightInfo = pallet_staking::weights::SubstrateWeight; - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type DisablingStrategy = + pallet_staking::UpToLimitWithReEnablingDisablingStrategy; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; } diff --git a/substrate/frame/session/src/lib.rs b/substrate/frame/session/src/lib.rs index 325758d54dd8..e8b4a355f49a 100644 --- a/substrate/frame/session/src/lib.rs +++ b/substrate/frame/session/src/lib.rs @@ -127,8 +127,8 @@ use frame_support::{ dispatch::DispatchResult, ensure, traits::{ - EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get, OneSessionHandler, - ValidatorRegistration, ValidatorSet, + Defensive, EstimateNextNewSession, EstimateNextSessionRotation, FindAuthor, Get, + OneSessionHandler, ValidatorRegistration, ValidatorSet, }, weights::Weight, Parameter, @@ -735,6 +735,23 @@ impl Pallet { }) } + /// Re-enable the validator of index `i`, returns `false` if the validator was already enabled. + pub fn enable_index(i: u32) -> bool { + if i >= Validators::::decode_len().defensive_unwrap_or(0) as u32 { + return false + } + + // If the validator is not disabled, return false. + DisabledValidators::::mutate(|disabled| { + if let Ok(index) = disabled.binary_search(&i) { + disabled.remove(index); + true + } else { + false + } + }) + } + /// Disable the validator identified by `c`. (If using with the staking pallet, /// this would be their *stash* account.) /// diff --git a/substrate/frame/staking/CHANGELOG.md b/substrate/frame/staking/CHANGELOG.md index 113b7a6200b6..064a7d4a48f4 100644 --- a/substrate/frame/staking/CHANGELOG.md +++ b/substrate/frame/staking/CHANGELOG.md @@ -7,6 +7,18 @@ on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). We maintain a single integer version number for staking pallet to keep track of all storage migrations. +## [v16] + + +### Added + +- New default implementation of `DisablingStrategy` - `UpToLimitWithReEnablingDisablingStrategy`. + Same as `UpToLimitDisablingStrategy` except when a limit (1/3 default) is reached. When limit is + reached the offender is only disabled if his offence is greater or equal than some other already + disabled offender. The smallest possible offender is re-enabled to make space for the new greater + offender. A limit should thus always be respected. +- `DisabledValidators` changed format to include severity of the offence. + ## [v15] ### Added diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index a4a6e71af0df..6361663b2b1c 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -324,7 +324,7 @@ use sp_runtime::{ Perbill, Perquintill, Rounding, RuntimeDebug, Saturating, }; use sp_staking::{ - offence::{Offence, OffenceError, ReportOffence}, + offence::{Offence, OffenceError, OffenceSeverity, ReportOffence}, EraIndex, ExposurePage, OnStakingUpdate, Page, PagedExposureMetadata, SessionIndex, StakingAccount, }; @@ -849,6 +849,9 @@ pub trait SessionInterface { /// Disable the validator at the given index, returns `false` if the validator was already /// disabled or the index is out of bounds. fn disable_validator(validator_index: u32) -> bool; + /// Re-enable a validator that was previously disabled. Returns `false` if the validator was + /// already enabled or the index is out of bounds. + fn enable_validator(validator_index: u32) -> bool; /// Get the validators from session. fn validators() -> Vec; /// Prune historical session tries up to but not including the given index. @@ -873,6 +876,10 @@ where >::disable_index(validator_index) } + fn enable_validator(validator_index: u32) -> bool { + >::enable_index(validator_index) + } + fn validators() -> Vec<::AccountId> { >::validators() } @@ -886,6 +893,9 @@ impl SessionInterface for () { fn disable_validator(_: u32) -> bool { true } + fn enable_validator(_: u32) -> bool { + true + } fn validators() -> Vec { Vec::new() } @@ -1271,19 +1281,47 @@ impl BenchmarkingConfig for TestBenchmarkingConfig { /// Controls validator disabling pub trait DisablingStrategy { - /// Make a disabling decision. Returns the index of the validator to disable or `None` if no new - /// validator should be disabled. + /// Make a disabling decision. Returning a [`DisablingDecision`] fn decision( offender_stash: &T::AccountId, + offender_slash_severity: OffenceSeverity, slash_era: EraIndex, - currently_disabled: &Vec, - ) -> Option; + currently_disabled: &Vec<(u32, OffenceSeverity)>, + ) -> DisablingDecision; } -/// Implementation of [`DisablingStrategy`] which disables validators from the active set up to a -/// threshold. `DISABLING_LIMIT_FACTOR` is the factor of the maximum disabled validators in the -/// active set. E.g. setting this value to `3` means no more than 1/3 of the validators in the -/// active set can be disabled in an era. +/// Helper struct representing a decision coming from a given [`DisablingStrategy`] implementing +/// `decision` +/// +/// `disable` is the index of the validator to disable, +/// `reenable` is the index of the validator to re-enable. +#[derive(Debug)] +pub struct DisablingDecision { + pub disable: Option, + pub reenable: Option, +} + +/// Calculate the disabling limit based on the number of validators and the disabling limit factor. +/// +/// This is a sensible default implementation for the disabling limit factor for most disabling +/// strategies. +/// +/// Disabling limit factor n=2 -> 1/n = 1/2 = 50% of validators can be disabled +fn factor_based_disable_limit(validators_len: usize, disabling_limit_factor: usize) -> usize { + validators_len + .saturating_sub(1) + .checked_div(disabling_limit_factor) + .unwrap_or_else(|| { + defensive!("DISABLING_LIMIT_FACTOR should not be 0"); + 0 + }) +} + +/// Implementation of [`DisablingStrategy`] using factor_based_disable_limit which disables +/// validators from the active set up to a threshold. `DISABLING_LIMIT_FACTOR` is the factor of the +/// maximum disabled validators in the active set. E.g. setting this value to `3` means no more than +/// 1/3 of the validators in the active set can be disabled in an era. +/// /// By default a factor of 3 is used which is the byzantine threshold. pub struct UpToLimitDisablingStrategy; @@ -1291,13 +1329,7 @@ impl UpToLimitDisablingStrategy usize { - validators_len - .saturating_sub(1) - .checked_div(DISABLING_LIMIT_FACTOR) - .unwrap_or_else(|| { - defensive!("DISABLING_LIMIT_FACTOR should not be 0"); - 0 - }) + factor_based_disable_limit(validators_len, DISABLING_LIMIT_FACTOR) } } @@ -1306,9 +1338,10 @@ impl DisablingStrategy { fn decision( offender_stash: &T::AccountId, + _offender_slash_severity: OffenceSeverity, slash_era: EraIndex, - currently_disabled: &Vec, - ) -> Option { + currently_disabled: &Vec<(u32, OffenceSeverity)>, + ) -> DisablingDecision { let active_set = T::SessionInterface::validators(); // We don't disable more than the limit @@ -1318,7 +1351,7 @@ impl DisablingStrategy "Won't disable: reached disabling limit {:?}", Self::disable_limit(active_set.len()) ); - return None + return DisablingDecision { disable: None, reenable: None } } // We don't disable for offences in previous eras @@ -1329,18 +1362,116 @@ impl DisablingStrategy CurrentEra::::get().unwrap_or_default(), slash_era ); - return None + return DisablingDecision { disable: None, reenable: None } } let offender_idx = if let Some(idx) = active_set.iter().position(|i| i == offender_stash) { idx as u32 } else { log!(debug, "Won't disable: offender not in active set",); - return None + return DisablingDecision { disable: None, reenable: None } }; log!(debug, "Will disable {:?}", offender_idx); - Some(offender_idx) + DisablingDecision { disable: Some(offender_idx), reenable: None } + } +} + +/// Implementation of [`DisablingStrategy`] which disables validators from the active set up to a +/// limit (factor_based_disable_limit) and if the limit is reached and the new offender is higher +/// (bigger punishment/severity) then it re-enables the lowest offender to free up space for the new +/// offender. +/// +/// This strategy is not based on cumulative severity of offences but only on the severity of the +/// highest offence. Offender first committing a 25% offence and then a 50% offence will be treated +/// the same as an offender committing 50% offence. +/// +/// An extension of [`UpToLimitDisablingStrategy`]. +pub struct UpToLimitWithReEnablingDisablingStrategy; + +impl + UpToLimitWithReEnablingDisablingStrategy +{ + /// Disabling limit calculated from the total number of validators in the active set. When + /// reached re-enabling logic might kick in. + pub fn disable_limit(validators_len: usize) -> usize { + factor_based_disable_limit(validators_len, DISABLING_LIMIT_FACTOR) + } +} + +impl DisablingStrategy + for UpToLimitWithReEnablingDisablingStrategy +{ + fn decision( + offender_stash: &T::AccountId, + offender_slash_severity: OffenceSeverity, + slash_era: EraIndex, + currently_disabled: &Vec<(u32, OffenceSeverity)>, + ) -> DisablingDecision { + let active_set = T::SessionInterface::validators(); + + // We don't disable for offences in previous eras + if ActiveEra::::get().map(|e| e.index).unwrap_or_default() > slash_era { + log!( + debug, + "Won't disable: current_era {:?} > slash_era {:?}", + Pallet::::current_era().unwrap_or_default(), + slash_era + ); + return DisablingDecision { disable: None, reenable: None } + } + + // We don't disable validators that are not in the active set + let offender_idx = if let Some(idx) = active_set.iter().position(|i| i == offender_stash) { + idx as u32 + } else { + log!(debug, "Won't disable: offender not in active set",); + return DisablingDecision { disable: None, reenable: None } + }; + + // Check if offender is already disabled + if let Some((_, old_severity)) = + currently_disabled.iter().find(|(idx, _)| *idx == offender_idx) + { + if offender_slash_severity > *old_severity { + log!(debug, "Offender already disabled but with lower severity, will disable again to refresh severity of {:?}", offender_idx); + return DisablingDecision { disable: Some(offender_idx), reenable: None }; + } else { + log!(debug, "Offender already disabled with higher or equal severity"); + return DisablingDecision { disable: None, reenable: None }; + } + } + + // We don't disable more than the limit (but we can re-enable a smaller offender to make + // space) + if currently_disabled.len() >= Self::disable_limit(active_set.len()) { + log!( + debug, + "Reached disabling limit {:?}, checking for re-enabling", + Self::disable_limit(active_set.len()) + ); + + // Find the smallest offender to re-enable that is not higher than + // offender_slash_severity + if let Some((smallest_idx, _)) = currently_disabled + .iter() + .filter(|(_, severity)| *severity <= offender_slash_severity) + .min_by_key(|(_, severity)| *severity) + { + log!(debug, "Will disable {:?} and re-enable {:?}", offender_idx, smallest_idx); + return DisablingDecision { + disable: Some(offender_idx), + reenable: Some(*smallest_idx), + } + } else { + log!(debug, "No smaller offender found to re-enable"); + return DisablingDecision { disable: None, reenable: None } + } + } else { + // If we are not at the limit, just disable the new offender and dont re-enable anyone + log!(debug, "Will disable {:?}", offender_idx); + return DisablingDecision { disable: Some(offender_idx), reenable: None } + } } } diff --git a/substrate/frame/staking/src/migrations.rs b/substrate/frame/staking/src/migrations.rs index 5c9cf8613213..9dfa93c70b32 100644 --- a/substrate/frame/staking/src/migrations.rs +++ b/substrate/frame/staking/src/migrations.rs @@ -60,6 +60,79 @@ impl Default for ObsoleteReleases { #[storage_alias] type StorageVersion = StorageValue, ObsoleteReleases, ValueQuery>; +/// Migrating `DisabledValidators` from `Vec` to `Vec<(u32, OffenceSeverity)>` to track offense +/// severity for re-enabling purposes. +pub mod v16 { + use super::*; + use sp_staking::offence::OffenceSeverity; + + pub struct VersionUncheckedMigrateV15ToV16(core::marker::PhantomData); + impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV15ToV16 { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + let old_disabled_validators = v15::DisabledValidators::::get(); + Ok(old_disabled_validators.encode()) + } + + fn on_runtime_upgrade() -> Weight { + // Migrating `DisabledValidators` from `Vec` to `Vec<(u32, OffenceSeverity)>`. + // Using max severity (PerBill 100%) for the migration which effectively makes it so + // offenders before the migration will not be re-enabled this era unless there are + // other 100% offenders. + let max_offence = OffenceSeverity(Perbill::from_percent(100)); + // Inject severity + let migrated = v15::DisabledValidators::::take() + .into_iter() + .map(|v| (v, max_offence)) + .collect::>(); + + DisabledValidators::::set(migrated); + + log!(info, "v16 applied successfully."); + T::DbWeight::get().reads_writes(1, 1) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: Vec) -> Result<(), TryRuntimeError> { + // Decode state to get old_disabled_validators in a format of Vec + let old_disabled_validators = + Vec::::decode(&mut state.as_slice()).expect("Failed to decode state"); + let new_disabled_validators = DisabledValidators::::get(); + + // Compare lengths + frame_support::ensure!( + old_disabled_validators.len() == new_disabled_validators.len(), + "DisabledValidators length mismatch" + ); + + // Compare contents + let new_disabled_validators = + new_disabled_validators.into_iter().map(|(v, _)| v).collect::>(); + frame_support::ensure!( + old_disabled_validators == new_disabled_validators, + "DisabledValidator ids mismatch" + ); + + // Verify severity + let max_severity = OffenceSeverity(Perbill::from_percent(100)); + let new_disabled_validators = DisabledValidators::::get(); + for (_, severity) in new_disabled_validators { + frame_support::ensure!(severity == max_severity, "Severity mismatch"); + } + + Ok(()) + } + } + + pub type MigrateV15ToV16 = VersionedMigration< + 15, + 16, + VersionUncheckedMigrateV15ToV16, + Pallet, + ::DbWeight, + >; +} + /// Migrating `OffendingValidators` from `Vec<(u32, bool)>` to `Vec` pub mod v15 { use super::*; @@ -67,6 +140,9 @@ pub mod v15 { // The disabling strategy used by staking pallet type DefaultDisablingStrategy = UpToLimitDisablingStrategy; + #[storage_alias] + pub(crate) type DisabledValidators = StorageValue, Vec, ValueQuery>; + pub struct VersionUncheckedMigrateV14ToV15(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV14ToV15 { fn on_runtime_upgrade() -> Weight { diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 2d3446d2dabc..df8cb38e8b37 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -258,7 +258,8 @@ impl OnStakingUpdate for EventListenerMock { } } -// Disabling threshold for `UpToLimitDisablingStrategy` +// Disabling threshold for `UpToLimitDisablingStrategy` and +// `UpToLimitWithReEnablingDisablingStrategy`` pub(crate) const DISABLING_LIMIT_FACTOR: usize = 3; #[derive_impl(crate::config_preludes::TestDefaultConfig)] @@ -284,7 +285,8 @@ impl crate::pallet::pallet::Config for Test { type HistoryDepth = HistoryDepth; type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type EventListeners = EventListenerMock; - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type DisablingStrategy = + pallet_staking::UpToLimitWithReEnablingDisablingStrategy; } pub struct WeightedNominationsQuota; diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index 972d0f3d47b9..2ae925d03643 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -510,7 +510,7 @@ impl Pallet { } // disable all offending validators that have been disabled for the whole era - for index in >::get() { + for (index, _) in >::get() { T::SessionInterface::disable_validator(index); } } @@ -1497,6 +1497,12 @@ where continue } + Self::deposit_event(Event::::SlashReported { + validator: stash.clone(), + fraction: *slash_fraction, + slash_era, + }); + let unapplied = slashing::compute_slash::(slashing::SlashParams { stash, slash: *slash_fraction, @@ -1507,12 +1513,6 @@ where reward_proportion, }); - Self::deposit_event(Event::::SlashReported { - validator: stash.clone(), - fraction: *slash_fraction, - slash_era, - }); - if let Some(mut unapplied) = unapplied { let nominators_len = unapplied.others.len() as u64; let reporters_len = details.reporters.len() as u64; @@ -2303,9 +2303,10 @@ impl Pallet { Ok(()) } + // Sorted by index fn ensure_disabled_validators_sorted() -> Result<(), TryRuntimeError> { ensure!( - DisabledValidators::::get().windows(2).all(|pair| pair[0] <= pair[1]), + DisabledValidators::::get().windows(2).all(|pair| pair[0].0 <= pair[1].0), "DisabledValidators is not sorted" ); Ok(()) diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index d33b863a521a..b3f8c18f704c 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -38,6 +38,7 @@ use sp_runtime::{ }; use sp_staking::{ + offence::OffenceSeverity, EraIndex, Page, SessionIndex, StakingAccount::{self, Controller, Stash}, StakingInterface, @@ -69,7 +70,7 @@ pub mod pallet { use super::*; /// The in-code storage version. - const STORAGE_VERSION: StorageVersion = StorageVersion::new(15); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(16); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -704,11 +705,15 @@ pub mod pallet { /// implementor of [`DisablingStrategy`] defines if a validator should be disabled which /// implicitly means that the implementor also controls the max number of disabled validators. /// - /// The vec is always kept sorted so that we can find whether a given validator has previously - /// offended using binary search. + /// The vec is always kept sorted based on the u32 index so that we can find whether a given + /// validator has previously offended using binary search. + /// + /// Additionally, each disabled validator is associated with an `OffenceSeverity` which + /// represents how severe is the offence that got the validator disabled. #[pallet::storage] #[pallet::unbounded] - pub type DisabledValidators = StorageValue<_, Vec, ValueQuery>; + pub type DisabledValidators = + StorageValue<_, Vec<(u32, OffenceSeverity)>, ValueQuery>; /// The threshold for when users can start calling `chill_other` for other validators / /// nominators. The threshold is compared to the actual number of validators / nominators @@ -849,6 +854,10 @@ pub mod pallet { ForceEra { mode: Forcing }, /// Report of a controller batch deprecation. ControllerBatchDeprecated { failures: u32 }, + /// Validator has been disabled. + ValidatorDisabled { stash: T::AccountId }, + /// Validator has been re-enabled. + ValidatorReenabled { stash: T::AccountId }, } #[pallet::error] diff --git a/substrate/frame/staking/src/slashing.rs b/substrate/frame/staking/src/slashing.rs index 9fb782265b8b..ae76b0707dcb 100644 --- a/substrate/frame/staking/src/slashing.rs +++ b/substrate/frame/staking/src/slashing.rs @@ -65,7 +65,7 @@ use sp_runtime::{ traits::{Saturating, Zero}, DispatchResult, RuntimeDebug, }; -use sp_staking::{EraIndex, StakingInterface}; +use sp_staking::{offence::OffenceSeverity, EraIndex, StakingInterface}; /// The proportion of the slashing reward to be paid out on the first slashing detection. /// This is f_1 in the paper. @@ -321,17 +321,48 @@ fn kick_out_if_recent(params: SlashParams) { } /// Inform the [`DisablingStrategy`] implementation about the new offender and disable the list of -/// validators provided by [`make_disabling_decision`]. +/// validators provided by [`decision`]. fn add_offending_validator(params: &SlashParams) { DisabledValidators::::mutate(|disabled| { - if let Some(offender) = - T::DisablingStrategy::decision(params.stash, params.slash_era, &disabled) - { - // Add the validator to `DisabledValidators` and disable it. Do nothing if it is - // already disabled. - if let Err(index) = disabled.binary_search_by_key(&offender, |index| *index) { - disabled.insert(index, offender); - T::SessionInterface::disable_validator(offender); + let new_severity = OffenceSeverity(params.slash); + let decision = + T::DisablingStrategy::decision(params.stash, new_severity, params.slash_era, &disabled); + + if let Some(offender_idx) = decision.disable { + // Check if the offender is already disabled + match disabled.binary_search_by_key(&offender_idx, |(index, _)| *index) { + // Offender is already disabled, update severity if the new one is higher + Ok(index) => { + let (_, old_severity) = &mut disabled[index]; + if new_severity > *old_severity { + *old_severity = new_severity; + } + }, + Err(index) => { + // Offender is not disabled, add to `DisabledValidators` and disable it + disabled.insert(index, (offender_idx, new_severity)); + // Propagate disablement to session level + T::SessionInterface::disable_validator(offender_idx); + // Emit event that a validator got disabled + >::deposit_event(super::Event::::ValidatorDisabled { + stash: params.stash.clone(), + }); + }, + } + } + + if let Some(reenable_idx) = decision.reenable { + // Remove the validator from `DisabledValidators` and re-enable it. + if let Ok(index) = disabled.binary_search_by_key(&reenable_idx, |(index, _)| *index) { + disabled.remove(index); + // Propagate re-enablement to session level + T::SessionInterface::enable_validator(reenable_idx); + // Emit event that a validator got re-enabled + let reenabled_stash = + T::SessionInterface::validators()[reenable_idx as usize].clone(); + >::deposit_event(super::Event::::ValidatorReenabled { + stash: reenabled_stash, + }); } } }); diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index ffa317618f1f..6c2335e1aac8 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -3402,6 +3402,7 @@ fn slash_kicks_validators_not_nominators_and_disables_nominator_for_kicked_valid fraction: Perbill::from_percent(10), slash_era: 1 }, + Event::ValidatorDisabled { stash: 11 }, Event::Slashed { staker: 11, amount: 100 }, Event::Slashed { staker: 101, amount: 12 }, ] @@ -3474,11 +3475,13 @@ fn non_slashable_offence_disables_validator() { fraction: Perbill::from_percent(0), slash_era: 1 }, + Event::ValidatorDisabled { stash: 11 }, Event::SlashReported { validator: 21, fraction: Perbill::from_percent(25), slash_era: 1 }, + Event::ValidatorDisabled { stash: 21 }, Event::Slashed { staker: 21, amount: 250 }, Event::Slashed { staker: 101, amount: 94 } ] @@ -3506,6 +3509,7 @@ fn slashing_independent_of_disabling_validator() { let now = ActiveEra::::get().unwrap().index; + // --- Disable without a slash --- // offence with no slash associated on_offence_in_era( &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], @@ -3516,7 +3520,18 @@ fn slashing_independent_of_disabling_validator() { // nomination remains untouched. assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); - // offence that slashes 25% of the bond + // first validator is disabled but not slashed + assert!(is_disabled(11)); + + // --- Slash without disabling --- + // offence that slashes 50% of the bond (setup for next slash) + on_offence_in_era( + &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], + &[Perbill::from_percent(50)], + now, + ); + + // offence that slashes 25% of the bond but does not disable on_offence_in_era( &[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }], &[Perbill::from_percent(25)], @@ -3526,6 +3541,10 @@ fn slashing_independent_of_disabling_validator() { // nomination remains untouched. assert_eq!(Nominators::::get(101).unwrap().targets, vec![11, 21]); + // second validator is slashed but not disabled + assert!(!is_disabled(21)); + assert!(is_disabled(11)); + assert_eq!( staking_events_since_last_call(), vec![ @@ -3536,6 +3555,14 @@ fn slashing_independent_of_disabling_validator() { fraction: Perbill::from_percent(0), slash_era: 1 }, + Event::ValidatorDisabled { stash: 11 }, + Event::SlashReported { + validator: 11, + fraction: Perbill::from_percent(50), + slash_era: 1 + }, + Event::Slashed { staker: 11, amount: 500 }, + Event::Slashed { staker: 101, amount: 62 }, Event::SlashReported { validator: 21, fraction: Perbill::from_percent(25), @@ -3545,11 +3572,6 @@ fn slashing_independent_of_disabling_validator() { Event::Slashed { staker: 101, amount: 94 } ] ); - - // first validator is disabled but not slashed - assert!(is_disabled(11)); - // second validator is slashed but not disabled - assert!(!is_disabled(21)); }); } @@ -3563,7 +3585,7 @@ fn offence_threshold_doesnt_trigger_new_era() { assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41]); assert_eq!( - UpToLimitDisablingStrategy::::disable_limit( + UpToLimitWithReEnablingDisablingStrategy::::disable_limit( Session::validators().len() ), 1 @@ -3578,7 +3600,7 @@ fn offence_threshold_doesnt_trigger_new_era() { on_offence_now( &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], - &[Perbill::zero()], + &[Perbill::from_percent(50)], ); // 11 should be disabled because the byzantine threshold is 1 @@ -8277,11 +8299,14 @@ mod byzantine_threshold_disabling_strategy { use crate::{ tests::Test, ActiveEra, ActiveEraInfo, DisablingStrategy, UpToLimitDisablingStrategy, }; - use sp_staking::EraIndex; + use sp_runtime::Perbill; + use sp_staking::{offence::OffenceSeverity, EraIndex}; // Common test data - the stash of the offending validator, the era of the offence and the // active set const OFFENDER_ID: ::AccountId = 7; + const MAX_OFFENDER_SEVERITY: OffenceSeverity = OffenceSeverity(Perbill::from_percent(100)); + const MIN_OFFENDER_SEVERITY: OffenceSeverity = OffenceSeverity(Perbill::from_percent(0)); const SLASH_ERA: EraIndex = 1; const ACTIVE_SET: [::ValidatorId; 7] = [1, 2, 3, 4, 5, 6, 7]; const OFFENDER_VALIDATOR_IDX: u32 = 6; // the offender is with index 6 in the active set @@ -8293,48 +8318,431 @@ mod byzantine_threshold_disabling_strategy { pallet_session::Validators::::put(ACTIVE_SET.to_vec()); ActiveEra::::put(ActiveEraInfo { index: 2, start: None }); - let disable_offender = + let disabling_decision = >::decision( &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, SLASH_ERA, &initially_disabled, ); - assert!(disable_offender.is_none()); + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); }); } #[test] fn dont_disable_beyond_byzantine_threshold() { sp_io::TestExternalities::default().execute_with(|| { - let initially_disabled = vec![1, 2]; + let initially_disabled = vec![(1, MIN_OFFENDER_SEVERITY), (2, MAX_OFFENDER_SEVERITY)]; pallet_session::Validators::::put(ACTIVE_SET.to_vec()); - let disable_offender = + let disabling_decision = >::decision( &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, SLASH_ERA, &initially_disabled, ); - assert!(disable_offender.is_none()); + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); }); } #[test] fn disable_when_below_byzantine_threshold() { sp_io::TestExternalities::default().execute_with(|| { - let initially_disabled = vec![1]; + let initially_disabled = vec![(1, MAX_OFFENDER_SEVERITY)]; pallet_session::Validators::::put(ACTIVE_SET.to_vec()); - let disable_offender = + let disabling_decision = >::decision( &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert_eq!(disabling_decision.disable, Some(OFFENDER_VALIDATOR_IDX)); + }); + } +} + +mod disabling_strategy_with_reenabling { + use crate::{ + tests::Test, ActiveEra, ActiveEraInfo, DisablingStrategy, + UpToLimitWithReEnablingDisablingStrategy, + }; + use sp_runtime::Perbill; + use sp_staking::{offence::OffenceSeverity, EraIndex}; + + // Common test data - the stash of the offending validator, the era of the offence and the + // active set + const OFFENDER_ID: ::AccountId = 7; + const MAX_OFFENDER_SEVERITY: OffenceSeverity = OffenceSeverity(Perbill::from_percent(100)); + const LOW_OFFENDER_SEVERITY: OffenceSeverity = OffenceSeverity(Perbill::from_percent(0)); + const SLASH_ERA: EraIndex = 1; + const ACTIVE_SET: [::ValidatorId; 7] = [1, 2, 3, 4, 5, 6, 7]; + const OFFENDER_VALIDATOR_IDX: u32 = 6; // the offender is with index 6 in the active set + + #[test] + fn dont_disable_for_ancient_offence() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + ActiveEra::::put(ActiveEraInfo { index: 2, start: None }); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); + }); + } + + #[test] + fn disable_when_below_byzantine_threshold() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![(0, MAX_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + // Disable Offender and do not re-enable anyone + assert_eq!(disabling_decision.disable, Some(OFFENDER_VALIDATOR_IDX)); + assert_eq!(disabling_decision.reenable, None); + }); + } + + #[test] + fn reenable_arbitrary_on_equal_severity() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![(0, MAX_OFFENDER_SEVERITY), (1, MAX_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_some() && disabling_decision.reenable.is_some()); + // Disable 7 and enable 1 + assert_eq!(disabling_decision.disable.unwrap(), OFFENDER_VALIDATOR_IDX); + assert_eq!(disabling_decision.reenable.unwrap(), 0); + }); + } + + #[test] + fn do_not_reenable_higher_offenders() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![(0, MAX_OFFENDER_SEVERITY), (1, MAX_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + LOW_OFFENDER_SEVERITY, SLASH_ERA, &initially_disabled, ); - assert_eq!(disable_offender, Some(OFFENDER_VALIDATOR_IDX)); + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); + }); + } + + #[test] + fn reenable_lower_offenders() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![(0, LOW_OFFENDER_SEVERITY), (1, LOW_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_some() && disabling_decision.reenable.is_some()); + // Disable 7 and enable 1 + assert_eq!(disabling_decision.disable.unwrap(), OFFENDER_VALIDATOR_IDX); + assert_eq!(disabling_decision.reenable.unwrap(), 0); + }); + } + + #[test] + fn reenable_lower_offenders_unordered() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = vec![(0, MAX_OFFENDER_SEVERITY), (1, LOW_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_some() && disabling_decision.reenable.is_some()); + // Disable 7 and enable 1 + assert_eq!(disabling_decision.disable.unwrap(), OFFENDER_VALIDATOR_IDX); + assert_eq!(disabling_decision.reenable.unwrap(), 1); + }); + } + + #[test] + fn update_severity() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = + vec![(OFFENDER_VALIDATOR_IDX, LOW_OFFENDER_SEVERITY), (0, MAX_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_some() && disabling_decision.reenable.is_none()); + // Disable 7 "again" AKA update their severity + assert_eq!(disabling_decision.disable.unwrap(), OFFENDER_VALIDATOR_IDX); + }); + } + + #[test] + fn update_cannot_lower_severity() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = + vec![(OFFENDER_VALIDATOR_IDX, MAX_OFFENDER_SEVERITY), (0, MAX_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + LOW_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); + }); + } + + #[test] + fn no_accidental_reenablement_on_repeated_offence() { + sp_io::TestExternalities::default().execute_with(|| { + let initially_disabled = + vec![(OFFENDER_VALIDATOR_IDX, MAX_OFFENDER_SEVERITY), (0, LOW_OFFENDER_SEVERITY)]; + pallet_session::Validators::::put(ACTIVE_SET.to_vec()); + + let disabling_decision = + >::decision( + &OFFENDER_ID, + MAX_OFFENDER_SEVERITY, + SLASH_ERA, + &initially_disabled, + ); + + assert!(disabling_decision.disable.is_none() && disabling_decision.reenable.is_none()); + }); + } +} + +#[test] +fn reenable_lower_offenders_mock() { + ExtBuilder::default() + .validator_count(7) + .set_status(41, StakerStatus::Validator) + .set_status(51, StakerStatus::Validator) + .set_status(201, StakerStatus::Validator) + .set_status(202, StakerStatus::Validator) + .build_and_execute(|| { + mock::start_active_era(1); + assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41, 51, 201, 202]); + + let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_31 = Staking::eras_stakers(Staking::active_era().unwrap().index, &31); + + // offence with a low slash + on_offence_now( + &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], + &[Perbill::from_percent(10)], + ); + on_offence_now( + &[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }], + &[Perbill::from_percent(20)], + ); + + // it does NOT affect the nominator. + assert_eq!(Staking::nominators(101).unwrap().targets, vec![11, 21]); + + // both validators should be disabled + assert!(is_disabled(11)); + assert!(is_disabled(21)); + + // offence with a higher slash + on_offence_now( + &[OffenceDetails { offender: (31, exposure_31.clone()), reporters: vec![] }], + &[Perbill::from_percent(50)], + ); + + // First offender is no longer disabled + assert!(!is_disabled(11)); + // Mid offender is still disabled + assert!(is_disabled(21)); + // New offender is disabled + assert!(is_disabled(31)); + + assert_eq!( + staking_events_since_last_call(), + vec![ + Event::StakersElected, + Event::EraPaid { era_index: 0, validator_payout: 11075, remainder: 33225 }, + Event::SlashReported { + validator: 11, + fraction: Perbill::from_percent(10), + slash_era: 1 + }, + Event::ValidatorDisabled { stash: 11 }, + Event::Slashed { staker: 11, amount: 100 }, + Event::Slashed { staker: 101, amount: 12 }, + Event::SlashReported { + validator: 21, + fraction: Perbill::from_percent(20), + slash_era: 1 + }, + Event::ValidatorDisabled { stash: 21 }, + Event::Slashed { staker: 21, amount: 200 }, + Event::Slashed { staker: 101, amount: 75 }, + Event::SlashReported { + validator: 31, + fraction: Perbill::from_percent(50), + slash_era: 1 + }, + Event::ValidatorDisabled { stash: 31 }, + Event::ValidatorReenabled { stash: 11 }, + Event::Slashed { staker: 31, amount: 250 }, + ] + ); + }); +} + +#[test] +fn do_not_reenable_higher_offenders_mock() { + ExtBuilder::default() + .validator_count(7) + .set_status(41, StakerStatus::Validator) + .set_status(51, StakerStatus::Validator) + .set_status(201, StakerStatus::Validator) + .set_status(202, StakerStatus::Validator) + .build_and_execute(|| { + mock::start_active_era(1); + assert_eq_uvec!(Session::validators(), vec![11, 21, 31, 41, 51, 201, 202]); + + let exposure_11 = Staking::eras_stakers(Staking::active_era().unwrap().index, &11); + let exposure_21 = Staking::eras_stakers(Staking::active_era().unwrap().index, &21); + let exposure_31 = Staking::eras_stakers(Staking::active_era().unwrap().index, &31); + + // offence with a major slash + on_offence_now( + &[OffenceDetails { offender: (11, exposure_11.clone()), reporters: vec![] }], + &[Perbill::from_percent(50)], + ); + on_offence_now( + &[OffenceDetails { offender: (21, exposure_21.clone()), reporters: vec![] }], + &[Perbill::from_percent(50)], + ); + + // both validators should be disabled + assert!(is_disabled(11)); + assert!(is_disabled(21)); + + // offence with a minor slash + on_offence_now( + &[OffenceDetails { offender: (31, exposure_31.clone()), reporters: vec![] }], + &[Perbill::from_percent(10)], + ); + + // First and second offenders are still disabled + assert!(is_disabled(11)); + assert!(is_disabled(21)); + // New offender is not disabled as limit is reached and his prio is lower + assert!(!is_disabled(31)); + + assert_eq!( + staking_events_since_last_call(), + vec![ + Event::StakersElected, + Event::EraPaid { era_index: 0, validator_payout: 11075, remainder: 33225 }, + Event::SlashReported { + validator: 11, + fraction: Perbill::from_percent(50), + slash_era: 1 + }, + Event::ValidatorDisabled { stash: 11 }, + Event::Slashed { staker: 11, amount: 500 }, + Event::Slashed { staker: 101, amount: 62 }, + Event::SlashReported { + validator: 21, + fraction: Perbill::from_percent(50), + slash_era: 1 + }, + Event::ValidatorDisabled { stash: 21 }, + Event::Slashed { staker: 21, amount: 500 }, + Event::Slashed { staker: 101, amount: 187 }, + Event::SlashReported { + validator: 31, + fraction: Perbill::from_percent(10), + slash_era: 1 + }, + Event::Slashed { staker: 31, amount: 50 }, + ] + ); + }); +} + +#[cfg(all(feature = "try-runtime", test))] +mod migration_tests { + use super::*; + use frame_support::traits::UncheckedOnRuntimeUpgrade; + use migrations::{v15, v16}; + + #[test] + fn migrate_v15_to_v16_with_try_runtime() { + ExtBuilder::default().validator_count(7).build_and_execute(|| { + // Initial setup: Create old `DisabledValidators` in the form of `Vec` + let old_disabled_validators = vec![1u32, 2u32]; + v15::DisabledValidators::::put(old_disabled_validators.clone()); + + // Run pre-upgrade checks + let pre_upgrade_result = v16::VersionUncheckedMigrateV15ToV16::::pre_upgrade(); + assert!(pre_upgrade_result.is_ok()); + let pre_upgrade_state = pre_upgrade_result.unwrap(); + + // Run the migration + v16::VersionUncheckedMigrateV15ToV16::::on_runtime_upgrade(); + + // Run post-upgrade checks + let post_upgrade_result = + v16::VersionUncheckedMigrateV15ToV16::::post_upgrade(pre_upgrade_state); + assert!(post_upgrade_result.is_ok()); }); } } diff --git a/substrate/primitives/staking/src/offence.rs b/substrate/primitives/staking/src/offence.rs index 2c2ebc1fc971..e73e8efe5839 100644 --- a/substrate/primitives/staking/src/offence.rs +++ b/substrate/primitives/staking/src/offence.rs @@ -242,3 +242,28 @@ impl OffenceReportSystem for () { Ok(()) } } + +/// Wrapper type representing the severity of an offence. +/// +/// As of now the only meaningful value taken into account +/// when deciding the severity of an offence is the associated +/// slash amount `Perbill`. +/// +/// For instance used for the purposes of distinguishing who should be +/// prioritized for disablement. +#[derive( + Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug, scale_info::TypeInfo, +)] +pub struct OffenceSeverity(pub Perbill); + +impl PartialOrd for OffenceSeverity { + fn partial_cmp(&self, other: &Self) -> Option { + self.0.partial_cmp(&other.0) + } +} + +impl Ord for OffenceSeverity { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.0.cmp(&other.0) + } +} diff --git a/substrate/primitives/state-machine/src/trie_backend.rs b/substrate/primitives/state-machine/src/trie_backend.rs index f91ce5d2e52f..8d4dfd34240d 100644 --- a/substrate/primitives/state-machine/src/trie_backend.rs +++ b/substrate/primitives/state-machine/src/trie_backend.rs @@ -73,7 +73,10 @@ pub trait TrieCacheProvider { #[cfg(feature = "std")] impl TrieCacheProvider for LocalTrieCache { - type Cache<'a> = TrieCache<'a, H> where H: 'a; + type Cache<'a> + = TrieCache<'a, H> + where + H: 'a; fn as_trie_db_cache(&self, storage_root: H::Out) -> Self::Cache<'_> { self.as_trie_db_cache(storage_root) @@ -90,7 +93,10 @@ impl TrieCacheProvider for LocalTrieCache { #[cfg(feature = "std")] impl TrieCacheProvider for &LocalTrieCache { - type Cache<'a> = TrieCache<'a, H> where Self: 'a; + type Cache<'a> + = TrieCache<'a, H> + where + Self: 'a; fn as_trie_db_cache(&self, storage_root: H::Out) -> Self::Cache<'_> { (*self).as_trie_db_cache(storage_root) @@ -139,7 +145,10 @@ impl trie_db::TrieCache> for UnimplementedCacheProvider< #[cfg(not(feature = "std"))] impl TrieCacheProvider for UnimplementedCacheProvider { - type Cache<'a> = UnimplementedCacheProvider where H: 'a; + type Cache<'a> + = UnimplementedCacheProvider + where + H: 'a; fn as_trie_db_cache(&self, _storage_root: ::Out) -> Self::Cache<'_> { unimplemented!() @@ -176,7 +185,10 @@ impl trie_db::TrieRecorder for UnimplementedRecorderProvider< #[cfg(not(feature = "std"))] impl TrieRecorderProvider for UnimplementedRecorderProvider { - type Recorder<'a> = UnimplementedRecorderProvider where H: 'a; + type Recorder<'a> + = UnimplementedRecorderProvider + where + H: 'a; fn drain_storage_proof(self) -> Option { unimplemented!() diff --git a/substrate/primitives/trie/src/recorder.rs b/substrate/primitives/trie/src/recorder.rs index 2886577eddc6..4ec13066ded7 100644 --- a/substrate/primitives/trie/src/recorder.rs +++ b/substrate/primitives/trie/src/recorder.rs @@ -252,7 +252,10 @@ pub struct TrieRecorder<'a, H: Hasher> { } impl crate::TrieRecorderProvider for Recorder { - type Recorder<'a> = TrieRecorder<'a, H> where H: 'a; + type Recorder<'a> + = TrieRecorder<'a, H> + where + H: 'a; fn drain_storage_proof(self) -> Option { Some(Recorder::drain_storage_proof(self)) From 09757a4164d44f224b44291f1e01b1e813a52220 Mon Sep 17 00:00:00 2001 From: Kazunobu Ndong <33208377+ndkazu@users.noreply.github.com> Date: Wed, 20 Nov 2024 04:08:46 +0900 Subject: [PATCH 112/166] Migrate pallet-democracy benchmarks to benchmark v2 syntax (#6509) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Migrates pallet-democracy benchmarks to benchmark v2 syntax This is Part of https://github.com/paritytech/polkadot-sdk/issues/6202 --------- Co-authored-by: Bastian Köcher Co-authored-by: command-bot <> Co-authored-by: Dmitry Markin Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> --- prdoc/pr_6509.prdoc | 13 + substrate/frame/democracy/src/benchmarking.rs | 548 +++++++++++------- substrate/frame/democracy/src/weights.rs | 302 +++++----- 3 files changed, 498 insertions(+), 365 deletions(-) create mode 100644 prdoc/pr_6509.prdoc diff --git a/prdoc/pr_6509.prdoc b/prdoc/pr_6509.prdoc new file mode 100644 index 000000000000..74215fe0084c --- /dev/null +++ b/prdoc/pr_6509.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Migrate pallet-democracy benchmark to v2 + +doc: + - audience: Runtime Dev + description: | + "Part of issue #6202." + +crates: +- name: pallet-democracy + bump: patch diff --git a/substrate/frame/democracy/src/benchmarking.rs b/substrate/frame/democracy/src/benchmarking.rs index ee36e9212f52..f9c810e56192 100644 --- a/substrate/frame/democracy/src/benchmarking.rs +++ b/substrate/frame/democracy/src/benchmarking.rs @@ -17,9 +17,11 @@ //! Democracy pallet benchmarking. +#![cfg(feature = "runtime-benchmarks")] + use super::*; -use frame_benchmarking::v1::{account, benchmarks, whitelist_account, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::{ assert_noop, assert_ok, traits::{Currency, EnsureOrigin, Get, OnInitialize, UnfilteredDispatchable}, @@ -94,11 +96,15 @@ fn note_preimage() -> T::Hash { hash } -benchmarks! { - propose { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn propose() -> Result<(), BenchmarkError> { let p = T::MaxProposals::get(); - for i in 0 .. (p - 1) { + for i in 0..(p - 1) { add_proposal::(i)?; } @@ -106,18 +112,22 @@ benchmarks! { let proposal = make_proposal::(0); let value = T::MinimumDeposit::get(); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), proposal, value) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller), proposal, value); + assert_eq!(PublicProps::::get().len(), p as usize, "Proposals not created."); + Ok(()) } - second { + #[benchmark] + fn second() -> Result<(), BenchmarkError> { let caller = funded_account::("caller", 0); add_proposal::(0)?; // Create s existing "seconds" // we must reserve one deposit for the `proposal` and one for our benchmarked `second` call. - for i in 0 .. T::MaxDeposits::get() - 2 { + for i in 0..T::MaxDeposits::get() - 2 { let seconder = funded_account::("seconder", i); Democracy::::second(RawOrigin::Signed(seconder).into(), 0)?; } @@ -125,20 +135,32 @@ benchmarks! { let deposits = DepositOf::::get(0).ok_or("Proposal not created")?; assert_eq!(deposits.0.len(), (T::MaxDeposits::get() - 1) as usize, "Seconds not recorded"); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), 0) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller), 0); + let deposits = DepositOf::::get(0).ok_or("Proposal not created")?; - assert_eq!(deposits.0.len(), (T::MaxDeposits::get()) as usize, "`second` benchmark did not work"); + assert_eq!( + deposits.0.len(), + (T::MaxDeposits::get()) as usize, + "`second` benchmark did not work" + ); + Ok(()) } - vote_new { + #[benchmark] + fn vote_new() -> Result<(), BenchmarkError> { let caller = funded_account::("caller", 0); let account_vote = account_vote::(100u32.into()); // We need to create existing direct votes - for i in 0 .. T::MaxVotes::get() - 1 { + for i in 0..T::MaxVotes::get() - 1 { let ref_index = add_referendum::(i).0; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_index, account_vote)?; + Democracy::::vote( + RawOrigin::Signed(caller.clone()).into(), + ref_index, + account_vote, + )?; } let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, @@ -148,23 +170,32 @@ benchmarks! { let ref_index = add_referendum::(T::MaxVotes::get() - 1).0; whitelist_account!(caller); - }: vote(RawOrigin::Signed(caller.clone()), ref_index, account_vote) - verify { + + #[extrinsic_call] + vote(RawOrigin::Signed(caller.clone()), ref_index, account_vote); + let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, _ => return Err("Votes are not direct".into()), }; + assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Vote was not recorded."); + Ok(()) } - vote_existing { + #[benchmark] + fn vote_existing() -> Result<(), BenchmarkError> { let caller = funded_account::("caller", 0); let account_vote = account_vote::(100u32.into()); // We need to create existing direct votes for i in 0..T::MaxVotes::get() { let ref_index = add_referendum::(i).0; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_index, account_vote)?; + Democracy::::vote( + RawOrigin::Signed(caller.clone()).into(), + ref_index, + account_vote, + )?; } let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, @@ -179,43 +210,50 @@ benchmarks! { // This tests when a user changes a vote whitelist_account!(caller); - }: vote(RawOrigin::Signed(caller.clone()), ref_index, new_vote) - verify { + + #[extrinsic_call] + vote(RawOrigin::Signed(caller.clone()), ref_index, new_vote); + let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, _ => return Err("Votes are not direct".into()), }; assert_eq!(votes.len(), T::MaxVotes::get() as usize, "Vote was incorrectly added"); - let referendum_info = ReferendumInfoOf::::get(ref_index) - .ok_or("referendum doesn't exist")?; - let tally = match referendum_info { + let referendum_info = + ReferendumInfoOf::::get(ref_index).ok_or("referendum doesn't exist")?; + let tally = match referendum_info { ReferendumInfo::Ongoing(r) => r.tally, _ => return Err("referendum not ongoing".into()), }; assert_eq!(tally.nays, 1000u32.into(), "changed vote was not recorded"); + Ok(()) } - emergency_cancel { - let origin = - T::CancellationOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + #[benchmark] + fn emergency_cancel() -> Result<(), BenchmarkError> { + let origin = T::CancellationOrigin::try_successful_origin() + .map_err(|_| BenchmarkError::Weightless)?; let (ref_index, _, preimage_hash) = add_referendum::(0); assert_ok!(Democracy::::referendum_status(ref_index)); - }: _(origin, ref_index) - verify { + + #[extrinsic_call] + _(origin as T::RuntimeOrigin, ref_index); // Referendum has been canceled - assert_noop!( - Democracy::::referendum_status(ref_index), - Error::::ReferendumInvalid, + assert_noop!(Democracy::::referendum_status(ref_index), Error::::ReferendumInvalid,); + assert_last_event::( + crate::Event::MetadataCleared { + owner: MetadataOwner::Referendum(ref_index), + hash: preimage_hash, + } + .into(), ); - assert_last_event::(crate::Event::MetadataCleared { - owner: MetadataOwner::Referendum(ref_index), - hash: preimage_hash, - }.into()); + Ok(()) } - blacklist { + #[benchmark] + fn blacklist() -> Result<(), BenchmarkError> { // Place our proposal at the end to make sure it's worst case. - for i in 0 .. T::MaxProposals::get() - 1 { + for i in 0..T::MaxProposals::get() - 1 { add_proposal::(i)?; } // We should really add a lot of seconds here, but we're not doing it elsewhere. @@ -231,21 +269,24 @@ benchmarks! { )); let origin = T::BlacklistOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - }: _(origin, hash, Some(ref_index)) - verify { + #[extrinsic_call] + _(origin as T::RuntimeOrigin, hash, Some(ref_index)); + // Referendum has been canceled - assert_noop!( - Democracy::::referendum_status(ref_index), - Error::::ReferendumInvalid + assert_noop!(Democracy::::referendum_status(ref_index), Error::::ReferendumInvalid); + assert_has_event::( + crate::Event::MetadataCleared { + owner: MetadataOwner::Referendum(ref_index), + hash: preimage_hash, + } + .into(), ); - assert_has_event::(crate::Event::MetadataCleared { - owner: MetadataOwner::Referendum(ref_index), - hash: preimage_hash, - }.into()); + Ok(()) } // Worst case scenario, we external propose a previously blacklisted proposal - external_propose { + #[benchmark] + fn external_propose() -> Result<(), BenchmarkError> { let origin = T::ExternalOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let proposal = make_proposal::(0); @@ -258,33 +299,42 @@ benchmarks! { .try_into() .unwrap(); Blacklist::::insert(proposal.hash(), (BlockNumberFor::::zero(), addresses)); - }: _(origin, proposal) - verify { + #[extrinsic_call] + _(origin as T::RuntimeOrigin, proposal); + // External proposal created ensure!(NextExternal::::exists(), "External proposal didn't work"); + Ok(()) } - external_propose_majority { + #[benchmark] + fn external_propose_majority() -> Result<(), BenchmarkError> { let origin = T::ExternalMajorityOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; let proposal = make_proposal::(0); - }: _(origin, proposal) - verify { + #[extrinsic_call] + _(origin as T::RuntimeOrigin, proposal); + // External proposal created ensure!(NextExternal::::exists(), "External proposal didn't work"); + Ok(()) } - external_propose_default { + #[benchmark] + fn external_propose_default() -> Result<(), BenchmarkError> { let origin = T::ExternalDefaultOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; let proposal = make_proposal::(0); - }: _(origin, proposal) - verify { + #[extrinsic_call] + _(origin as T::RuntimeOrigin, proposal); + // External proposal created ensure!(NextExternal::::exists(), "External proposal didn't work"); + Ok(()) } - fast_track { + #[benchmark] + fn fast_track() -> Result<(), BenchmarkError> { let origin_propose = T::ExternalDefaultOrigin::try_successful_origin() .expect("ExternalDefaultOrigin has no successful origin required for the benchmark"); let proposal = make_proposal::(0); @@ -295,23 +345,30 @@ benchmarks! { assert_ok!(Democracy::::set_metadata( origin_propose, MetadataOwner::External, - Some(preimage_hash))); + Some(preimage_hash) + )); // NOTE: Instant origin may invoke a little bit more logic, but may not always succeed. let origin_fast_track = T::FastTrackOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; let voting_period = T::FastTrackVotingPeriod::get(); let delay = 0u32; - }: _(origin_fast_track, proposal_hash, voting_period, delay.into()) - verify { + #[extrinsic_call] + _(origin_fast_track as T::RuntimeOrigin, proposal_hash, voting_period, delay.into()); + assert_eq!(ReferendumCount::::get(), 1, "referendum not created"); - assert_last_event::(crate::Event::MetadataTransferred { - prev_owner: MetadataOwner::External, - owner: MetadataOwner::Referendum(0), - hash: preimage_hash, - }.into()); + assert_last_event::( + crate::Event::MetadataTransferred { + prev_owner: MetadataOwner::External, + owner: MetadataOwner::Referendum(0), + hash: preimage_hash, + } + .into(), + ); + Ok(()) } - veto_external { + #[benchmark] + fn veto_external() -> Result<(), BenchmarkError> { let proposal = make_proposal::(0); let proposal_hash = proposal.hash(); @@ -323,28 +380,32 @@ benchmarks! { assert_ok!(Democracy::::set_metadata( origin_propose, MetadataOwner::External, - Some(preimage_hash)) - ); + Some(preimage_hash) + )); let mut vetoers: BoundedVec = Default::default(); - for i in 0 .. (T::MaxBlacklisted::get() - 1) { + for i in 0..(T::MaxBlacklisted::get() - 1) { vetoers.try_push(account::("vetoer", i, SEED)).unwrap(); } vetoers.sort(); Blacklist::::insert(proposal_hash, (BlockNumberFor::::zero(), vetoers)); - let origin = T::VetoOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let origin = + T::VetoOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; ensure!(NextExternal::::get().is_some(), "no external proposal"); - }: _(origin, proposal_hash) - verify { + #[extrinsic_call] + _(origin as T::RuntimeOrigin, proposal_hash); + assert!(NextExternal::::get().is_none()); let (_, new_vetoers) = Blacklist::::get(&proposal_hash).ok_or("no blacklist")?; assert_eq!(new_vetoers.len(), T::MaxBlacklisted::get() as usize, "vetoers not added"); + Ok(()) } - cancel_proposal { + #[benchmark] + fn cancel_proposal() -> Result<(), BenchmarkError> { // Place our proposal at the end to make sure it's worst case. - for i in 0 .. T::MaxProposals::get() { + for i in 0..T::MaxProposals::get() { add_proposal::(i)?; } // Add metadata to the first proposal. @@ -353,31 +414,41 @@ benchmarks! { assert_ok!(Democracy::::set_metadata( RawOrigin::Signed(proposer).into(), MetadataOwner::Proposal(0), - Some(preimage_hash))); + Some(preimage_hash) + )); let cancel_origin = T::CancelProposalOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; - }: _(cancel_origin, 0) - verify { - assert_last_event::(crate::Event::MetadataCleared { - owner: MetadataOwner::Proposal(0), - hash: preimage_hash, - }.into()); + #[extrinsic_call] + _(cancel_origin as T::RuntimeOrigin, 0); + + assert_last_event::( + crate::Event::MetadataCleared { + owner: MetadataOwner::Proposal(0), + hash: preimage_hash, + } + .into(), + ); + Ok(()) } - cancel_referendum { + #[benchmark] + fn cancel_referendum() -> Result<(), BenchmarkError> { let (ref_index, _, preimage_hash) = add_referendum::(0); - }: _(RawOrigin::Root, ref_index) - verify { - assert_last_event::(crate::Event::MetadataCleared { - owner: MetadataOwner::Referendum(0), - hash: preimage_hash, - }.into()); - } + #[extrinsic_call] + _(RawOrigin::Root, ref_index); - #[extra] - on_initialize_external { - let r in 0 .. REFERENDUM_COUNT_HINT; + assert_last_event::( + crate::Event::MetadataCleared { + owner: MetadataOwner::Referendum(0), + hash: preimage_hash, + } + .into(), + ); + Ok(()) + } + #[benchmark(extra)] + fn on_initialize_external(r: Linear<0, REFERENDUM_COUNT_HINT>) -> Result<(), BenchmarkError> { for i in 0..r { add_referendum::(i); } @@ -397,14 +468,17 @@ benchmarks! { let block_number = T::LaunchPeriod::get(); - }: { Democracy::::on_initialize(block_number) } - verify { + #[block] + { + Democracy::::on_initialize(block_number); + } + // One extra because of next external assert_eq!(ReferendumCount::::get(), r + 1, "referenda not created"); ensure!(!NextExternal::::exists(), "External wasn't taken"); // All but the new next external should be finished - for i in 0 .. r { + for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { ReferendumInfo::Finished { .. } => (), @@ -412,12 +486,13 @@ benchmarks! { } } } + Ok(()) } - #[extra] - on_initialize_public { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark(extra)] + fn on_initialize_public( + r: Linear<0, { T::MaxVotes::get() - 1 }>, + ) -> Result<(), BenchmarkError> { for i in 0..r { add_referendum::(i); } @@ -430,13 +505,16 @@ benchmarks! { let block_number = T::LaunchPeriod::get(); - }: { Democracy::::on_initialize(block_number) } - verify { + #[block] + { + Democracy::::on_initialize(block_number); + } + // One extra because of next public assert_eq!(ReferendumCount::::get(), r + 1, "proposal not accepted"); // All should be finished - for i in 0 .. r { + for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { ReferendumInfo::Finished { .. } => (), @@ -444,12 +522,12 @@ benchmarks! { } } } + Ok(()) } // No launch no maturing referenda. - on_initialize_base { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark] + fn on_initialize_base(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> { for i in 0..r { add_referendum::(i); } @@ -464,22 +542,28 @@ benchmarks! { assert_eq!(ReferendumCount::::get(), r, "referenda not created"); assert_eq!(LowestUnbaked::::get(), 0, "invalid referenda init"); - }: { Democracy::::on_initialize(1u32.into()) } - verify { + #[block] + { + Democracy::::on_initialize(1u32.into()); + } + // All should be on going - for i in 0 .. r { + for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { - ReferendumInfo::Finished { .. } => return Err("Referendum has been finished".into()), + ReferendumInfo::Finished { .. } => + return Err("Referendum has been finished".into()), ReferendumInfo::Ongoing(_) => (), } } } + Ok(()) } - on_initialize_base_with_launch_period { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark] + fn on_initialize_base_with_launch_period( + r: Linear<0, { T::MaxVotes::get() - 1 }>, + ) -> Result<(), BenchmarkError> { for i in 0..r { add_referendum::(i); } @@ -496,22 +580,26 @@ benchmarks! { let block_number = T::LaunchPeriod::get(); - }: { Democracy::::on_initialize(block_number) } - verify { + #[block] + { + Democracy::::on_initialize(block_number); + } + // All should be on going - for i in 0 .. r { + for i in 0..r { if let Some(value) = ReferendumInfoOf::::get(i) { match value { - ReferendumInfo::Finished { .. } => return Err("Referendum has been finished".into()), + ReferendumInfo::Finished { .. } => + return Err("Referendum has been finished".into()), ReferendumInfo::Ongoing(_) => (), } } } + Ok(()) } - delegate { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark] + fn delegate(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> { let initial_balance: BalanceOf = 100u32.into(); let delegated_balance: BalanceOf = 1000u32.into(); @@ -538,7 +626,11 @@ benchmarks! { // We need to create existing direct votes for the `new_delegate` for i in 0..r { let ref_index = add_referendum::(i).0; - Democracy::::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_index, account_vote)?; + Democracy::::vote( + RawOrigin::Signed(new_delegate.clone()).into(), + ref_index, + account_vote, + )?; } let votes = match VotingOf::::get(&new_delegate) { Voting::Direct { votes, .. } => votes, @@ -546,8 +638,15 @@ benchmarks! { }; assert_eq!(votes.len(), r as usize, "Votes were not recorded."); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), new_delegate_lookup, Conviction::Locked1x, delegated_balance) - verify { + + #[extrinsic_call] + _( + RawOrigin::Signed(caller.clone()), + new_delegate_lookup, + Conviction::Locked1x, + delegated_balance, + ); + let (target, balance) = match VotingOf::::get(&caller) { Voting::Delegating { target, balance, .. } => (target, balance), _ => return Err("Votes are not direct".into()), @@ -559,11 +658,11 @@ benchmarks! { _ => return Err("Votes are not direct".into()), }; assert_eq!(delegations.capital, delegated_balance, "delegation was not recorded."); + Ok(()) } - undelegate { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark] + fn undelegate(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> { let initial_balance: BalanceOf = 100u32.into(); let delegated_balance: BalanceOf = 1000u32.into(); @@ -590,7 +689,7 @@ benchmarks! { Democracy::::vote( RawOrigin::Signed(the_delegate.clone()).into(), ref_index, - account_vote + account_vote, )?; } let votes = match VotingOf::::get(&the_delegate) { @@ -599,31 +698,38 @@ benchmarks! { }; assert_eq!(votes.len(), r as usize, "Votes were not recorded."); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone())) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone())); + // Voting should now be direct match VotingOf::::get(&caller) { Voting::Direct { .. } => (), _ => return Err("undelegation failed".into()), } + Ok(()) } - clear_public_proposals { + #[benchmark] + fn clear_public_proposals() -> Result<(), BenchmarkError> { add_proposal::(0)?; - }: _(RawOrigin::Root) + #[extrinsic_call] + _(RawOrigin::Root); - // Test when unlock will remove locks - unlock_remove { - let r in 0 .. (T::MaxVotes::get() - 1); + Ok(()) + } + // Test when unlock will remove locks + #[benchmark] + fn unlock_remove(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> { let locker = funded_account::("locker", 0); let locker_lookup = T::Lookup::unlookup(locker.clone()); // Populate votes so things are locked let base_balance: BalanceOf = 100u32.into(); let small_vote = account_vote::(base_balance); // Vote and immediately unvote - for i in 0 .. r { + for i in 0..r { let ref_index = add_referendum::(i).0; Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_index, small_vote)?; Democracy::::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_index)?; @@ -631,23 +737,25 @@ benchmarks! { let caller = funded_account::("caller", 0); whitelist_account!(caller); - }: unlock(RawOrigin::Signed(caller), locker_lookup) - verify { + + #[extrinsic_call] + unlock(RawOrigin::Signed(caller), locker_lookup); + // Note that we may want to add a `get_lock` api to actually verify let voting = VotingOf::::get(&locker); assert_eq!(voting.locked_balance(), BalanceOf::::zero()); + Ok(()) } // Test when unlock will set a new value - unlock_set { - let r in 0 .. (T::MaxVotes::get() - 1); - + #[benchmark] + fn unlock_set(r: Linear<0, { T::MaxVotes::get() - 1 }>) -> Result<(), BenchmarkError> { let locker = funded_account::("locker", 0); let locker_lookup = T::Lookup::unlookup(locker.clone()); // Populate votes so things are locked let base_balance: BalanceOf = 100u32.into(); let small_vote = account_vote::(base_balance); - for i in 0 .. r { + for i in 0..r { let ref_index = add_referendum::(i).0; Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_index, small_vote)?; } @@ -670,8 +778,10 @@ benchmarks! { let caller = funded_account::("caller", 0); whitelist_account!(caller); - }: unlock(RawOrigin::Signed(caller), locker_lookup) - verify { + + #[extrinsic_call] + unlock(RawOrigin::Signed(caller), locker_lookup); + let votes = match VotingOf::::get(&locker) { Voting::Direct { votes, .. } => votes, _ => return Err("Votes are not direct".into()), @@ -681,17 +791,21 @@ benchmarks! { let voting = VotingOf::::get(&locker); // Note that we may want to add a `get_lock` api to actually verify assert_eq!(voting.locked_balance(), if r > 0 { base_balance } else { 0u32.into() }); + Ok(()) } - remove_vote { - let r in 1 .. T::MaxVotes::get(); - + #[benchmark] + fn remove_vote(r: Linear<1, { T::MaxVotes::get() }>) -> Result<(), BenchmarkError> { let caller = funded_account::("caller", 0); let account_vote = account_vote::(100u32.into()); - for i in 0 .. r { + for i in 0..r { let ref_index = add_referendum::(i).0; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_index, account_vote)?; + Democracy::::vote( + RawOrigin::Signed(caller.clone()).into(), + ref_index, + account_vote, + )?; } let votes = match VotingOf::::get(&caller) { @@ -702,26 +816,32 @@ benchmarks! { let ref_index = r - 1; whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), ref_index) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), ref_index); + let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, _ => return Err("Votes are not direct".into()), }; assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed"); + Ok(()) } // Worst case is when target == caller and referendum is ongoing - remove_other_vote { - let r in 1 .. T::MaxVotes::get(); - + #[benchmark] + fn remove_other_vote(r: Linear<1, { T::MaxVotes::get() }>) -> Result<(), BenchmarkError> { let caller = funded_account::("caller", r); let caller_lookup = T::Lookup::unlookup(caller.clone()); let account_vote = account_vote::(100u32.into()); - for i in 0 .. r { + for i in 0..r { let ref_index = add_referendum::(i).0; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_index, account_vote)?; + Democracy::::vote( + RawOrigin::Signed(caller.clone()).into(), + ref_index, + account_vote, + )?; } let votes = match VotingOf::::get(&caller) { @@ -732,68 +852,71 @@ benchmarks! { let ref_index = r - 1; whitelist_account!(caller); - }: _(RawOrigin::Signed(caller.clone()), caller_lookup, ref_index) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller.clone()), caller_lookup, ref_index); + let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, _ => return Err("Votes are not direct".into()), }; assert_eq!(votes.len(), (r - 1) as usize, "Vote was not removed"); + Ok(()) } - set_external_metadata { + #[benchmark] + fn set_external_metadata() -> Result<(), BenchmarkError> { let origin = T::ExternalOrigin::try_successful_origin() .expect("ExternalOrigin has no successful origin required for the benchmark"); - assert_ok!( - Democracy::::external_propose(origin.clone(), make_proposal::(0)) - ); + assert_ok!(Democracy::::external_propose(origin.clone(), make_proposal::(0))); let owner = MetadataOwner::External; let hash = note_preimage::(); - }: set_metadata(origin, owner.clone(), Some(hash)) - verify { - assert_last_event::(crate::Event::MetadataSet { - owner, - hash, - }.into()); + + #[extrinsic_call] + set_metadata(origin as T::RuntimeOrigin, owner.clone(), Some(hash)); + + assert_last_event::(crate::Event::MetadataSet { owner, hash }.into()); + Ok(()) } - clear_external_metadata { + #[benchmark] + fn clear_external_metadata() -> Result<(), BenchmarkError> { let origin = T::ExternalOrigin::try_successful_origin() .expect("ExternalOrigin has no successful origin required for the benchmark"); - assert_ok!( - Democracy::::external_propose(origin.clone(), make_proposal::(0)) - ); + assert_ok!(Democracy::::external_propose(origin.clone(), make_proposal::(0))); let owner = MetadataOwner::External; - let proposer = funded_account::("proposer", 0); + let _proposer = funded_account::("proposer", 0); let hash = note_preimage::(); assert_ok!(Democracy::::set_metadata(origin.clone(), owner.clone(), Some(hash))); - }: set_metadata(origin, owner.clone(), None) - verify { - assert_last_event::(crate::Event::MetadataCleared { - owner, - hash, - }.into()); + + #[extrinsic_call] + set_metadata(origin as T::RuntimeOrigin, owner.clone(), None); + + assert_last_event::(crate::Event::MetadataCleared { owner, hash }.into()); + Ok(()) } - set_proposal_metadata { + #[benchmark] + fn set_proposal_metadata() -> Result<(), BenchmarkError> { // Place our proposal at the end to make sure it's worst case. - for i in 0 .. T::MaxProposals::get() { + for i in 0..T::MaxProposals::get() { add_proposal::(i)?; } let owner = MetadataOwner::Proposal(0); let proposer = funded_account::("proposer", 0); let hash = note_preimage::(); - }: set_metadata(RawOrigin::Signed(proposer).into(), owner.clone(), Some(hash)) - verify { - assert_last_event::(crate::Event::MetadataSet { - owner, - hash, - }.into()); + + #[extrinsic_call] + set_metadata(RawOrigin::Signed(proposer), owner.clone(), Some(hash)); + + assert_last_event::(crate::Event::MetadataSet { owner, hash }.into()); + Ok(()) } - clear_proposal_metadata { + #[benchmark] + fn clear_proposal_metadata() -> Result<(), BenchmarkError> { // Place our proposal at the end to make sure it's worst case. - for i in 0 .. T::MaxProposals::get() { + for i in 0..T::MaxProposals::get() { add_proposal::(i)?; } let proposer = funded_account::("proposer", 0); @@ -802,33 +925,36 @@ benchmarks! { assert_ok!(Democracy::::set_metadata( RawOrigin::Signed(proposer.clone()).into(), owner.clone(), - Some(hash))); - }: set_metadata(RawOrigin::Signed(proposer).into(), owner.clone(), None) - verify { - assert_last_event::(crate::Event::MetadataCleared { - owner, - hash, - }.into()); + Some(hash) + )); + + #[extrinsic_call] + set_metadata::(RawOrigin::Signed(proposer), owner.clone(), None); + + assert_last_event::(crate::Event::MetadataCleared { owner, hash }.into()); + Ok(()) } - set_referendum_metadata { + #[benchmark] + fn set_referendum_metadata() -> Result<(), BenchmarkError> { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, ReferendumInfo::Finished { end: BlockNumberFor::::zero(), approved: true }, ); let owner = MetadataOwner::Referendum(0); - let caller = funded_account::("caller", 0); + let _caller = funded_account::("caller", 0); let hash = note_preimage::(); - }: set_metadata(RawOrigin::Root.into(), owner.clone(), Some(hash)) - verify { - assert_last_event::(crate::Event::MetadataSet { - owner, - hash, - }.into()); + + #[extrinsic_call] + set_metadata::(RawOrigin::Root, owner.clone(), Some(hash)); + + assert_last_event::(crate::Event::MetadataSet { owner, hash }.into()); + Ok(()) } - clear_referendum_metadata { + #[benchmark] + fn clear_referendum_metadata() -> Result<(), BenchmarkError> { // create not ongoing referendum. ReferendumInfoOf::::insert( 0, @@ -838,17 +964,13 @@ benchmarks! { let hash = note_preimage::(); MetadataOf::::insert(owner.clone(), hash); let caller = funded_account::("caller", 0); - }: set_metadata(RawOrigin::Signed(caller).into(), owner.clone(), None) - verify { - assert_last_event::(crate::Event::MetadataCleared { - owner, - hash, - }.into()); + + #[extrinsic_call] + set_metadata::(RawOrigin::Signed(caller), owner.clone(), None); + + assert_last_event::(crate::Event::MetadataCleared { owner, hash }.into()); + Ok(()) } - impl_benchmark_test_suite!( - Democracy, - crate::tests::new_test_ext(), - crate::tests::Test - ); + impl_benchmark_test_suite!(Democracy, crate::tests::new_test_ext(), crate::tests::Test); } diff --git a/substrate/frame/democracy/src/weights.rs b/substrate/frame/democracy/src/weights.rs index 0a2200a78b5d..765ee57f0eb3 100644 --- a/substrate/frame/democracy/src/weights.rs +++ b/substrate/frame/democracy/src/weights.rs @@ -18,27 +18,25 @@ //! Autogenerated weights for `pallet_democracy` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// ./target/production/substrate-node +// target/production/substrate-node // benchmark // pallet -// --chain=dev // --steps=50 // --repeat=20 -// --pallet=pallet_democracy -// --no-storage-info -// --no-median-slopes -// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --output=./substrate/frame/democracy/src/weights.rs +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_democracy +// --chain=dev // --header=./substrate/HEADER-APACHE2 +// --output=./substrate/frame/democracy/src/weights.rs // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -96,8 +94,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4834` // Estimated: `18187` - // Minimum execution time: 48_991_000 picoseconds. - Weight::from_parts(50_476_000, 18187) + // Minimum execution time: 49_681_000 picoseconds. + Weight::from_parts(51_578_000, 18187) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -107,8 +105,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3589` // Estimated: `6695` - // Minimum execution time: 43_129_000 picoseconds. - Weight::from_parts(45_076_000, 6695) + // Minimum execution time: 45_001_000 picoseconds. + Weight::from_parts(45_990_000, 6695) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -124,8 +122,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3503` // Estimated: `7260` - // Minimum execution time: 63_761_000 picoseconds. - Weight::from_parts(65_424_000, 7260) + // Minimum execution time: 65_095_000 picoseconds. + Weight::from_parts(67_484_000, 7260) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -141,8 +139,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3525` // Estimated: `7260` - // Minimum execution time: 66_543_000 picoseconds. - Weight::from_parts(69_537_000, 7260) + // Minimum execution time: 66_877_000 picoseconds. + Weight::from_parts(68_910_000, 7260) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -156,8 +154,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `399` // Estimated: `3666` - // Minimum execution time: 28_934_000 picoseconds. - Weight::from_parts(29_982_000, 3666) + // Minimum execution time: 29_312_000 picoseconds. + Weight::from_parts(30_040_000, 3666) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -179,8 +177,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `5943` // Estimated: `18187` - // Minimum execution time: 108_004_000 picoseconds. - Weight::from_parts(110_779_000, 18187) + // Minimum execution time: 107_932_000 picoseconds. + Weight::from_parts(108_940_000, 18187) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -192,8 +190,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3449` // Estimated: `6703` - // Minimum execution time: 17_630_000 picoseconds. - Weight::from_parts(18_419_000, 6703) + // Minimum execution time: 17_703_000 picoseconds. + Weight::from_parts(18_188_000, 6703) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -203,8 +201,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_572_000 picoseconds. - Weight::from_parts(2_810_000, 0) + // Minimum execution time: 2_672_000 picoseconds. + Weight::from_parts(2_814_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) @@ -213,8 +211,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_628_000 picoseconds. - Weight::from_parts(2_724_000, 0) + // Minimum execution time: 2_584_000 picoseconds. + Weight::from_parts(2_846_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) @@ -229,8 +227,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 24_624_000 picoseconds. - Weight::from_parts(25_518_000, 3518) + // Minimum execution time: 24_603_000 picoseconds. + Weight::from_parts(25_407_000, 3518) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -244,8 +242,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3552` // Estimated: `6703` - // Minimum execution time: 31_786_000 picoseconds. - Weight::from_parts(32_786_000, 6703) + // Minimum execution time: 31_721_000 picoseconds. + Weight::from_parts(32_785_000, 6703) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -261,8 +259,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `5854` // Estimated: `18187` - // Minimum execution time: 87_352_000 picoseconds. - Weight::from_parts(89_670_000, 18187) + // Minimum execution time: 86_981_000 picoseconds. + Weight::from_parts(89_140_000, 18187) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -274,8 +272,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `304` // Estimated: `3518` - // Minimum execution time: 17_561_000 picoseconds. - Weight::from_parts(18_345_000, 3518) + // Minimum execution time: 17_465_000 picoseconds. + Weight::from_parts(18_018_000, 3518) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -290,10 +288,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `1489 + r * (2676 ±0)` - // Minimum execution time: 6_801_000 picoseconds. - Weight::from_parts(8_524_132, 1489) - // Standard Error: 10_028 - .saturating_add(Weight::from_parts(4_073_619, 0).saturating_mul(r.into())) + // Minimum execution time: 6_746_000 picoseconds. + Weight::from_parts(7_381_932, 1489) + // Standard Error: 10_311 + .saturating_add(Weight::from_parts(4_107_935, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -316,10 +314,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `18187 + r * (2676 ±0)` - // Minimum execution time: 10_160_000 picoseconds. - Weight::from_parts(11_472_067, 18187) - // Standard Error: 10_730 - .saturating_add(Weight::from_parts(4_104_654, 0).saturating_mul(r.into())) + // Minimum execution time: 9_766_000 picoseconds. + Weight::from_parts(9_788_895, 18187) + // Standard Error: 11_913 + .saturating_add(Weight::from_parts(4_130_441, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -338,10 +336,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `863 + r * (108 ±0)` // Estimated: `19800 + r * (2676 ±0)` - // Minimum execution time: 49_741_000 picoseconds. - Weight::from_parts(53_544_421, 19800) - // Standard Error: 11_984 - .saturating_add(Weight::from_parts(5_123_946, 0).saturating_mul(r.into())) + // Minimum execution time: 48_992_000 picoseconds. + Weight::from_parts(55_524_560, 19800) + // Standard Error: 11_278 + .saturating_add(Weight::from_parts(4_987_109, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -357,10 +355,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `526 + r * (108 ±0)` // Estimated: `13530 + r * (2676 ±0)` - // Minimum execution time: 24_977_000 picoseconds. - Weight::from_parts(22_449_729, 13530) - // Standard Error: 10_846 - .saturating_add(Weight::from_parts(5_058_209, 0).saturating_mul(r.into())) + // Minimum execution time: 23_828_000 picoseconds. + Weight::from_parts(23_638_577, 13530) + // Standard Error: 10_946 + .saturating_add(Weight::from_parts(4_971_245, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -373,8 +371,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_700_000 picoseconds. - Weight::from_parts(3_028_000, 0) + // Minimum execution time: 2_759_000 picoseconds. + Weight::from_parts(2_850_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) @@ -390,10 +388,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `596` // Estimated: `7260` - // Minimum execution time: 31_183_000 picoseconds. - Weight::from_parts(43_105_470, 7260) - // Standard Error: 3_096 - .saturating_add(Weight::from_parts(98_571, 0).saturating_mul(r.into())) + // Minimum execution time: 30_804_000 picoseconds. + Weight::from_parts(42_750_018, 7260) + // Standard Error: 3_300 + .saturating_add(Weight::from_parts(99_997, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -410,10 +408,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `597 + r * (22 ±0)` // Estimated: `7260` - // Minimum execution time: 39_672_000 picoseconds. - Weight::from_parts(44_120_387, 7260) - // Standard Error: 1_890 - .saturating_add(Weight::from_parts(130_089, 0).saturating_mul(r.into())) + // Minimum execution time: 39_946_000 picoseconds. + Weight::from_parts(44_500_306, 7260) + // Standard Error: 1_914 + .saturating_add(Weight::from_parts(116_987, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -426,10 +424,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 21_396_000 picoseconds. - Weight::from_parts(26_151_983, 7260) - // Standard Error: 2_052 - .saturating_add(Weight::from_parts(131_709, 0).saturating_mul(r.into())) + // Minimum execution time: 21_677_000 picoseconds. + Weight::from_parts(25_329_290, 7260) + // Standard Error: 1_998 + .saturating_add(Weight::from_parts(157_800, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -442,10 +440,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 21_425_000 picoseconds. - Weight::from_parts(26_335_367, 7260) - // Standard Error: 2_170 - .saturating_add(Weight::from_parts(130_502, 0).saturating_mul(r.into())) + // Minimum execution time: 21_777_000 picoseconds. + Weight::from_parts(26_635_600, 7260) + // Standard Error: 2_697 + .saturating_add(Weight::from_parts(135_641, 0).saturating_mul(r.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -461,8 +459,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3556` - // Minimum execution time: 19_765_000 picoseconds. - Weight::from_parts(20_266_000, 3556) + // Minimum execution time: 19_914_000 picoseconds. + Weight::from_parts(20_450_000, 3556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -474,8 +472,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 16_560_000 picoseconds. - Weight::from_parts(17_277_000, 3518) + // Minimum execution time: 16_212_000 picoseconds. + Weight::from_parts(16_745_000, 3518) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -491,8 +489,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4883` // Estimated: `18187` - // Minimum execution time: 47_711_000 picoseconds. - Weight::from_parts(48_669_000, 18187) + // Minimum execution time: 47_225_000 picoseconds. + Weight::from_parts(47_976_000, 18187) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -504,8 +502,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4855` // Estimated: `18187` - // Minimum execution time: 43_809_000 picoseconds. - Weight::from_parts(45_698_000, 18187) + // Minimum execution time: 43_140_000 picoseconds. + Weight::from_parts(43_924_000, 18187) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -519,8 +517,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 14_736_000 picoseconds. - Weight::from_parts(15_191_000, 3556) + // Minimum execution time: 14_614_000 picoseconds. + Weight::from_parts(15_376_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -532,8 +530,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `335` // Estimated: `3666` - // Minimum execution time: 22_803_000 picoseconds. - Weight::from_parts(23_732_000, 3666) + // Minimum execution time: 22_588_000 picoseconds. + Weight::from_parts(23_267_000, 3666) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -553,8 +551,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4834` // Estimated: `18187` - // Minimum execution time: 48_991_000 picoseconds. - Weight::from_parts(50_476_000, 18187) + // Minimum execution time: 49_681_000 picoseconds. + Weight::from_parts(51_578_000, 18187) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -564,8 +562,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3589` // Estimated: `6695` - // Minimum execution time: 43_129_000 picoseconds. - Weight::from_parts(45_076_000, 6695) + // Minimum execution time: 45_001_000 picoseconds. + Weight::from_parts(45_990_000, 6695) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -581,8 +579,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3503` // Estimated: `7260` - // Minimum execution time: 63_761_000 picoseconds. - Weight::from_parts(65_424_000, 7260) + // Minimum execution time: 65_095_000 picoseconds. + Weight::from_parts(67_484_000, 7260) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -598,8 +596,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3525` // Estimated: `7260` - // Minimum execution time: 66_543_000 picoseconds. - Weight::from_parts(69_537_000, 7260) + // Minimum execution time: 66_877_000 picoseconds. + Weight::from_parts(68_910_000, 7260) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -613,8 +611,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `399` // Estimated: `3666` - // Minimum execution time: 28_934_000 picoseconds. - Weight::from_parts(29_982_000, 3666) + // Minimum execution time: 29_312_000 picoseconds. + Weight::from_parts(30_040_000, 3666) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -636,8 +634,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `5943` // Estimated: `18187` - // Minimum execution time: 108_004_000 picoseconds. - Weight::from_parts(110_779_000, 18187) + // Minimum execution time: 107_932_000 picoseconds. + Weight::from_parts(108_940_000, 18187) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -649,8 +647,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3449` // Estimated: `6703` - // Minimum execution time: 17_630_000 picoseconds. - Weight::from_parts(18_419_000, 6703) + // Minimum execution time: 17_703_000 picoseconds. + Weight::from_parts(18_188_000, 6703) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -660,8 +658,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_572_000 picoseconds. - Weight::from_parts(2_810_000, 0) + // Minimum execution time: 2_672_000 picoseconds. + Weight::from_parts(2_814_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:0 w:1) @@ -670,8 +668,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_628_000 picoseconds. - Weight::from_parts(2_724_000, 0) + // Minimum execution time: 2_584_000 picoseconds. + Weight::from_parts(2_846_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::NextExternal` (r:1 w:1) @@ -686,8 +684,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 24_624_000 picoseconds. - Weight::from_parts(25_518_000, 3518) + // Minimum execution time: 24_603_000 picoseconds. + Weight::from_parts(25_407_000, 3518) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -701,8 +699,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3552` // Estimated: `6703` - // Minimum execution time: 31_786_000 picoseconds. - Weight::from_parts(32_786_000, 6703) + // Minimum execution time: 31_721_000 picoseconds. + Weight::from_parts(32_785_000, 6703) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -718,8 +716,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `5854` // Estimated: `18187` - // Minimum execution time: 87_352_000 picoseconds. - Weight::from_parts(89_670_000, 18187) + // Minimum execution time: 86_981_000 picoseconds. + Weight::from_parts(89_140_000, 18187) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -731,8 +729,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `304` // Estimated: `3518` - // Minimum execution time: 17_561_000 picoseconds. - Weight::from_parts(18_345_000, 3518) + // Minimum execution time: 17_465_000 picoseconds. + Weight::from_parts(18_018_000, 3518) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -747,10 +745,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `1489 + r * (2676 ±0)` - // Minimum execution time: 6_801_000 picoseconds. - Weight::from_parts(8_524_132, 1489) - // Standard Error: 10_028 - .saturating_add(Weight::from_parts(4_073_619, 0).saturating_mul(r.into())) + // Minimum execution time: 6_746_000 picoseconds. + Weight::from_parts(7_381_932, 1489) + // Standard Error: 10_311 + .saturating_add(Weight::from_parts(4_107_935, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -773,10 +771,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `277 + r * (86 ±0)` // Estimated: `18187 + r * (2676 ±0)` - // Minimum execution time: 10_160_000 picoseconds. - Weight::from_parts(11_472_067, 18187) - // Standard Error: 10_730 - .saturating_add(Weight::from_parts(4_104_654, 0).saturating_mul(r.into())) + // Minimum execution time: 9_766_000 picoseconds. + Weight::from_parts(9_788_895, 18187) + // Standard Error: 11_913 + .saturating_add(Weight::from_parts(4_130_441, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -795,10 +793,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `863 + r * (108 ±0)` // Estimated: `19800 + r * (2676 ±0)` - // Minimum execution time: 49_741_000 picoseconds. - Weight::from_parts(53_544_421, 19800) - // Standard Error: 11_984 - .saturating_add(Weight::from_parts(5_123_946, 0).saturating_mul(r.into())) + // Minimum execution time: 48_992_000 picoseconds. + Weight::from_parts(55_524_560, 19800) + // Standard Error: 11_278 + .saturating_add(Weight::from_parts(4_987_109, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -814,10 +812,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `526 + r * (108 ±0)` // Estimated: `13530 + r * (2676 ±0)` - // Minimum execution time: 24_977_000 picoseconds. - Weight::from_parts(22_449_729, 13530) - // Standard Error: 10_846 - .saturating_add(Weight::from_parts(5_058_209, 0).saturating_mul(r.into())) + // Minimum execution time: 23_828_000 picoseconds. + Weight::from_parts(23_638_577, 13530) + // Standard Error: 10_946 + .saturating_add(Weight::from_parts(4_971_245, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -830,8 +828,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_700_000 picoseconds. - Weight::from_parts(3_028_000, 0) + // Minimum execution time: 2_759_000 picoseconds. + Weight::from_parts(2_850_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Democracy::VotingOf` (r:1 w:1) @@ -847,10 +845,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `596` // Estimated: `7260` - // Minimum execution time: 31_183_000 picoseconds. - Weight::from_parts(43_105_470, 7260) - // Standard Error: 3_096 - .saturating_add(Weight::from_parts(98_571, 0).saturating_mul(r.into())) + // Minimum execution time: 30_804_000 picoseconds. + Weight::from_parts(42_750_018, 7260) + // Standard Error: 3_300 + .saturating_add(Weight::from_parts(99_997, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -867,10 +865,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `597 + r * (22 ±0)` // Estimated: `7260` - // Minimum execution time: 39_672_000 picoseconds. - Weight::from_parts(44_120_387, 7260) - // Standard Error: 1_890 - .saturating_add(Weight::from_parts(130_089, 0).saturating_mul(r.into())) + // Minimum execution time: 39_946_000 picoseconds. + Weight::from_parts(44_500_306, 7260) + // Standard Error: 1_914 + .saturating_add(Weight::from_parts(116_987, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -883,10 +881,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 21_396_000 picoseconds. - Weight::from_parts(26_151_983, 7260) - // Standard Error: 2_052 - .saturating_add(Weight::from_parts(131_709, 0).saturating_mul(r.into())) + // Minimum execution time: 21_677_000 picoseconds. + Weight::from_parts(25_329_290, 7260) + // Standard Error: 1_998 + .saturating_add(Weight::from_parts(157_800, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -899,10 +897,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `761 + r * (26 ±0)` // Estimated: `7260` - // Minimum execution time: 21_425_000 picoseconds. - Weight::from_parts(26_335_367, 7260) - // Standard Error: 2_170 - .saturating_add(Weight::from_parts(130_502, 0).saturating_mul(r.into())) + // Minimum execution time: 21_777_000 picoseconds. + Weight::from_parts(26_635_600, 7260) + // Standard Error: 2_697 + .saturating_add(Weight::from_parts(135_641, 0).saturating_mul(r.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -918,8 +916,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `351` // Estimated: `3556` - // Minimum execution time: 19_765_000 picoseconds. - Weight::from_parts(20_266_000, 3556) + // Minimum execution time: 19_914_000 picoseconds. + Weight::from_parts(20_450_000, 3556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -931,8 +929,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319` // Estimated: `3518` - // Minimum execution time: 16_560_000 picoseconds. - Weight::from_parts(17_277_000, 3518) + // Minimum execution time: 16_212_000 picoseconds. + Weight::from_parts(16_745_000, 3518) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -948,8 +946,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4883` // Estimated: `18187` - // Minimum execution time: 47_711_000 picoseconds. - Weight::from_parts(48_669_000, 18187) + // Minimum execution time: 47_225_000 picoseconds. + Weight::from_parts(47_976_000, 18187) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -961,8 +959,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4855` // Estimated: `18187` - // Minimum execution time: 43_809_000 picoseconds. - Weight::from_parts(45_698_000, 18187) + // Minimum execution time: 43_140_000 picoseconds. + Weight::from_parts(43_924_000, 18187) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -976,8 +974,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 14_736_000 picoseconds. - Weight::from_parts(15_191_000, 3556) + // Minimum execution time: 14_614_000 picoseconds. + Weight::from_parts(15_376_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -989,8 +987,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `335` // Estimated: `3666` - // Minimum execution time: 22_803_000 picoseconds. - Weight::from_parts(23_732_000, 3666) + // Minimum execution time: 22_588_000 picoseconds. + Weight::from_parts(23_267_000, 3666) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } From cccf3417e5f0dace12a0da2ee157f1f284651700 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Tue, 19 Nov 2024 22:02:12 +0000 Subject: [PATCH 113/166] Forward logging directives to Polkadot workers (#6534) This pull request forward all the logging directives given to the node via `RUST_LOG` or `-l` to the workers, instead of only forwarding `RUST_LOG`. --------- Co-authored-by: GitHub Action --- Cargo.lock | 1 + polkadot/node/core/pvf/Cargo.toml | 1 + polkadot/node/core/pvf/src/worker_interface.rs | 6 ++---- prdoc/pr_6534.prdoc | 10 ++++++++++ substrate/client/tracing/src/logging/directives.rs | 7 ++++++- 5 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 prdoc/pr_6534.prdoc diff --git a/Cargo.lock b/Cargo.lock index 02d7da8f7657..330c2563d976 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17553,6 +17553,7 @@ dependencies = [ "rococo-runtime", "rusty-fork", "sc-sysinfo", + "sc-tracing", "slotmap", "sp-core 28.0.0", "sp-maybe-compressed-blob 11.0.0", diff --git a/polkadot/node/core/pvf/Cargo.toml b/polkadot/node/core/pvf/Cargo.toml index a9f97c308f26..37d5878ea597 100644 --- a/polkadot/node/core/pvf/Cargo.toml +++ b/polkadot/node/core/pvf/Cargo.toml @@ -38,6 +38,7 @@ polkadot-node-primitives = { workspace = true, default-features = true } polkadot-node-subsystem = { workspace = true, default-features = true } polkadot-primitives = { workspace = true, default-features = true } +sc-tracing = { workspace = true } sp-core = { workspace = true, default-features = true } sp-maybe-compressed-blob = { optional = true, workspace = true, default-features = true } polkadot-node-core-pvf-prepare-worker = { optional = true, workspace = true, default-features = true } diff --git a/polkadot/node/core/pvf/src/worker_interface.rs b/polkadot/node/core/pvf/src/worker_interface.rs index e63778d4692f..f279fbb53544 100644 --- a/polkadot/node/core/pvf/src/worker_interface.rs +++ b/polkadot/node/core/pvf/src/worker_interface.rs @@ -237,10 +237,8 @@ impl WorkerHandle { // Clear all env vars from the spawned process. let mut command = process::Command::new(program.as_ref()); command.env_clear(); - // Add back any env vars we want to keep. - if let Ok(value) = std::env::var("RUST_LOG") { - command.env("RUST_LOG", value); - } + + command.env("RUST_LOG", sc_tracing::logging::get_directives().join(",")); let mut child = command .args(extra_args) diff --git a/prdoc/pr_6534.prdoc b/prdoc/pr_6534.prdoc new file mode 100644 index 000000000000..7a92fe3c857b --- /dev/null +++ b/prdoc/pr_6534.prdoc @@ -0,0 +1,10 @@ +title: Forward logging directives to Polkadot workers +doc: +- audience: Node Dev + description: |- + This pull request forward all the logging directives given to the node via `RUST_LOG` or `-l` to the workers, instead of only forwarding `RUST_LOG`. +crates: +- name: polkadot-node-core-pvf + bump: patch +- name: sc-tracing + bump: patch diff --git a/substrate/client/tracing/src/logging/directives.rs b/substrate/client/tracing/src/logging/directives.rs index a99e9c4c8909..811511bb20f5 100644 --- a/substrate/client/tracing/src/logging/directives.rs +++ b/substrate/client/tracing/src/logging/directives.rs @@ -40,7 +40,7 @@ pub(crate) fn add_default_directives(directives: &str) { add_directives(directives); } -/// Add directives to current directives +/// Add directives to current directives. pub fn add_directives(directives: &str) { CURRENT_DIRECTIVES .get_or_init(|| Mutex::new(Vec::new())) @@ -48,6 +48,11 @@ pub fn add_directives(directives: &str) { .push(directives.to_owned()); } +/// Returns the current directives. +pub fn get_directives() -> Vec { + CURRENT_DIRECTIVES.get_or_init(|| Mutex::new(Vec::new())).lock().clone() +} + /// Parse `Directive` and add to default directives if successful. /// /// Ensures the supplied directive will be restored when resetting the log filter. From ce20d0a5a1bdaf2e2776cf159656b31073da07e4 Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Wed, 20 Nov 2024 07:34:43 +0800 Subject: [PATCH 114/166] Support block gap created by fast sync (#5703) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This is part 2 of https://github.com/paritytech/polkadot-sdk/issues/5406#issuecomment-2325064863, properly handling the block gap generated during fast sync. Although #5406 remains unresolved due to the known issues in #5663, I decided to open up this PR earlier than later to speed up the overall progress. I've tested the fast sync locally with this PR, and it appears to be functioning well. (I was doing a fast sync from a discontinued archive node locally, thus the issue highlighted in https://github.com/paritytech/polkadot-sdk/pull/5663#discussion_r1752124039 was bypassed exactly.) Once the edge cases in #5663 are addressed, we can move forward by removing the body attribute from the LightState block request and complete the work on #5406. The changes in this PR are incremental, so reviewing commit by commit should provide the best clarity. cc @dmitry-markin --------- Co-authored-by: Bastian Köcher --- prdoc/pr_5703.prdoc | 13 +++++ substrate/client/db/src/lib.rs | 100 +++++++++++++++++++++++---------- 2 files changed, 83 insertions(+), 30 deletions(-) create mode 100644 prdoc/pr_5703.prdoc diff --git a/prdoc/pr_5703.prdoc b/prdoc/pr_5703.prdoc new file mode 100644 index 000000000000..3cef4468a87d --- /dev/null +++ b/prdoc/pr_5703.prdoc @@ -0,0 +1,13 @@ +title: Properly handle block gap created by fast sync + +doc: + - audience: Node Dev + description: | + Implements support for handling block gaps generated during fast sync. This includes managing the creation, + updating, and removal of block gaps. + Note that this feature is not fully activated until the `body` attribute is removed from the `LightState` + block request in chain sync, which will occur after the issue #5406 is resolved. + +crates: + - name: sc-client-db + bump: patch diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index cec981c05602..092101945107 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -1486,6 +1486,7 @@ impl Backend { .map(|(n, _)| n) .unwrap_or(Zero::zero()); let existing_header = number <= highest_leaf && self.blockchain.header(hash)?.is_some(); + let existing_body = pending_block.body.is_some(); // blocks are keyed by number + hash. let lookup_key = utils::number_and_hash_to_lookup_key(number, hash)?; @@ -1677,6 +1678,23 @@ impl Backend { children, ); } + } + + let should_check_block_gap = !existing_header || !existing_body; + + if should_check_block_gap { + let insert_new_gap = + |transaction: &mut Transaction, + new_gap: BlockGap>, + block_gap: &mut Option>>| { + transaction.set(columns::META, meta_keys::BLOCK_GAP, &new_gap.encode()); + transaction.set( + columns::META, + meta_keys::BLOCK_GAP_VERSION, + &BLOCK_GAP_CURRENT_VERSION.encode(), + ); + block_gap.replace(new_gap); + }; if let Some(mut gap) = block_gap { match gap.gap_type { @@ -1695,43 +1713,65 @@ impl Backend { block_gap = None; debug!(target: "db", "Removed block gap."); } else { - block_gap = Some(gap); + insert_new_gap(&mut transaction, gap, &mut block_gap); debug!(target: "db", "Update block gap. {block_gap:?}"); - transaction.set( - columns::META, - meta_keys::BLOCK_GAP, - &gap.encode(), - ); - transaction.set( - columns::META, - meta_keys::BLOCK_GAP_VERSION, - &BLOCK_GAP_CURRENT_VERSION.encode(), - ); } block_gap_updated = true; }, BlockGapType::MissingBody => { - unreachable!("Unsupported block gap. TODO: https://github.com/paritytech/polkadot-sdk/issues/5406") + // Gap increased when syncing the header chain during fast sync. + if number == gap.end + One::one() && !existing_body { + gap.end += One::one(); + utils::insert_number_to_key_mapping( + &mut transaction, + columns::KEY_LOOKUP, + number, + hash, + )?; + insert_new_gap(&mut transaction, gap, &mut block_gap); + debug!(target: "db", "Update block gap. {block_gap:?}"); + block_gap_updated = true; + // Gap decreased when downloading the full blocks. + } else if number == gap.start && existing_body { + gap.start += One::one(); + if gap.start > gap.end { + transaction.remove(columns::META, meta_keys::BLOCK_GAP); + transaction.remove(columns::META, meta_keys::BLOCK_GAP_VERSION); + block_gap = None; + debug!(target: "db", "Removed block gap."); + } else { + insert_new_gap(&mut transaction, gap, &mut block_gap); + debug!(target: "db", "Update block gap. {block_gap:?}"); + } + block_gap_updated = true; + } }, } - } else if operation.create_gap && - number > best_num + One::one() && - self.blockchain.header(parent_hash)?.is_none() - { - let gap = BlockGap { - start: best_num + One::one(), - end: number - One::one(), - gap_type: BlockGapType::MissingHeaderAndBody, - }; - transaction.set(columns::META, meta_keys::BLOCK_GAP, &gap.encode()); - transaction.set( - columns::META, - meta_keys::BLOCK_GAP_VERSION, - &BLOCK_GAP_CURRENT_VERSION.encode(), - ); - block_gap = Some(gap); - block_gap_updated = true; - debug!(target: "db", "Detected block gap {block_gap:?}"); + } else if operation.create_gap { + if number > best_num + One::one() && + self.blockchain.header(parent_hash)?.is_none() + { + let gap = BlockGap { + start: best_num + One::one(), + end: number - One::one(), + gap_type: BlockGapType::MissingHeaderAndBody, + }; + insert_new_gap(&mut transaction, gap, &mut block_gap); + block_gap_updated = true; + debug!(target: "db", "Detected block gap (warp sync) {block_gap:?}"); + } else if number == best_num + One::one() && + self.blockchain.header(parent_hash)?.is_some() && + !existing_body + { + let gap = BlockGap { + start: number, + end: number, + gap_type: BlockGapType::MissingBody, + }; + insert_new_gap(&mut transaction, gap, &mut block_gap); + block_gap_updated = true; + debug!(target: "db", "Detected block gap (fast sync) {block_gap:?}"); + } } } From 07a593338fd2fd221c7165c0da308dc8fbf3f985 Mon Sep 17 00:00:00 2001 From: Liu-Cheng Xu Date: Wed, 20 Nov 2024 07:57:11 +0800 Subject: [PATCH 115/166] Pure state sync refactoring (part-2) (#6521) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR is the second part of the pure state sync refactoring, encapsulating `StateSyncMetadata` as a separate entity. Now it's pretty straightforward what changes are needed for the persistent state sync as observed in the struct `StateSync`: - `state`: redirect directly to the DB layer instead of being accumulated in the memory. - `metadata`: handle the state sync metadata on disk whenever the state is forwarded to the DB, resume an ongoing state sync on a restart, etc. --------- Co-authored-by: Bastian Köcher Co-authored-by: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> --- prdoc/pr_6521.prdoc | 10 ++ .../network/sync/src/strategy/state_sync.rs | 136 ++++++++++-------- 2 files changed, 90 insertions(+), 56 deletions(-) create mode 100644 prdoc/pr_6521.prdoc diff --git a/prdoc/pr_6521.prdoc b/prdoc/pr_6521.prdoc new file mode 100644 index 000000000000..6f4acf8d028b --- /dev/null +++ b/prdoc/pr_6521.prdoc @@ -0,0 +1,10 @@ +title: Pure state sync refactoring (part-2) + +doc: +- audience: Node Dev + description: | + This is the last part of the pure refactoring of state sync, focusing on encapsulating `StateSyncMetadata` as a separate entity. + +crates: +- name: sc-network-sync + bump: none diff --git a/substrate/client/network/sync/src/strategy/state_sync.rs b/substrate/client/network/sync/src/strategy/state_sync.rs index 7a0cc1191609..47d859a1b7c6 100644 --- a/substrate/client/network/sync/src/strategy/state_sync.rs +++ b/substrate/client/network/sync/src/strategy/state_sync.rs @@ -89,22 +89,62 @@ pub enum ImportResult { BadResponse, } -/// State sync state machine. Accumulates partial state data until it -/// is ready to be imported. -pub struct StateSync { - target_block: B::Hash, +struct StateSyncMetadata { + last_key: SmallVec<[Vec; 2]>, target_header: B::Header, - target_root: B::Hash, target_body: Option>, target_justifications: Option, - last_key: SmallVec<[Vec; 2]>, - state: HashMap, (Vec<(Vec, Vec)>, Vec>)>, complete: bool, - client: Arc, imported_bytes: u64, skip_proof: bool, } +impl StateSyncMetadata { + fn target_hash(&self) -> B::Hash { + self.target_header.hash() + } + + /// Returns target block number. + fn target_number(&self) -> NumberFor { + *self.target_header.number() + } + + fn target_root(&self) -> B::Hash { + *self.target_header.state_root() + } + + fn next_request(&self) -> StateRequest { + StateRequest { + block: self.target_hash().encode(), + start: self.last_key.clone().into_vec(), + no_proof: self.skip_proof, + } + } + + fn progress(&self) -> StateSyncProgress { + let cursor = *self.last_key.get(0).and_then(|last| last.get(0)).unwrap_or(&0u8); + let percent_done = cursor as u32 * 100 / 256; + StateSyncProgress { + percentage: percent_done, + size: self.imported_bytes, + phase: if self.complete { + StateSyncPhase::ImportingState + } else { + StateSyncPhase::DownloadingState + }, + } + } +} + +/// State sync state machine. +/// +/// Accumulates partial state data until it is ready to be imported. +pub struct StateSync { + metadata: StateSyncMetadata, + state: HashMap, (Vec<(Vec, Vec)>, Vec>)>, + client: Arc, +} + impl StateSync where B: BlockT, @@ -120,16 +160,16 @@ where ) -> Self { Self { client, - target_block: target_header.hash(), - target_root: *target_header.state_root(), - target_header, - target_body, - target_justifications, - last_key: SmallVec::default(), + metadata: StateSyncMetadata { + last_key: SmallVec::default(), + target_header, + target_body, + target_justifications, + complete: false, + imported_bytes: 0, + skip_proof, + }, state: HashMap::default(), - complete: false, - imported_bytes: 0, - skip_proof, } } @@ -155,7 +195,7 @@ where if is_top && well_known_keys::is_child_storage_key(key.as_slice()) { child_storage_roots.push((value, key)); } else { - self.imported_bytes += key.len() as u64; + self.metadata.imported_bytes += key.len() as u64; entry.0.push((key, value)); } } @@ -177,11 +217,11 @@ where // the parent cursor stays valid. // Empty parent trie content only happens when all the response content // is part of a single child trie. - if self.last_key.len() == 2 && response.entries[0].entries.is_empty() { + if self.metadata.last_key.len() == 2 && response.entries[0].entries.is_empty() { // Do not remove the parent trie position. - self.last_key.pop(); + self.metadata.last_key.pop(); } else { - self.last_key.clear(); + self.metadata.last_key.clear(); } for state in response.entries { debug!( @@ -193,7 +233,7 @@ where if !state.complete { if let Some(e) = state.entries.last() { - self.last_key.push(e.key.clone()); + self.metadata.last_key.push(e.key.clone()); } complete = false; } @@ -219,11 +259,11 @@ where debug!(target: LOG_TARGET, "Bad state response"); return ImportResult::BadResponse } - if !self.skip_proof && response.proof.is_empty() { + if !self.metadata.skip_proof && response.proof.is_empty() { debug!(target: LOG_TARGET, "Missing proof"); return ImportResult::BadResponse } - let complete = if !self.skip_proof { + let complete = if !self.metadata.skip_proof { debug!(target: LOG_TARGET, "Importing state from {} trie nodes", response.proof.len()); let proof_size = response.proof.len() as u64; let proof = match CompactProof::decode(&mut response.proof.as_ref()) { @@ -234,9 +274,9 @@ where }, }; let (values, completed) = match self.client.verify_range_proof( - self.target_root, + self.metadata.target_root(), proof, - self.last_key.as_slice(), + self.metadata.last_key.as_slice(), ) { Err(e) => { debug!( @@ -251,27 +291,25 @@ where debug!(target: LOG_TARGET, "Imported with {} keys", values.len()); let complete = completed == 0; - if !complete && !values.update_last_key(completed, &mut self.last_key) { + if !complete && !values.update_last_key(completed, &mut self.metadata.last_key) { debug!(target: LOG_TARGET, "Error updating key cursor, depth: {}", completed); }; self.process_state_verified(values); - self.imported_bytes += proof_size; + self.metadata.imported_bytes += proof_size; complete } else { self.process_state_unverified(response) }; if complete { - self.complete = true; + self.metadata.complete = true; + let target_hash = self.metadata.target_hash(); ImportResult::Import( - self.target_block, - self.target_header.clone(), - ImportedState { - block: self.target_block, - state: std::mem::take(&mut self.state).into(), - }, - self.target_body.clone(), - self.target_justifications.clone(), + target_hash, + self.metadata.target_header.clone(), + ImportedState { block: target_hash, state: std::mem::take(&mut self.state).into() }, + self.metadata.target_body.clone(), + self.metadata.target_justifications.clone(), ) } else { ImportResult::Continue @@ -280,40 +318,26 @@ where /// Produce next state request. fn next_request(&self) -> StateRequest { - StateRequest { - block: self.target_block.encode(), - start: self.last_key.clone().into_vec(), - no_proof: self.skip_proof, - } + self.metadata.next_request() } /// Check if the state is complete. fn is_complete(&self) -> bool { - self.complete + self.metadata.complete } /// Returns target block number. fn target_number(&self) -> NumberFor { - *self.target_header.number() + self.metadata.target_number() } /// Returns target block hash. fn target_hash(&self) -> B::Hash { - self.target_block + self.metadata.target_hash() } /// Returns state sync estimated progress. fn progress(&self) -> StateSyncProgress { - let cursor = *self.last_key.get(0).and_then(|last| last.get(0)).unwrap_or(&0u8); - let percent_done = cursor as u32 * 100 / 256; - StateSyncProgress { - percentage: percent_done, - size: self.imported_bytes, - phase: if self.complete { - StateSyncPhase::ImportingState - } else { - StateSyncPhase::DownloadingState - }, - } + self.metadata.progress() } } From ca8beaed148a1fc65d181aedeb91b23c262886e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20R=2E=20Bald=C3=A9?= Date: Wed, 20 Nov 2024 01:10:30 +0000 Subject: [PATCH 116/166] Add and test events in `pallet-conviction-voting` (#6544) # Description https://github.com/paritytech/polkadot-sdk/pull/4613 introduced events for `pallet_conviction_voting::{vote, remove_vote, remove_other_vote}`. However: 1. it did not include `unlock` 2. the pallet's unit tests were missing an update ## Integration N/A ## Review Notes This is as https://github.com/paritytech/polkadot-sdk/pull/6261 was, so it is a trivial change. --- prdoc/pr_6544.prdoc | 14 +++ substrate/frame/conviction-voting/src/lib.rs | 7 +- .../frame/conviction-voting/src/tests.rs | 85 ++++++++++++++++--- .../frame/conviction-voting/src/types.rs | 9 +- 4 files changed, 96 insertions(+), 19 deletions(-) create mode 100644 prdoc/pr_6544.prdoc diff --git a/prdoc/pr_6544.prdoc b/prdoc/pr_6544.prdoc new file mode 100644 index 000000000000..f2bc9627697d --- /dev/null +++ b/prdoc/pr_6544.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add and test events to conviction voting pallet + +doc: + - audience: Runtime Dev + description: | + Add event for the unlocking of an expired conviction vote's funds, and test recently added + voting events. + +crates: + - name: pallet-conviction-voting + bump: major diff --git a/substrate/frame/conviction-voting/src/lib.rs b/substrate/frame/conviction-voting/src/lib.rs index 85da1aed3c27..31bd6b85ec86 100644 --- a/substrate/frame/conviction-voting/src/lib.rs +++ b/substrate/frame/conviction-voting/src/lib.rs @@ -171,10 +171,12 @@ pub mod pallet { Delegated(T::AccountId, T::AccountId), /// An \[account\] has cancelled a previous delegation operation. Undelegated(T::AccountId), - /// An account that has voted + /// An account has voted Voted { who: T::AccountId, vote: AccountVote> }, - /// A vote that been removed + /// A vote has been removed VoteRemoved { who: T::AccountId, vote: AccountVote> }, + /// The lockup period of a conviction vote expired, and the funds have been unlocked. + VoteUnlocked { who: T::AccountId, class: ClassOf }, } #[pallet::error] @@ -315,6 +317,7 @@ pub mod pallet { ensure_signed(origin)?; let target = T::Lookup::lookup(target)?; Self::update_lock(&class, &target); + Self::deposit_event(Event::VoteUnlocked { who: target, class }); Ok(()) } diff --git a/substrate/frame/conviction-voting/src/tests.rs b/substrate/frame/conviction-voting/src/tests.rs index 37cdd7a5b338..dd9ee33ee183 100644 --- a/substrate/frame/conviction-voting/src/tests.rs +++ b/substrate/frame/conviction-voting/src/tests.rs @@ -238,27 +238,52 @@ fn basic_stuff() { fn basic_voting_works() { new_test_ext().execute_with(|| { assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(2, 5))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: aye(2, 5), + })); assert_eq!(tally(3), Tally::from_parts(10, 0, 2)); assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(2, 5))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: nay(2, 5), + })); assert_eq!(tally(3), Tally::from_parts(0, 10, 0)); assert_eq!(Balances::usable_balance(1), 8); assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(5, 1))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: aye(5, 1), + })); assert_eq!(tally(3), Tally::from_parts(5, 0, 5)); assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(5, 1))); assert_eq!(tally(3), Tally::from_parts(0, 5, 0)); assert_eq!(Balances::usable_balance(1), 5); assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, aye(10, 0))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: aye(10, 0), + })); assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, nay(10, 0))); assert_eq!(tally(3), Tally::from_parts(0, 1, 0)); assert_eq!(Balances::usable_balance(1), 0); assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), None, 3)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteRemoved { + who: 1, + vote: nay(10, 0), + })); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), class(3), 1)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteUnlocked { + who: 1, + class: class(3), + })); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -267,15 +292,32 @@ fn basic_voting_works() { fn split_voting_works() { new_test_ext().execute_with(|| { assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, split(10, 0))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: split(10, 0), + })); assert_eq!(tally(3), Tally::from_parts(1, 0, 10)); + assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, split(5, 5))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: split(5, 5), + })); assert_eq!(tally(3), Tally::from_parts(0, 0, 5)); assert_eq!(Balances::usable_balance(1), 0); assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), None, 3)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteRemoved { + who: 1, + vote: split(5, 5), + })); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), class(3), 1)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteUnlocked { + who: 1, + class: class(3), + })); assert_eq!(Balances::usable_balance(1), 10); }); } @@ -284,25 +326,48 @@ fn split_voting_works() { fn abstain_voting_works() { new_test_ext().execute_with(|| { assert_ok!(Voting::vote(RuntimeOrigin::signed(1), 3, split_abstain(0, 0, 10))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 1, + vote: split_abstain(0, 0, 10), + })); assert_eq!(tally(3), Tally::from_parts(0, 0, 10)); - assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 3, split_abstain(0, 0, 20))); - assert_eq!(tally(3), Tally::from_parts(0, 0, 30)); - assert_ok!(Voting::vote(RuntimeOrigin::signed(2), 3, split_abstain(10, 0, 10))); - assert_eq!(tally(3), Tally::from_parts(1, 0, 30)); + + assert_ok!(Voting::vote(RuntimeOrigin::signed(6), 3, split_abstain(10, 0, 20))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 6, + vote: split_abstain(10, 0, 20), + })); + assert_eq!(tally(3), Tally::from_parts(1, 0, 40)); + + assert_ok!(Voting::vote(RuntimeOrigin::signed(6), 3, split_abstain(0, 0, 40))); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::Voted { + who: 6, + vote: split_abstain(0, 0, 40), + })); + + assert_eq!(tally(3), Tally::from_parts(0, 0, 50)); assert_eq!(Balances::usable_balance(1), 0); - assert_eq!(Balances::usable_balance(2), 0); + assert_eq!(Balances::usable_balance(6), 20); assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(1), None, 3)); - assert_eq!(tally(3), Tally::from_parts(1, 0, 20)); - - assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(2), None, 3)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteRemoved { + who: 1, + vote: split_abstain(0, 0, 10), + })); + assert_eq!(tally(3), Tally::from_parts(0, 0, 40)); + + assert_ok!(Voting::remove_vote(RuntimeOrigin::signed(6), Some(class(3)), 3)); + System::assert_last_event(tests::RuntimeEvent::Voting(Event::VoteRemoved { + who: 6, + vote: split_abstain(0, 0, 40), + })); assert_eq!(tally(3), Tally::from_parts(0, 0, 0)); assert_ok!(Voting::unlock(RuntimeOrigin::signed(1), class(3), 1)); assert_eq!(Balances::usable_balance(1), 10); - assert_ok!(Voting::unlock(RuntimeOrigin::signed(2), class(3), 2)); - assert_eq!(Balances::usable_balance(2), 20); + assert_ok!(Voting::unlock(RuntimeOrigin::signed(6), class(3), 6)); + assert_eq!(Balances::usable_balance(6), 60); }); } diff --git a/substrate/frame/conviction-voting/src/types.rs b/substrate/frame/conviction-voting/src/types.rs index d6bbb678a14b..aa7dd578fbad 100644 --- a/substrate/frame/conviction-voting/src/types.rs +++ b/substrate/frame/conviction-voting/src/types.rs @@ -117,14 +117,9 @@ impl< pub fn from_parts( ayes_with_conviction: Votes, nays_with_conviction: Votes, - ayes: Votes, + support: Votes, ) -> Self { - Self { - ayes: ayes_with_conviction, - nays: nays_with_conviction, - support: ayes, - dummy: PhantomData, - } + Self { ayes: ayes_with_conviction, nays: nays_with_conviction, support, dummy: PhantomData } } /// Add an account's vote into the tally. From 65a92ba5d444c7278d038c8181086bd9f006f68d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Wed, 20 Nov 2024 11:19:28 +0000 Subject: [PATCH 117/166] Increase default trie cache size to 1GiB (#6546) The default trie cache size before was set to `64MiB`, which is quite low to achieve real speed ups. `1GiB` should be a reasonable number as the requirements for validators/collators/full nodes are much higher when it comes to minimum memory requirements. Also the cache will not use `1GiB` from the start and fills over time. The setting can be changed by setting `--trie-cache-size BYTE_SIZE`. --------- Co-authored-by: GitHub Action --- prdoc/pr_6546.prdoc | 13 +++++++++++++ substrate/client/cli/src/params/import_params.rs | 10 +--------- 2 files changed, 14 insertions(+), 9 deletions(-) create mode 100644 prdoc/pr_6546.prdoc diff --git a/prdoc/pr_6546.prdoc b/prdoc/pr_6546.prdoc new file mode 100644 index 000000000000..353578a7f58f --- /dev/null +++ b/prdoc/pr_6546.prdoc @@ -0,0 +1,13 @@ +title: Increase default trie cache size to 1GiB +doc: +- audience: Node Operator + description: "The default trie cache size before was set to `64MiB`, which is quite\ + \ low to achieve real speed ups. `1GiB` should be a reasonable number as the requirements\ + \ for validators/collators/full nodes are much higher when it comes to minimum\ + \ memory requirements. Also the cache will not use `1GiB` from the start and fills\ + \ over time. The setting can be changed by setting `--trie-cache-size BYTE_SIZE`.\ + The CLI option `--state-cache-size` is also removed, which was not having any effect anymore.\r\ + \n" +crates: +- name: sc-cli + bump: patch diff --git a/substrate/client/cli/src/params/import_params.rs b/substrate/client/cli/src/params/import_params.rs index add7cb4f8505..e4b8b9644feb 100644 --- a/substrate/client/cli/src/params/import_params.rs +++ b/substrate/client/cli/src/params/import_params.rs @@ -78,21 +78,13 @@ pub struct ImportParams { /// Specify the state cache size. /// /// Providing `0` will disable the cache. - #[arg(long, value_name = "Bytes", default_value_t = 67108864)] + #[arg(long, value_name = "Bytes", default_value_t = 1024 * 1024 * 1024)] pub trie_cache_size: usize, - - /// DEPRECATED: switch to `--trie-cache-size`. - #[arg(long)] - state_cache_size: Option, } impl ImportParams { /// Specify the trie cache maximum size. pub fn trie_cache_maximum_size(&self) -> Option { - if self.state_cache_size.is_some() { - eprintln!("`--state-cache-size` was deprecated. Please switch to `--trie-cache-size`."); - } - if self.trie_cache_size == 0 { None } else { From bd0d0cde53272833deaaa0bcaddf95fba290ea77 Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Wed, 20 Nov 2024 13:23:37 +0100 Subject: [PATCH 118/166] Bridges testing improvements (#6536) This PR includes: - Refactored integrity tests to support standalone deployment of `pallet-bridge-messages`. - Refactored the `open_and_close_bridge_works` test case to support multiple scenarios, such as: 1. A local chain opening a bridge. 2. Sibling parachains opening a bridge. 3. The relay chain opening a bridge. - Previously, we added instance support for `pallet-bridge-relayer` but overlooked updating the `DeliveryConfirmationPaymentsAdapter`. --------- Co-authored-by: GitHub Action --- bridges/bin/runtime-common/src/integrity.rs | 95 +++++++++++---- bridges/bin/runtime-common/src/mock.rs | 1 + bridges/modules/relayers/src/lib.rs | 5 +- bridges/modules/relayers/src/mock.rs | 15 +-- .../modules/relayers/src/payment_adapter.rs | 24 ++-- .../src/bridge_to_bulletin_config.rs | 1 - .../src/bridge_to_westend_config.rs | 3 +- .../bridge-hub-rococo/tests/tests.rs | 30 +++-- .../src/bridge_to_rococo_config.rs | 3 +- .../bridge-hub-westend/tests/tests.rs | 15 ++- .../test-utils/src/test_cases/helpers.rs | 112 +++++++++++------- .../test-utils/src/test_cases/mod.rs | 28 +++-- .../parachains/runtimes/test-utils/src/lib.rs | 22 ++-- prdoc/pr_6536.prdoc | 24 ++++ 14 files changed, 251 insertions(+), 127 deletions(-) create mode 100644 prdoc/pr_6536.prdoc diff --git a/bridges/bin/runtime-common/src/integrity.rs b/bridges/bin/runtime-common/src/integrity.rs index 2ff6c4c9165a..535f1a26e5e8 100644 --- a/bridges/bin/runtime-common/src/integrity.rs +++ b/bridges/bin/runtime-common/src/integrity.rs @@ -89,13 +89,11 @@ macro_rules! assert_bridge_messages_pallet_types( /// Macro that combines four other macro calls - `assert_chain_types`, `assert_bridge_types`, /// and `assert_bridge_messages_pallet_types`. It may be used -/// at the chain that is implementing complete standard messages bridge (i.e. with bridge GRANDPA -/// and messages pallets deployed). +/// at the chain that is implementing standard messages bridge with messages pallets deployed. #[macro_export] macro_rules! assert_complete_bridge_types( ( runtime: $r:path, - with_bridged_chain_grandpa_instance: $gi:path, with_bridged_chain_messages_instance: $mi:path, this_chain: $this:path, bridged_chain: $bridged:path, @@ -186,34 +184,55 @@ where ); } -/// Parameters for asserting bridge pallet names. +/// Parameters for asserting bridge GRANDPA pallet names. #[derive(Debug)] -pub struct AssertBridgePalletNames<'a> { +struct AssertBridgeGrandpaPalletNames<'a> { /// Name of the GRANDPA pallet, deployed at this chain and used to bridge with the bridged /// chain. pub with_bridged_chain_grandpa_pallet_name: &'a str, - /// Name of the messages pallet, deployed at this chain and used to bridge with the bridged - /// chain. - pub with_bridged_chain_messages_pallet_name: &'a str, } /// Tests that bridge pallet names used in `construct_runtime!()` macro call are matching constants /// from chain primitives crates. -fn assert_bridge_pallet_names(params: AssertBridgePalletNames) +fn assert_bridge_grandpa_pallet_names(params: AssertBridgeGrandpaPalletNames) where - R: pallet_bridge_grandpa::Config + pallet_bridge_messages::Config, + R: pallet_bridge_grandpa::Config, GI: 'static, - MI: 'static, { // check that the bridge GRANDPA pallet has required name assert_eq!( - pallet_bridge_grandpa::PalletOwner::::storage_value_final_key().to_vec(), + pallet_bridge_grandpa::PalletOwner::::storage_value_final_key().to_vec(), + bp_runtime::storage_value_key( + params.with_bridged_chain_grandpa_pallet_name, + "PalletOwner", + ) + .0, + ); + assert_eq!( + pallet_bridge_grandpa::PalletOperatingMode::::storage_value_final_key().to_vec(), bp_runtime::storage_value_key( params.with_bridged_chain_grandpa_pallet_name, - "PalletOwner", - ).0, + "PalletOperatingMode", + ) + .0, ); +} +/// Parameters for asserting bridge messages pallet names. +#[derive(Debug)] +struct AssertBridgeMessagesPalletNames<'a> { + /// Name of the messages pallet, deployed at this chain and used to bridge with the bridged + /// chain. + pub with_bridged_chain_messages_pallet_name: &'a str, +} + +/// Tests that bridge pallet names used in `construct_runtime!()` macro call are matching constants +/// from chain primitives crates. +fn assert_bridge_messages_pallet_names(params: AssertBridgeMessagesPalletNames) +where + R: pallet_bridge_messages::Config, + MI: 'static, +{ // check that the bridge messages pallet has required name assert_eq!( pallet_bridge_messages::PalletOwner::::storage_value_final_key().to_vec(), @@ -223,6 +242,14 @@ where ) .0, ); + assert_eq!( + pallet_bridge_messages::PalletOperatingMode::::storage_value_final_key().to_vec(), + bp_runtime::storage_value_key( + params.with_bridged_chain_messages_pallet_name, + "PalletOperatingMode", + ) + .0, + ); } /// Parameters for asserting complete standard messages bridge. @@ -246,9 +273,11 @@ pub fn assert_complete_with_relay_chain_bridge_constants( assert_chain_constants::(params.this_chain_constants); assert_bridge_grandpa_pallet_constants::(); assert_bridge_messages_pallet_constants::(); - assert_bridge_pallet_names::(AssertBridgePalletNames { + assert_bridge_grandpa_pallet_names::(AssertBridgeGrandpaPalletNames { with_bridged_chain_grandpa_pallet_name: >::BridgedChain::WITH_CHAIN_GRANDPA_PALLET_NAME, + }); + assert_bridge_messages_pallet_names::(AssertBridgeMessagesPalletNames { with_bridged_chain_messages_pallet_name: >::BridgedChain::WITH_CHAIN_MESSAGES_PALLET_NAME, }); @@ -256,21 +285,43 @@ pub fn assert_complete_with_relay_chain_bridge_constants( /// All bridge-related constants tests for the complete standard parachain messages bridge /// (i.e. with bridge GRANDPA, parachains and messages pallets deployed). -pub fn assert_complete_with_parachain_bridge_constants( +pub fn assert_complete_with_parachain_bridge_constants( params: AssertCompleteBridgeConstants, ) where R: frame_system::Config - + pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + pallet_bridge_messages::Config, - GI: 'static, + >::BridgedRelayChain: ChainWithGrandpa, + PI: 'static, + MI: 'static, +{ + assert_chain_constants::(params.this_chain_constants); + assert_bridge_grandpa_pallet_constants::(); + assert_bridge_messages_pallet_constants::(); + assert_bridge_grandpa_pallet_names::( + AssertBridgeGrandpaPalletNames { + with_bridged_chain_grandpa_pallet_name: + <>::BridgedRelayChain>::WITH_CHAIN_GRANDPA_PALLET_NAME, + }, + ); + assert_bridge_messages_pallet_names::(AssertBridgeMessagesPalletNames { + with_bridged_chain_messages_pallet_name: + >::BridgedChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + }); +} + +/// All bridge-related constants tests for the standalone messages bridge deployment (only with +/// messages pallets deployed). +pub fn assert_standalone_messages_bridge_constants(params: AssertCompleteBridgeConstants) +where + R: frame_system::Config + pallet_bridge_messages::Config, MI: 'static, - RelayChain: ChainWithGrandpa, { assert_chain_constants::(params.this_chain_constants); - assert_bridge_grandpa_pallet_constants::(); assert_bridge_messages_pallet_constants::(); - assert_bridge_pallet_names::(AssertBridgePalletNames { - with_bridged_chain_grandpa_pallet_name: RelayChain::WITH_CHAIN_GRANDPA_PALLET_NAME, + assert_bridge_messages_pallet_names::(AssertBridgeMessagesPalletNames { with_bridged_chain_messages_pallet_name: >::BridgedChain::WITH_CHAIN_MESSAGES_PALLET_NAME, }); diff --git a/bridges/bin/runtime-common/src/mock.rs b/bridges/bin/runtime-common/src/mock.rs index 6cf04b452da7..88037d9deff5 100644 --- a/bridges/bin/runtime-common/src/mock.rs +++ b/bridges/bin/runtime-common/src/mock.rs @@ -196,6 +196,7 @@ impl pallet_bridge_messages::Config for TestRuntime { type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< TestRuntime, (), + (), ConstU64<100_000>, >; type OnMessagesDelivered = (); diff --git a/bridges/modules/relayers/src/lib.rs b/bridges/modules/relayers/src/lib.rs index f06c2e16ac24..d1c71b6d3051 100644 --- a/bridges/modules/relayers/src/lib.rs +++ b/bridges/modules/relayers/src/lib.rs @@ -22,8 +22,9 @@ use bp_relayers::{ ExplicitOrAccountParams, PaymentProcedure, Registration, RelayerRewardsKeyProvider, - RewardsAccountParams, StakeAndSlash, + StakeAndSlash, }; +pub use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; use bp_runtime::StorageDoubleMapKeyProvider; use frame_support::fail; use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero}; @@ -31,7 +32,7 @@ use sp_runtime::{traits::CheckedSub, Saturating}; use sp_std::marker::PhantomData; pub use pallet::*; -pub use payment_adapter::DeliveryConfirmationPaymentsAdapter; +pub use payment_adapter::{DeliveryConfirmationPaymentsAdapter, PayRewardFromAccount}; pub use stake_adapter::StakeAndSlashNamed; pub use weights::WeightInfo; pub use weights_ext::WeightInfoExt; diff --git a/bridges/modules/relayers/src/mock.rs b/bridges/modules/relayers/src/mock.rs index d186e968e648..7dc213249379 100644 --- a/bridges/modules/relayers/src/mock.rs +++ b/bridges/modules/relayers/src/mock.rs @@ -171,14 +171,14 @@ pub type TestStakeAndSlash = pallet_bridge_relayers::StakeAndSlashNamed< frame_support::construct_runtime! { pub enum TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, + System: frame_system, Utility: pallet_utility, - Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, - TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event}, - BridgeRelayers: pallet_bridge_relayers::{Pallet, Call, Storage, Event}, - BridgeGrandpa: pallet_bridge_grandpa::{Pallet, Call, Storage, Event}, - BridgeParachains: pallet_bridge_parachains::{Pallet, Call, Storage, Event}, - BridgeMessages: pallet_bridge_messages::{Pallet, Call, Storage, Event, Config}, + Balances: pallet_balances, + TransactionPayment: pallet_transaction_payment, + BridgeRelayers: pallet_bridge_relayers, + BridgeGrandpa: pallet_bridge_grandpa, + BridgeParachains: pallet_bridge_parachains, + BridgeMessages: pallet_bridge_messages, } } @@ -267,6 +267,7 @@ impl pallet_bridge_messages::Config for TestRuntime { type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< TestRuntime, (), + (), ConstU64<100_000>, >; type OnMessagesDelivered = (); diff --git a/bridges/modules/relayers/src/payment_adapter.rs b/bridges/modules/relayers/src/payment_adapter.rs index 5383cba5ecbd..5af0d8f9dfbf 100644 --- a/bridges/modules/relayers/src/payment_adapter.rs +++ b/bridges/modules/relayers/src/payment_adapter.rs @@ -22,6 +22,7 @@ use bp_messages::{ source_chain::{DeliveryConfirmationPayments, RelayersRewards}, MessageNonce, }; +pub use bp_relayers::PayRewardFromAccount; use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; use bp_runtime::Chain; use frame_support::{sp_runtime::SaturatedConversion, traits::Get}; @@ -31,15 +32,16 @@ use sp_std::{collections::vec_deque::VecDeque, marker::PhantomData, ops::RangeIn /// Adapter that allows relayers pallet to be used as a delivery+dispatch payment mechanism /// for the messages pallet. -pub struct DeliveryConfirmationPaymentsAdapter( - PhantomData<(T, MI, DeliveryReward)>, +pub struct DeliveryConfirmationPaymentsAdapter( + PhantomData<(T, MI, RI, DeliveryReward)>, ); -impl DeliveryConfirmationPayments> - for DeliveryConfirmationPaymentsAdapter +impl DeliveryConfirmationPayments> + for DeliveryConfirmationPaymentsAdapter where - T: Config + pallet_bridge_messages::Config::LaneId>, + T: Config + pallet_bridge_messages::Config>::LaneId>, MI: 'static, + RI: 'static, DeliveryReward: Get, { type Error = &'static str; @@ -54,7 +56,7 @@ where bp_messages::calc_relayers_rewards::(messages_relayers, received_range); let rewarded_relayers = relayers_rewards.len(); - register_relayers_rewards::( + register_relayers_rewards::( confirmation_relayer, relayers_rewards, RewardsAccountParams::new( @@ -70,7 +72,7 @@ where } // Update rewards to given relayers, optionally rewarding confirmation relayer. -fn register_relayers_rewards( +fn register_relayers_rewards, I: 'static>( confirmation_relayer: &T::AccountId, relayers_rewards: RelayersRewards, lane_id: RewardsAccountParams, @@ -84,7 +86,7 @@ fn register_relayers_rewards( let relayer_reward = T::Reward::saturated_from(messages).saturating_mul(delivery_fee); if relayer != *confirmation_relayer { - Pallet::::register_relayer_reward(lane_id, &relayer, relayer_reward); + Pallet::::register_relayer_reward(lane_id, &relayer, relayer_reward); } else { confirmation_relayer_reward = confirmation_relayer_reward.saturating_add(relayer_reward); @@ -92,7 +94,7 @@ fn register_relayers_rewards( } // finally - pay reward to confirmation relayer - Pallet::::register_relayer_reward( + Pallet::::register_relayer_reward( lane_id, confirmation_relayer, confirmation_relayer_reward, @@ -115,7 +117,7 @@ mod tests { #[test] fn confirmation_relayer_is_rewarded_if_it_has_also_delivered_messages() { run_test(|| { - register_relayers_rewards::( + register_relayers_rewards::( &RELAYER_2, relayers_rewards(), test_reward_account_param(), @@ -136,7 +138,7 @@ mod tests { #[test] fn confirmation_relayer_is_not_rewarded_if_it_has_not_delivered_any_messages() { run_test(|| { - register_relayers_rewards::( + register_relayers_rewards::( &RELAYER_3, relayers_rewards(), test_reward_account_param(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs index 7e0385692375..b284fa9e7af7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs @@ -201,7 +201,6 @@ mod tests { fn ensure_bridge_integrity() { assert_complete_bridge_types!( runtime: Runtime, - with_bridged_chain_grandpa_instance: BridgeGrandpaRococoBulletinInstance, with_bridged_chain_messages_instance: WithRococoBulletinMessagesInstance, this_chain: bp_bridge_hub_rococo::BridgeHubRococo, bridged_chain: bp_polkadot_bulletin::PolkadotBulletin, diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs index 0eab3c74a7e2..2710d033d64b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs @@ -121,6 +121,7 @@ impl pallet_bridge_messages::Config for Ru type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< Runtime, WithBridgeHubWestendMessagesInstance, + RelayersForLegacyLaneIdsMessagesInstance, DeliveryRewardInBalance, >; @@ -256,7 +257,6 @@ mod tests { fn ensure_bridge_integrity() { assert_complete_bridge_types!( runtime: Runtime, - with_bridged_chain_grandpa_instance: BridgeGrandpaWestendInstance, with_bridged_chain_messages_instance: WithBridgeHubWestendMessagesInstance, this_chain: bp_bridge_hub_rococo::BridgeHubRococo, bridged_chain: bp_bridge_hub_westend::BridgeHubWestend, @@ -266,7 +266,6 @@ mod tests { Runtime, BridgeGrandpaWestendInstance, WithBridgeHubWestendMessagesInstance, - bp_westend::Westend, >(AssertCompleteBridgeConstants { this_chain_constants: AssertChainConstants { block_length: bp_bridge_hub_rococo::BlockLength::get(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index 2e7dd98e9dce..6ca858e961d3 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -324,11 +324,12 @@ mod bridge_hub_westend_tests { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubWestendInstance - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) } ).1 }, @@ -388,11 +389,12 @@ mod bridge_hub_westend_tests { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubWestendInstance, - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) }, ) .1 @@ -422,11 +424,12 @@ mod bridge_hub_westend_tests { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubWestendInstance, - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) }, ) .1 @@ -591,11 +594,12 @@ mod bridge_hub_bulletin_tests { >( SiblingPeopleParachainLocation::get(), BridgedBulletinLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverPolkadotBulletinInstance - >(locations, fee, HashedLaneId::try_new(1, 2).unwrap()) + >(locations, HashedLaneId::try_new(1, 2).unwrap()) } ).1 }, @@ -654,11 +658,12 @@ mod bridge_hub_bulletin_tests { >( SiblingPeopleParachainLocation::get(), BridgedBulletinLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverPolkadotBulletinInstance, - >(locations, fee, HashedLaneId::try_new(1, 2).unwrap()) + >(locations, HashedLaneId::try_new(1, 2).unwrap()) }, ) .1 @@ -687,11 +692,12 @@ mod bridge_hub_bulletin_tests { >( SiblingPeopleParachainLocation::get(), BridgedBulletinLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverPolkadotBulletinInstance, - >(locations, fee, HashedLaneId::try_new(1, 2).unwrap()) + >(locations, HashedLaneId::try_new(1, 2).unwrap()) }, ) .1 diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs index 62c93da7c831..cd3465513144 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs @@ -152,6 +152,7 @@ impl pallet_bridge_messages::Config for Run type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< Runtime, WithBridgeHubRococoMessagesInstance, + RelayersForLegacyLaneIdsMessagesInstance, DeliveryRewardInBalance, >; @@ -284,7 +285,6 @@ mod tests { fn ensure_bridge_integrity() { assert_complete_bridge_types!( runtime: Runtime, - with_bridged_chain_grandpa_instance: BridgeGrandpaRococoInstance, with_bridged_chain_messages_instance: WithBridgeHubRococoMessagesInstance, this_chain: bp_bridge_hub_westend::BridgeHubWestend, bridged_chain: bp_bridge_hub_rococo::BridgeHubRococo, @@ -294,7 +294,6 @@ mod tests { Runtime, BridgeGrandpaRococoInstance, WithBridgeHubRococoMessagesInstance, - bp_rococo::Rococo, >(AssertCompleteBridgeConstants { this_chain_constants: AssertChainConstants { block_length: bp_bridge_hub_westend::BlockLength::get(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index 69301b34fe6b..84025c4cefeb 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -246,10 +246,11 @@ fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubRococoInstance - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) } ).1 }, @@ -307,11 +308,12 @@ fn relayed_incoming_message_works() { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubRococoInstance, - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) }, ) .1 @@ -341,11 +343,12 @@ fn free_relay_extrinsic_works() { >( SiblingParachainLocation::get(), BridgedUniversalLocation::get(), - |locations, fee| { + false, + |locations, _fee| { bridge_hub_test_utils::open_bridge_with_storage::< Runtime, XcmOverBridgeHubRococoInstance, - >(locations, fee, LegacyLaneId([0, 0, 0, 1])) + >(locations, LegacyLaneId([0, 0, 0, 1])) }, ) .1 diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs index aac60bba0b53..03ddc4313b45 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs @@ -29,7 +29,7 @@ use core::marker::PhantomData; use frame_support::{ assert_ok, dispatch::GetDispatchInfo, - traits::{fungible::Mutate, OnFinalize, OnInitialize, PalletInfoAccess}, + traits::{fungible::Mutate, Contains, OnFinalize, OnInitialize, PalletInfoAccess}, }; use frame_system::pallet_prelude::BlockNumberFor; use pallet_bridge_grandpa::{BridgedBlockHash, BridgedHeader}; @@ -395,7 +395,7 @@ pub fn ensure_opened_bridge< XcmOverBridgePalletInstance, LocationToAccountId, TokenLocation> -(source: Location, destination: InteriorLocation, bridge_opener: impl Fn(BridgeLocations, Asset)) -> (BridgeLocations, pallet_xcm_bridge_hub::LaneIdOf) +(source: Location, destination: InteriorLocation, is_paid_xcm_execution: bool, bridge_opener: impl Fn(BridgeLocations, Option)) -> (BridgeLocations, pallet_xcm_bridge_hub::LaneIdOf) where Runtime: BasicParachainRuntime + BridgeXcmOverBridgeConfig, XcmOverBridgePalletInstance: 'static, @@ -416,24 +416,37 @@ TokenLocation: Get{ ) .is_none()); - // required balance: ED + fee + BridgeDeposit - let bridge_deposit = - >::BridgeDeposit::get( - ); - // random high enough value for `BuyExecution` fees - let buy_execution_fee_amount = 5_000_000_000_000_u128; - let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); - let balance_needed = ::ExistentialDeposit::get() + - buy_execution_fee_amount.into() + - bridge_deposit.into(); - // SA of source location needs to have some required balance - let source_account_id = LocationToAccountId::convert_location(&source).expect("valid location"); - let _ = >::mint_into(&source_account_id, balance_needed) - .expect("mint_into passes"); + if !>::AllowWithoutBridgeDeposit::contains(&source) { + // required balance: ED + fee + BridgeDeposit + let bridge_deposit = + >::BridgeDeposit::get( + ); + let balance_needed = ::ExistentialDeposit::get() + bridge_deposit.into(); + + let source_account_id = LocationToAccountId::convert_location(&source).expect("valid location"); + let _ = >::mint_into(&source_account_id, balance_needed) + .expect("mint_into passes"); + }; + + let maybe_paid_execution = if is_paid_xcm_execution { + // random high enough value for `BuyExecution` fees + let buy_execution_fee_amount = 5_000_000_000_000_u128; + let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); + + let balance_needed = ::ExistentialDeposit::get() + + buy_execution_fee_amount.into(); + let source_account_id = + LocationToAccountId::convert_location(&source).expect("valid location"); + let _ = >::mint_into(&source_account_id, balance_needed) + .expect("mint_into passes"); + Some(buy_execution_fee) + } else { + None + }; // call the bridge opener - bridge_opener(*locations.clone(), buy_execution_fee); + bridge_opener(*locations.clone(), maybe_paid_execution); // check opened bridge let bridge = pallet_xcm_bridge_hub::Bridges::::get( @@ -452,8 +465,9 @@ TokenLocation: Get{ /// Utility for opening bridge with dedicated `pallet_xcm_bridge_hub`'s extrinsic. pub fn open_bridge_with_extrinsic( - locations: BridgeLocations, - buy_execution_fee: Asset, + (origin, origin_kind): (Location, OriginKind), + bridge_destination_universal_location: InteriorLocation, + maybe_paid_execution: Option, ) where Runtime: frame_system::Config + pallet_xcm_bridge_hub::Config @@ -469,15 +483,15 @@ pub fn open_bridge_with_extrinsic( XcmOverBridgePalletInstance, >::open_bridge { bridge_destination_universal_location: Box::new( - locations.bridge_destination_universal_location().clone().into(), + bridge_destination_universal_location.clone().into(), ), }); // execute XCM as source origin would do with `Transact -> Origin::Xcm` - assert_ok!(RuntimeHelper::::execute_as_origin_xcm( - locations.bridge_origin_relative_location().clone(), + assert_ok!(RuntimeHelper::::execute_as_origin( + (origin, origin_kind), open_bridge_call, - buy_execution_fee + maybe_paid_execution ) .ensure_complete()); } @@ -486,7 +500,6 @@ pub fn open_bridge_with_extrinsic( /// purposes). pub fn open_bridge_with_storage( locations: BridgeLocations, - _buy_execution_fee: Asset, lane_id: pallet_xcm_bridge_hub::LaneIdOf, ) where Runtime: pallet_xcm_bridge_hub::Config, @@ -503,8 +516,12 @@ pub fn open_bridge_with_storage( } /// Helper function to close the bridge/lane for `source` and `destination`. -pub fn close_bridge(source: Location, destination: InteriorLocation) -where +pub fn close_bridge( + expected_source: Location, + bridge_destination_universal_location: InteriorLocation, + (origin, origin_kind): (Location, OriginKind), + is_paid_xcm_execution: bool +) where Runtime: BasicParachainRuntime + BridgeXcmOverBridgeConfig, XcmOverBridgePalletInstance: 'static, ::RuntimeCall: GetDispatchInfo + From>, @@ -515,8 +532,8 @@ TokenLocation: Get{ // construct expected bridge configuration let locations = pallet_xcm_bridge_hub::Pallet::::bridge_locations( - source.clone().into(), - destination.clone().into(), + expected_source.clone().into(), + bridge_destination_universal_location.clone().into(), ) .expect("valid bridge locations"); assert!(pallet_xcm_bridge_hub::Bridges::::get( @@ -525,35 +542,38 @@ TokenLocation: Get{ .is_some()); // required balance: ED + fee + BridgeDeposit - let bridge_deposit = - >::BridgeDeposit::get( - ); - // random high enough value for `BuyExecution` fees - let buy_execution_fee_amount = 2_500_000_000_000_u128; - let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); - let balance_needed = ::ExistentialDeposit::get() + - buy_execution_fee_amount.into() + - bridge_deposit.into(); - - // SA of source location needs to have some required balance - let source_account_id = LocationToAccountId::convert_location(&source).expect("valid location"); - let _ = >::mint_into(&source_account_id, balance_needed) - .expect("mint_into passes"); + let maybe_paid_execution = if is_paid_xcm_execution { + // random high enough value for `BuyExecution` fees + let buy_execution_fee_amount = 2_500_000_000_000_u128; + let buy_execution_fee = (TokenLocation::get(), buy_execution_fee_amount).into(); + + let balance_needed = ::ExistentialDeposit::get() + + buy_execution_fee_amount.into(); + let source_account_id = + LocationToAccountId::convert_location(&expected_source).expect("valid location"); + let _ = >::mint_into(&source_account_id, balance_needed) + .expect("mint_into passes"); + Some(buy_execution_fee) + } else { + None + }; // close bridge with `Transact` call let close_bridge_call = RuntimeCallOf::::from(BridgeXcmOverBridgeCall::< Runtime, XcmOverBridgePalletInstance, >::close_bridge { - bridge_destination_universal_location: Box::new(destination.into()), + bridge_destination_universal_location: Box::new( + bridge_destination_universal_location.into(), + ), may_prune_messages: 16, }); // execute XCM as source origin would do with `Transact -> Origin::Xcm` - assert_ok!(RuntimeHelper::::execute_as_origin_xcm( - source.clone(), + assert_ok!(RuntimeHelper::::execute_as_origin( + (origin, origin_kind), close_bridge_call, - buy_execution_fee + maybe_paid_execution ) .ensure_complete()); diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs index ad6db0b83e80..f96d0bf405b9 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs @@ -654,8 +654,10 @@ where pub fn open_and_close_bridge_works( collator_session_key: CollatorSessionKeys, runtime_para_id: u32, - source: Location, + expected_source: Location, destination: InteriorLocation, + origin_with_origin_kind: (Location, OriginKind), + is_paid_xcm_execution: bool, ) where Runtime: BasicParachainRuntime + BridgeXcmOverBridgeConfig, XcmOverBridgePalletInstance: 'static, @@ -669,7 +671,7 @@ pub fn open_and_close_bridge_works(collator_session_key, runtime_para_id, vec![], || { // construct expected bridge configuration let locations = pallet_xcm_bridge_hub::Pallet::::bridge_locations( - source.clone().into(), + expected_source.clone().into(), destination.clone().into(), ).expect("valid bridge locations"); let expected_lane_id = @@ -704,7 +706,7 @@ pub fn open_and_close_bridge_works( - source.clone(), + expected_source.clone(), destination.clone(), - open_bridge_with_extrinsic:: + is_paid_xcm_execution, + |locations, maybe_paid_execution| open_bridge_with_extrinsic::< + Runtime, + XcmOverBridgePalletInstance, + >( + origin_with_origin_kind.clone(), + locations.bridge_destination_universal_location().clone(), + maybe_paid_execution + ) ) .0 .bridge_id(), @@ -727,7 +737,7 @@ pub fn open_and_close_bridge_works(source.clone(), destination); + >(expected_source, destination, origin_with_origin_kind, is_paid_xcm_execution); // check bridge/lane DOES not exist assert_eq!( diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index 05ecf6ca8e81..3f2e721d13f6 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -460,18 +460,26 @@ impl< ) } - pub fn execute_as_origin_xcm( - origin: Location, + pub fn execute_as_origin( + (origin, origin_kind): (Location, OriginKind), call: Call, - buy_execution_fee: Asset, + maybe_buy_execution_fee: Option, ) -> Outcome { + let mut instructions = if let Some(buy_execution_fee) = maybe_buy_execution_fee { + vec![ + WithdrawAsset(buy_execution_fee.clone().into()), + BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, + ] + } else { + vec![UnpaidExecution { check_origin: None, weight_limit: Unlimited }] + }; + // prepare `Transact` xcm - let xcm = Xcm(vec![ - WithdrawAsset(buy_execution_fee.clone().into()), - BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, - Transact { origin_kind: OriginKind::Xcm, call: call.encode().into() }, + instructions.extend(vec![ + Transact { origin_kind, call: call.encode().into() }, ExpectTransactStatus(MaybeErrorCode::Success), ]); + let xcm = Xcm(instructions); // execute xcm as parent origin let mut hash = xcm.using_encoded(sp_io::hashing::blake2_256); diff --git a/prdoc/pr_6536.prdoc b/prdoc/pr_6536.prdoc new file mode 100644 index 000000000000..676b5c131f17 --- /dev/null +++ b/prdoc/pr_6536.prdoc @@ -0,0 +1,24 @@ +title: Bridges testing improvements +doc: +- audience: Runtime Dev + description: |- + This PR includes: + - Refactored integrity tests to support standalone deployment of `pallet-bridge-messages`. + - Refactored the `open_and_close_bridge_works` test case to support multiple scenarios, such as: + 1. A local chain opening a bridge. + 2. Sibling parachains opening a bridge. + 3. The relay chain opening a bridge. + - Previously, we added instance support for `pallet-bridge-relayer` but overlooked updating the `DeliveryConfirmationPaymentsAdapter`. +crates: +- name: bridge-runtime-common + bump: patch +- name: pallet-bridge-relayers + bump: patch +- name: bridge-hub-rococo-runtime + bump: patch +- name: bridge-hub-westend-runtime + bump: patch +- name: bridge-hub-test-utils + bump: major +- name: parachains-runtimes-test-utils + bump: major From 70b6c7b08a0bc27c6155bca66461af97b829d208 Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Thu, 21 Nov 2024 00:04:46 +0800 Subject: [PATCH 119/166] Migrate pallet-scheduler benchmark to v2 (#6292) Part of: - #6202. --------- Signed-off-by: Xavier Lau Co-authored-by: Giuseppe Re Co-authored-by: Guillaume Thiolliere --- substrate/frame/scheduler/src/benchmarking.rs | 306 ++++++++++++------ 1 file changed, 202 insertions(+), 104 deletions(-) diff --git a/substrate/frame/scheduler/src/benchmarking.rs b/substrate/frame/scheduler/src/benchmarking.rs index d0a14fc73d64..ff40e8ef8abf 100644 --- a/substrate/frame/scheduler/src/benchmarking.rs +++ b/substrate/frame/scheduler/src/benchmarking.rs @@ -17,25 +17,23 @@ //! Scheduler pallet benchmarking. -use super::*; use alloc::vec; -use frame_benchmarking::v1::{account, benchmarks, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::{ ensure, traits::{schedule::Priority, BoundedInline}, weights::WeightMeter, }; -use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use frame_system::{EventRecord, RawOrigin}; -use crate::Pallet as Scheduler; -use frame_system::{Call as SystemCall, EventRecord}; +use crate::*; -const SEED: u32 = 0; +type SystemCall = frame_system::Call; +type SystemOrigin = ::RuntimeOrigin; +const SEED: u32 = 0; const BLOCK_NUMBER: u32 = 2; -type SystemOrigin = ::RuntimeOrigin; - fn assert_last_event(generic_event: ::RuntimeEvent) { let events = frame_system::Pallet::::events(); let system_event: ::RuntimeEvent = generic_event.into(); @@ -61,7 +59,7 @@ fn fill_schedule( let call = make_call::(None); let period = Some(((i + 100).into(), 100)); let name = u32_to_name(i); - Scheduler::::do_schedule_named(name, t, period, 0, origin.clone(), call)?; + Pallet::::do_schedule_named(name, t, period, 0, origin.clone(), call)?; } ensure!(Agenda::::get(when).len() == n as usize, "didn't fill schedule"); Ok(()) @@ -134,107 +132,160 @@ fn make_origin(signed: bool) -> ::PalletsOrigin { } } -benchmarks! { +#[benchmarks] +mod benchmarks { + use super::*; + // `service_agendas` when no work is done. - service_agendas_base { - let now = BlockNumberFor::::from(BLOCK_NUMBER); + #[benchmark] + fn service_agendas_base() { + let now = BLOCK_NUMBER.into(); IncompleteSince::::put(now - One::one()); - }: { - Scheduler::::service_agendas(&mut WeightMeter::new(), now, 0); - } verify { + + #[block] + { + Pallet::::service_agendas(&mut WeightMeter::new(), now, 0); + } + assert_eq!(IncompleteSince::::get(), Some(now - One::one())); } // `service_agenda` when no work is done. - service_agenda_base { + #[benchmark] + fn service_agenda_base( + s: Linear<0, { T::MaxScheduledPerBlock::get() }>, + ) -> Result<(), BenchmarkError> { let now = BLOCK_NUMBER.into(); - let s in 0 .. T::MaxScheduledPerBlock::get(); fill_schedule::(now, s)?; let mut executed = 0; - }: { - Scheduler::::service_agenda(&mut WeightMeter::new(), &mut executed, now, now, 0); - } verify { + + #[block] + { + Pallet::::service_agenda(&mut WeightMeter::new(), &mut executed, now, now, 0); + } + assert_eq!(executed, 0); + + Ok(()) } // `service_task` when the task is a non-periodic, non-named, non-fetched call which is not // dispatched (e.g. due to being overweight). - service_task_base { + #[benchmark] + fn service_task_base() { let now = BLOCK_NUMBER.into(); let task = make_task::(false, false, false, None, 0); // prevent any tasks from actually being executed as we only want the surrounding weight. let mut counter = WeightMeter::with_limit(Weight::zero()); - }: { - let result = Scheduler::::service_task(&mut counter, now, now, 0, true, task); - } verify { - //assert_eq!(result, Ok(())); + let _result; + + #[block] + { + _result = Pallet::::service_task(&mut counter, now, now, 0, true, task); + } + + // assert!(_result.is_ok()); } // `service_task` when the task is a non-periodic, non-named, fetched call (with a known // preimage length) and which is not dispatched (e.g. due to being overweight). - #[pov_mode = MaxEncodedLen { + #[benchmark(pov_mode = MaxEncodedLen { // Use measured PoV size for the Preimages since we pass in a length witness. Preimage::PreimageFor: Measured - }] - service_task_fetched { - let s in (BoundedInline::bound() as u32) .. (T::Preimages::MAX_LENGTH as u32); + })] + fn service_task_fetched( + s: Linear<{ BoundedInline::bound() as u32 }, { T::Preimages::MAX_LENGTH as u32 }>, + ) { let now = BLOCK_NUMBER.into(); let task = make_task::(false, false, false, Some(s), 0); // prevent any tasks from actually being executed as we only want the surrounding weight. let mut counter = WeightMeter::with_limit(Weight::zero()); - }: { - let result = Scheduler::::service_task(&mut counter, now, now, 0, true, task); - } verify { + let _result; + + #[block] + { + _result = Pallet::::service_task(&mut counter, now, now, 0, true, task); + } + + // assert!(result.is_ok()); } // `service_task` when the task is a non-periodic, named, non-fetched call which is not // dispatched (e.g. due to being overweight). - service_task_named { + #[benchmark] + fn service_task_named() { let now = BLOCK_NUMBER.into(); let task = make_task::(false, true, false, None, 0); // prevent any tasks from actually being executed as we only want the surrounding weight. let mut counter = WeightMeter::with_limit(Weight::zero()); - }: { - let result = Scheduler::::service_task(&mut counter, now, now, 0, true, task); - } verify { + let _result; + + #[block] + { + _result = Pallet::::service_task(&mut counter, now, now, 0, true, task); + } + + // assert!(result.is_ok()); } // `service_task` when the task is a periodic, non-named, non-fetched call which is not // dispatched (e.g. due to being overweight). - service_task_periodic { + #[benchmark] + fn service_task_periodic() { let now = BLOCK_NUMBER.into(); let task = make_task::(true, false, false, None, 0); // prevent any tasks from actually being executed as we only want the surrounding weight. let mut counter = WeightMeter::with_limit(Weight::zero()); - }: { - let result = Scheduler::::service_task(&mut counter, now, now, 0, true, task); - } verify { + let _result; + + #[block] + { + _result = Pallet::::service_task(&mut counter, now, now, 0, true, task); + } + + // assert!(result.is_ok()); } // `execute_dispatch` when the origin is `Signed`, not counting the dispatchable's weight. - execute_dispatch_signed { + #[benchmark] + fn execute_dispatch_signed() -> Result<(), BenchmarkError> { let mut counter = WeightMeter::new(); let origin = make_origin::(true); - let call = T::Preimages::realize(&make_call::(None)).unwrap().0; - }: { - assert!(Scheduler::::execute_dispatch(&mut counter, origin, call).is_ok()); - } - verify { + let call = T::Preimages::realize(&make_call::(None))?.0; + let result; + + #[block] + { + result = Pallet::::execute_dispatch(&mut counter, origin, call); + } + + assert!(result.is_ok()); + + Ok(()) } // `execute_dispatch` when the origin is not `Signed`, not counting the dispatchable's weight. - execute_dispatch_unsigned { + #[benchmark] + fn execute_dispatch_unsigned() -> Result<(), BenchmarkError> { let mut counter = WeightMeter::new(); let origin = make_origin::(false); - let call = T::Preimages::realize(&make_call::(None)).unwrap().0; - }: { - assert!(Scheduler::::execute_dispatch(&mut counter, origin, call).is_ok()); - } - verify { + let call = T::Preimages::realize(&make_call::(None))?.0; + let result; + + #[block] + { + result = Pallet::::execute_dispatch(&mut counter, origin, call); + } + + assert!(result.is_ok()); + + Ok(()) } - schedule { - let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); + #[benchmark] + fn schedule( + s: Linear<0, { T::MaxScheduledPerBlock::get() - 1 }>, + ) -> Result<(), BenchmarkError> { let when = BLOCK_NUMBER.into(); let periodic = Some((BlockNumberFor::::one(), 100)); let priority = 0; @@ -242,24 +293,27 @@ benchmarks! { let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); fill_schedule::(when, s)?; - }: _(RawOrigin::Root, when, periodic, priority, call) - verify { - ensure!( - Agenda::::get(when).len() == (s + 1) as usize, - "didn't add to schedule" - ); + + #[extrinsic_call] + _(RawOrigin::Root, when, periodic, priority, call); + + ensure!(Agenda::::get(when).len() == s as usize + 1, "didn't add to schedule"); + + Ok(()) } - cancel { - let s in 1 .. T::MaxScheduledPerBlock::get(); + #[benchmark] + fn cancel(s: Linear<1, { T::MaxScheduledPerBlock::get() }>) -> Result<(), BenchmarkError> { let when = BLOCK_NUMBER.into(); fill_schedule::(when, s)?; assert_eq!(Agenda::::get(when).len(), s as usize); let schedule_origin = T::ScheduleOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - }: _>(schedule_origin, when, 0) - verify { + + #[extrinsic_call] + _(schedule_origin as SystemOrigin, when, 0); + ensure!( s == 1 || Lookup::::get(u32_to_name(0)).is_none(), "didn't remove from lookup if more than 1 task scheduled for `when`" @@ -273,10 +327,14 @@ benchmarks! { s > 1 || Agenda::::get(when).len() == 0, "remove from schedule if only 1 task scheduled for `when`" ); + + Ok(()) } - schedule_named { - let s in 0 .. (T::MaxScheduledPerBlock::get() - 1); + #[benchmark] + fn schedule_named( + s: Linear<0, { T::MaxScheduledPerBlock::get() - 1 }>, + ) -> Result<(), BenchmarkError> { let id = u32_to_name(s); let when = BLOCK_NUMBER.into(); let periodic = Some((BlockNumberFor::::one(), 100)); @@ -285,21 +343,26 @@ benchmarks! { let call = Box::new(SystemCall::set_storage { items: vec![] }.into()); fill_schedule::(when, s)?; - }: _(RawOrigin::Root, id, when, periodic, priority, call) - verify { - ensure!( - Agenda::::get(when).len() == (s + 1) as usize, - "didn't add to schedule" - ); + + #[extrinsic_call] + _(RawOrigin::Root, id, when, periodic, priority, call); + + ensure!(Agenda::::get(when).len() == s as usize + 1, "didn't add to schedule"); + + Ok(()) } - cancel_named { - let s in 1 .. T::MaxScheduledPerBlock::get(); + #[benchmark] + fn cancel_named( + s: Linear<1, { T::MaxScheduledPerBlock::get() }>, + ) -> Result<(), BenchmarkError> { let when = BLOCK_NUMBER.into(); fill_schedule::(when, s)?; - }: _(RawOrigin::Root, u32_to_name(0)) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, u32_to_name(0)); + ensure!( s == 1 || Lookup::::get(u32_to_name(0)).is_none(), "didn't remove from lookup if more than 1 task scheduled for `when`" @@ -313,33 +376,49 @@ benchmarks! { s > 1 || Agenda::::get(when).len() == 0, "remove from schedule if only 1 task scheduled for `when`" ); + + Ok(()) } - schedule_retry { - let s in 1 .. T::MaxScheduledPerBlock::get(); + #[benchmark] + fn schedule_retry( + s: Linear<1, { T::MaxScheduledPerBlock::get() }>, + ) -> Result<(), BenchmarkError> { let when = BLOCK_NUMBER.into(); fill_schedule::(when, s)?; let name = u32_to_name(s - 1); let address = Lookup::::get(name).unwrap(); - let period: BlockNumberFor = 1u32.into(); - let root: ::PalletsOrigin = frame_system::RawOrigin::Root.into(); + let period: BlockNumberFor = 1_u32.into(); let retry_config = RetryConfig { total_retries: 10, remaining: 10, period }; Retries::::insert(address, retry_config); let (mut when, index) = address; let task = Agenda::::get(when)[index as usize].clone().unwrap(); let mut weight_counter = WeightMeter::with_limit(T::MaximumWeight::get()); - }: { - Scheduler::::schedule_retry(&mut weight_counter, when, when, index, &task, retry_config); - } verify { + + #[block] + { + Pallet::::schedule_retry( + &mut weight_counter, + when, + when, + index, + &task, + retry_config, + ); + } + when = when + BlockNumberFor::::one(); assert_eq!( Retries::::get((when, 0)), Some(RetryConfig { total_retries: 10, remaining: 9, period }) ); + + Ok(()) } - set_retry { + #[benchmark] + fn set_retry() -> Result<(), BenchmarkError> { let s = T::MaxScheduledPerBlock::get(); let when = BLOCK_NUMBER.into(); @@ -348,8 +427,10 @@ benchmarks! { let address = Lookup::::get(name).unwrap(); let (when, index) = address; let period = BlockNumberFor::::one(); - }: _(RawOrigin::Root, (when, index), 10, period) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, (when, index), 10, period); + assert_eq!( Retries::::get((when, index)), Some(RetryConfig { total_retries: 10, remaining: 10, period }) @@ -357,9 +438,12 @@ benchmarks! { assert_last_event::( Event::RetrySet { task: address, id: None, period, retries: 10 }.into(), ); + + Ok(()) } - set_retry_named { + #[benchmark] + fn set_retry_named() -> Result<(), BenchmarkError> { let s = T::MaxScheduledPerBlock::get(); let when = BLOCK_NUMBER.into(); @@ -368,8 +452,10 @@ benchmarks! { let address = Lookup::::get(name).unwrap(); let (when, index) = address; let period = BlockNumberFor::::one(); - }: _(RawOrigin::Root, name, 10, period) - verify { + + #[extrinsic_call] + _(RawOrigin::Root, name, 10, period); + assert_eq!( Retries::::get((when, index)), Some(RetryConfig { total_retries: 10, remaining: 10, period }) @@ -377,9 +463,12 @@ benchmarks! { assert_last_event::( Event::RetrySet { task: address, id: Some(name), period, retries: 10 }.into(), ); + + Ok(()) } - cancel_retry { + #[benchmark] + fn cancel_retry() -> Result<(), BenchmarkError> { let s = T::MaxScheduledPerBlock::get(); let when = BLOCK_NUMBER.into(); @@ -388,16 +477,19 @@ benchmarks! { let address = Lookup::::get(name).unwrap(); let (when, index) = address; let period = BlockNumberFor::::one(); - assert!(Scheduler::::set_retry(RawOrigin::Root.into(), (when, index), 10, period).is_ok()); - }: _(RawOrigin::Root, (when, index)) - verify { + assert!(Pallet::::set_retry(RawOrigin::Root.into(), (when, index), 10, period).is_ok()); + + #[extrinsic_call] + _(RawOrigin::Root, (when, index)); + assert!(!Retries::::contains_key((when, index))); - assert_last_event::( - Event::RetryCancelled { task: address, id: None }.into(), - ); + assert_last_event::(Event::RetryCancelled { task: address, id: None }.into()); + + Ok(()) } - cancel_retry_named { + #[benchmark] + fn cancel_retry_named() -> Result<(), BenchmarkError> { let s = T::MaxScheduledPerBlock::get(); let when = BLOCK_NUMBER.into(); @@ -406,14 +498,20 @@ benchmarks! { let address = Lookup::::get(name).unwrap(); let (when, index) = address; let period = BlockNumberFor::::one(); - assert!(Scheduler::::set_retry_named(RawOrigin::Root.into(), name, 10, period).is_ok()); - }: _(RawOrigin::Root, name) - verify { + assert!(Pallet::::set_retry_named(RawOrigin::Root.into(), name, 10, period).is_ok()); + + #[extrinsic_call] + _(RawOrigin::Root, name); + assert!(!Retries::::contains_key((when, index))); - assert_last_event::( - Event::RetryCancelled { task: address, id: Some(name) }.into(), - ); + assert_last_event::(Event::RetryCancelled { task: address, id: Some(name) }.into()); + + Ok(()) } - impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test); + impl_benchmark_test_suite! { + Pallet, + mock::new_test_ext(), + mock::Test + } } From a8722784fb36e13c811605bd5631d78643273e24 Mon Sep 17 00:00:00 2001 From: gupnik Date: Thu, 21 Nov 2024 09:53:55 +0530 Subject: [PATCH 120/166] Removes constraint in `BlockNumberProvider` from treasury (#6522) https://github.com/paritytech/polkadot-sdk/pull/3970 updated the treasury pallet to support relay chain block number provider. However, it added a constraint to the BlockNumberProvider to have the same block number type as frame_system: ```rust type BlockNumberProvider: BlockNumberProvider>; ``` This PR removes that constraint as suggested by @gui1117 --- prdoc/pr_6522.prdoc | 18 +++++++++ substrate/frame/bounties/src/benchmarking.rs | 6 +-- substrate/frame/bounties/src/lib.rs | 19 +++++---- .../frame/child-bounties/src/benchmarking.rs | 2 +- substrate/frame/child-bounties/src/lib.rs | 8 +++- substrate/frame/treasury/src/benchmarking.rs | 2 +- substrate/frame/treasury/src/lib.rs | 40 ++++++++++--------- .../primitives/runtime/src/traits/mod.rs | 3 +- 8 files changed, 64 insertions(+), 34 deletions(-) create mode 100644 prdoc/pr_6522.prdoc diff --git a/prdoc/pr_6522.prdoc b/prdoc/pr_6522.prdoc new file mode 100644 index 000000000000..bd59e9cb08dc --- /dev/null +++ b/prdoc/pr_6522.prdoc @@ -0,0 +1,18 @@ +title: Removes constraint in BlockNumberProvider from treasury + +doc: +- audience: Runtime Dev + description: |- + https://github.com/paritytech/polkadot-sdk/pull/3970 updated the treasury pallet to support + relay chain block number provider. However, it added a constraint to the `BlockNumberProvider` + trait to have the same block number type as `frame_system`: + + ```rust + type BlockNumberProvider: BlockNumberProvider>; + ``` + + This PR removes that constraint and allows the treasury pallet to use any block number type. + +crates: +- name: pallet-treasury + bump: major \ No newline at end of file diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index 8ad85d5420ed..1e931958898d 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -25,7 +25,7 @@ use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, }; -use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use frame_system::{pallet_prelude::BlockNumberFor as SystemBlockNumberFor, RawOrigin}; use sp_runtime::traits::{BlockNumberProvider, Bounded}; use crate::Pallet as Bounties; @@ -33,7 +33,7 @@ use pallet_treasury::Pallet as Treasury; const SEED: u32 = 0; -fn set_block_number, I: 'static>(n: BlockNumberFor) { +fn set_block_number, I: 'static>(n: BlockNumberFor) { >::BlockNumberProvider::set_block_number(n); } @@ -132,7 +132,7 @@ benchmarks_instance_pallet! { Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; let bounty_id = BountyCount::::get() - 1; let approve_origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - Treasury::::on_initialize(BlockNumberFor::::zero()); + Treasury::::on_initialize(SystemBlockNumberFor::::zero()); }: _(approve_origin, bounty_id, curator_lookup, fee) verify { assert_last_event::( diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 3ed408a19120..729c76b5cc75 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -105,7 +105,9 @@ use sp_runtime::{ use frame_support::{dispatch::DispatchResultWithPostInfo, traits::EnsureOrigin}; use frame_support::pallet_prelude::*; -use frame_system::pallet_prelude::*; +use frame_system::pallet_prelude::{ + ensure_signed, BlockNumberFor as SystemBlockNumberFor, OriginFor, +}; use scale_info::TypeInfo; pub use weights::WeightInfo; @@ -120,6 +122,9 @@ pub type BountyIndex = u32; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; +type BlockNumberFor = + <>::BlockNumberProvider as BlockNumberProvider>::BlockNumber; + /// A bounty proposal. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] pub struct Bounty { @@ -213,11 +218,11 @@ pub mod pallet { /// The delay period for which a bounty beneficiary need to wait before claim the payout. #[pallet::constant] - type BountyDepositPayoutDelay: Get>; + type BountyDepositPayoutDelay: Get>; /// Bounty duration in blocks. #[pallet::constant] - type BountyUpdatePeriod: Get>; + type BountyUpdatePeriod: Get>; /// The curator deposit is calculated as a percentage of the curator fee. /// @@ -326,7 +331,7 @@ pub mod pallet { _, Twox64Concat, BountyIndex, - Bounty, BlockNumberFor>, + Bounty, BlockNumberFor>, >; /// The description of each bounty. @@ -876,9 +881,9 @@ pub mod pallet { } #[pallet::hooks] - impl, I: 'static> Hooks> for Pallet { + impl, I: 'static> Hooks> for Pallet { #[cfg(feature = "try-runtime")] - fn try_state(_n: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { + fn try_state(_n: SystemBlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { Self::do_try_state() } } @@ -928,7 +933,7 @@ impl, I: 'static> Pallet { /// Get the block number used in the treasury pallet. /// /// It may be configured to use the relay chain block number on a parachain. - pub fn treasury_block_number() -> BlockNumberFor { + pub fn treasury_block_number() -> BlockNumberFor { >::BlockNumberProvider::current_block_number() } diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index 4b2d62cd920e..2864f3ab5048 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -22,7 +22,7 @@ use alloc::vec; use frame_benchmarking::{v2::*, BenchmarkError}; use frame_support::ensure; -use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use frame_system::RawOrigin; use pallet_bounties::Pallet as Bounties; use pallet_treasury::Pallet as Treasury; use sp_runtime::traits::BlockNumberProvider; diff --git a/substrate/frame/child-bounties/src/lib.rs b/substrate/frame/child-bounties/src/lib.rs index ea1d9547d465..9fca26510989 100644 --- a/substrate/frame/child-bounties/src/lib.rs +++ b/substrate/frame/child-bounties/src/lib.rs @@ -79,7 +79,9 @@ use sp_runtime::{ }; use frame_support::pallet_prelude::*; -use frame_system::pallet_prelude::*; +use frame_system::pallet_prelude::{ + ensure_signed, BlockNumberFor as SystemBlockNumberFor, OriginFor, +}; use pallet_bounties::BountyStatus; use scale_info::TypeInfo; pub use weights::WeightInfo; @@ -90,6 +92,8 @@ type BalanceOf = pallet_treasury::BalanceOf; type BountiesError = pallet_bounties::Error; type BountyIndex = pallet_bounties::BountyIndex; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; +type BlockNumberFor = + <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; /// A child bounty proposal. #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo, MaxEncodedLen)] @@ -810,7 +814,7 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet { + impl Hooks> for Pallet { fn integrity_test() { let parent_bounty_id: BountyIndex = 1; let child_bounty_id: BountyIndex = 2; diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index a03ee149db9b..a11723a27b2c 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -198,7 +198,7 @@ mod benchmarks { None, ); - let valid_from = frame_system::Pallet::::block_number(); + let valid_from = T::BlockNumberProvider::current_block_number(); let expire_at = valid_from.saturating_add(T::PayoutPeriod::get()); assert_last_event::( Event::AssetSpendApproved { diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index faacda1c0783..281012ffb4c9 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -106,7 +106,7 @@ use frame_support::{ weights::Weight, BoundedVec, PalletId, }; -use frame_system::pallet_prelude::BlockNumberFor; +use frame_system::pallet_prelude::BlockNumberFor as SystemBlockNumberFor; pub use pallet::*; pub use weights::WeightInfo; @@ -122,6 +122,8 @@ pub type NegativeImbalanceOf = <>::Currency as Currenc >>::NegativeImbalance; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; type BeneficiaryLookupOf = <>::BeneficiaryLookup as StaticLookup>::Source; +pub type BlockNumberFor = + <>::BlockNumberProvider as BlockNumberProvider>::BlockNumber; /// A trait to allow the Treasury Pallet to spend it's funds for other purposes. /// There is an expectation that the implementer of this trait will correctly manage @@ -202,7 +204,7 @@ pub mod pallet { pallet_prelude::*, traits::tokens::{ConversionFromAssetBalance, PaymentStatus}, }; - use frame_system::pallet_prelude::*; + use frame_system::pallet_prelude::{ensure_signed, OriginFor}; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -221,7 +223,7 @@ pub mod pallet { /// Period between successive spends. #[pallet::constant] - type SpendPeriod: Get>; + type SpendPeriod: Get>; /// Percentage of spare funds (if any) that are burnt per spend period. #[pallet::constant] @@ -277,14 +279,14 @@ pub mod pallet { /// The period during which an approved treasury spend has to be claimed. #[pallet::constant] - type PayoutPeriod: Get>; + type PayoutPeriod: Get>; /// Helper type for benchmarks. #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper: ArgumentsFactory; /// Provider for the block number. Normally this is the `frame_system` pallet. - type BlockNumberProvider: BlockNumberProvider>; + type BlockNumberProvider: BlockNumberProvider; } /// DEPRECATED: associated with `spend_local` call and will be removed in May 2025. @@ -335,7 +337,7 @@ pub mod pallet { T::AssetKind, AssetBalanceOf, T::Beneficiary, - BlockNumberFor, + BlockNumberFor, ::Id, >, OptionQuery, @@ -343,7 +345,7 @@ pub mod pallet { /// The blocknumber for the last triggered spend period. #[pallet::storage] - pub(crate) type LastSpendPeriod = StorageValue<_, BlockNumberFor, OptionQuery>; + pub(crate) type LastSpendPeriod = StorageValue<_, BlockNumberFor, OptionQuery>; #[pallet::genesis_config] #[derive(frame_support::DefaultNoBound)] @@ -391,8 +393,8 @@ pub mod pallet { asset_kind: T::AssetKind, amount: AssetBalanceOf, beneficiary: T::Beneficiary, - valid_from: BlockNumberFor, - expire_at: BlockNumberFor, + valid_from: BlockNumberFor, + expire_at: BlockNumberFor, }, /// An approved spend was voided. AssetSpendVoided { index: SpendIndex }, @@ -434,10 +436,10 @@ pub mod pallet { } #[pallet::hooks] - impl, I: 'static> Hooks> for Pallet { + impl, I: 'static> Hooks> for Pallet { /// ## Complexity /// - `O(A)` where `A` is the number of approvals - fn on_initialize(_do_not_use_local_block_number: BlockNumberFor) -> Weight { + fn on_initialize(_do_not_use_local_block_number: SystemBlockNumberFor) -> Weight { let block_number = T::BlockNumberProvider::current_block_number(); let pot = Self::pot(); let deactivated = Deactivated::::get(); @@ -458,7 +460,7 @@ pub mod pallet { // empty. .unwrap_or_else(|| Self::update_last_spend_period()); let blocks_since_last_spend_period = block_number.saturating_sub(last_spend_period); - let safe_spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); + let safe_spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); // Safe because of `max(1)` above. let (spend_periods_passed, extra_blocks) = ( @@ -466,7 +468,7 @@ pub mod pallet { blocks_since_last_spend_period % safe_spend_period, ); let new_last_spend_period = block_number.saturating_sub(extra_blocks); - if spend_periods_passed > BlockNumberFor::::zero() { + if spend_periods_passed > BlockNumberFor::::zero() { Self::spend_funds(spend_periods_passed, new_last_spend_period) } else { Weight::zero() @@ -474,7 +476,7 @@ pub mod pallet { } #[cfg(feature = "try-runtime")] - fn try_state(_: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { + fn try_state(_: SystemBlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { Self::do_try_state()?; Ok(()) } @@ -638,7 +640,7 @@ pub mod pallet { asset_kind: Box, #[pallet::compact] amount: AssetBalanceOf, beneficiary: Box>, - valid_from: Option>, + valid_from: Option>, ) -> DispatchResult { let max_amount = T::SpendOrigin::ensure_origin(origin)?; let beneficiary = T::BeneficiaryLookup::lookup(*beneficiary)?; @@ -844,9 +846,9 @@ impl, I: 'static> Pallet { // Backfill the `LastSpendPeriod` storage, assuming that no configuration has changed // since introducing this code. Used specifically for a migration-less switch to populate // `LastSpendPeriod`. - fn update_last_spend_period() -> BlockNumberFor { + fn update_last_spend_period() -> BlockNumberFor { let block_number = T::BlockNumberProvider::current_block_number(); - let spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); + let spend_period = T::SpendPeriod::get().max(BlockNumberFor::::one()); let time_since_last_spend = block_number % spend_period; // If it happens that this logic runs directly on a spend period block, we need to backdate // to the last spend period so a spend still occurs this block. @@ -889,8 +891,8 @@ impl, I: 'static> Pallet { /// Spend some money! returns number of approvals before spend. pub fn spend_funds( - spend_periods_passed: BlockNumberFor, - new_last_spend_period: BlockNumberFor, + spend_periods_passed: BlockNumberFor, + new_last_spend_period: BlockNumberFor, ) -> Weight { LastSpendPeriod::::put(new_last_spend_period); let mut total_weight = Weight::zero(); diff --git a/substrate/primitives/runtime/src/traits/mod.rs b/substrate/primitives/runtime/src/traits/mod.rs index 01bdcca86b6f..02bc7adc8ba5 100644 --- a/substrate/primitives/runtime/src/traits/mod.rs +++ b/substrate/primitives/runtime/src/traits/mod.rs @@ -2349,7 +2349,8 @@ pub trait BlockNumberProvider { + TypeInfo + Debug + MaxEncodedLen - + Copy; + + Copy + + EncodeLike; /// Returns the current block number. /// From b290f27c9bdbc76ca0f21272e4567c346da23f08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Thei=C3=9Fen?= Date: Thu, 21 Nov 2024 10:13:23 +0100 Subject: [PATCH 121/166] revive: Bump connect timeout to fix flaky tests (#6567) The eth RPC tests fail sometimes because they run into a connect timeout because the node takes a long time to start. This bumps the connect timeout from 30 to 120 seconds. Locally they take around 40s for me. As a drive by I also remove a apparently duplicated nextest config. --------- Co-authored-by: ordian --- .config/nextest.toml | 1 - substrate/.config/nextest.toml | 124 ------------------------ substrate/frame/revive/rpc/src/tests.rs | 4 +- 3 files changed, 2 insertions(+), 127 deletions(-) delete mode 100644 substrate/.config/nextest.toml diff --git a/.config/nextest.toml b/.config/nextest.toml index 912bf2514a77..b4bdec4aea92 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -21,7 +21,6 @@ retries = 5 # The number of threads to run tests with. Supported values are either an integer or # the string "num-cpus". Can be overridden through the `--test-threads` option. # test-threads = "num-cpus" - test-threads = 20 # The number of threads required for each test. This is generally used in overrides to diff --git a/substrate/.config/nextest.toml b/substrate/.config/nextest.toml deleted file mode 100644 index eb0ed09cad92..000000000000 --- a/substrate/.config/nextest.toml +++ /dev/null @@ -1,124 +0,0 @@ -# This is the default config used by nextest. It is embedded in the binary at -# build time. It may be used as a template for .config/nextest.toml. - -[store] -# The directory under the workspace root at which nextest-related files are -# written. Profile-specific storage is currently written to dir/. -dir = "target/nextest" - -# This section defines the default nextest profile. Custom profiles are layered -# on top of the default profile. -[profile.default] -# "retries" defines the number of times a test should be retried. If set to a -# non-zero value, tests that succeed on a subsequent attempt will be marked as -# non-flaky. Can be overridden through the `--retries` option. -# Examples -# * retries = 3 -# * retries = { backoff = "fixed", count = 2, delay = "1s" } -# * retries = { backoff = "exponential", count = 10, delay = "1s", jitter = true, max-delay = "10s" } -retries = 5 - -# The number of threads to run tests with. Supported values are either an integer or -# the string "num-cpus". Can be overridden through the `--test-threads` option. -test-threads = "num-cpus" - -# The number of threads required for each test. This is generally used in overrides to -# mark certain tests as heavier than others. However, it can also be set as a global parameter. -threads-required = 1 - -# Show these test statuses in the output. -# -# The possible values this can take are: -# * none: no output -# * fail: show failed (including exec-failed) tests -# * retry: show flaky and retried tests -# * slow: show slow tests -# * pass: show passed tests -# * skip: show skipped tests (most useful for CI) -# * all: all of the above -# -# Each value includes all the values above it; for example, "slow" includes -# failed and retried tests. -# -# Can be overridden through the `--status-level` flag. -status-level = "pass" - -# Similar to status-level, show these test statuses at the end of the run. -final-status-level = "flaky" - -# "failure-output" defines when standard output and standard error for failing tests are produced. -# Accepted values are -# * "immediate": output failures as soon as they happen -# * "final": output failures at the end of the test run -# * "immediate-final": output failures as soon as they happen and at the end of -# the test run; combination of "immediate" and "final" -# * "never": don't output failures at all -# -# For large test suites and CI it is generally useful to use "immediate-final". -# -# Can be overridden through the `--failure-output` option. -failure-output = "immediate" - -# "success-output" controls production of standard output and standard error on success. This should -# generally be set to "never". -success-output = "never" - -# Cancel the test run on the first failure. For CI runs, consider setting this -# to false. -fail-fast = true - -# Treat a test that takes longer than the configured 'period' as slow, and print a message. -# See for more information. -# -# Optional: specify the parameter 'terminate-after' with a non-zero integer, -# which will cause slow tests to be terminated after the specified number of -# periods have passed. -# Example: slow-timeout = { period = "60s", terminate-after = 2 } -slow-timeout = { period = "60s" } - -# Treat a test as leaky if after the process is shut down, standard output and standard error -# aren't closed within this duration. -# -# This usually happens in case of a test that creates a child process and lets it inherit those -# handles, but doesn't clean the child process up (especially when it fails). -# -# See for more information. -leak-timeout = "100ms" - -[profile.default.junit] -# Output a JUnit report into the given file inside 'store.dir/'. -# If unspecified, JUnit is not written out. - -path = "junit.xml" - -# The name of the top-level "report" element in JUnit report. If aggregating -# reports across different test runs, it may be useful to provide separate names -# for each report. -report-name = "substrate" - -# Whether standard output and standard error for passing tests should be stored in the JUnit report. -# Output is stored in the and elements of the element. -store-success-output = false - -# Whether standard output and standard error for failing tests should be stored in the JUnit report. -# Output is stored in the and elements of the element. -# -# Note that if a description can be extracted from the output, it is always stored in the -# element. -store-failure-output = true - -# This profile is activated if MIRI_SYSROOT is set. -[profile.default-miri] -# Miri tests take up a lot of memory, so only run 1 test at a time by default. -test-threads = 1 - -# Mutual exclusion of tests with `cargo build` invocation as a lock to avoid multiple -# simultaneous invocations clobbering each other. -[test-groups] -serial-integration = { max-threads = 1 } - -# Running UI tests sequentially -# More info can be found here: https://github.com/paritytech/ci_cd/issues/754 -[[profile.default.overrides]] -filter = 'test(/(^ui$|_ui|ui_)/)' -test-group = 'serial-integration' diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index eb23bd7583a0..7734c8c57209 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -32,9 +32,9 @@ use static_init::dynamic; use std::thread; use substrate_cli_test_utils::*; -/// Create a websocket client with a 30s timeout. +/// Create a websocket client with a 120s timeout. async fn ws_client_with_retry(url: &str) -> WsClient { - let timeout = tokio::time::Duration::from_secs(30); + let timeout = tokio::time::Duration::from_secs(120); tokio::time::timeout(timeout, async { loop { if let Ok(client) = WsClientBuilder::default().build(url).await { From 7c9e34b576ad91aba2575ddaaddca0ad1aecae83 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Thu, 21 Nov 2024 11:58:44 +0200 Subject: [PATCH 122/166] network-gossip: Ensure sync event is processed on unknown peer roles (#6553) The `GossipEngine::poll_next` implementation polls both the `notification_service` and the `sync_event_stream`. If both polls produce valid data to be processed (`Poll::Ready(Some(..))`), then the sync event is ignored when we receive `NotificationEvent::NotificationStreamOpened` and the role cannot be deduced. This PR ensures both events are processed gracefully. While at it, I have added a warning to the sync engine related to `notification_service` producing `Poll::Ready(None)`. This effectively ensures that `SyncEvents` propagate to the network potentially fixing any state mismatch. For more context: https://github.com/paritytech/polkadot-sdk/issues/6507 cc @paritytech/sdk-node --------- Signed-off-by: Alexandru Vasile --- prdoc/pr_6553.prdoc | 13 ++++++++++++ substrate/client/network-gossip/src/bridge.rs | 20 +++++++++---------- substrate/client/network/sync/src/engine.rs | 9 ++++++++- 3 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 prdoc/pr_6553.prdoc diff --git a/prdoc/pr_6553.prdoc b/prdoc/pr_6553.prdoc new file mode 100644 index 000000000000..8692eba3a9f5 --- /dev/null +++ b/prdoc/pr_6553.prdoc @@ -0,0 +1,13 @@ +title: Ensure sync event is processed on unknown peer roles + +doc: + - audience: Node Dev + description: | + The GossipEngine::poll_next implementation polls both the notification_service and the sync_event_stream. + This PR ensures both events are processed gracefully. + +crates: + - name: sc-network-gossip + bump: patch + - name: sc-network-sync + bump: patch diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index a4bd922a76d5..2daf1e49ee4b 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -220,18 +220,16 @@ impl Future for GossipEngine { }, NotificationEvent::NotificationStreamOpened { peer, handshake, .. - } => { - let Some(role) = this.network.peer_role(peer, handshake) else { + } => + if let Some(role) = this.network.peer_role(peer, handshake) { + this.state_machine.new_peer( + &mut this.notification_service, + peer, + role, + ); + } else { log::debug!(target: "gossip", "role for {peer} couldn't be determined"); - continue - }; - - this.state_machine.new_peer( - &mut this.notification_service, - peer, - role, - ); - }, + }, NotificationEvent::NotificationStreamClosed { peer } => { this.state_machine .peer_disconnected(&mut this.notification_service, peer); diff --git a/substrate/client/network/sync/src/engine.rs b/substrate/client/network/sync/src/engine.rs index cc2089d1974c..349c41ee1f4a 100644 --- a/substrate/client/network/sync/src/engine.rs +++ b/substrate/client/network/sync/src/engine.rs @@ -545,7 +545,14 @@ where self.process_service_command(command), notification_event = self.notification_service.next_event() => match notification_event { Some(event) => self.process_notification_event(event), - None => return, + None => { + error!( + target: LOG_TARGET, + "Terminating `SyncingEngine` because `NotificationService` has terminated.", + ); + + return; + } }, response_event = self.pending_responses.select_next_some() => self.process_response_event(response_event), From 56d97c3ad8c86e602bc7ac368751210517c4309f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Thu, 21 Nov 2024 10:14:36 +0000 Subject: [PATCH 123/166] slot-based-collator: Move spawning of the futures (#6561) Move spawning of the slot-based collator into the `run` function. Also the tasks are being spawned as blocking task and not just as normal tasks. --------- Co-authored-by: GitHub Action --- .../aura/src/collators/slot_based/mod.rs | 82 ++++++++++++------- .../polkadot-omni-node/lib/src/nodes/aura.rs | 23 ++---- cumulus/test/service/src/lib.rs | 14 +--- prdoc/pr_6561.prdoc | 11 +++ 4 files changed, 73 insertions(+), 57 deletions(-) create mode 100644 prdoc/pr_6561.prdoc diff --git a/cumulus/client/consensus/aura/src/collators/slot_based/mod.rs b/cumulus/client/consensus/aura/src/collators/slot_based/mod.rs index 7453d3c89d08..18e63681d578 100644 --- a/cumulus/client/consensus/aura/src/collators/slot_based/mod.rs +++ b/cumulus/client/consensus/aura/src/collators/slot_based/mod.rs @@ -28,6 +28,7 @@ //! during the relay chain block. After the block is built, the block builder task sends it to //! the collation task which compresses it and submits it to the collation-generation subsystem. +use self::{block_builder_task::run_block_builder, collation_task::run_collation_task}; use codec::Codec; use consensus_common::ParachainCandidate; use cumulus_client_collator::service::ServiceInterface as CollatorServiceInterface; @@ -36,32 +37,28 @@ use cumulus_client_consensus_proposer::ProposerInterface; use cumulus_primitives_aura::AuraUnincludedSegmentApi; use cumulus_primitives_core::GetCoreSelectorApi; use cumulus_relay_chain_interface::RelayChainInterface; +use futures::FutureExt; use polkadot_primitives::{ CollatorPair, CoreIndex, Hash as RelayHash, Id as ParaId, ValidationCodeHash, }; - use sc_client_api::{backend::AuxStore, BlockBackend, BlockOf, UsageProvider}; use sc_consensus::BlockImport; use sc_utils::mpsc::tracing_unbounded; - use sp_api::ProvideRuntimeApi; use sp_application_crypto::AppPublic; use sp_blockchain::HeaderBackend; use sp_consensus_aura::AuraApi; -use sp_core::crypto::Pair; +use sp_core::{crypto::Pair, traits::SpawnNamed}; use sp_inherents::CreateInherentDataProviders; use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, Member}; - use std::{sync::Arc, time::Duration}; -use self::{block_builder_task::run_block_builder, collation_task::run_collation_task}; - mod block_builder_task; mod collation_task; /// Parameters for [`run`]. -pub struct Params { +pub struct Params { /// Inherent data providers. Only non-consensus inherent data should be provided, i.e. /// the timestamp, slot, and paras inherents should be omitted, as they are set by this /// collator. @@ -93,13 +90,30 @@ pub struct Params { /// Drift slots by a fixed duration. This can be used to create more preferrable authoring /// timings. pub slot_drift: Duration, + /// Spawner for spawning futures. + pub spawner: Spawner, } /// Run aura-based block building and collation task. -pub fn run( - params: Params, -) -> (impl futures::Future, impl futures::Future) -where +pub fn run( + Params { + create_inherent_data_providers, + block_import, + para_client, + para_backend, + relay_client, + code_hash_provider, + keystore, + collator_key, + para_id, + proposer, + collator_service, + authoring_duration, + reinitialize, + slot_drift, + spawner, + }: Params, +) where Block: BlockT, Client: ProvideRuntimeApi + BlockOf @@ -123,39 +137,49 @@ where P: Pair + 'static, P::Public: AppPublic + Member + Codec, P::Signature: TryFrom> + Member + Codec, + Spawner: SpawnNamed, { let (tx, rx) = tracing_unbounded("mpsc_builder_to_collator", 100); let collator_task_params = collation_task::Params { - relay_client: params.relay_client.clone(), - collator_key: params.collator_key, - para_id: params.para_id, - reinitialize: params.reinitialize, - collator_service: params.collator_service.clone(), + relay_client: relay_client.clone(), + collator_key, + para_id, + reinitialize, + collator_service: collator_service.clone(), collator_receiver: rx, }; let collation_task_fut = run_collation_task::(collator_task_params); let block_builder_params = block_builder_task::BuilderTaskParams { - create_inherent_data_providers: params.create_inherent_data_providers, - block_import: params.block_import, - para_client: params.para_client, - para_backend: params.para_backend, - relay_client: params.relay_client, - code_hash_provider: params.code_hash_provider, - keystore: params.keystore, - para_id: params.para_id, - proposer: params.proposer, - collator_service: params.collator_service, - authoring_duration: params.authoring_duration, + create_inherent_data_providers, + block_import, + para_client, + para_backend, + relay_client, + code_hash_provider, + keystore, + para_id, + proposer, + collator_service, + authoring_duration, collator_sender: tx, - slot_drift: params.slot_drift, + slot_drift, }; let block_builder_fut = run_block_builder::(block_builder_params); - (collation_task_fut, block_builder_fut) + spawner.spawn_blocking( + "slot-based-block-builder", + Some("slot-based-collator"), + block_builder_fut.boxed(), + ); + spawner.spawn_blocking( + "slot-based-collation", + Some("slot-based-collator"), + collation_task_fut.boxed(), + ); } /// Message to be sent from the block builder to the collation task. diff --git a/cumulus/polkadot-omni-node/lib/src/nodes/aura.rs b/cumulus/polkadot-omni-node/lib/src/nodes/aura.rs index ec5d0a439ec4..0b2c230f695d 100644 --- a/cumulus/polkadot-omni-node/lib/src/nodes/aura.rs +++ b/cumulus/polkadot-omni-node/lib/src/nodes/aura.rs @@ -54,6 +54,7 @@ use sc_service::{Configuration, Error, TaskManager}; use sc_telemetry::TelemetryHandle; use sc_transaction_pool::TransactionPoolHandle; use sp_api::ProvideRuntimeApi; +use sp_core::traits::SpawnNamed; use sp_inherents::CreateInherentDataProviders; use sp_keystore::KeystorePtr; use sp_runtime::{ @@ -242,7 +243,7 @@ where AuraId: AuraIdT + Sync, { #[docify::export_content] - fn launch_slot_based_collator( + fn launch_slot_based_collator( params: SlotBasedParams< ParachainBlockImport, CIDP, @@ -252,28 +253,17 @@ where CHP, Proposer, CS, + Spawner, >, - task_manager: &TaskManager, ) where CIDP: CreateInherentDataProviders + 'static, CIDP::InherentDataProviders: Send, CHP: cumulus_client_consensus_common::ValidationCodeHashProvider + Send + 'static, Proposer: ProposerInterface + Send + Sync + 'static, CS: CollatorServiceInterface + Send + Sync + Clone + 'static, + Spawner: SpawnNamed, { - let (collation_future, block_builder_future) = - slot_based::run::::Pair, _, _, _, _, _, _, _, _>(params); - - task_manager.spawn_essential_handle().spawn( - "collation-task", - Some("parachain-block-authoring"), - collation_future, - ); - task_manager.spawn_essential_handle().spawn( - "block-builder-task", - Some("parachain-block-authoring"), - block_builder_future, - ); + slot_based::run::::Pair, _, _, _, _, _, _, _, _, _>(params); } } @@ -335,11 +325,12 @@ where authoring_duration: Duration::from_millis(2000), reinitialize: false, slot_drift: Duration::from_secs(1), + spawner: task_manager.spawn_handle(), }; // We have a separate function only to be able to use `docify::export` on this piece of // code. - Self::launch_slot_based_collator(params, task_manager); + Self::launch_slot_based_collator(params); Ok(()) } diff --git a/cumulus/test/service/src/lib.rs b/cumulus/test/service/src/lib.rs index 9234442d399c..f01da9becef1 100644 --- a/cumulus/test/service/src/lib.rs +++ b/cumulus/test/service/src/lib.rs @@ -497,20 +497,10 @@ where authoring_duration: Duration::from_millis(2000), reinitialize: false, slot_drift: Duration::from_secs(1), + spawner: task_manager.spawn_handle(), }; - let (collation_future, block_builder_future) = - slot_based::run::(params); - task_manager.spawn_essential_handle().spawn( - "collation-task", - None, - collation_future, - ); - task_manager.spawn_essential_handle().spawn( - "block-builder-task", - None, - block_builder_future, - ); + slot_based::run::(params); } else { tracing::info!(target: LOG_TARGET, "Starting block authoring with lookahead collator."); let params = AuraParams { diff --git a/prdoc/pr_6561.prdoc b/prdoc/pr_6561.prdoc new file mode 100644 index 000000000000..714521925a6b --- /dev/null +++ b/prdoc/pr_6561.prdoc @@ -0,0 +1,11 @@ +title: 'slot-based-collator: Move spawning of the futures' +doc: +- audience: Node Dev + description: "Move spawning of the slot-based collator into the `run` function.\ + \ Also the tasks are being spawned as blocking task and not just as normal tasks.\r\ + \n" +crates: +- name: cumulus-client-consensus-aura + bump: major +- name: polkadot-omni-node-lib + bump: major From 1f7765b63530e362d6b1b4a225b47daddda03637 Mon Sep 17 00:00:00 2001 From: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> Date: Thu, 21 Nov 2024 15:39:08 +0200 Subject: [PATCH 124/166] github/workflows: add ARM macos build binaries job (#6427) # Description This PR adds the required changes to release `polkadot`, `polkadot-parachain` and `polkadot-omni-node` binaries built on Apple Sillicon macos. ## Integration This addresses requests from the community for such binaries: #802, and they should be part of the Github release page. ## Review Notes Test on paritytech-stg solely focused on macos binaries: https://github.com/paritytech-stg/polkadot-sdk/actions/runs/11824692766/job/32946793308, except the steps related to `pgpkms` (which need AWS credentials, missing from paritytech-stg). The binary names don't have a `darwin-arm` identifier, and conflict with the existing x86_64-linux binaries. I haven't tested building everything on `paritytech-stg` because the x86_64-linux builds run on `unbutu-latest-m` which isn't enabled on `pairtytech-stg` (and I haven't asked CI team to enable one), so testing how to go around naming conflicts should be covered next. ### TODO - [x] Test the workflow start to end (especially the last bits related to uploading the binaries on S3 and ensuring the previous binaries and the new ones coexist harmoniously on S3/action artifacts storage without naming conflicts) @EgorPopelyaev - [x] Publish the arm binaries on the Github release page - to clarify what's needed @iulianbarbu . Current practice is to manually publish the binaries built via `release-build-rc.yml` workflow, taken from S3. Would be great to have the binaries there in the first place before working on automating this, but I would also do it in a follow up PR. ### Follow ups - [ ] unify the binaries building under `release-30_publish_release_draft.yml` maybe? - [ ] automate binary artifacts upload to S3 in `release-30_publish_release_draft.yml` --------- Signed-off-by: Iulian Barbu Co-authored-by: EgorPopelyaev --- .../scripts/release/build-linux-release.sh | 4 +- .../scripts/release/build-macos-release.sh | 37 +++ .github/scripts/release/release_lib.sh | 38 ++-- .../release-30_publish_release_draft.yml | 4 +- .github/workflows/release-build-rc.yml | 91 ++++++++ .../workflows/release-reusable-rc-buid.yml | 212 +++++++++++++++++- .../workflows/release-reusable-s3-upload.yml | 17 +- 7 files changed, 376 insertions(+), 27 deletions(-) create mode 100755 .github/scripts/release/build-macos-release.sh diff --git a/.github/scripts/release/build-linux-release.sh b/.github/scripts/release/build-linux-release.sh index a6bd658d292a..874c9b44788b 100755 --- a/.github/scripts/release/build-linux-release.sh +++ b/.github/scripts/release/build-linux-release.sh @@ -3,6 +3,8 @@ # This is used to build our binaries: # - polkadot # - polkadot-parachain +# - polkadot-omni-node +# # set -e BIN=$1 @@ -21,7 +23,7 @@ time cargo build --profile $PROFILE --locked --verbose --bin $BIN --package $PAC echo "Artifact target: $ARTIFACTS" cp ./target/$PROFILE/$BIN "$ARTIFACTS" -pushd "$ARTIFACTS" > /dev/nul +pushd "$ARTIFACTS" > /dev/null sha256sum "$BIN" | tee "$BIN.sha256" EXTRATAG="$($ARTIFACTS/$BIN --version | diff --git a/.github/scripts/release/build-macos-release.sh b/.github/scripts/release/build-macos-release.sh new file mode 100755 index 000000000000..ba6dcc65d650 --- /dev/null +++ b/.github/scripts/release/build-macos-release.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +# This is used to build our binaries: +# - polkadot +# - polkadot-parachain +# - polkadot-omni-node +# set -e + +BIN=$1 +PACKAGE=${2:-$BIN} + +PROFILE=${PROFILE:-production} +# parity-macos runner needs a path where it can +# write, so make it relative to github workspace. +ARTIFACTS=$GITHUB_WORKSPACE/artifacts/$BIN +VERSION=$(git tag -l --contains HEAD | grep -E "^v.*") + +echo "Artifacts will be copied into $ARTIFACTS" +mkdir -p "$ARTIFACTS" + +git log --pretty=oneline -n 1 +time cargo build --profile $PROFILE --locked --verbose --bin $BIN --package $PACKAGE + +echo "Artifact target: $ARTIFACTS" + +cp ./target/$PROFILE/$BIN "$ARTIFACTS" +pushd "$ARTIFACTS" > /dev/null +sha256sum "$BIN" | tee "$BIN.sha256" + +EXTRATAG="$($ARTIFACTS/$BIN --version | + sed -n -r 's/^'$BIN' ([0-9.]+.*-[0-9a-f]{7,13})-.*$/\1/p')" + +EXTRATAG="${VERSION}-${EXTRATAG}-$(cut -c 1-8 $ARTIFACTS/$BIN.sha256)" + +echo "$BIN version = ${VERSION} (EXTRATAG = ${EXTRATAG})" +echo -n ${VERSION} > "$ARTIFACTS/VERSION" +echo -n ${EXTRATAG} > "$ARTIFACTS/EXTRATAG" diff --git a/.github/scripts/release/release_lib.sh b/.github/scripts/release/release_lib.sh index f5032073b617..8b9254ec3f29 100644 --- a/.github/scripts/release/release_lib.sh +++ b/.github/scripts/release/release_lib.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# Set the new version by replacing the value of the constant given as patetrn +# Set the new version by replacing the value of the constant given as pattern # in the file. # # input: pattern, version, file @@ -119,21 +119,23 @@ set_polkadot_parachain_binary_version() { upload_s3_release() { - alias aws='podman run --rm -it docker.io/paritytech/awscli -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_BUCKET aws' - - product=$1 - version=$2 - - echo "Working on product: $product " - echo "Working on version: $version " - - echo "Current content, should be empty on new uploads:" - aws s3 ls "s3://releases.parity.io/polkadot/${version}/" --recursive --human-readable --summarize || true - echo "Content to be uploaded:" - artifacts="artifacts/$product/" - ls "$artifacts" - aws s3 sync --acl public-read "$artifacts" "s3://releases.parity.io/polkadot/${version}/" - echo "Uploaded files:" - aws s3 ls "s3://releases.parity.io/polkadot/${version}/" --recursive --human-readable --summarize - echo "✅ The release should be at https://releases.parity.io/polkadot/${version}" + alias aws='podman run --rm -it docker.io/paritytech/awscli -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_BUCKET aws' + + product=$1 + version=$2 + target=$3 + + echo "Working on product: $product " + echo "Working on version: $version " + echo "Working on platform: $target " + + echo "Current content, should be empty on new uploads:" + aws s3 ls "s3://releases.parity.io/${product}/${version}/${target}" --recursive --human-readable --summarize || true + echo "Content to be uploaded:" + artifacts="artifacts/$product/" + ls "$artifacts" + aws s3 sync --acl public-read "$artifacts" "s3://releases.parity.io/${product}/${version}/${target}" + echo "Uploaded files:" + aws s3 ls "s3://releases.parity.io/${product}/${version}/${target}" --recursive --human-readable --summarize + echo "✅ The release should be at https://releases.parity.io/${product}/${version}/${target}" } diff --git a/.github/workflows/release-30_publish_release_draft.yml b/.github/workflows/release-30_publish_release_draft.yml index 376f5fbce909..4364b4f80457 100644 --- a/.github/workflows/release-30_publish_release_draft.yml +++ b/.github/workflows/release-30_publish_release_draft.yml @@ -34,7 +34,7 @@ jobs: strategy: matrix: # Tuples of [package, binary-name] - binary: [ [frame-omni-bencher, frame-omni-bencher], [staging-chain-spec-builder, chain-spec-builder], [polkadot-omni-node, polkadot-omni-node] ] + binary: [ [frame-omni-bencher, frame-omni-bencher], [staging-chain-spec-builder, chain-spec-builder] ] steps: - name: Checkout sources uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.0.0 @@ -161,7 +161,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - binary: [frame-omni-bencher, chain-spec-builder, polkadot-omni-node] + binary: [frame-omni-bencher, chain-spec-builder] steps: - name: Download artifacts diff --git a/.github/workflows/release-build-rc.yml b/.github/workflows/release-build-rc.yml index 94bacf320898..a43c2b282a8d 100644 --- a/.github/workflows/release-build-rc.yml +++ b/.github/workflows/release-build-rc.yml @@ -10,6 +10,7 @@ on: options: - polkadot - polkadot-parachain + - polkadot-omni-node - all release_tag: @@ -47,6 +48,7 @@ jobs: binary: '["polkadot", "polkadot-prepare-worker", "polkadot-execute-worker"]' package: polkadot release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: x86_64-unknown-linux-gnu secrets: PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} @@ -68,6 +70,95 @@ jobs: binary: '["polkadot-parachain"]' package: "polkadot-parachain-bin" release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: x86_64-unknown-linux-gnu + secrets: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read + + build-polkadot-omni-node-binary: + needs: [validate-inputs] + if: ${{ inputs.binary == 'polkadot-omni-node' || inputs.binary == 'all' }} + uses: "./.github/workflows/release-reusable-rc-buid.yml" + with: + binary: '["polkadot-omni-node"]' + package: "polkadot-omni-node" + release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: x86_64-unknown-linux-gnu + secrets: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read + + build-polkadot-macos-binary: + needs: [validate-inputs] + if: ${{ inputs.binary == 'polkadot' || inputs.binary == 'all' }} + uses: "./.github/workflows/release-reusable-rc-buid.yml" + with: + binary: '["polkadot", "polkadot-prepare-worker", "polkadot-execute-worker"]' + package: polkadot + release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: aarch64-apple-darwin + secrets: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read + + build-polkadot-parachain-macos-binary: + needs: [validate-inputs] + if: ${{ inputs.binary == 'polkadot-parachain' || inputs.binary == 'all' }} + uses: "./.github/workflows/release-reusable-rc-buid.yml" + with: + binary: '["polkadot-parachain"]' + package: "polkadot-parachain-bin" + release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: aarch64-apple-darwin + secrets: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + permissions: + id-token: write + attestations: write + contents: read + + build-polkadot-omni-node-macos-binary: + needs: [validate-inputs] + if: ${{ inputs.binary == 'polkadot-omni-node' || inputs.binary == 'all' }} + uses: "./.github/workflows/release-reusable-rc-buid.yml" + with: + binary: '["polkadot-omni-node"]' + package: "polkadot-omni-node" + release_tag: ${{ needs.validate-inputs.outputs.release_tag }} + target: aarch64-apple-darwin secrets: PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} diff --git a/.github/workflows/release-reusable-rc-buid.yml b/.github/workflows/release-reusable-rc-buid.yml index d925839fb84a..7e31a4744b59 100644 --- a/.github/workflows/release-reusable-rc-buid.yml +++ b/.github/workflows/release-reusable-rc-buid.yml @@ -10,7 +10,7 @@ on: type: string package: - description: Package to be built, for now is either polkadot or polkadot-parachain-bin + description: Package to be built, for now can be polkadot, polkadot-parachain-bin, or polkadot-omni-node required: true type: string @@ -19,6 +19,11 @@ on: required: true type: string + target: + description: Target triple for which the artifacts are being built (e.g. x86_64-unknown-linux-gnu) + required: true + type: string + secrets: PGP_KMS_KEY: required: true @@ -57,6 +62,7 @@ jobs: run: cat .github/env >> $GITHUB_OUTPUT build-rc: + if: ${{ inputs.target == 'x86_64-unknown-linux-gnu' }} needs: [set-image] runs-on: ubuntu-latest-m environment: release @@ -130,8 +136,124 @@ jobs: name: ${{ matrix.binaries }} path: /artifacts/${{ matrix.binaries }} + build-macos-rc: + if: ${{ inputs.target == 'aarch64-apple-darwin' }} + runs-on: parity-macos + environment: release + strategy: + matrix: + binaries: ${{ fromJSON(inputs.binary) }} + env: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + SKIP_WASM_BUILD: 1 + steps: + - name: Checkout sources + uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 + with: + ref: ${{ inputs.release_tag }} + fetch-depth: 0 + + - name: Set rust version from env file + run: | + RUST_VERSION=$(cat .github/env | sed -E 's/.*ci-unified:([^-]+)-([^-]+).*/\2/') + echo $RUST_VERSION + echo "RUST_VERSION=${RUST_VERSION}" >> $GITHUB_ENV + - name: Set workspace environment variable + # relevant for artifacts upload, which can not interpolate Github Action variable syntax when + # used within valid paths. We can not use root-based paths either, since it is set as read-only + # on the `parity-macos` runner. + run: echo "ARTIFACTS_PATH=${GITHUB_WORKSPACE}/artifacts/${{ matrix.binaries }}" >> $GITHUB_ENV + + - name: Set up Homebrew + uses: Homebrew/actions/setup-homebrew@1ccc07ccd54b6048295516a3eb89b192c35057dc # master from 12.09.2024 + - name: Set homebrew binaries location on path + run: echo "/opt/homebrew/bin" >> $GITHUB_PATH + + - name: Install rust ${{ env.RUST_VERSION }} + uses: actions-rust-lang/setup-rust-toolchain@11df97af8e8102fd60b60a77dfbf58d40cd843b8 # v1.10.1 + with: + cache: false + toolchain: ${{ env.RUST_VERSION }} + target: wasm32-unknown-unknown + components: cargo, clippy, rust-docs, rust-src, rustfmt, rustc, rust-std + + - name: cargo info + run: | + echo "######## rustup show ########" + rustup show + echo "######## cargo --version ########" + cargo --version + + - name: Install protobuf + run: brew install protobuf + - name: Install gpg + run: | + brew install gnupg + # Setup for being able to resolve: keyserver.ubuntu.com. + # See: https://github.com/actions/runner-images/issues/9777 + mkdir -p ~/.gnupg/ + touch ~/.gnupg/dirmngr.conf + echo "standard-resolver" > ~/.gnupg/dirmngr.conf + - name: Install sha256sum + run: | + brew install coreutils + + - name: Install pgpkkms + run: | + # Install pgpkms that is used to sign built artifacts + python3 -m pip install "pgpkms @ git+https://github.com/paritytech-release/pgpkms.git@5a8f82fbb607ea102d8c178e761659de54c7af69" --break-system-packages + + - name: Import gpg keys + shell: bash + run: | + . ./.github/scripts/common/lib.sh + + import_gpg_keys + + - name: Build binary + run: | + git config --global --add safe.directory "${GITHUB_WORKSPACE}" #avoid "detected dubious ownership" error + ./.github/scripts/release/build-macos-release.sh ${{ matrix.binaries }} ${{ inputs.package }} + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@1c608d11d69870c2092266b3f9a6f3abbf17002c # v1.4.3 + with: + subject-path: ${{ env.ARTIFACTS_PATH }}/${{ matrix.binaries }} + + - name: Sign artifacts + working-directory: ${{ env.ARTIFACTS_PATH }} + run: | + python3 -m pgpkms sign --input ${{matrix.binaries }} -o ${{ matrix.binaries }}.asc + + - name: Check sha256 ${{ matrix.binaries }} + working-directory: ${{ env.ARTIFACTS_PATH }} + shell: bash + run: | + . "${GITHUB_WORKSPACE}"/.github/scripts/common/lib.sh + + echo "Checking binary ${{ matrix.binaries }}" + check_sha256 ${{ matrix.binaries }} + + - name: Check GPG ${{ matrix.binaries }} + working-directory: ${{ env.ARTIFACTS_PATH }} + shell: bash + run: | + . "${GITHUB_WORKSPACE}"/.github/scripts/common/lib.sh + + check_gpg ${{ matrix.binaries }} + + - name: Upload ${{ matrix.binaries }} artifacts + uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 + with: + name: ${{ matrix.binaries }}_${{ inputs.target }} + path: ${{ env.ARTIFACTS_PATH }} + build-polkadot-deb-package: - if: ${{ inputs.package == 'polkadot' }} + if: ${{ inputs.package == 'polkadot' && inputs.target == 'x86_64-unknown-linux-gnu' }} needs: [build-rc] runs-on: ubuntu-latest @@ -168,12 +290,13 @@ jobs: overwrite: true upload-polkadot-artifacts-to-s3: - if: ${{ inputs.package == 'polkadot' }} + if: ${{ inputs.package == 'polkadot' && inputs.target == 'x86_64-unknown-linux-gnu' }} needs: [build-polkadot-deb-package] uses: ./.github/workflows/release-reusable-s3-upload.yml with: package: ${{ inputs.package }} release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} secrets: AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} @@ -181,12 +304,93 @@ jobs: upload-polkadot-parachain-artifacts-to-s3: - if: ${{ inputs.package == 'polkadot-parachain-bin' }} + if: ${{ inputs.package == 'polkadot-parachain-bin' && inputs.target == 'x86_64-unknown-linux-gnu' }} needs: [build-rc] uses: ./.github/workflows/release-reusable-s3-upload.yml with: package: polkadot-parachain release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-omni-node-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot-omni-node' && inputs.target == 'x86_64-unknown-linux-gnu' }} + needs: [build-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: ${{ inputs.package }} + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-macos-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot' && inputs.target == 'aarch64-apple-darwin' }} + # TODO: add and use a `build-polkadot-homebrew-package` which packs all `polkadot` binaries: + # `polkadot`, `polkadot-prepare-worker` and `polkadot-execute-worker`. + needs: [build-macos-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: ${{ inputs.package }} + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-prepare-worker-macos-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot' && inputs.target == 'aarch64-apple-darwin' }} + needs: [build-macos-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: polkadot-prepare-worker + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-execute-worker-macos-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot' && inputs.target == 'aarch64-apple-darwin' }} + needs: [build-macos-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: polkadot-execute-worker + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-omni-node-macos-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot-omni-node' && inputs.target == 'aarch64-apple-darwin' }} + needs: [build-macos-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: ${{ inputs.package }} + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} + secrets: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_RELEASE_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + + upload-polkadot-parachain-macos-artifacts-to-s3: + if: ${{ inputs.package == 'polkadot-parachain-bin' && inputs.target == 'aarch64-apple-darwin' }} + needs: [build-macos-rc] + uses: ./.github/workflows/release-reusable-s3-upload.yml + with: + package: polkadot-parachain + release_tag: ${{ inputs.release_tag }} + target: ${{ inputs.target }} secrets: AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} AWS_RELEASE_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} diff --git a/.github/workflows/release-reusable-s3-upload.yml b/.github/workflows/release-reusable-s3-upload.yml index 6776b78da8e6..f85466bc8c07 100644 --- a/.github/workflows/release-reusable-s3-upload.yml +++ b/.github/workflows/release-reusable-s3-upload.yml @@ -13,6 +13,11 @@ on: required: true type: string + target: + description: Target triple for which the artifacts are being uploaded (e.g aarch64-apple-darwin) + required: true + type: string + secrets: AWS_DEFAULT_REGION: required: true @@ -34,12 +39,20 @@ jobs: - name: Checkout uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 - - name: Download artifacts + - name: Download amd64 artifacts + if: ${{ inputs.target == 'x86_64-unknown-linux-gnu' }} uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 with: name: ${{ inputs.package }} path: artifacts/${{ inputs.package }} + - name: Download arm artifacts + if: ${{ inputs.target == 'aarch64-apple-darwin' }} + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: ${{ inputs.package }}_aarch64-apple-darwin + path: artifacts/${{ inputs.package }} + - name: Configure AWS Credentials uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2 with: @@ -50,4 +63,4 @@ jobs: - name: Upload ${{ inputs.package }} artifacts to s3 run: | . ./.github/scripts/release/release_lib.sh - upload_s3_release ${{ inputs.package }} ${{ inputs.release_tag }} + upload_s3_release ${{ inputs.package }} ${{ inputs.release_tag }} ${{ inputs.target }} From bf20a9ee18f7215210bbbabf79e955c8c35b3360 Mon Sep 17 00:00:00 2001 From: Ankan <10196091+Ank4n@users.noreply.github.com> Date: Thu, 21 Nov 2024 21:04:47 +0700 Subject: [PATCH 125/166] [Fix|NominationPools] Only allow apply slash to be executed if the slash amount is atleast ED (#6540) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This change prevents `pools::apply_slash` from being executed when the pending slash amount of the member is lower than the ED. The issue came to light with the failing [benchmark test](https://github.com/polkadot-fellows/runtimes/actions/runs/11879471717/job/33101445269?pr=490#step:11:765) in Kusama. The problem arises from the inexact conversion between points and balance. Specifically, when points are converted to balance and then back to points, rounding can introduce a small discrepancy between the input and the resulting value. This issue surfaced in Kusama due to its ED being different from Westend and Polkadot (1 UNIT/300), making the rounding issue noticeable. This fix is also significant because applying a slash is feeless and permissionless. Allowing super small slash amounts to be applied without a fee is undesirable. With this change, such small slashes will still be applied but only when member funds are withdrawn. --------- Co-authored-by: Dónal Murray --- prdoc/pr_6540.prdoc | 16 ++++++++ .../nomination-pools/runtime-api/src/lib.rs | 3 ++ substrate/frame/nomination-pools/src/lib.rs | 23 +++++++++--- .../test-delegate-stake/Cargo.toml | 2 +- .../test-delegate-stake/src/lib.rs | 37 +++++++++++++++++-- 5 files changed, 71 insertions(+), 10 deletions(-) create mode 100644 prdoc/pr_6540.prdoc diff --git a/prdoc/pr_6540.prdoc b/prdoc/pr_6540.prdoc new file mode 100644 index 000000000000..5e0305205521 --- /dev/null +++ b/prdoc/pr_6540.prdoc @@ -0,0 +1,16 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Only allow apply slash to be executed if the slash amount is atleast ED + +doc: + - audience: Runtime User + description: | + This change prevents `pools::apply_slash` from being executed when the pending slash amount of the member is lower + than the ED. With this change, such small slashes will still be applied but only when member funds are withdrawn. + +crates: +- name: pallet-nomination-pools-runtime-api + bump: patch +- name: pallet-nomination-pools + bump: major diff --git a/substrate/frame/nomination-pools/runtime-api/src/lib.rs b/substrate/frame/nomination-pools/runtime-api/src/lib.rs index 4138dd22d898..644ee07fd634 100644 --- a/substrate/frame/nomination-pools/runtime-api/src/lib.rs +++ b/substrate/frame/nomination-pools/runtime-api/src/lib.rs @@ -43,6 +43,9 @@ sp_api::decl_runtime_apis! { fn pool_pending_slash(pool_id: PoolId) -> Balance; /// Returns the pending slash for a given pool member. + /// + /// If pending slash of the member exceeds `ExistentialDeposit`, it can be reported on + /// chain. fn member_pending_slash(member: AccountId) -> Balance; /// Returns true if the pool with `pool_id` needs migration. diff --git a/substrate/frame/nomination-pools/src/lib.rs b/substrate/frame/nomination-pools/src/lib.rs index 201b0af1d608..dc82bf3a37c6 100644 --- a/substrate/frame/nomination-pools/src/lib.rs +++ b/substrate/frame/nomination-pools/src/lib.rs @@ -1944,6 +1944,8 @@ pub mod pallet { NothingToAdjust, /// No slash pending that can be applied to the member. NothingToSlash, + /// The slash amount is too low to be applied. + SlashTooLow, /// The pool or member delegation has already migrated to delegate stake. AlreadyMigrated, /// The pool or member delegation has not migrated yet to delegate stake. @@ -2300,7 +2302,7 @@ pub mod pallet { let slash_weight = // apply slash if any before withdraw. - match Self::do_apply_slash(&member_account, None) { + match Self::do_apply_slash(&member_account, None, false) { Ok(_) => T::WeightInfo::apply_slash(), Err(e) => { let no_pending_slash: DispatchResult = Err(Error::::NothingToSlash.into()); @@ -2974,8 +2976,10 @@ pub mod pallet { /// Fails unless [`crate::pallet::Config::StakeAdapter`] is of strategy type: /// [`adapter::StakeStrategyType::Delegate`]. /// - /// This call can be dispatched permissionlessly (i.e. by any account). If the member has - /// slash to be applied, caller may be rewarded with the part of the slash. + /// The pending slash amount of the member must be equal or more than `ExistentialDeposit`. + /// This call can be dispatched permissionlessly (i.e. by any account). If the execution + /// is successful, fee is refunded and caller may be rewarded with a part of the slash + /// based on the [`crate::pallet::Config::StakeAdapter`] configuration. #[pallet::call_index(23)] #[pallet::weight(T::WeightInfo::apply_slash())] pub fn apply_slash( @@ -2989,7 +2993,7 @@ pub mod pallet { let who = ensure_signed(origin)?; let member_account = T::Lookup::lookup(member_account)?; - Self::do_apply_slash(&member_account, Some(who))?; + Self::do_apply_slash(&member_account, Some(who), true)?; // If successful, refund the fees. Ok(Pays::No.into()) @@ -3574,15 +3578,21 @@ impl Pallet { fn do_apply_slash( member_account: &T::AccountId, reporter: Option, + enforce_min_slash: bool, ) -> DispatchResult { let member = PoolMembers::::get(member_account).ok_or(Error::::PoolMemberNotFound)?; let pending_slash = Self::member_pending_slash(Member::from(member_account.clone()), member.clone())?; - // if nothing to slash, return error. + // ensure there is something to slash. ensure!(!pending_slash.is_zero(), Error::::NothingToSlash); + if enforce_min_slash { + // ensure slashed amount is at least the minimum balance. + ensure!(pending_slash >= T::Currency::minimum_balance(), Error::::SlashTooLow); + } + T::StakeAdapter::member_slash( Member::from(member_account.clone()), Pool::from(Pallet::::generate_bonded_account(member.pool_id)), @@ -3946,6 +3956,9 @@ impl Pallet { /// Returns the unapplied slash of a member. /// /// Pending slash is only applicable with [`adapter::DelegateStake`] strategy. + /// + /// If pending slash of the member exceeds `ExistentialDeposit`, it can be reported on + /// chain via [`Call::apply_slash`]. pub fn api_member_pending_slash(who: T::AccountId) -> BalanceOf { PoolMembers::::get(who.clone()) .map(|pool_member| { diff --git a/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml b/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml index 7940caaff775..70e1591409b8 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml +++ b/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml @@ -26,7 +26,7 @@ sp-staking = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } frame-system = { workspace = true, default-features = true } -frame-support = { workspace = true, default-features = true } +frame-support = { features = ["experimental"], workspace = true, default-features = true } frame-election-provider-support = { workspace = true, default-features = true } pallet-timestamp = { workspace = true, default-features = true } diff --git a/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs b/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs index 40025cdbb3cd..cc6335959ab7 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs +++ b/substrate/frame/nomination-pools/test-delegate-stake/src/lib.rs @@ -20,7 +20,7 @@ mod mock; use frame_support::{ - assert_noop, assert_ok, + assert_noop, assert_ok, hypothetically, traits::{fungible::InspectHold, Currency}, }; use mock::*; @@ -537,10 +537,10 @@ fn pool_slash_proportional() { // a typical example where 3 pool members unbond in era 99, 100, and 101, and a slash that // happened in era 100 should only affect the latter two. new_test_ext().execute_with(|| { - ExistentialDeposit::set(1); + ExistentialDeposit::set(2); BondingDuration::set(28); - assert_eq!(Balances::minimum_balance(), 1); - assert_eq!(CurrentEra::::get(), None); + assert_eq!(Balances::minimum_balance(), 2); + assert_eq!(Staking::current_era(), None); // create the pool, we know this has id 1. assert_ok!(Pools::create(RuntimeOrigin::signed(10), 40, 10, 10, 10)); @@ -670,6 +670,34 @@ fn pool_slash_proportional() { // no pending slash yet. assert_eq!(Pools::api_pool_pending_slash(1), 0); + // and therefore applying slash fails + assert_noop!( + Pools::apply_slash(RuntimeOrigin::signed(10), 21), + PoolsError::::NothingToSlash + ); + + hypothetically!({ + // a very small amount is slashed + pallet_staking::slashing::do_slash::( + &POOL1_BONDED, + 3, + &mut Default::default(), + &mut Default::default(), + 100, + ); + + // ensure correct amount is pending to be slashed + assert_eq!(Pools::api_pool_pending_slash(1), 3); + + // 21 has pending slash lower than ED (2) + assert_eq!(Pools::api_member_pending_slash(21), 1); + + // slash fails as minimum pending slash amount not met. + assert_noop!( + Pools::apply_slash(RuntimeOrigin::signed(10), 21), + PoolsError::::SlashTooLow + ); + }); pallet_staking::slashing::do_slash::( &POOL1_BONDED, @@ -909,6 +937,7 @@ fn pool_slash_non_proportional_bonded_pool_and_chunks() { ); }); } + #[test] fn pool_migration_e2e() { new_test_ext().execute_with(|| { From 6d59c3b1417cd07ae8d502236e8a98c3498f76b1 Mon Sep 17 00:00:00 2001 From: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> Date: Thu, 21 Nov 2024 20:19:14 +0200 Subject: [PATCH 126/166] parachain-template-node: add properties for dev chain-spec (#6560) # Description Reused as before the `properties` variable when defining a development chain spec for parachain-template-node. ## Integration N/A ## Review Notes One line change, pretty self explanatory (it got lost within the history of changes over the parachain-template-node/chain_spec.rs file). To be honest, not really sure how useful it is, but I had the choice of removing the `properties` var or reuse it as before, and I went with the latter. Signed-off-by: Iulian Barbu --- templates/parachain/node/src/chain_spec.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/templates/parachain/node/src/chain_spec.rs b/templates/parachain/node/src/chain_spec.rs index 55a099dd022b..7ae3c4900e42 100644 --- a/templates/parachain/node/src/chain_spec.rs +++ b/templates/parachain/node/src/chain_spec.rs @@ -45,6 +45,7 @@ pub fn development_chain_spec() -> ChainSpec { .with_id("dev") .with_chain_type(ChainType::Development) .with_genesis_config_preset_name(sp_genesis_builder::DEV_RUNTIME_PRESET) + .with_properties(properties) .build() } From d8ce550256f08c42d1ba6630990ed7e2e9ce0352 Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Thu, 21 Nov 2024 21:44:42 +0100 Subject: [PATCH 127/166] [pallet-revive] Support all eth tx types (#6461) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add support for all eth tx types Note that js libs will continue to use the Legacy type since we don't include base_fee_per_gas yet in the block. We can think about setting these values after we revisit how we encode the gas into weight & deposit_limit in a follow up PR --------- Co-authored-by: Alexander Theißen Co-authored-by: GitHub Action --- prdoc/pr_6461.prdoc | 12 + substrate/frame/revive/rpc/src/client.rs | 24 +- substrate/frame/revive/rpc/src/example.rs | 9 +- substrate/frame/revive/rpc/src/lib.rs | 57 +-- substrate/frame/revive/src/evm/api.rs | 2 - substrate/frame/revive/src/evm/api/account.rs | 28 +- .../frame/revive/src/evm/api/rlp_codec.rs | 471 ++++++++++++++++-- .../frame/revive/src/evm/api/rpc_types.rs | 140 +++++- .../frame/revive/src/evm/api/rpc_types_gen.rs | 18 +- .../frame/revive/src/evm/api/signature.rs | 190 +++++-- substrate/frame/revive/src/evm/api/type_id.rs | 22 +- substrate/frame/revive/src/evm/runtime.rs | 39 +- substrate/frame/revive/src/lib.rs | 2 +- 13 files changed, 824 insertions(+), 190 deletions(-) create mode 100644 prdoc/pr_6461.prdoc diff --git a/prdoc/pr_6461.prdoc b/prdoc/pr_6461.prdoc new file mode 100644 index 000000000000..1b3d1e8b0364 --- /dev/null +++ b/prdoc/pr_6461.prdoc @@ -0,0 +1,12 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json +title: '[pallet-revive] add support for all eth tx types' +doc: +- audience: Runtime Dev + description: Add support for 1559, 4844, and 2930 transaction types +crates: +- name: pallet-revive-eth-rpc + bump: minor +- name: pallet-revive + bump: minor + diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index 1ca1a6d37c53..d37f1d760065 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -17,13 +17,12 @@ //! The client connects to the source substrate chain //! and is used by the rpc server to query and send transactions to the substrate chain. use crate::{ - rlp, runtime::GAS_PRICE, subxt_client::{ revive::{calls::types::EthTransact, events::ContractEmitted}, runtime_types::pallet_revive::storage::ContractInfo, }, - TransactionLegacySigned, LOG_TARGET, + LOG_TARGET, }; use futures::{stream, StreamExt}; use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObjectOwned}; @@ -269,25 +268,26 @@ impl ClientInner { let extrinsics = extrinsics.iter().flat_map(|ext| { let call = ext.as_extrinsic::().ok()??; let transaction_hash = H256(keccak_256(&call.payload)); - let tx = rlp::decode::(&call.payload).ok()?; - let from = tx.recover_eth_address().ok()?; - let contract_address = if tx.transaction_legacy_unsigned.to.is_none() { - Some(create1(&from, tx.transaction_legacy_unsigned.nonce.try_into().ok()?)) + let signed_tx = TransactionSigned::decode(&call.payload).ok()?; + let from = signed_tx.recover_eth_address().ok()?; + let tx_info = GenericTransaction::from_signed(signed_tx.clone(), Some(from)); + let contract_address = if tx_info.to.is_none() { + Some(create1(&from, tx_info.nonce.unwrap_or_default().try_into().ok()?)) } else { None }; - Some((from, tx, transaction_hash, contract_address, ext)) + Some((from, signed_tx, tx_info, transaction_hash, contract_address, ext)) }); // Map each extrinsic to a receipt stream::iter(extrinsics) - .map(|(from, tx, transaction_hash, contract_address, ext)| async move { + .map(|(from, signed_tx, tx_info, transaction_hash, contract_address, ext)| async move { let events = ext.events().await?; let tx_fees = events.find_first::()?.ok_or(ClientError::TxFeeNotFound)?; - let gas_price = tx.transaction_legacy_unsigned.gas_price; + let gas_price = tx_info.gas_price.unwrap_or_default(); let gas_used = (tx_fees.tip.saturating_add(tx_fees.actual_fee)) .checked_div(gas_price.as_u128()) .unwrap_or_default(); @@ -324,16 +324,16 @@ impl ClientInner { contract_address, from, logs, - tx.transaction_legacy_unsigned.to, + tx_info.to, gas_price, gas_used.into(), success, transaction_hash, transaction_index.into(), - tx.transaction_legacy_unsigned.r#type.as_byte() + tx_info.r#type.unwrap_or_default() ); - Ok::<_, ClientError>((receipt.transaction_hash, (tx.into(), receipt))) + Ok::<_, ClientError>((receipt.transaction_hash, (signed_tx, receipt))) }) .buffer_unordered(10) .collect::>>() diff --git a/substrate/frame/revive/rpc/src/example.rs b/substrate/frame/revive/rpc/src/example.rs index 20f00465b146..3b9a33296ef4 100644 --- a/substrate/frame/revive/rpc/src/example.rs +++ b/substrate/frame/revive/rpc/src/example.rs @@ -20,8 +20,7 @@ use crate::{EthRpcClient, ReceiptInfo}; use anyhow::Context; use pallet_revive::evm::{ - rlp::*, Account, BlockTag, Bytes, GenericTransaction, TransactionLegacyUnsigned, H160, H256, - U256, + Account, BlockTag, Bytes, GenericTransaction, TransactionLegacyUnsigned, H160, H256, U256, }; /// Wait for a transaction receipt. @@ -169,11 +168,11 @@ impl TransactionBuilder { mutate(&mut unsigned_tx); - let tx = signer.sign_transaction(unsigned_tx.clone()); - let bytes = tx.rlp_bytes().to_vec(); + let tx = signer.sign_transaction(unsigned_tx.into()); + let bytes = tx.signed_payload(); let hash = client - .send_raw_transaction(bytes.clone().into()) + .send_raw_transaction(bytes.into()) .await .with_context(|| "transaction failed")?; diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index 8d9d6fab829e..6a324e63a857 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -137,7 +137,7 @@ impl EthRpcServer for EthRpcServerImpl { async fn send_raw_transaction(&self, transaction: Bytes) -> RpcResult { let hash = H256(keccak_256(&transaction.0)); - let tx = rlp::decode::(&transaction.0).map_err(|err| { + let tx = TransactionSigned::decode(&transaction.0).map_err(|err| { log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}"); EthRpcError::from(err) })?; @@ -147,21 +147,10 @@ impl EthRpcServer for EthRpcServerImpl { EthRpcError::InvalidSignature })?; + let tx = GenericTransaction::from_signed(tx, Some(eth_addr)); + // Dry run the transaction to get the weight limit and storage deposit limit - let TransactionLegacyUnsigned { to, input, value, .. } = tx.transaction_legacy_unsigned; - let dry_run = self - .client - .dry_run( - &GenericTransaction { - from: Some(eth_addr), - input: Some(input.clone()), - to, - value: Some(value), - ..Default::default() - }, - BlockTag::Latest.into(), - ) - .await?; + let dry_run = self.client.dry_run(&tx, BlockTag::Latest.into()).await?; let EthContractResult { gas_required, storage_deposit, .. } = dry_run; let call = subxt_client::tx().revive().eth_transact( @@ -174,11 +163,10 @@ impl EthRpcServer for EthRpcServerImpl { Ok(hash) } - async fn send_transaction(&self, transaction: GenericTransaction) -> RpcResult { + async fn send_transaction(&self, mut transaction: GenericTransaction) -> RpcResult { log::debug!(target: LOG_TARGET, "{transaction:#?}"); - let GenericTransaction { from, gas, gas_price, input, to, value, r#type, .. } = transaction; - let Some(from) = from else { + let Some(from) = transaction.from else { log::debug!(target: LOG_TARGET, "Transaction must have a sender"); return Err(EthRpcError::InvalidTransaction.into()); }; @@ -189,27 +177,26 @@ impl EthRpcServer for EthRpcServerImpl { .find(|account| account.address() == from) .ok_or(EthRpcError::AccountNotFound(from))?; - let gas_price = gas_price.unwrap_or_else(|| U256::from(GAS_PRICE)); - let chain_id = Some(self.client.chain_id().into()); - let input = input.unwrap_or_default(); - let value = value.unwrap_or_default(); - let r#type = r#type.unwrap_or_default(); + if transaction.gas.is_none() { + transaction.gas = Some(self.estimate_gas(transaction.clone(), None).await?); + } - let Some(gas) = gas else { - log::debug!(target: LOG_TARGET, "Transaction must have a gas limit"); - return Err(EthRpcError::InvalidTransaction.into()); - }; + if transaction.gas_price.is_none() { + transaction.gas_price = Some(self.gas_price().await?); + } - let r#type = Type0::try_from_byte(r#type.clone()) - .map_err(|_| EthRpcError::TransactionTypeNotSupported(r#type))?; + if transaction.nonce.is_none() { + transaction.nonce = + Some(self.get_transaction_count(from, BlockTag::Latest.into()).await?); + } - let nonce = self.get_transaction_count(from, BlockTag::Latest.into()).await?; + if transaction.chain_id.is_none() { + transaction.chain_id = Some(self.chain_id().await?); + } - let tx = - TransactionLegacyUnsigned { chain_id, gas, gas_price, input, nonce, to, value, r#type }; - let tx = account.sign_transaction(tx); - let rlp_bytes = rlp::encode(&tx).to_vec(); - self.send_raw_transaction(Bytes(rlp_bytes)).await + let tx = transaction.try_into_unsigned().map_err(|_| EthRpcError::InvalidTransaction)?; + let payload = account.sign_transaction(tx).signed_payload(); + self.send_raw_transaction(Bytes(payload)).await } async fn get_block_by_hash( diff --git a/substrate/frame/revive/src/evm/api.rs b/substrate/frame/revive/src/evm/api.rs index 8185a2c8f6f8..fe18c8735bed 100644 --- a/substrate/frame/revive/src/evm/api.rs +++ b/substrate/frame/revive/src/evm/api.rs @@ -25,9 +25,7 @@ pub use rlp; mod type_id; pub use type_id::*; -#[cfg(feature = "std")] mod rpc_types; - mod rpc_types_gen; pub use rpc_types_gen::*; diff --git a/substrate/frame/revive/src/evm/api/account.rs b/substrate/frame/revive/src/evm/api/account.rs index 8365ebf83cae..ba1c68ea0cf7 100644 --- a/substrate/frame/revive/src/evm/api/account.rs +++ b/substrate/frame/revive/src/evm/api/account.rs @@ -16,10 +16,9 @@ // limitations under the License. //! Utilities for working with Ethereum accounts. use crate::{ - evm::{TransactionLegacySigned, TransactionLegacyUnsigned}, + evm::{TransactionSigned, TransactionUnsigned}, H160, }; -use rlp::Encodable; use sp_runtime::AccountId32; /// A simple account that can sign transactions @@ -38,6 +37,11 @@ impl From for Account { } impl Account { + /// Create a new account from a secret + pub fn from_secret_key(secret_key: [u8; 32]) -> Self { + subxt_signer::eth::Keypair::from_secret_key(secret_key).unwrap().into() + } + /// Get the [`H160`] address of the account. pub fn address(&self) -> H160 { H160::from_slice(&self.0.public_key().to_account_id().as_ref()) @@ -52,9 +56,21 @@ impl Account { } /// Sign a transaction. - pub fn sign_transaction(&self, tx: TransactionLegacyUnsigned) -> TransactionLegacySigned { - let rlp_encoded = tx.rlp_bytes(); - let signature = self.0.sign(&rlp_encoded); - TransactionLegacySigned::from(tx, signature.as_ref()) + pub fn sign_transaction(&self, tx: TransactionUnsigned) -> TransactionSigned { + let payload = tx.unsigned_payload(); + let signature = self.0.sign(&payload).0; + tx.with_signature(signature) } } + +#[test] +fn from_secret_key_works() { + let account = Account::from_secret_key(hex_literal::hex!( + "a872f6cbd25a0e04a08b1e21098017a9e6194d101d75e13111f71410c59cd57f" + )); + + assert_eq!( + account.address(), + H160::from(hex_literal::hex!("75e480db528101a381ce68544611c169ad7eb342")) + ) +} diff --git a/substrate/frame/revive/src/evm/api/rlp_codec.rs b/substrate/frame/revive/src/evm/api/rlp_codec.rs index e5f24c28a482..3442ed73acca 100644 --- a/substrate/frame/revive/src/evm/api/rlp_codec.rs +++ b/substrate/frame/revive/src/evm/api/rlp_codec.rs @@ -21,6 +21,73 @@ use super::*; use alloc::vec::Vec; use rlp::{Decodable, Encodable}; +impl TransactionUnsigned { + /// Return the bytes to be signed by the private key. + pub fn unsigned_payload(&self) -> Vec { + use TransactionUnsigned::*; + let mut s = rlp::RlpStream::new(); + match self { + Transaction2930Unsigned(ref tx) => { + s.append(&tx.r#type.value()); + s.append(tx); + }, + Transaction1559Unsigned(ref tx) => { + s.append(&tx.r#type.value()); + s.append(tx); + }, + Transaction4844Unsigned(ref tx) => { + s.append(&tx.r#type.value()); + s.append(tx); + }, + TransactionLegacyUnsigned(ref tx) => { + s.append(tx); + }, + } + + s.out().to_vec() + } +} + +impl TransactionSigned { + /// Encode the Ethereum transaction into bytes. + pub fn signed_payload(&self) -> Vec { + use TransactionSigned::*; + let mut s = rlp::RlpStream::new(); + match self { + Transaction2930Signed(ref tx) => { + s.append(&tx.transaction_2930_unsigned.r#type.value()); + s.append(tx); + }, + Transaction1559Signed(ref tx) => { + s.append(&tx.transaction_1559_unsigned.r#type.value()); + s.append(tx); + }, + Transaction4844Signed(ref tx) => { + s.append(&tx.transaction_4844_unsigned.r#type.value()); + s.append(tx); + }, + TransactionLegacySigned(ref tx) => { + s.append(tx); + }, + } + + s.out().to_vec() + } + + /// Decode the Ethereum transaction from bytes. + pub fn decode(data: &[u8]) -> Result { + if data.len() < 1 { + return Err(rlp::DecoderError::RlpIsTooShort); + } + match data[0] { + TYPE_EIP2930 => rlp::decode::(&data[1..]).map(Into::into), + TYPE_EIP1559 => rlp::decode::(&data[1..]).map(Into::into), + TYPE_EIP4844 => rlp::decode::(&data[1..]).map(Into::into), + _ => rlp::decode::(data).map(Into::into), + } + } +} + impl TransactionLegacyUnsigned { /// Get the rlp encoded bytes of a signed transaction with a dummy 65 bytes signature. pub fn dummy_signed_payload(&self) -> Vec { @@ -47,8 +114,8 @@ impl Encodable for TransactionLegacyUnsigned { s.append(&self.value); s.append(&self.input.0); s.append(&chain_id); - s.append(&0_u8); - s.append(&0_u8); + s.append(&0u8); + s.append(&0u8); } else { s.begin_list(6); s.append(&self.nonce); @@ -64,7 +131,6 @@ impl Encodable for TransactionLegacyUnsigned { } } -/// See impl Decodable for TransactionLegacyUnsigned { fn decode(rlp: &rlp::Rlp) -> Result { Ok(TransactionLegacyUnsigned { @@ -95,16 +161,18 @@ impl Decodable for TransactionLegacyUnsigned { impl Encodable for TransactionLegacySigned { fn rlp_append(&self, s: &mut rlp::RlpStream) { + let tx = &self.transaction_legacy_unsigned; + s.begin_list(9); - s.append(&self.transaction_legacy_unsigned.nonce); - s.append(&self.transaction_legacy_unsigned.gas_price); - s.append(&self.transaction_legacy_unsigned.gas); - match self.transaction_legacy_unsigned.to { + s.append(&tx.nonce); + s.append(&tx.gas_price); + s.append(&tx.gas); + match tx.to { Some(ref to) => s.append(to), None => s.append_empty_data(), }; - s.append(&self.transaction_legacy_unsigned.value); - s.append(&self.transaction_legacy_unsigned.input.0); + s.append(&tx.value); + s.append(&tx.input.0); s.append(&self.v); s.append(&self.r); @@ -112,6 +180,232 @@ impl Encodable for TransactionLegacySigned { } } +impl Encodable for AccessListEntry { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + s.begin_list(2); + s.append(&self.address); + s.append_list(&self.storage_keys); + } +} + +impl Decodable for AccessListEntry { + fn decode(rlp: &rlp::Rlp) -> Result { + Ok(AccessListEntry { address: rlp.val_at(0)?, storage_keys: rlp.list_at(1)? }) + } +} + +/// See +impl Encodable for Transaction1559Unsigned { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + s.begin_list(9); + s.append(&self.chain_id); + s.append(&self.nonce); + s.append(&self.max_priority_fee_per_gas); + s.append(&self.max_fee_per_gas); + s.append(&self.gas); + match self.to { + Some(ref to) => s.append(to), + None => s.append_empty_data(), + }; + s.append(&self.value); + s.append(&self.input.0); + s.append_list(&self.access_list); + } +} + +/// See +impl Encodable for Transaction1559Signed { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + let tx = &self.transaction_1559_unsigned; + s.begin_list(12); + s.append(&tx.chain_id); + s.append(&tx.nonce); + s.append(&tx.max_priority_fee_per_gas); + s.append(&tx.max_fee_per_gas); + s.append(&tx.gas); + match tx.to { + Some(ref to) => s.append(to), + None => s.append_empty_data(), + }; + s.append(&tx.value); + s.append(&tx.input.0); + s.append_list(&tx.access_list); + + s.append(&self.y_parity); + s.append(&self.r); + s.append(&self.s); + } +} + +impl Decodable for Transaction1559Signed { + fn decode(rlp: &rlp::Rlp) -> Result { + Ok(Transaction1559Signed { + transaction_1559_unsigned: { + Transaction1559Unsigned { + chain_id: rlp.val_at(0)?, + nonce: rlp.val_at(1)?, + max_priority_fee_per_gas: rlp.val_at(2)?, + max_fee_per_gas: rlp.val_at(3)?, + gas: rlp.val_at(4)?, + to: { + let to = rlp.at(5)?; + if to.is_empty() { + None + } else { + Some(to.as_val()?) + } + }, + value: rlp.val_at(6)?, + input: Bytes(rlp.val_at(7)?), + access_list: rlp.list_at(8)?, + ..Default::default() + } + }, + y_parity: rlp.val_at(9)?, + r: rlp.val_at(10)?, + s: rlp.val_at(11)?, + ..Default::default() + }) + } +} + +//See https://eips.ethereum.org/EIPS/eip-2930 +impl Encodable for Transaction2930Unsigned { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + s.begin_list(8); + s.append(&self.chain_id); + s.append(&self.nonce); + s.append(&self.gas_price); + s.append(&self.gas); + match self.to { + Some(ref to) => s.append(to), + None => s.append_empty_data(), + }; + s.append(&self.value); + s.append(&self.input.0); + s.append_list(&self.access_list); + } +} + +//See https://eips.ethereum.org/EIPS/eip-2930 +impl Encodable for Transaction2930Signed { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + let tx = &self.transaction_2930_unsigned; + s.begin_list(11); + s.append(&tx.chain_id); + s.append(&tx.nonce); + s.append(&tx.gas_price); + s.append(&tx.gas); + match tx.to { + Some(ref to) => s.append(to), + None => s.append_empty_data(), + }; + s.append(&tx.value); + s.append(&tx.input.0); + s.append_list(&tx.access_list); + s.append(&self.y_parity); + s.append(&self.r); + s.append(&self.s); + } +} + +impl Decodable for Transaction2930Signed { + fn decode(rlp: &rlp::Rlp) -> Result { + Ok(Transaction2930Signed { + transaction_2930_unsigned: { + Transaction2930Unsigned { + chain_id: rlp.val_at(0)?, + nonce: rlp.val_at(1)?, + gas_price: rlp.val_at(2)?, + gas: rlp.val_at(3)?, + to: { + let to = rlp.at(4)?; + if to.is_empty() { + None + } else { + Some(to.as_val()?) + } + }, + value: rlp.val_at(5)?, + input: Bytes(rlp.val_at(6)?), + access_list: rlp.list_at(7)?, + ..Default::default() + } + }, + y_parity: rlp.val_at(8)?, + r: rlp.val_at(9)?, + s: rlp.val_at(10)?, + ..Default::default() + }) + } +} + +//See https://eips.ethereum.org/EIPS/eip-4844 +impl Encodable for Transaction4844Unsigned { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + s.begin_list(11); + s.append(&self.chain_id); + s.append(&self.nonce); + s.append(&self.max_priority_fee_per_gas); + s.append(&self.max_fee_per_gas); + s.append(&self.gas); + s.append(&self.to); + s.append(&self.value); + s.append(&self.input.0); + s.append_list(&self.access_list); + s.append(&self.max_fee_per_blob_gas); + s.append_list(&self.blob_versioned_hashes); + } +} + +//See https://eips.ethereum.org/EIPS/eip-4844 +impl Encodable for Transaction4844Signed { + fn rlp_append(&self, s: &mut rlp::RlpStream) { + let tx = &self.transaction_4844_unsigned; + s.begin_list(14); + s.append(&tx.chain_id); + s.append(&tx.nonce); + s.append(&tx.max_priority_fee_per_gas); + s.append(&tx.max_fee_per_gas); + s.append(&tx.gas); + s.append(&tx.to); + s.append(&tx.value); + s.append(&tx.input.0); + s.append_list(&tx.access_list); + s.append(&tx.max_fee_per_blob_gas); + s.append_list(&tx.blob_versioned_hashes); + s.append(&self.y_parity); + s.append(&self.r); + s.append(&self.s); + } +} + +impl Decodable for Transaction4844Signed { + fn decode(rlp: &rlp::Rlp) -> Result { + Ok(Transaction4844Signed { + transaction_4844_unsigned: { + Transaction4844Unsigned { + chain_id: rlp.val_at(0)?, + nonce: rlp.val_at(1)?, + max_priority_fee_per_gas: rlp.val_at(2)?, + max_fee_per_gas: rlp.val_at(3)?, + gas: rlp.val_at(4)?, + to: rlp.val_at(5)?, + value: rlp.val_at(6)?, + input: Bytes(rlp.val_at(7)?), + access_list: rlp.list_at(8)?, + max_fee_per_blob_gas: rlp.val_at(9)?, + blob_versioned_hashes: rlp.list_at(10)?, + ..Default::default() + } + }, + y_parity: rlp.val_at(11)?, + r: rlp.val_at(12)?, + s: rlp.val_at(13)?, + }) + } +} + /// See impl Decodable for TransactionLegacySigned { fn decode(rlp: &rlp::Rlp) -> Result { @@ -142,7 +436,7 @@ impl Decodable for TransactionLegacySigned { value: rlp.val_at(4)?, input: Bytes(rlp.val_at(5)?), chain_id: extract_chain_id(v).map(|v| v.into()), - r#type: Type0 {}, + r#type: TypeLegacy {}, } }, v, @@ -157,26 +451,118 @@ mod test { use super::*; #[test] - fn encode_decode_legacy_transaction_works() { - let tx = TransactionLegacyUnsigned { - chain_id: Some(596.into()), - gas: U256::from(21000), - nonce: U256::from(1), - gas_price: U256::from("0x640000006a"), - to: Some(Account::from(subxt_signer::eth::dev::baltathar()).address()), - value: U256::from(123123), - input: Bytes(vec![]), - r#type: Type0, - }; + fn encode_decode_tx_works() { + let txs = [ + // Legacy + ( + "f86080808301e24194095e7baea6a6c7c4c2dfeb977efac326af552d87808025a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + r#" + { + "chainId": "0x1", + "gas": "0x1e241", + "gasPrice": "0x0", + "input": "0x", + "nonce": "0x0", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "type": "0x0", + "value": "0x0", + "r": "0xfe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0", + "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + "v": "0x25" + } + "# + ), + // type 1: EIP2930 + ( + "01f89b0180808301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + r#" + { + "accessList": [ + { + "address": "0x0000000000000000000000000000000000000001", + "storageKeys": ["0x0000000000000000000000000000000000000000000000000000000000000000"] + } + ], + "chainId": "0x1", + "gas": "0x1e241", + "gasPrice": "0x0", + "input": "0x", + "nonce": "0x0", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "type": "0x1", + "value": "0x0", + "r": "0xfe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0", + "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + "yParity": "0x0" + } + "# + ), + // type 2: EIP1559 + ( + "02f89c018080018301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + r#" + { + "accessList": [ + { + "address": "0x0000000000000000000000000000000000000001", + "storageKeys": ["0x0000000000000000000000000000000000000000000000000000000000000000"] + } + ], + "chainId": "0x1", + "gas": "0x1e241", + "gasPrice": "0x0", + "input": "0x", + "maxFeePerGas": "0x1", + "maxPriorityFeePerGas": "0x0", + "nonce": "0x0", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "type": "0x2", + "value": "0x0", + "r": "0xfe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0", + "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + "yParity": "0x0" - let rlp_bytes = rlp::encode(&tx); - let decoded = rlp::decode::(&rlp_bytes).unwrap(); - assert_eq!(&tx, &decoded); + } + "# + ), + // type 3: EIP4844 + ( - let tx = Account::default().sign_transaction(tx); - let rlp_bytes = rlp::encode(&tx); - let decoded = rlp::decode::(&rlp_bytes).unwrap(); - assert_eq!(&tx, &decoded); + "03f8bf018002018301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080e1a0000000000000000000000000000000000000000000000000000000000000000080a0fe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0a06de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + r#" + { + "accessList": [ + { + "address": "0x0000000000000000000000000000000000000001", + "storageKeys": ["0x0000000000000000000000000000000000000000000000000000000000000000"] + } + ], + "blobVersionedHashes": ["0x0000000000000000000000000000000000000000000000000000000000000000"], + "chainId": "0x1", + "gas": "0x1e241", + "input": "0x", + "maxFeePerBlobGas": "0x0", + "maxFeePerGas": "0x1", + "maxPriorityFeePerGas": "0x2", + "nonce": "0x0", + "to": "0x095e7baea6a6c7c4c2dfeb977efac326af552d87", + "type": "0x3", + "value": "0x0", + "r": "0xfe38ca4e44a30002ac54af7cf922a6ac2ba11b7d22f548e8ecb3f51f41cb31b0", + "s": "0x6de6a5cbae13c0c856e33acf021b51819636cfc009d39eafb9f606d546e305a8", + "yParity": "0x0" + } + "# + ) + ]; + + for (tx, json) in txs { + let raw_tx = hex::decode(tx).unwrap(); + let tx = TransactionSigned::decode(&raw_tx).unwrap(); + assert_eq!(tx.signed_payload(), raw_tx); + let expected_tx = serde_json::from_str(json).unwrap(); + assert_eq!(tx, expected_tx); + } } #[test] @@ -189,31 +575,12 @@ mod test { to: Some(Account::from(subxt_signer::eth::dev::baltathar()).address()), value: U256::from(123123), input: Bytes(vec![]), - r#type: Type0, + r#type: TypeLegacy, }; - let signed_tx = Account::default().sign_transaction(tx.clone()); - let rlp_bytes = rlp::encode(&signed_tx); - assert_eq!(tx.dummy_signed_payload().len(), rlp_bytes.len()); - } - - #[test] - fn recover_address_works() { - let account = Account::default(); - - let unsigned_tx = TransactionLegacyUnsigned { - value: 200_000_000_000_000_000_000u128.into(), - gas_price: 100_000_000_200u64.into(), - gas: 100_107u32.into(), - nonce: 3.into(), - to: Some(Account::from(subxt_signer::eth::dev::baltathar()).address()), - chain_id: Some(596.into()), - ..Default::default() - }; - - let tx = account.sign_transaction(unsigned_tx.clone()); - let recovered_address = tx.recover_eth_address().unwrap(); - - assert_eq!(account.address(), recovered_address); + let dummy_signed_payload = tx.dummy_signed_payload(); + let tx: TransactionUnsigned = tx.into(); + let payload = Account::default().sign_transaction(tx).signed_payload(); + assert_eq!(dummy_signed_payload.len(), payload.len()); } } diff --git a/substrate/frame/revive/src/evm/api/rpc_types.rs b/substrate/frame/revive/src/evm/api/rpc_types.rs index dd1a2642724d..1cf8d984b68b 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types.rs @@ -16,7 +16,8 @@ // limitations under the License. //! Utility impl for the RPC types. use super::*; -use sp_core::U256; +use alloc::vec::Vec; +use sp_core::{H160, U256}; impl TransactionInfo { /// Create a new [`TransactionInfo`] from a receipt and a signed transaction. @@ -138,3 +139,140 @@ fn logs_bloom_works() { .unwrap(); assert_eq!(receipt.logs_bloom, ReceiptInfo::logs_bloom(&receipt.logs)); } + +impl GenericTransaction { + /// Create a new [`GenericTransaction`] from a signed transaction. + pub fn from_signed(tx: TransactionSigned, from: Option) -> Self { + use TransactionSigned::*; + match tx { + TransactionLegacySigned(tx) => { + let tx = tx.transaction_legacy_unsigned; + GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: tx.chain_id, + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + ..Default::default() + } + }, + Transaction4844Signed(tx) => { + let tx = tx.transaction_4844_unsigned; + GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: Some(tx.to), + gas: Some(tx.gas), + gas_price: Some(tx.max_fee_per_blob_gas), + access_list: Some(tx.access_list), + blob_versioned_hashes: Some(tx.blob_versioned_hashes), + max_fee_per_blob_gas: Some(tx.max_fee_per_blob_gas), + max_fee_per_gas: Some(tx.max_fee_per_gas), + max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), + ..Default::default() + } + }, + Transaction1559Signed(tx) => { + let tx = tx.transaction_1559_unsigned; + GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + access_list: Some(tx.access_list), + max_fee_per_gas: Some(tx.max_fee_per_gas), + max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), + ..Default::default() + } + }, + Transaction2930Signed(tx) => { + let tx = tx.transaction_2930_unsigned; + GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + access_list: Some(tx.access_list), + ..Default::default() + } + }, + } + } + + /// Convert to a [`TransactionUnsigned`]. + pub fn try_into_unsigned(self) -> Result { + match self.r#type.unwrap_or_default().0 { + TYPE_LEGACY => Ok(TransactionLegacyUnsigned { + r#type: TypeLegacy {}, + chain_id: self.chain_id, + input: self.input.unwrap_or_default(), + nonce: self.nonce.unwrap_or_default(), + value: self.value.unwrap_or_default(), + to: self.to, + gas: self.gas.unwrap_or_default(), + gas_price: self.gas_price.unwrap_or_default(), + } + .into()), + TYPE_EIP1559 => Ok(Transaction1559Unsigned { + r#type: TypeEip1559 {}, + chain_id: self.chain_id.unwrap_or_default(), + input: self.input.unwrap_or_default(), + nonce: self.nonce.unwrap_or_default(), + value: self.value.unwrap_or_default(), + to: self.to, + gas: self.gas.unwrap_or_default(), + gas_price: self.gas_price.unwrap_or_default(), + access_list: self.access_list.unwrap_or_default(), + max_fee_per_gas: self.max_fee_per_gas.unwrap_or_default(), + max_priority_fee_per_gas: self.max_priority_fee_per_gas.unwrap_or_default(), + } + .into()), + TYPE_EIP2930 => Ok(Transaction2930Unsigned { + r#type: TypeEip2930 {}, + chain_id: self.chain_id.unwrap_or_default(), + input: self.input.unwrap_or_default(), + nonce: self.nonce.unwrap_or_default(), + value: self.value.unwrap_or_default(), + to: self.to, + gas: self.gas.unwrap_or_default(), + gas_price: self.gas_price.unwrap_or_default(), + access_list: self.access_list.unwrap_or_default(), + } + .into()), + TYPE_EIP4844 => Ok(Transaction4844Unsigned { + r#type: TypeEip4844 {}, + chain_id: self.chain_id.unwrap_or_default(), + input: self.input.unwrap_or_default(), + nonce: self.nonce.unwrap_or_default(), + value: self.value.unwrap_or_default(), + to: self.to.unwrap_or_default(), + gas: self.gas.unwrap_or_default(), + max_fee_per_gas: self.max_fee_per_gas.unwrap_or_default(), + max_fee_per_blob_gas: self.max_fee_per_blob_gas.unwrap_or_default(), + max_priority_fee_per_gas: self.max_priority_fee_per_gas.unwrap_or_default(), + access_list: self.access_list.unwrap_or_default(), + blob_versioned_hashes: self.blob_versioned_hashes.unwrap_or_default(), + } + .into()), + _ => Err(()), + } + } +} diff --git a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs index 48045a6acc86..5037ec05d881 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs @@ -17,7 +17,7 @@ //! Generated JSON-RPC types. #![allow(missing_docs)] -use super::{byte::*, Type0, Type1, Type2, Type3}; +use super::{byte::*, TypeEip1559, TypeEip2930, TypeEip4844, TypeLegacy}; use alloc::vec::Vec; use codec::{Decode, Encode}; use derive_more::{From, TryInto}; @@ -455,7 +455,7 @@ pub struct Transaction1559Unsigned { /// to address pub to: Option

, /// type - pub r#type: Type2, + pub r#type: TypeEip1559, /// value pub value: U256, } @@ -486,7 +486,7 @@ pub struct Transaction2930Unsigned { /// to address pub to: Option
, /// type - pub r#type: Type1, + pub r#type: TypeEip2930, /// value pub value: U256, } @@ -530,7 +530,7 @@ pub struct Transaction4844Unsigned { /// to address pub to: Address, /// type - pub r#type: Type3, + pub r#type: TypeEip4844, /// value pub value: U256, } @@ -557,7 +557,7 @@ pub struct TransactionLegacyUnsigned { /// to address pub to: Option
, /// type - pub r#type: Type0, + pub r#type: TypeLegacy, /// value pub value: U256, } @@ -622,8 +622,8 @@ pub struct Transaction1559Signed { pub v: Option, /// yParity /// The parity (0 for even, 1 for odd) of the y-value of the secp256k1 signature. - #[serde(rename = "yParity", skip_serializing_if = "Option::is_none")] - pub y_parity: Option, + #[serde(rename = "yParity")] + pub y_parity: U256, } /// Signed 2930 Transaction @@ -661,8 +661,8 @@ pub struct Transaction4844Signed { pub s: U256, /// yParity /// The parity (0 for even, 1 for odd) of the y-value of the secp256k1 signature. - #[serde(rename = "yParity", skip_serializing_if = "Option::is_none")] - pub y_parity: Option, + #[serde(rename = "yParity")] + pub y_parity: U256, } /// Signed Legacy Transaction diff --git a/substrate/frame/revive/src/evm/api/signature.rs b/substrate/frame/revive/src/evm/api/signature.rs index 957d50c8e324..9f39b92b461e 100644 --- a/substrate/frame/revive/src/evm/api/signature.rs +++ b/substrate/frame/revive/src/evm/api/signature.rs @@ -15,49 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. //! Ethereum signature utilities -use super::{TransactionLegacySigned, TransactionLegacyUnsigned}; -use rlp::Encodable; +use super::*; use sp_core::{H160, U256}; use sp_io::{crypto::secp256k1_ecdsa_recover, hashing::keccak_256}; -impl TransactionLegacyUnsigned { - /// Recover the Ethereum address, from an RLP encoded transaction and a 65 bytes signature. - pub fn recover_eth_address(rlp_encoded: &[u8], signature: &[u8; 65]) -> Result { - let hash = keccak_256(rlp_encoded); - let mut addr = H160::default(); - let pk = secp256k1_ecdsa_recover(&signature, &hash).map_err(|_| ())?; - addr.assign_from_slice(&keccak_256(&pk[..])[12..]); - - Ok(addr) - } -} - impl TransactionLegacySigned { - /// Create a signed transaction from an [`TransactionLegacyUnsigned`] and a signature. - pub fn from( - transaction_legacy_unsigned: TransactionLegacyUnsigned, - signature: &[u8; 65], - ) -> TransactionLegacySigned { - let r = U256::from_big_endian(&signature[..32]); - let s = U256::from_big_endian(&signature[32..64]); - let recovery_id = signature[64] as u32; - let v = transaction_legacy_unsigned - .chain_id - .map(|chain_id| chain_id * 2 + 35 + recovery_id) - .unwrap_or_else(|| U256::from(27) + recovery_id); - - TransactionLegacySigned { transaction_legacy_unsigned, r, s, v } - } - - /// Get the raw 65 bytes signature from the signed transaction. - pub fn raw_signature(&self) -> Result<[u8; 65], ()> { - let mut s = [0u8; 65]; - self.r.write_as_big_endian(s[0..32].as_mut()); - self.s.write_as_big_endian(s[32..64].as_mut()); - s[64] = self.extract_recovery_id().ok_or(())?; - Ok(s) - } - /// Get the recovery ID from the signed transaction. /// See https://eips.ethereum.org/EIPS/eip-155 fn extract_recovery_id(&self) -> Option { @@ -71,10 +33,154 @@ impl TransactionLegacySigned { self.v.try_into().ok() } } +} + +impl TransactionUnsigned { + /// Extract the unsigned transaction from a signed transaction. + pub fn from_signed(tx: TransactionSigned) -> Self { + match tx { + TransactionSigned::TransactionLegacySigned(signed) => + Self::TransactionLegacyUnsigned(signed.transaction_legacy_unsigned), + TransactionSigned::Transaction4844Signed(signed) => + Self::Transaction4844Unsigned(signed.transaction_4844_unsigned), + TransactionSigned::Transaction1559Signed(signed) => + Self::Transaction1559Unsigned(signed.transaction_1559_unsigned), + TransactionSigned::Transaction2930Signed(signed) => + Self::Transaction2930Unsigned(signed.transaction_2930_unsigned), + } + } + + /// Create a signed transaction from an [`TransactionUnsigned`] and a signature. + pub fn with_signature(self, signature: [u8; 65]) -> TransactionSigned { + let r = U256::from_big_endian(&signature[..32]); + let s = U256::from_big_endian(&signature[32..64]); + let recovery_id = signature[64]; + + match self { + TransactionUnsigned::Transaction2930Unsigned(transaction_2930_unsigned) => + Transaction2930Signed { + transaction_2930_unsigned, + r, + s, + v: None, + y_parity: U256::from(recovery_id), + } + .into(), + TransactionUnsigned::Transaction1559Unsigned(transaction_1559_unsigned) => + Transaction1559Signed { + transaction_1559_unsigned, + r, + s, + v: None, + y_parity: U256::from(recovery_id), + } + .into(), + + TransactionUnsigned::Transaction4844Unsigned(transaction_4844_unsigned) => + Transaction4844Signed { + transaction_4844_unsigned, + r, + s, + y_parity: U256::from(recovery_id), + } + .into(), + + TransactionUnsigned::TransactionLegacyUnsigned(transaction_legacy_unsigned) => { + let v = transaction_legacy_unsigned + .chain_id + .map(|chain_id| { + chain_id + .saturating_mul(U256::from(2)) + .saturating_add(U256::from(35u32 + recovery_id as u32)) + }) + .unwrap_or_else(|| U256::from(27u32 + recovery_id as u32)); + + TransactionLegacySigned { transaction_legacy_unsigned, r, s, v }.into() + }, + } + } +} + +impl TransactionSigned { + /// Get the raw 65 bytes signature from the signed transaction. + pub fn raw_signature(&self) -> Result<[u8; 65], ()> { + use TransactionSigned::*; + let (r, s, v) = match self { + TransactionLegacySigned(tx) => (tx.r, tx.s, tx.extract_recovery_id().ok_or(())?), + Transaction4844Signed(tx) => (tx.r, tx.s, tx.y_parity.try_into().map_err(|_| ())?), + Transaction1559Signed(tx) => (tx.r, tx.s, tx.y_parity.try_into().map_err(|_| ())?), + Transaction2930Signed(tx) => (tx.r, tx.s, tx.y_parity.try_into().map_err(|_| ())?), + }; + let mut sig = [0u8; 65]; + r.write_as_big_endian(sig[0..32].as_mut()); + s.write_as_big_endian(sig[32..64].as_mut()); + sig[64] = v; + Ok(sig) + } - /// Recover the Ethereum address from the signed transaction. + /// Recover the Ethereum address, from a signed transaction. pub fn recover_eth_address(&self) -> Result { - let rlp_encoded = self.transaction_legacy_unsigned.rlp_bytes(); - TransactionLegacyUnsigned::recover_eth_address(&rlp_encoded, &self.raw_signature()?) + use TransactionSigned::*; + + let mut s = rlp::RlpStream::new(); + match self { + TransactionLegacySigned(tx) => { + let tx = &tx.transaction_legacy_unsigned; + s.append(tx); + }, + Transaction4844Signed(tx) => { + let tx = &tx.transaction_4844_unsigned; + s.append(&tx.r#type.value()); + s.append(tx); + }, + Transaction1559Signed(tx) => { + let tx = &tx.transaction_1559_unsigned; + s.append(&tx.r#type.value()); + s.append(tx); + }, + Transaction2930Signed(tx) => { + let tx = &tx.transaction_2930_unsigned; + s.append(&tx.r#type.value()); + s.append(tx); + }, + } + let bytes = s.out().to_vec(); + let signature = self.raw_signature()?; + + let hash = keccak_256(&bytes); + let mut addr = H160::default(); + let pk = secp256k1_ecdsa_recover(&signature, &hash).map_err(|_| ())?; + addr.assign_from_slice(&keccak_256(&pk[..])[12..]); + Ok(addr) + } +} + +#[test] +fn sign_and_recover_work() { + use crate::evm::TransactionUnsigned; + let txs = [ + // Legacy + "f86080808301e24194095e7baea6a6c7c4c2dfeb977efac326af552d87808026a07b2e762a17a71a46b422e60890a04512cf0d907ccf6b78b5bd6e6977efdc2bf5a01ea673d50bbe7c2236acb498ceb8346a8607c941f0b8cbcde7cf439aa9369f1f", + //// type 1: EIP2930 + "01f89b0180808301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a0c45a61b3d1d00169c649e7326e02857b850efb96e587db4b9aad29afc80d0752a070ae1eb47ab4097dbed2f19172ae286492621b46ac737ee6c32fb18a00c94c9c", + // type 2: EIP1559 + "02f89c018080018301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080a055d72bbc3047d4b9d3e4b8099f187143202407746118204cc2e0cb0c85a68baea04f6ef08a1418c70450f53398d9f0f2d78d9e9d6b8a80cba886b67132c4a744f2", + // type 3: EIP4844 + "03f8bf018002018301e24194095e7baea6a6c7c4c2dfeb977efac326af552d878080f838f7940000000000000000000000000000000000000001e1a0000000000000000000000000000000000000000000000000000000000000000080e1a0000000000000000000000000000000000000000000000000000000000000000001a0672b8bac466e2cf1be3148c030988d40d582763ecebbc07700dfc93bb070d8a4a07c635887005b11cb58964c04669ac2857fa633aa66f662685dadfd8bcacb0f21", + ]; + let account = Account::from_secret_key(hex_literal::hex!( + "a872f6cbd25a0e04a08b1e21098017a9e6194d101d75e13111f71410c59cd57f" + )); + + for tx in txs { + let raw_tx = hex::decode(tx).unwrap(); + let tx = TransactionSigned::decode(&raw_tx).unwrap(); + + let address = tx.recover_eth_address(); + assert_eq!(address.unwrap(), account.address()); + + let unsigned = TransactionUnsigned::from_signed(tx.clone()); + let signed = account.sign_transaction(unsigned); + assert_eq!(tx, signed); } } diff --git a/substrate/frame/revive/src/evm/api/type_id.rs b/substrate/frame/revive/src/evm/api/type_id.rs index 7434ca6e9b7f..c6e018a379b3 100644 --- a/substrate/frame/revive/src/evm/api/type_id.rs +++ b/substrate/frame/revive/src/evm/api/type_id.rs @@ -17,6 +17,7 @@ //! Ethereum Typed Transaction types use super::Byte; use codec::{Decode, Encode}; +use paste::paste; use rlp::Decodable; use scale_info::TypeInfo; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -29,8 +30,14 @@ macro_rules! transaction_type { #[derive(Clone, Default, Debug, Eq, PartialEq)] pub struct $name; + // upper case const name + paste! { + #[doc = concat!("Transaction value for type identifier: ", $value)] + pub const [<$name:snake:upper>]: u8 = $value; + } + impl $name { - /// Get the value of the type + /// Convert to u8 pub fn value(&self) -> u8 { $value } @@ -107,7 +114,12 @@ macro_rules! transaction_type { }; } -transaction_type!(Type0, 0); -transaction_type!(Type1, 1); -transaction_type!(Type2, 2); -transaction_type!(Type3, 3); +transaction_type!(TypeLegacy, 0); +transaction_type!(TypeEip2930, 1); +transaction_type!(TypeEip1559, 2); +transaction_type!(TypeEip4844, 3); + +#[test] +fn transaction_type() { + assert_eq!(TYPE_EIP2930, 1u8); +} diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index 21294fdf6baa..40c210304ca2 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -16,7 +16,7 @@ // limitations under the License. //! Runtime types for integrating `pallet-revive` with the EVM. use crate::{ - evm::api::{TransactionLegacySigned, TransactionLegacyUnsigned}, + evm::api::{GenericTransaction, TransactionSigned}, AccountIdOf, AddressMapper, BalanceOf, MomentOf, Weight, LOG_TARGET, }; use codec::{Decode, Encode}; @@ -293,7 +293,7 @@ pub trait EthExtra { CallOf: From>, ::Hash: frame_support::traits::IsType, { - let tx = rlp::decode::(&payload).map_err(|err| { + let tx = TransactionSigned::decode(&payload).map_err(|err| { log::debug!(target: LOG_TARGET, "Failed to decode transaction: {err:?}"); InvalidTransaction::Call })?; @@ -305,33 +305,33 @@ pub trait EthExtra { let signer = ::AddressMapper::to_fallback_account_id(&signer); - let TransactionLegacyUnsigned { nonce, chain_id, to, value, input, gas, gas_price, .. } = - tx.transaction_legacy_unsigned; + let GenericTransaction { nonce, chain_id, to, value, input, gas, gas_price, .. } = + GenericTransaction::from_signed(tx, None); if chain_id.unwrap_or_default() != ::ChainId::get().into() { log::debug!(target: LOG_TARGET, "Invalid chain_id {chain_id:?}"); return Err(InvalidTransaction::Call); } - let value = crate::Pallet::::convert_evm_to_native(value).map_err(|err| { - log::debug!(target: LOG_TARGET, "Failed to convert value to native: {err:?}"); - InvalidTransaction::Call - })?; + let value = crate::Pallet::::convert_evm_to_native(value.unwrap_or_default()) + .map_err(|err| { + log::debug!(target: LOG_TARGET, "Failed to convert value to native: {err:?}"); + InvalidTransaction::Call + })?; + let data = input.unwrap_or_default().0; let call = if let Some(dest) = to { crate::Call::call:: { dest, value, gas_limit, storage_deposit_limit, - data: input.0, + data, } } else { - let blob = match polkavm::ProgramBlob::blob_length(&input.0) { - Some(blob_len) => blob_len - .try_into() - .ok() - .and_then(|blob_len| (input.0.split_at_checked(blob_len))), + let blob = match polkavm::ProgramBlob::blob_length(&data) { + Some(blob_len) => + blob_len.try_into().ok().and_then(|blob_len| (data.split_at_checked(blob_len))), _ => None, }; @@ -350,18 +350,18 @@ pub trait EthExtra { } }; - let nonce = nonce.try_into().map_err(|_| InvalidTransaction::Call)?; + let nonce = nonce.unwrap_or_default().try_into().map_err(|_| InvalidTransaction::Call)?; // Fees calculated with the fixed `GAS_PRICE` // When we dry-run the transaction, we set the gas to `Fee / GAS_PRICE` let eth_fee_no_tip = U256::from(GAS_PRICE) - .saturating_mul(gas) + .saturating_mul(gas.unwrap_or_default()) .try_into() .map_err(|_| InvalidTransaction::Call)?; // Fees with the actual gas_price from the transaction. - let eth_fee: BalanceOf = U256::from(gas_price) - .saturating_mul(gas) + let eth_fee: BalanceOf = U256::from(gas_price.unwrap_or_default()) + .saturating_mul(gas.unwrap_or_default()) .try_into() .map_err(|_| InvalidTransaction::Call)?; @@ -414,7 +414,6 @@ mod test { }; use frame_support::{error::LookupError, traits::fungible::Mutate}; use pallet_revive_fixtures::compile_module; - use rlp::Encodable; use sp_runtime::{ traits::{Checkable, DispatchTransaction}, MultiAddress, MultiSignature, @@ -523,7 +522,7 @@ mod test { 100_000_000_000_000, ); - let payload = account.sign_transaction(tx).rlp_bytes().to_vec(); + let payload = account.sign_transaction(tx.into()).signed_payload(); let call = RuntimeCall::Contracts(crate::Call::eth_transact { payload, gas_limit, diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index caecf07c4071..b55854e2eec5 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -768,7 +768,7 @@ pub mod pallet { /// /// # Parameters /// - /// * `payload`: The RLP-encoded [`crate::evm::TransactionLegacySigned`]. + /// * `payload`: The encoded [`crate::evm::TransactionSigned`]. /// * `gas_limit`: The gas limit enforced during contract execution. /// * `storage_deposit_limit`: The maximum balance that can be charged to the caller for /// storage usage. From 7c5224cb01710d0c14c87bf3463cc79e49b3e7b5 Mon Sep 17 00:00:00 2001 From: gupnik Date: Fri, 22 Nov 2024 10:16:45 +0530 Subject: [PATCH 128/166] Adds `BlockNumberProvider` in multisig, proxy and nft pallets (#5723) Step in https://github.com/paritytech/polkadot-sdk/issues/3268 This PR adds the ability for these pallets to specify their source of the block number. This is useful when these pallets are migrated from the relay chain to a parachain and vice versa. This change is backwards compatible: 1. If the `BlockNumberProvider` continues to use the system pallet's block number 2. When a pallet deployed on the relay chain is moved to a parachain, but still uses the relay chain's block number However, we would need migrations if the deployed pallets are upgraded on an existing parachain, and the `BlockNumberProvider` uses the relay chain block number. --------- Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- .../assets/asset-hub-rococo/src/lib.rs | 3 ++ .../assets/asset-hub-westend/src/lib.rs | 3 ++ .../bridge-hubs/bridge-hub-rococo/src/lib.rs | 1 + .../bridge-hubs/bridge-hub-westend/src/lib.rs | 1 + .../collectives-westend/src/lib.rs | 2 ++ .../contracts/contracts-rococo/src/lib.rs | 1 + .../coretime/coretime-rococo/src/lib.rs | 2 ++ .../coretime/coretime-westend/src/lib.rs | 2 ++ .../runtimes/people/people-rococo/src/lib.rs | 2 ++ .../runtimes/people/people-westend/src/lib.rs | 2 ++ polkadot/runtime/rococo/src/lib.rs | 2 ++ polkadot/runtime/westend/src/lib.rs | 2 ++ prdoc/pr_5723.prdoc | 24 +++++++++++++++ substrate/bin/node/runtime/src/lib.rs | 3 ++ substrate/frame/contracts/src/tests.rs | 1 + substrate/frame/multisig/src/lib.rs | 10 +++++-- substrate/frame/multisig/src/tests.rs | 1 + .../frame/nft-fractionalization/src/mock.rs | 1 + substrate/frame/nfts/src/benchmarking.rs | 22 +++++++------- .../frame/nfts/src/features/approvals.rs | 6 ++-- .../frame/nfts/src/features/atomic_swap.rs | 8 ++--- .../frame/nfts/src/features/attributes.rs | 2 +- .../nfts/src/features/create_delete_item.rs | 2 +- substrate/frame/nfts/src/features/settings.rs | 6 +--- substrate/frame/nfts/src/lib.rs | 29 ++++++++++--------- substrate/frame/nfts/src/mock.rs | 1 + substrate/frame/nfts/src/types.rs | 12 ++++---- substrate/frame/proxy/src/benchmarking.rs | 6 ++-- substrate/frame/proxy/src/lib.rs | 12 ++++++-- substrate/frame/proxy/src/tests.rs | 1 + substrate/frame/revive/src/tests.rs | 1 + substrate/frame/safe-mode/src/mock.rs | 1 + substrate/frame/src/lib.rs | 4 +-- substrate/frame/tx-pause/src/mock.rs | 1 + 34 files changed, 125 insertions(+), 52 deletions(-) create mode 100644 prdoc/pr_5723.prdoc diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index 2f9d83bd9d0b..bc48c2d805fd 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -467,6 +467,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { @@ -652,6 +653,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -918,6 +920,7 @@ impl pallet_nfts::Config for Runtime { type WeightInfo = weights::pallet_nfts::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type Helper = (); + type BlockNumberProvider = frame_system::Pallet; } /// XCM router instance to BridgeHub with bridging capabilities for `Westend` global 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 2206aea78ec2..cafea3b6ff8b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -466,6 +466,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { @@ -651,6 +652,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -912,6 +914,7 @@ impl pallet_nfts::Config for Runtime { type WeightInfo = weights::pallet_nfts::WeightInfo; #[cfg(feature = "runtime-benchmarks")] type Helper = (); + type BlockNumberProvider = frame_system::Pallet; } /// XCM router instance to BridgeHub with bridging capabilities for `Rococo` global diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index ff7af475f5e2..3f3316d0be49 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -537,6 +537,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs index 065400016791..65e7d291dc37 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs @@ -513,6 +513,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index c3e105a84fb6..0ee3a4068718 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -258,6 +258,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { @@ -382,6 +383,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index f661a8bdccfe..2951662a979b 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -268,6 +268,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = pallet_multisig::weights::SubstrateWeight; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index 31700c2e25ff..3f3126b749d8 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -445,6 +445,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } /// The type used to represent the kinds of proxying allowed. @@ -577,6 +578,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index 1f0f54884fa8..098a17cc9984 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -446,6 +446,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } /// The type used to represent the kinds of proxying allowed. @@ -578,6 +579,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs index 25356a84806d..7921030f2bb8 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs @@ -407,6 +407,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } /// The type used to represent the kinds of proxying allowed. @@ -520,6 +521,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs index 1c5183636c49..19a64ab8d6e8 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs @@ -406,6 +406,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } /// The type used to represent the kinds of proxying allowed. @@ -519,6 +520,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_utility::Config for Runtime { diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 96a97faa4750..5da9da86f02e 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -767,6 +767,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -971,6 +972,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl parachains_origin::Config for Runtime {} diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 7a5562cc98c1..9f0b701f20be 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -1004,6 +1004,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = weights::pallet_multisig::WeightInfo; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -1204,6 +1205,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } impl parachains_origin::Config for Runtime {} diff --git a/prdoc/pr_5723.prdoc b/prdoc/pr_5723.prdoc new file mode 100644 index 000000000000..ded5f9cebd1d --- /dev/null +++ b/prdoc/pr_5723.prdoc @@ -0,0 +1,24 @@ +title: Adds `BlockNumberProvider` in multisig, proxy and nft pallets + +doc: + - audience: Runtime Dev + description: | + This PR adds the ability for these pallets to specify their source of the block number. + This is useful when these pallets are migrated from the relay chain to a parachain and + vice versa. + + This change is backwards compatible: + 1. If the `BlockNumberProvider` continues to use the system pallet's block number + 2. When a pallet deployed on the relay chain is moved to a parachain, but still uses the + relay chain's block number + + However, we would need migrations if the deployed pallets are upgraded on an existing parachain, + and the `BlockNumberProvider` uses the relay chain block number. + +crates: + - name: pallet-multisig + bump: major + - name: pallet-proxy + bump: major + - name: pallet-nfts + bump: major diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index e68e04840776..bff263548087 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -392,6 +392,7 @@ impl pallet_multisig::Config for Runtime { type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type WeightInfo = pallet_multisig::weights::SubstrateWeight; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -479,6 +480,7 @@ impl pallet_proxy::Config for Runtime { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { @@ -2048,6 +2050,7 @@ impl pallet_nfts::Config for Runtime { type Helper = (); type CreateOrigin = AsEnsureOriginWithArg>; type Locker = (); + type BlockNumberProvider = frame_system::Pallet; } impl pallet_transaction_storage::Config for Runtime { diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index c3b6e3273f34..b01d0aa4fa48 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -399,6 +399,7 @@ impl pallet_proxy::Config for Test { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = ConstU64<1>; type AnnouncementDepositFactor = ConstU64<1>; + type BlockNumberProvider = frame_system::Pallet; } impl pallet_dummy::Config for Test {} diff --git a/substrate/frame/multisig/src/lib.rs b/substrate/frame/multisig/src/lib.rs index 4a30b5c119b9..869b4adc2adc 100644 --- a/substrate/frame/multisig/src/lib.rs +++ b/substrate/frame/multisig/src/lib.rs @@ -77,6 +77,9 @@ macro_rules! log { type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type BlockNumberFor = + <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; + /// A global extrinsic index, formed as the extrinsic index within a block, together with that /// block's height. This allows a transaction in which a multisig operation of a particular /// composite was created to be uniquely identified. @@ -153,6 +156,9 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: weights::WeightInfo; + + /// Provider for the block number. Normally this is the `frame_system` pallet. + type BlockNumberProvider: BlockNumberProvider; } /// The in-code storage version. @@ -235,7 +241,7 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet {} + impl Hooks> for Pallet {} #[pallet::call] impl Pallet { @@ -626,7 +632,7 @@ impl Pallet { /// The current `Timepoint`. pub fn timepoint() -> Timepoint> { Timepoint { - height: >::block_number(), + height: T::BlockNumberProvider::current_block_number(), index: >::extrinsic_index().unwrap_or_default(), } } diff --git a/substrate/frame/multisig/src/tests.rs b/substrate/frame/multisig/src/tests.rs index c5a98845270c..4065ce73f905 100644 --- a/substrate/frame/multisig/src/tests.rs +++ b/substrate/frame/multisig/src/tests.rs @@ -66,6 +66,7 @@ impl Config for Test { type DepositFactor = ConstU64<1>; type MaxSignatories = ConstU32<3>; type WeightInfo = (); + type BlockNumberProvider = frame_system::Pallet; } use pallet_balances::Call as BalancesCall; diff --git a/substrate/frame/nft-fractionalization/src/mock.rs b/substrate/frame/nft-fractionalization/src/mock.rs index 50b41b5fc64e..762c1776e30f 100644 --- a/substrate/frame/nft-fractionalization/src/mock.rs +++ b/substrate/frame/nft-fractionalization/src/mock.rs @@ -115,6 +115,7 @@ impl pallet_nfts::Config for Test { type OffchainSignature = Signature; type OffchainPublic = AccountPublic; type WeightInfo = (); + type BlockNumberProvider = frame_system::Pallet; pallet_nfts::runtime_benchmarks_enabled! { type Helper = (); } diff --git a/substrate/frame/nfts/src/benchmarking.rs b/substrate/frame/nfts/src/benchmarking.rs index bc81096b459d..81828be5fa09 100644 --- a/substrate/frame/nfts/src/benchmarking.rs +++ b/substrate/frame/nfts/src/benchmarking.rs @@ -29,7 +29,7 @@ use frame_support::{ traits::{EnsureOrigin, Get, UnfilteredDispatchable}, BoundedVec, }; -use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; +use frame_system::RawOrigin as SystemOrigin; use sp_runtime::traits::{Bounded, One}; use crate::Pallet as Nfts; @@ -577,7 +577,7 @@ benchmarks_instance_pallet! { let (item, ..) = mint_item::(0); let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); - let deadline = BlockNumberFor::::max_value(); + let deadline = BlockNumberFor::::max_value(); }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup, Some(deadline)) verify { assert_last_event::(Event::TransferApproved { collection, item, owner: caller, delegate, deadline: Some(deadline) }.into()); @@ -589,7 +589,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = BlockNumberFor::::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item, delegate_lookup) verify { @@ -602,7 +602,7 @@ benchmarks_instance_pallet! { let delegate: T::AccountId = account("delegate", 0, SEED); let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let origin = SystemOrigin::Signed(caller.clone()).into(); - let deadline = BlockNumberFor::::max_value(); + let deadline = BlockNumberFor::::max_value(); Nfts::::approve_transfer(origin, collection, item, delegate_lookup.clone(), Some(deadline))?; }: _(SystemOrigin::Signed(caller.clone()), collection, item) verify { @@ -712,10 +712,10 @@ benchmarks_instance_pallet! { let price_direction = PriceDirection::Receive; let price_with_direction = PriceWithDirection { amount: price, direction: price_direction }; let duration = T::MaxDeadlineDuration::get(); - frame_system::Pallet::::set_block_number(One::one()); + T::BlockNumberProvider::set_block_number(One::one()); }: _(SystemOrigin::Signed(caller.clone()), collection, item1, collection, Some(item2), Some(price_with_direction.clone()), duration) verify { - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); assert_last_event::(Event::SwapCreated { offered_collection: collection, offered_item: item1, @@ -735,7 +735,7 @@ benchmarks_instance_pallet! { let duration = T::MaxDeadlineDuration::get(); let price_direction = PriceDirection::Receive; let price_with_direction = PriceWithDirection { amount: price, direction: price_direction }; - frame_system::Pallet::::set_block_number(One::one()); + T::BlockNumberProvider::set_block_number(One::one()); Nfts::::create_swap(origin, collection, item1, collection, Some(item2), Some(price_with_direction.clone()), duration)?; }: _(SystemOrigin::Signed(caller.clone()), collection, item1) verify { @@ -761,7 +761,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); T::Currency::make_free_balance_be(&target, T::Currency::minimum_balance()); let origin = SystemOrigin::Signed(caller.clone()); - frame_system::Pallet::::set_block_number(One::one()); + T::BlockNumberProvider::set_block_number(One::one()); Nfts::::transfer(origin.clone().into(), collection, item2, target_lookup)?; Nfts::::create_swap( origin.clone().into(), @@ -774,7 +774,7 @@ benchmarks_instance_pallet! { )?; }: _(SystemOrigin::Signed(target.clone()), collection, item2, collection, item1, Some(price_with_direction.clone())) verify { - let current_block = frame_system::Pallet::::block_number(); + let current_block = T::BlockNumberProvider::current_block_number(); assert_last_event::(Event::SwapClaimed { sent_collection: collection, sent_item: item2, @@ -822,7 +822,7 @@ benchmarks_instance_pallet! { let target: T::AccountId = account("target", 0, SEED); T::Currency::make_free_balance_be(&target, DepositBalanceOf::::max_value()); - frame_system::Pallet::::set_block_number(One::one()); + T::BlockNumberProvider::set_block_number(One::one()); }: _(SystemOrigin::Signed(target.clone()), Box::new(mint_data), signature.into(), caller) verify { let metadata: BoundedVec<_, _> = metadata.try_into().unwrap(); @@ -865,7 +865,7 @@ benchmarks_instance_pallet! { let message = Encode::encode(&pre_signed_data); let signature = T::Helper::sign(&signer_public, &message); - frame_system::Pallet::::set_block_number(One::one()); + T::BlockNumberProvider::set_block_number(One::one()); }: _(SystemOrigin::Signed(item_owner.clone()), pre_signed_data, signature.into(), signer.clone()) verify { assert_last_event::( diff --git a/substrate/frame/nfts/src/features/approvals.rs b/substrate/frame/nfts/src/features/approvals.rs index 053fa67163b9..4738f69f83c4 100644 --- a/substrate/frame/nfts/src/features/approvals.rs +++ b/substrate/frame/nfts/src/features/approvals.rs @@ -46,7 +46,7 @@ impl, I: 'static> Pallet { collection: T::CollectionId, item: T::ItemId, delegate: T::AccountId, - maybe_deadline: Option>, + maybe_deadline: Option>, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Approvals), @@ -65,7 +65,7 @@ impl, I: 'static> Pallet { ensure!(check_origin == details.owner, Error::::NoPermission); } - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let deadline = maybe_deadline.map(|d| d.saturating_add(now)); details @@ -111,7 +111,7 @@ impl, I: 'static> Pallet { let maybe_deadline = details.approvals.get(&delegate).ok_or(Error::::NotDelegate)?; let is_past_deadline = if let Some(deadline) = maybe_deadline { - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); now > *deadline } else { false diff --git a/substrate/frame/nfts/src/features/atomic_swap.rs b/substrate/frame/nfts/src/features/atomic_swap.rs index 830283b73c2a..03ebd35b81b2 100644 --- a/substrate/frame/nfts/src/features/atomic_swap.rs +++ b/substrate/frame/nfts/src/features/atomic_swap.rs @@ -53,7 +53,7 @@ impl, I: 'static> Pallet { desired_collection_id: T::CollectionId, maybe_desired_item_id: Option, maybe_price: Option>>, - duration: frame_system::pallet_prelude::BlockNumberFor, + duration: BlockNumberFor, ) -> DispatchResult { ensure!( Self::is_pallet_feature_enabled(PalletFeature::Swaps), @@ -76,7 +76,7 @@ impl, I: 'static> Pallet { ), }; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); let deadline = duration.saturating_add(now); PendingSwapOf::::insert( @@ -119,7 +119,7 @@ impl, I: 'static> Pallet { let swap = PendingSwapOf::::get(&offered_collection_id, &offered_item_id) .ok_or(Error::::UnknownSwap)?; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if swap.deadline > now { let item = Item::::get(&offered_collection_id, &offered_item_id) .ok_or(Error::::UnknownItem)?; @@ -187,7 +187,7 @@ impl, I: 'static> Pallet { ensure!(desired_item == send_item_id, Error::::UnknownSwap); } - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); ensure!(now <= swap.deadline, Error::::DeadlineExpired); if let Some(ref price) = swap.price { diff --git a/substrate/frame/nfts/src/features/attributes.rs b/substrate/frame/nfts/src/features/attributes.rs index 28f7bd2c58ce..2cd09f7d2193 100644 --- a/substrate/frame/nfts/src/features/attributes.rs +++ b/substrate/frame/nfts/src/features/attributes.rs @@ -225,7 +225,7 @@ impl, I: 'static> Pallet { Error::::MaxAttributesLimitReached ); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); ensure!(deadline >= now, Error::::DeadlineExpired); let item_details = diff --git a/substrate/frame/nfts/src/features/create_delete_item.rs b/substrate/frame/nfts/src/features/create_delete_item.rs index 37f64ae1b1b9..57366127f142 100644 --- a/substrate/frame/nfts/src/features/create_delete_item.rs +++ b/substrate/frame/nfts/src/features/create_delete_item.rs @@ -145,7 +145,7 @@ impl, I: 'static> Pallet { ensure!(account == mint_to, Error::::WrongOrigin); } - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); ensure!(deadline >= now, Error::::DeadlineExpired); ensure!( diff --git a/substrate/frame/nfts/src/features/settings.rs b/substrate/frame/nfts/src/features/settings.rs index d4f7533ffa4e..48719ae2c20e 100644 --- a/substrate/frame/nfts/src/features/settings.rs +++ b/substrate/frame/nfts/src/features/settings.rs @@ -96,11 +96,7 @@ impl, I: 'static> Pallet { pub(crate) fn do_update_mint_settings( maybe_check_origin: Option, collection: T::CollectionId, - mint_settings: MintSettings< - BalanceOf, - frame_system::pallet_prelude::BlockNumberFor, - T::CollectionId, - >, + mint_settings: MintSettings, BlockNumberFor, T::CollectionId>, ) -> DispatchResult { if let Some(check_origin) = &maybe_check_origin { ensure!( diff --git a/substrate/frame/nfts/src/lib.rs b/substrate/frame/nfts/src/lib.rs index 4e5493a3c755..346ad162c503 100644 --- a/substrate/frame/nfts/src/lib.rs +++ b/substrate/frame/nfts/src/lib.rs @@ -58,7 +58,7 @@ use frame_support::traits::{ }; use frame_system::Config as SystemConfig; use sp_runtime::{ - traits::{IdentifyAccount, Saturating, StaticLookup, Verify, Zero}, + traits::{BlockNumberProvider, IdentifyAccount, Saturating, StaticLookup, Verify, Zero}, RuntimeDebug, }; @@ -76,7 +76,7 @@ type AccountIdLookupOf = <::Lookup as StaticLookup>::Sourc pub mod pallet { use super::*; use frame_support::{pallet_prelude::*, traits::ExistenceRequirement}; - use frame_system::pallet_prelude::*; + use frame_system::{ensure_signed, pallet_prelude::OriginFor}; /// The in-code storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); @@ -210,7 +210,7 @@ pub mod pallet { /// The max duration in blocks for deadlines. #[pallet::constant] - type MaxDeadlineDuration: Get>; + type MaxDeadlineDuration: Get>; /// The max number of attributes a user could set per call. #[pallet::constant] @@ -242,6 +242,9 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + /// Provider for the block number. Normally this is the `frame_system` pallet. + type BlockNumberProvider: BlockNumberProvider; } /// Details of a collection. @@ -388,7 +391,7 @@ pub mod pallet { T::CollectionId, T::ItemId, PriceWithDirection>, - BlockNumberFor, + BlockNumberFor, >, OptionQuery, >; @@ -459,7 +462,7 @@ pub mod pallet { item: T::ItemId, owner: T::AccountId, delegate: T::AccountId, - deadline: Option>, + deadline: Option>, }, /// An approval for a `delegate` account to transfer the `item` of an item /// `collection` was cancelled by its `owner`. @@ -554,7 +557,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: BlockNumberFor, + deadline: BlockNumberFor, }, /// The swap was cancelled. SwapCancelled { @@ -563,7 +566,7 @@ pub mod pallet { desired_collection: T::CollectionId, desired_item: Option, price: Option>>, - deadline: BlockNumberFor, + deadline: BlockNumberFor, }, /// The swap has been claimed. SwapClaimed { @@ -574,7 +577,7 @@ pub mod pallet { received_item: T::ItemId, received_item_owner: T::AccountId, price: Option>>, - deadline: BlockNumberFor, + deadline: BlockNumberFor, }, /// New attributes have been set for an `item` of the `collection`. PreSignedAttributesSet { @@ -857,7 +860,7 @@ pub mod pallet { item_config, |collection_details, collection_config| { let mint_settings = collection_config.mint_settings; - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); if let Some(start_block) = mint_settings.start_block { ensure!(start_block <= now, Error::::MintNotStarted); @@ -1029,7 +1032,7 @@ pub mod pallet { let deadline = details.approvals.get(&origin).ok_or(Error::::NoPermission)?; if let Some(d) = deadline { - let block_number = frame_system::Pallet::::block_number(); + let block_number = T::BlockNumberProvider::current_block_number(); ensure!(block_number <= *d, Error::::ApprovalExpired); } } @@ -1290,7 +1293,7 @@ pub mod pallet { collection: T::CollectionId, item: T::ItemId, delegate: AccountIdLookupOf, - maybe_deadline: Option>, + maybe_deadline: Option>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1713,7 +1716,7 @@ pub mod pallet { pub fn update_mint_settings( origin: OriginFor, collection: T::CollectionId, - mint_settings: MintSettings, BlockNumberFor, T::CollectionId>, + mint_settings: MintSettings, BlockNumberFor, T::CollectionId>, ) -> DispatchResult { let maybe_check_origin = T::ForceOrigin::try_origin(origin) .map(|_| None) @@ -1809,7 +1812,7 @@ pub mod pallet { desired_collection: T::CollectionId, maybe_desired_item: Option, maybe_price: Option>>, - duration: BlockNumberFor, + duration: BlockNumberFor, ) -> DispatchResult { let origin = ensure_signed(origin)?; Self::do_create_swap( diff --git a/substrate/frame/nfts/src/mock.rs b/substrate/frame/nfts/src/mock.rs index 5b589f591ca3..291c3c081334 100644 --- a/substrate/frame/nfts/src/mock.rs +++ b/substrate/frame/nfts/src/mock.rs @@ -92,6 +92,7 @@ impl Config for Test { type WeightInfo = (); #[cfg(feature = "runtime-benchmarks")] type Helper = (); + type BlockNumberProvider = frame_system::Pallet; } pub(crate) fn new_test_ext() -> sp_io::TestExternalities { diff --git a/substrate/frame/nfts/src/types.rs b/substrate/frame/nfts/src/types.rs index d67fb404ea79..3ab85993473a 100644 --- a/substrate/frame/nfts/src/types.rs +++ b/substrate/frame/nfts/src/types.rs @@ -27,9 +27,11 @@ use frame_support::{ traits::Get, BoundedBTreeMap, BoundedBTreeSet, }; -use frame_system::pallet_prelude::BlockNumberFor; use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter}; +pub type BlockNumberFor = + <>::BlockNumberProvider as BlockNumberProvider>::BlockNumber; + /// A type alias for handling balance deposits. pub type DepositBalanceOf = <>::Currency as Currency<::AccountId>>::Balance; @@ -39,7 +41,7 @@ pub type CollectionDetailsFor = /// A type alias for keeping track of approvals used by a single item. pub type ApprovalsOf = BoundedBTreeMap< ::AccountId, - Option>, + Option>, >::ApprovalsLimit, >; /// A type alias for keeping track of approvals for an item's attributes. @@ -70,13 +72,13 @@ pub type ItemTipOf = ItemTip< >; /// A type alias for the settings configuration of a collection. pub type CollectionConfigFor = - CollectionConfig, BlockNumberFor, >::CollectionId>; + CollectionConfig, BlockNumberFor, >::CollectionId>; /// A type alias for the pre-signed minting configuration for a specified collection. pub type PreSignedMintOf = PreSignedMint< >::CollectionId, >::ItemId, ::AccountId, - BlockNumberFor, + BlockNumberFor, BalanceOf, >; /// A type alias for the pre-signed minting configuration on the attribute level of an item. @@ -84,7 +86,7 @@ pub type PreSignedAttributesOf = PreSignedAttributes< >::CollectionId, >::ItemId, ::AccountId, - BlockNumberFor, + BlockNumberFor, >; /// Information about a collection. diff --git a/substrate/frame/proxy/src/benchmarking.rs b/substrate/frame/proxy/src/benchmarking.rs index eebb506bf374..b72f53af8e72 100644 --- a/substrate/frame/proxy/src/benchmarking.rs +++ b/substrate/frame/proxy/src/benchmarking.rs @@ -22,7 +22,9 @@ use super::*; use crate::Pallet as Proxy; use alloc::{boxed::Box, vec}; -use frame::benchmarking::prelude::*; +use frame::benchmarking::prelude::{ + account, benchmarks, impl_test_function, whitelisted_caller, BenchmarkError, RawOrigin, +}; const SEED: u32 = 0; @@ -317,7 +319,7 @@ mod benchmarks { BlockNumberFor::::zero(), 0, )?; - let height = frame_system::Pallet::::block_number(); + let height = T::BlockNumberProvider::current_block_number(); let ext_index = frame_system::Pallet::::extrinsic_index().unwrap_or(0); let pure_account = Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None); diff --git a/substrate/frame/proxy/src/lib.rs b/substrate/frame/proxy/src/lib.rs index cc8aeedcc5f9..cc21db7469b2 100644 --- a/substrate/frame/proxy/src/lib.rs +++ b/substrate/frame/proxy/src/lib.rs @@ -47,6 +47,9 @@ type CallHashOf = <::CallHasher as Hash>::Output; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; +pub type BlockNumberFor = + <::BlockNumberProvider as BlockNumberProvider>::BlockNumber; + type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; /// The parameters under which a particular account has a proxy relationship with some other @@ -163,6 +166,9 @@ pub mod pallet { /// into a pre-existing storage value. #[pallet::constant] type AnnouncementDepositFactor: Get>; + + /// Provider for the block number. Normally this is the `frame_system` pallet. + type BlockNumberProvider: BlockNumberProvider; } #[pallet::call] @@ -379,7 +385,7 @@ pub mod pallet { let announcement = Announcement { real: real.clone(), call_hash, - height: frame_system::Pallet::::block_number(), + height: T::BlockNumberProvider::current_block_number(), }; Announcements::::try_mutate(&who, |(ref mut pending, ref mut deposit)| { @@ -490,7 +496,7 @@ pub mod pallet { let def = Self::find_proxy(&real, &delegate, force_proxy_type)?; let call_hash = T::CallHasher::hash_of(&call); - let now = frame_system::Pallet::::block_number(); + let now = T::BlockNumberProvider::current_block_number(); Self::edit_announcements(&delegate, |ann| { ann.real != real || ann.call_hash != call_hash || @@ -626,7 +632,7 @@ impl Pallet { ) -> T::AccountId { let (height, ext_index) = maybe_when.unwrap_or_else(|| { ( - frame_system::Pallet::::block_number(), + T::BlockNumberProvider::current_block_number(), frame_system::Pallet::::extrinsic_index().unwrap_or_default(), ) }); diff --git a/substrate/frame/proxy/src/tests.rs b/substrate/frame/proxy/src/tests.rs index 5baf9bb9e838..afc668188e6c 100644 --- a/substrate/frame/proxy/src/tests.rs +++ b/substrate/frame/proxy/src/tests.rs @@ -119,6 +119,7 @@ impl Config for Test { type MaxPending = ConstU32<2>; type AnnouncementDepositBase = ConstU64<1>; type AnnouncementDepositFactor = ConstU64<1>; + type BlockNumberProvider = frame_system::Pallet; } use super::{Call as ProxyCall, Event as ProxyEvent}; diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 177b8dff706b..34afe8aabfe6 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -416,6 +416,7 @@ impl pallet_proxy::Config for Test { type CallHasher = BlakeTwo256; type AnnouncementDepositBase = ConstU64<1>; type AnnouncementDepositFactor = ConstU64<1>; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { diff --git a/substrate/frame/safe-mode/src/mock.rs b/substrate/frame/safe-mode/src/mock.rs index ec1ad8249514..aaf3456272fa 100644 --- a/substrate/frame/safe-mode/src/mock.rs +++ b/substrate/frame/safe-mode/src/mock.rs @@ -138,6 +138,7 @@ impl pallet_proxy::Config for Test { type MaxPending = ConstU32<2>; type AnnouncementDepositBase = ConstU64<1>; type AnnouncementDepositFactor = ConstU64<1>; + type BlockNumberProvider = frame_system::Pallet; } /// The calls that can always bypass safe-mode. diff --git a/substrate/frame/src/lib.rs b/substrate/frame/src/lib.rs index 0ca36ca8545a..03d815e349df 100644 --- a/substrate/frame/src/lib.rs +++ b/substrate/frame/src/lib.rs @@ -219,8 +219,8 @@ pub mod prelude { /// Runtime traits #[doc(no_inline)] pub use sp_runtime::traits::{ - Bounded, DispatchInfoOf, Dispatchable, SaturatedConversion, Saturating, StaticLookup, - TrailingZeroInput, + BlockNumberProvider, Bounded, DispatchInfoOf, Dispatchable, SaturatedConversion, + Saturating, StaticLookup, TrailingZeroInput, }; /// Other error/result types for runtime diff --git a/substrate/frame/tx-pause/src/mock.rs b/substrate/frame/tx-pause/src/mock.rs index 84ce45e83528..fd9b3b552ccd 100644 --- a/substrate/frame/tx-pause/src/mock.rs +++ b/substrate/frame/tx-pause/src/mock.rs @@ -105,6 +105,7 @@ impl pallet_proxy::Config for Test { type MaxPending = ConstU32<2>; type AnnouncementDepositBase = ConstU64<1>; type AnnouncementDepositFactor = ConstU64<1>; + type BlockNumberProvider = frame_system::Pallet; } parameter_types! { From 08ec8cdbfdbdd29c7921a8a141187e04354a449e Mon Sep 17 00:00:00 2001 From: eskimor Date: Fri, 22 Nov 2024 14:19:40 +0100 Subject: [PATCH 129/166] Only mess with coretime if we are registering an actual parachain. (#6554) Co-authored-by: Robert Co-authored-by: ordian --- polkadot/runtime/common/src/paras_sudo_wrapper.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/polkadot/runtime/common/src/paras_sudo_wrapper.rs b/polkadot/runtime/common/src/paras_sudo_wrapper.rs index af93c70b4783..a93c209e9279 100644 --- a/polkadot/runtime/common/src/paras_sudo_wrapper.rs +++ b/polkadot/runtime/common/src/paras_sudo_wrapper.rs @@ -24,7 +24,7 @@ pub use pallet::*; use polkadot_primitives::Id as ParaId; use polkadot_runtime_parachains::{ configuration, dmp, hrmp, - paras::{self, AssignCoretime, ParaGenesisArgs}, + paras::{self, AssignCoretime, ParaGenesisArgs, ParaKind}, ParaLifecycle, }; @@ -80,10 +80,15 @@ pub mod pallet { genesis: ParaGenesisArgs, ) -> DispatchResult { ensure_root(origin)?; + + let assign_coretime = genesis.para_kind == ParaKind::Parachain; + polkadot_runtime_parachains::schedule_para_initialize::(id, genesis) .map_err(|_| Error::::ParaAlreadyExists)?; - T::AssignCoretime::assign_coretime(id)?; + if assign_coretime { + T::AssignCoretime::assign_coretime(id)?; + } Ok(()) } From 1e3b8e1639c1cf784eabf0a9afcab1f3987e0ca4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Sun, 24 Nov 2024 08:36:16 +0000 Subject: [PATCH 130/166] Notify telemetry only every second about the tx pool status (#6605) Before this was done for every imported transaction. When a lot of transactions got imported, the import notification channel was filled. The underlying problem was that the `status` call is read locking the `validated_pool` which will be write locked by the internal submitting logic. Thus, the submitting and status reading was interferring which each other. --------- Co-authored-by: GitHub Action --- Cargo.lock | 1 + cumulus/client/service/Cargo.toml | 1 + prdoc/pr_6605.prdoc | 10 +++++ substrate/client/service/src/builder.rs | 58 +++++++++++++++++-------- 4 files changed, 53 insertions(+), 17 deletions(-) create mode 100644 prdoc/pr_6605.prdoc diff --git a/Cargo.lock b/Cargo.lock index 330c2563d976..c79adee6f38e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4680,6 +4680,7 @@ dependencies = [ "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", "futures", + "futures-timer", "polkadot-primitives 7.0.0", "sc-client-api", "sc-consensus", diff --git a/cumulus/client/service/Cargo.toml b/cumulus/client/service/Cargo.toml index 8e9e41ca89dc..0a77b465d96a 100644 --- a/cumulus/client/service/Cargo.toml +++ b/cumulus/client/service/Cargo.toml @@ -11,6 +11,7 @@ workspace = true [dependencies] futures = { workspace = true } +futures-timer = { workspace = true } # Substrate sc-client-api = { workspace = true, default-features = true } diff --git a/prdoc/pr_6605.prdoc b/prdoc/pr_6605.prdoc new file mode 100644 index 000000000000..2adb1d8aee35 --- /dev/null +++ b/prdoc/pr_6605.prdoc @@ -0,0 +1,10 @@ +title: Notify telemetry only every second about the tx pool status +doc: +- audience: Node Operator + description: |- + Before this was done for every imported transaction. When a lot of transactions got imported, the import notification channel was filled. The underlying problem was that the `status` call is read locking the `validated_pool` which will be write locked by the internal submitting logic. Thus, the submitting and status reading was interferring which each other. +crates: +- name: cumulus-client-service + bump: patch +- name: sc-service + bump: patch diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 68ac94539df8..ac9371a8941b 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -25,7 +25,7 @@ use crate::{ start_rpc_servers, BuildGenesisBlock, GenesisBlockBuilder, RpcHandlers, SpawnTaskHandle, TaskManager, TransactionPoolAdapter, }; -use futures::{future::ready, FutureExt, StreamExt}; +use futures::{select, FutureExt, StreamExt}; use jsonrpsee::RpcModule; use log::info; use prometheus_endpoint::Registry; @@ -90,7 +90,11 @@ use sp_consensus::block_validation::{ use sp_core::traits::{CodeExecutor, SpawnNamed}; use sp_keystore::KeystorePtr; use sp_runtime::traits::{Block as BlockT, BlockIdTo, NumberFor, Zero}; -use std::{str::FromStr, sync::Arc, time::SystemTime}; +use std::{ + str::FromStr, + sync::Arc, + time::{Duration, SystemTime}, +}; /// Full client type. pub type TFullClient = @@ -577,22 +581,42 @@ pub async fn propagate_transaction_notifications( Block: BlockT, ExPool: MaintainedTransactionPool::Hash>, { + const TELEMETRY_INTERVAL: Duration = Duration::from_secs(1); + // transaction notifications - transaction_pool - .import_notification_stream() - .for_each(move |hash| { - tx_handler_controller.propagate_transaction(hash); - let status = transaction_pool.status(); - telemetry!( - telemetry; - SUBSTRATE_INFO; - "txpool.import"; - "ready" => status.ready, - "future" => status.future, - ); - ready(()) - }) - .await; + let mut notifications = transaction_pool.import_notification_stream().fuse(); + let mut timer = futures_timer::Delay::new(TELEMETRY_INTERVAL).fuse(); + let mut tx_imported = false; + + loop { + select! { + notification = notifications.next() => { + let Some(hash) = notification else { return }; + + tx_handler_controller.propagate_transaction(hash); + + tx_imported = true; + }, + _ = timer => { + timer = futures_timer::Delay::new(TELEMETRY_INTERVAL).fuse(); + + if !tx_imported { + continue; + } + + tx_imported = false; + let status = transaction_pool.status(); + + telemetry!( + telemetry; + SUBSTRATE_INFO; + "txpool.import"; + "ready" => status.ready, + "future" => status.future, + ); + } + } + } } /// Initialize telemetry with provided configuration and return telemetry handle From 6da7d36e060c6e5fd5a20395470db6910037a640 Mon Sep 17 00:00:00 2001 From: gupnik Date: Mon, 25 Nov 2024 10:56:21 +0530 Subject: [PATCH 131/166] Fixes cfg attributes in runtime macro (#6410) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes https://github.com/paritytech/polkadot-sdk/issues/6209 This PR adds the support for cfg attributes in the runtime macro. --------- Co-authored-by: Bastian Köcher --- .../procedural/src/runtime/parse/pallet.rs | 15 ++++- substrate/frame/support/test/tests/pallet.rs | 59 +++++++++++++++---- 2 files changed, 59 insertions(+), 15 deletions(-) diff --git a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs index 52f57cd2cd8b..1397b7266a18 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs @@ -21,7 +21,7 @@ use crate::{ }; use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; -use syn::{punctuated::Punctuated, token, Error}; +use syn::{punctuated::Punctuated, spanned::Spanned, token, Error}; impl Pallet { pub fn try_from( @@ -78,7 +78,18 @@ impl Pallet { }) .collect(); - let cfg_pattern = vec![]; + let cfg_pattern = item + .attrs + .iter() + .filter(|attr| attr.path().segments.first().map_or(false, |s| s.ident == "cfg")) + .map(|attr| { + attr.parse_args_with(|input: syn::parse::ParseStream| { + let input = input.parse::()?; + cfg_expr::Expression::parse(&input.to_string()) + .map_err(|e| syn::Error::new(attr.span(), e.to_string())) + }) + }) + .collect::>>()?; let docs = get_doc_literals(&item.attrs); diff --git a/substrate/frame/support/test/tests/pallet.rs b/substrate/frame/support/test/tests/pallet.rs index b0b83f772499..de7f7eb4bc97 100644 --- a/substrate/frame/support/test/tests/pallet.rs +++ b/substrate/frame/support/test/tests/pallet.rs @@ -799,20 +799,43 @@ where } } -frame_support::construct_runtime!( - pub struct Runtime { - // Exclude part `Storage` in order not to check its metadata in tests. - System: frame_system exclude_parts { Pallet, Storage }, - Example: pallet, - Example2: pallet2 exclude_parts { Call }, - #[cfg(feature = "frame-feature-testing")] - Example3: pallet3, - Example4: pallet4 use_parts { Call }, +#[frame_support::runtime] +mod runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Runtime; - #[cfg(feature = "frame-feature-testing-2")] - Example5: pallet5, - } -); + #[runtime::pallet_index(0)] + pub type System = frame_system + Call + Event; + + #[runtime::pallet_index(1)] + pub type Example = pallet; + + #[runtime::pallet_index(2)] + #[runtime::disable_call] + pub type Example2 = pallet2; + + #[cfg(feature = "frame-feature-testing")] + #[runtime::pallet_index(3)] + pub type Example3 = pallet3; + + #[runtime::pallet_index(4)] + pub type Example4 = pallet4; + + #[cfg(feature = "frame-feature-testing-2")] + #[runtime::pallet_index(5)] + pub type Example5 = pallet5; +} // Test that the part `RuntimeCall` is excluded from Example2 and included in Example4. fn _ensure_call_is_correctly_excluded_and_included(call: RuntimeCall) { @@ -1847,6 +1870,16 @@ fn metadata() { error: None, docs: vec![" Test that the supertrait check works when we pass some parameter to the `frame_system::Config`."], }, + PalletMetadata { + index: 4, + name: "Example4", + storage: None, + calls: Some(meta_type::>().into()), + event: None, + constants: vec![], + error: None, + docs: vec![], + }, #[cfg(feature = "frame-feature-testing-2")] PalletMetadata { index: 5, From 75e79fad682bd86451464bc95117f6e22b86dfd9 Mon Sep 17 00:00:00 2001 From: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Date: Mon, 25 Nov 2024 11:02:37 +0100 Subject: [PATCH 132/166] ci: fix node-bench-regression-guard for master (#6589) Closes https://github.com/paritytech/ci_cd/issues/1067 --- .github/workflows/tests-misc.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/tests-misc.yml b/.github/workflows/tests-misc.yml index cca32650b106..decd88f2e84c 100644 --- a/.github/workflows/tests-misc.yml +++ b/.github/workflows/tests-misc.yml @@ -165,12 +165,14 @@ jobs: - name: Download artifact (master run) uses: actions/download-artifact@v4.1.8 + continue-on-error: true with: name: cargo-check-benches-master-${{ github.sha }} path: ./artifacts/master - name: Download artifact (current run) uses: actions/download-artifact@v4.1.8 + continue-on-error: true with: name: cargo-check-benches-current-${{ github.sha }} path: ./artifacts/current @@ -183,6 +185,12 @@ jobs: exit 0 fi + # fail if no artifacts + if [ ! -d ./artifacts/master ] || [ ! -d ./artifacts/current ]; then + echo "No artifacts found" + exit 1 + fi + docker run --rm \ -v $PWD/artifacts/master:/artifacts/master \ -v $PWD/artifacts/current:/artifacts/current \ From e709c9f3db017309d88d240cb32d62c2df6f0a52 Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Mon, 25 Nov 2024 11:59:48 +0100 Subject: [PATCH 133/166] Error logging for send xcm to pallet-xcm (#6579) --- polkadot/xcm/pallet-xcm/src/lib.rs | 16 +++++++++++++--- .../xcm/xcm-builder/src/process_xcm_message.rs | 2 +- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 5e0512c6a9fd..6360298b21c3 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -363,7 +363,10 @@ pub mod pallet { let message: Xcm<()> = (*message).try_into().map_err(|()| Error::::BadVersion)?; let message_id = Self::send_xcm(interior, dest.clone(), message.clone()) - .map_err(Error::::from)?; + .map_err(|error| { + tracing::error!(target: "xcm::pallet_xcm::send", ?error, ?dest, ?message, "XCM send failed with error"); + Error::::from(error) + })?; let e = Event::Sent { origin: origin_location, destination: dest, message, message_id }; Self::deposit_event(e); Ok(message_id) @@ -1800,7 +1803,10 @@ impl Pallet { if let Some(remote_xcm) = remote_xcm { let (ticket, price) = validate_send::(dest.clone(), remote_xcm.clone()) - .map_err(Error::::from)?; + .map_err(|error| { + tracing::error!(target: "xcm::pallet_xcm::execute_xcm_transfer", ?error, ?dest, ?remote_xcm, "XCM validate_send failed with error"); + Error::::from(error) + })?; if origin != Here.into_location() { Self::charge_fees(origin.clone(), price.clone()).map_err(|error| { tracing::error!( @@ -1810,7 +1816,11 @@ impl Pallet { Error::::FeesNotMet })?; } - let message_id = T::XcmRouter::deliver(ticket).map_err(Error::::from)?; + let message_id = T::XcmRouter::deliver(ticket) + .map_err(|error| { + tracing::error!(target: "xcm::pallet_xcm::execute_xcm_transfer", ?error, ?dest, ?remote_xcm, "XCM deliver failed with error"); + Error::::from(error) + })?; let e = Event::Sent { origin, destination: dest, message: remote_xcm, message_id }; Self::deposit_event(e); diff --git a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs index 8dafbf66adf0..67c05c116e9d 100644 --- a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs +++ b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs @@ -58,7 +58,7 @@ impl< let message = Xcm::::try_from(versioned_message).map_err(|_| { log::trace!( target: LOG_TARGET, - "Failed to convert `VersionedXcm` into `XcmV3`.", + "Failed to convert `VersionedXcm` into `xcm::prelude::Xcm`!", ); ProcessMessageError::Unsupported From c422d8bbae8ba327597582203f05d30c26ef1392 Mon Sep 17 00:00:00 2001 From: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Date: Mon, 25 Nov 2024 13:12:22 +0100 Subject: [PATCH 134/166] ci: improve workflow-stopper ux (#6632) PR addresses https://github.com/paritytech/polkadot-sdk/pull/6265#issuecomment-2497506857 cc https://github.com/paritytech/ci_cd/issues/1084 --- .github/workflows/build-misc.yml | 4 ++-- .github/workflows/check-frame-omni-bencher.yml | 4 ++-- .github/workflows/checks-quick.yml | 2 +- .github/workflows/checks.yml | 6 +++--- .github/workflows/docs.yml | 4 ++-- .github/workflows/tests-linux-stable.yml | 8 ++++---- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.github/workflows/build-misc.yml b/.github/workflows/build-misc.yml index a9b433a94b64..c4a7281b9ebc 100644 --- a/.github/workflows/build-misc.yml +++ b/.github/workflows/build-misc.yml @@ -44,7 +44,7 @@ jobs: forklift cargo check -p rococo-runtime forklift cargo check -p polkadot-test-runtime - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -73,7 +73,7 @@ jobs: cd ./substrate/bin/utils/subkey forklift cargo build --locked --release - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} diff --git a/.github/workflows/check-frame-omni-bencher.yml b/.github/workflows/check-frame-omni-bencher.yml index b47c9d49feaf..bc0ff82b6774 100644 --- a/.github/workflows/check-frame-omni-bencher.yml +++ b/.github/workflows/check-frame-omni-bencher.yml @@ -41,7 +41,7 @@ jobs: forklift cargo build --locked --quiet --release -p asset-hub-westend-runtime --features runtime-benchmarks forklift cargo run --locked --release -p frame-omni-bencher --quiet -- v1 benchmark pallet --runtime target/release/wbuild/asset-hub-westend-runtime/asset_hub_westend_runtime.compact.compressed.wasm --all --steps 2 --repeat 1 --quiet - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -99,7 +99,7 @@ jobs: echo "Running command: $cmd" eval "$cmd" - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index 4fcaf80c83fc..c733a2517cb8 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -30,7 +30,7 @@ jobs: id: required run: cargo +nightly fmt --all -- --check - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index c240504fa1e7..02428711811f 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -36,7 +36,7 @@ jobs: cargo clippy --all-targets --locked --workspace --quiet cargo clippy --all-targets --all-features --locked --workspace --quiet - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -62,7 +62,7 @@ jobs: # experimental code may rely on try-runtime and vice-versa forklift cargo check --locked --all --features try-runtime,experimental --quiet - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -91,7 +91,7 @@ jobs: ./check-features-variants.sh cd - - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index cc84e7f9ad3b..b7c70c9e6d66 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -29,7 +29,7 @@ jobs: env: RUSTFLAGS: "-Cdebug-assertions=y -Dwarnings" - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -69,7 +69,7 @@ jobs: retention-days: 1 if-no-files-found: error - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} diff --git a/.github/workflows/tests-linux-stable.yml b/.github/workflows/tests-linux-stable.yml index b9d0605b2495..3f8dc4fe1240 100644 --- a/.github/workflows/tests-linux-stable.yml +++ b/.github/workflows/tests-linux-stable.yml @@ -37,7 +37,7 @@ jobs: id: required run: WASM_BUILD_NO_COLOR=1 forklift cargo test -p staging-node-cli --release --locked -- --ignored - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -63,7 +63,7 @@ jobs: id: required run: forklift cargo nextest run --workspace --features runtime-benchmarks benchmark --locked --cargo-profile testnet --cargo-quiet - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -113,7 +113,7 @@ jobs: if: ${{ matrix.partition == '1/3' }} run: forklift cargo nextest run -p sp-api-test --features enable-staging-api --cargo-quiet - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} @@ -155,7 +155,7 @@ jobs: --filter-expr " !test(/all_security_features_work/) - test(/nonexistent_cache_dir/)" \ --partition count:${{ matrix.partition }} \ - name: Stop all workflows if failed - if: ${{ failure() && steps.required.conclusion == 'failure' }} + if: ${{ failure() && steps.required.conclusion == 'failure' && !github.event.pull_request.head.repo.fork }} uses: ./.github/actions/workflow-stopper with: app-id: ${{ secrets.WORKFLOW_STOPPER_RUNNER_APP_ID }} From 41b6915ecb4b5691cdeeb585e26d46c4897ae151 Mon Sep 17 00:00:00 2001 From: jpserrat <35823283+jpserrat@users.noreply.github.com> Date: Mon, 25 Nov 2024 12:54:04 -0300 Subject: [PATCH 135/166] remove ReportCollator message (#6628) Closes #6415 # Description Remove unused message `ReportCollator` and test related to this message on the collator protocol validator side. cc: @tdimitrov --------- Co-authored-by: Tsvetomir Dimitrov Co-authored-by: command-bot <> --- .../src/collator_side/mod.rs | 2 +- .../src/validator_side/mod.rs | 3 - .../src/validator_side/tests/mod.rs | 60 ------------------- polkadot/node/subsystem-types/src/messages.rs | 15 ++--- .../src/node/collators/collator-protocol.md | 6 -- .../src/node/subsystems-and-jobs.md | 7 +-- .../src/types/overseer-protocol.md | 3 - prdoc/pr_6628.prdoc | 12 ++++ 8 files changed, 20 insertions(+), 88 deletions(-) create mode 100644 prdoc/pr_6628.prdoc diff --git a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs index 504b0d716043..d77480272cb4 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs @@ -899,7 +899,7 @@ async fn process_msg( ); } }, - msg @ (ReportCollator(..) | Invalid(..) | Seconded(..)) => { + msg @ (Invalid(..) | Seconded(..)) => { gum::warn!( target: LOG_TARGET, "{:?} message is not expected on the collator side of the protocol", diff --git a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs index 86358f503d04..36ec959c3406 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs @@ -1462,9 +1462,6 @@ async fn process_msg( "DistributeCollation message is not expected on the validator side of the protocol", ); }, - ReportCollator(id) => { - report_collator(&mut state.reputation, ctx.sender(), &state.peer_data, id).await; - }, NetworkBridgeUpdate(event) => { if let Err(e) = handle_network_msg(ctx, state, keystore, event).await { gum::warn!( diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs index 7bc61dd4ebec..f2f23c188a66 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs @@ -638,66 +638,6 @@ fn act_on_advertisement_v2() { }); } -// Test that other subsystems may modify collators' reputations. -#[test] -fn collator_reporting_works() { - let test_state = TestState::default(); - - test_harness(ReputationAggregator::new(|_| true), |test_harness| async move { - let TestHarness { mut virtual_overseer, .. } = test_harness; - - overseer_send( - &mut virtual_overseer, - CollatorProtocolMessage::NetworkBridgeUpdate(NetworkBridgeEvent::OurViewChange( - our_view![test_state.relay_parent], - )), - ) - .await; - - respond_to_runtime_api_queries(&mut virtual_overseer, &test_state, test_state.relay_parent) - .await; - - let peer_b = PeerId::random(); - let peer_c = PeerId::random(); - - connect_and_declare_collator( - &mut virtual_overseer, - peer_b, - test_state.collators[0].clone(), - test_state.chain_ids[0], - CollationVersion::V1, - ) - .await; - - connect_and_declare_collator( - &mut virtual_overseer, - peer_c, - test_state.collators[1].clone(), - test_state.chain_ids[0], - CollationVersion::V1, - ) - .await; - - overseer_send( - &mut virtual_overseer, - CollatorProtocolMessage::ReportCollator(test_state.collators[0].public()), - ) - .await; - - assert_matches!( - overseer_recv(&mut virtual_overseer).await, - AllMessages::NetworkBridgeTx( - NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(peer, rep)), - ) => { - assert_eq!(peer, peer_b); - assert_eq!(rep.value, COST_REPORT_BAD.cost_or_benefit()); - } - ); - - virtual_overseer - }); -} - // Test that we verify the signatures on `Declare` and `AdvertiseCollation` messages. #[test] fn collator_authentication_verification_works() { diff --git a/polkadot/node/subsystem-types/src/messages.rs b/polkadot/node/subsystem-types/src/messages.rs index 28a3a1ab82ab..b541f9519219 100644 --- a/polkadot/node/subsystem-types/src/messages.rs +++ b/polkadot/node/subsystem-types/src/messages.rs @@ -48,12 +48,12 @@ use polkadot_primitives::{ CommittedCandidateReceiptV2 as CommittedCandidateReceipt, CoreState, }, ApprovalVotingParams, AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateHash, - CandidateIndex, CollatorId, CoreIndex, DisputeState, ExecutorParams, GroupIndex, - GroupRotationInfo, Hash, HeadData, Header as BlockHeader, Id as ParaId, InboundDownwardMessage, - InboundHrmpMessage, MultiDisputeStatementSet, NodeFeatures, OccupiedCoreAssumption, - PersistedValidationData, PvfCheckStatement, PvfExecKind as RuntimePvfExecKind, SessionIndex, - SessionInfo, SignedAvailabilityBitfield, SignedAvailabilityBitfields, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, + CandidateIndex, CoreIndex, DisputeState, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, + HeadData, Header as BlockHeader, Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, + MultiDisputeStatementSet, NodeFeatures, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, PvfExecKind as RuntimePvfExecKind, SessionIndex, SessionInfo, + SignedAvailabilityBitfield, SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, + ValidatorId, ValidatorIndex, ValidatorSignature, }; use polkadot_statement_table::v2::Misbehavior; use std::{ @@ -250,9 +250,6 @@ pub enum CollatorProtocolMessage { /// The core index where the candidate should be backed. core_index: CoreIndex, }, - /// Report a collator as having provided an invalid collation. This should lead to disconnect - /// and blacklist of the collator. - ReportCollator(CollatorId), /// Get a network bridge update. #[from] NetworkBridgeUpdate(NetworkBridgeEvent), diff --git a/polkadot/roadmap/implementers-guide/src/node/collators/collator-protocol.md b/polkadot/roadmap/implementers-guide/src/node/collators/collator-protocol.md index 432d9ab69bab..586a4169b5bc 100644 --- a/polkadot/roadmap/implementers-guide/src/node/collators/collator-protocol.md +++ b/polkadot/roadmap/implementers-guide/src/node/collators/collator-protocol.md @@ -151,12 +151,6 @@ time per relay parent. This reduces the bandwidth requirements and as we can sec the others are probably not required anyway. If the request times out, we need to note the collator as being unreliable and reduce its priority relative to other collators. -As a validator, once the collation has been fetched some other subsystem will inspect and do deeper validation of the -collation. The subsystem will report to this subsystem with a [`CollatorProtocolMessage`][CPM]`::ReportCollator`. In -that case, if we are connected directly to the collator, we apply a cost to the `PeerId` associated with the collator -and potentially disconnect or blacklist it. If the collation is seconded, we notify the collator and apply a benefit to -the `PeerId` associated with the collator. - ### Interaction with [Candidate Backing][CB] As collators advertise the availability, a validator will simply second the first valid parablock candidate per relay diff --git a/polkadot/roadmap/implementers-guide/src/node/subsystems-and-jobs.md b/polkadot/roadmap/implementers-guide/src/node/subsystems-and-jobs.md index a3ca7347eb63..a96f3fa3d4a0 100644 --- a/polkadot/roadmap/implementers-guide/src/node/subsystems-and-jobs.md +++ b/polkadot/roadmap/implementers-guide/src/node/subsystems-and-jobs.md @@ -129,7 +129,6 @@ digraph { cand_sel -> coll_prot [arrowhead = "diamond", label = "FetchCollation"] cand_sel -> cand_back [arrowhead = "onormal", label = "Second"] - cand_sel -> coll_prot [arrowhead = "onormal", label = "ReportCollator"] cand_val -> runt_api [arrowhead = "diamond", label = "Request::PersistedValidationData"] cand_val -> runt_api [arrowhead = "diamond", label = "Request::ValidationCode"] @@ -231,7 +230,7 @@ sequenceDiagram VS ->> CandidateSelection: Collation - Note over CandidateSelection: Lots of other machinery in play here,
but there are only three outcomes from the
perspective of the `CollatorProtocol`: + Note over CandidateSelection: Lots of other machinery in play here,
but there are only two outcomes from the
perspective of the `CollatorProtocol`: alt happy path CandidateSelection -->> VS: FetchCollation @@ -242,10 +241,6 @@ sequenceDiagram NB ->> VS: Collation Deactivate VS - else collation invalid or unexpected - CandidateSelection ->> VS: ReportCollator - VS ->> NB: ReportPeer - else CandidateSelection already selected a different candidate Note over CandidateSelection: silently drop end diff --git a/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md b/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md index 85415e42a11c..cb862440727b 100644 --- a/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md +++ b/polkadot/roadmap/implementers-guide/src/types/overseer-protocol.md @@ -436,9 +436,6 @@ enum CollatorProtocolMessage { DistributeCollation(CandidateReceipt, PoV, Option>), /// Fetch a collation under the given relay-parent for the given ParaId. FetchCollation(Hash, ParaId, ResponseChannel<(CandidateReceipt, PoV)>), - /// Report a collator as having provided an invalid collation. This should lead to disconnect - /// and blacklist of the collator. - ReportCollator(CollatorId), /// Note a collator as having provided a good collation. NoteGoodCollation(CollatorId, SignedFullStatement), /// Notify a collator that its collation was seconded. diff --git a/prdoc/pr_6628.prdoc b/prdoc/pr_6628.prdoc new file mode 100644 index 000000000000..7ea0c4968385 --- /dev/null +++ b/prdoc/pr_6628.prdoc @@ -0,0 +1,12 @@ +title: "Remove ReportCollator message" + +doc: + - audience: Node Dev + description: | + Remove unused message ReportCollator and test related to this message on the collator protocol validator side. + +crates: + - name: polkadot-node-subsystem-types + bump: patch + - name: polkadot-collator-protocol + bump: major \ No newline at end of file From 6d5f8141ad42d7a528a09715c492974550709b92 Mon Sep 17 00:00:00 2001 From: Tarek Mohamed Abdalla Date: Mon, 25 Nov 2024 19:33:32 +0200 Subject: [PATCH 136/166] rpc server: fix subscription id_provider being reset to default one. (#6588) # Description The PR ensures that the id_provider variable is cloned instead of taken, which can help prevent issues related id provider being reset to the default. In [a test in moonbeam](https://github.com/moonbeam-foundation/moonbeam/blob/c6d07d703dfcdd94cc311fa83b553071b7d433ff/test/suites/dev/moonbase/test-subscription/test-subscription.ts#L20-L31) we found that the id_provider is being reset somehow and changed to the default one. Changing .take() to .clone() would fix the issue. # Checklist * [x] My PR includes a detailed description as outlined in the "Description" and its two subsections above. * [ ] My PR follows the [labeling requirements]( https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#Process ) of this project (at minimum one label for `T` required) * External contributors: ask maintainers to put the right label on your PR. * [ ] I have made corresponding changes to the documentation (if applicable) * [ ] I have added tests that prove my fix is effective or that my feature works (if applicable) --------- Co-authored-by: Niklas Adolfsson --- prdoc/pr_6588.prdoc | 14 ++++++++++++++ substrate/client/rpc-servers/src/lib.rs | 7 +++---- 2 files changed, 17 insertions(+), 4 deletions(-) create mode 100644 prdoc/pr_6588.prdoc diff --git a/prdoc/pr_6588.prdoc b/prdoc/pr_6588.prdoc new file mode 100644 index 000000000000..bf44b2ed3784 --- /dev/null +++ b/prdoc/pr_6588.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "rpc server: fix subscription id_provider being reset to default one" + +doc: + - audience: Node Dev + description: | + The modification ensures that the id_provider variable is cloned instead of taken, which can help prevent issues related id provider being reset to the default. + + +crates: + - name: sc-rpc-server + bump: patch \ No newline at end of file diff --git a/substrate/client/rpc-servers/src/lib.rs b/substrate/client/rpc-servers/src/lib.rs index 31e4042d81f2..ff21e2da768e 100644 --- a/substrate/client/rpc-servers/src/lib.rs +++ b/substrate/client/rpc-servers/src/lib.rs @@ -144,7 +144,7 @@ where local_addrs.push(local_addr); let cfg = cfg.clone(); - let mut id_provider2 = id_provider.clone(); + let id_provider2 = id_provider.clone(); tokio_handle.spawn(async move { loop { @@ -197,10 +197,9 @@ where .set_http_middleware(http_middleware) .set_message_buffer_capacity(max_buffer_capacity_per_connection) .set_batch_request_config(batch_config) - .custom_tokio_runtime(cfg.tokio_handle.clone()) - .set_id_provider(RandomStringIdProvider::new(16)); + .custom_tokio_runtime(cfg.tokio_handle.clone()); - if let Some(provider) = id_provider2.take() { + if let Some(provider) = id_provider2.clone() { builder = builder.set_id_provider(provider); } else { builder = builder.set_id_provider(RandomStringIdProvider::new(16)); From 7f64e66b3b01ff5e391e42a8159f601cbbeb46d8 Mon Sep 17 00:00:00 2001 From: Javier Viola <363911+pepoviola@users.noreply.github.com> Date: Tue, 26 Nov 2024 09:25:18 +0100 Subject: [PATCH 137/166] bump zombienet-sdk version `v0.2.16` (#6633) Fix #6575. cc: @iulianbarbu Co-authored-by: Iulian Barbu <14218860+iulianbarbu@users.noreply.github.com> --- Cargo.lock | 24 ++++++++++++------------ Cargo.toml | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c79adee6f38e..338d5025b662 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -31910,9 +31910,9 @@ dependencies = [ [[package]] name = "zombienet-configuration" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d7a8cc4f8e8bb3f40757b62d3b054da5c95f43321c775eb321edc89d431583e" +checksum = "8ad4fc5b0f1aa54de6bf2d6771c449b41cad47e1cf30559af0a71452686b47ab" dependencies = [ "anyhow", "lazy_static", @@ -31930,9 +31930,9 @@ dependencies = [ [[package]] name = "zombienet-orchestrator" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d32fa87851f41443a78971bd7110274f9a66d139ac834de159adc08f90cf8e3" +checksum = "e4a7dd25842ded75c7f4dc4f38f05fef567bd0b37fd3057c223d4ee34d8fa817" dependencies = [ "anyhow", "async-trait", @@ -31963,9 +31963,9 @@ dependencies = [ [[package]] name = "zombienet-prom-metrics-parser" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9acb9c94bc7c2c83f8eb8e26ed403f757af1632f22b89394d8876412ede990ca" +checksum = "a63e0c6024dd19b0f8b28afa94f78c211e5c163350ecda4a48084532d74d7cfe" dependencies = [ "pest", "pest_derive", @@ -31974,9 +31974,9 @@ dependencies = [ [[package]] name = "zombienet-provider" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc8f3f71d4d974fc4a2262fa9293c2eedc423540378bd7c1dc1b66cc95d1d1af" +checksum = "8d87c29390a342d0f4f62b6796861fb82e0e56c49929a272b689e8dbf24eaab9" dependencies = [ "anyhow", "async-trait", @@ -32005,9 +32005,9 @@ dependencies = [ [[package]] name = "zombienet-sdk" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5dbfddce7a6100cdc930b93301f1b6381e6577ecc013d6802258ea6902a2bebd" +checksum = "829e5111182caf00ba57cd63656cf0bde6ce6add7f6a9747d15821c202a3f27e" dependencies = [ "async-trait", "futures", @@ -32022,9 +32022,9 @@ dependencies = [ [[package]] name = "zombienet-support" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d20567c52b4fd46b600cda254dedb6a6dc30cabf512de91e4f6f78f0f7f4644b" +checksum = "99568384a1d9645458ab9de377b3517cb543a1ece5aba905aeb58d269139df4e" dependencies = [ "anyhow", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 533ea4c9e878..57e049885da5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1387,7 +1387,7 @@ xcm-procedural = { path = "polkadot/xcm/procedural", default-features = false } xcm-runtime-apis = { path = "polkadot/xcm/xcm-runtime-apis", default-features = false } xcm-simulator = { path = "polkadot/xcm/xcm-simulator", default-features = false } zeroize = { version = "1.7.0", default-features = false } -zombienet-sdk = { version = "0.2.15" } +zombienet-sdk = { version = "0.2.16" } zstd = { version = "0.12.4", default-features = false } [profile.release] From 86a917f59d04ea3b399b34edcb8effe76b6415e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 26 Nov 2024 08:49:46 +0000 Subject: [PATCH 138/166] Bump rustls from 0.23.14 to 0.23.18 (#6641) Bumps [rustls](https://github.com/rustls/rustls) from 0.23.14 to 0.23.18.
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=rustls&package-manager=cargo&previous-version=0.23.14&new-version=0.23.18)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/paritytech/polkadot-sdk/network/alerts).
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 2 +- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 338d5025b662..c2d2eb3e9644 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8530,7 +8530,7 @@ dependencies = [ "hyper 1.3.1", "hyper-util", "log", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-native-certs 0.8.0", "rustls-pki-types", "tokio", @@ -9145,7 +9145,7 @@ dependencies = [ "http 1.1.0", "jsonrpsee-core", "pin-project", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-pki-types", "rustls-platform-verifier", "soketto 0.8.0", @@ -9198,7 +9198,7 @@ dependencies = [ "hyper-util", "jsonrpsee-core", "jsonrpsee-types", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-platform-verifier", "serde", "serde_json", @@ -20609,7 +20609,7 @@ dependencies = [ "quinn-proto 0.11.8", "quinn-udp 0.5.4", "rustc-hash 2.0.0", - "rustls 0.23.14", + "rustls 0.23.18", "socket2 0.5.7", "thiserror", "tokio", @@ -20643,7 +20643,7 @@ dependencies = [ "rand", "ring 0.17.7", "rustc-hash 2.0.0", - "rustls 0.23.14", + "rustls 0.23.18", "slab", "thiserror", "tinyvec", @@ -21130,7 +21130,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn 0.11.5", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-pemfile 2.0.0", "rustls-pki-types", "serde", @@ -21734,9 +21734,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.14" +version = "0.23.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "415d9944693cb90382053259f89fbb077ea730ad7273047ec63b19bc9b160ba8" +checksum = "9c9cc1d47e243d655ace55ed38201c19ae02c148ae56412ab8750e8f0166ab7f" dependencies = [ "log", "once_cell", @@ -21806,9 +21806,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.9.0" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e696e35370c65c9c541198af4543ccd580cf17fc25d8e05c5a242b202488c55" +checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" [[package]] name = "rustls-platform-verifier" @@ -21821,7 +21821,7 @@ dependencies = [ "jni", "log", "once_cell", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-native-certs 0.7.0", "rustls-platform-verifier-android", "rustls-webpki 0.102.8", @@ -23128,7 +23128,7 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.3", "rand", - "rustls 0.23.14", + "rustls 0.23.18", "sc-block-builder", "sc-client-api", "sc-client-db", @@ -29529,7 +29529,7 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.23.14", + "rustls 0.23.18", "rustls-pki-types", "tokio", ] @@ -30240,7 +30240,7 @@ dependencies = [ "flate2", "log", "once_cell", - "rustls 0.23.14", + "rustls 0.23.18", "rustls-pki-types", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 57e049885da5..53f95406e79a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1136,7 +1136,7 @@ rstest = { version = "0.18.2" } rustc-hash = { version = "1.1.0" } rustc-hex = { version = "2.1.0", default-features = false } rustix = { version = "0.36.7", default-features = false } -rustls = { version = "0.23.14", default-features = false, features = ["logging", "ring", "std", "tls12"] } +rustls = { version = "0.23.18", default-features = false, features = ["logging", "ring", "std", "tls12"] } rustversion = { version = "1.0.17" } rusty-fork = { version = "0.3.0", default-features = false } safe-mix = { version = "1.0", default-features = false } From 8216235b480630c5a69636b172f5146711c88c9a Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Tue, 26 Nov 2024 10:58:48 +0200 Subject: [PATCH 139/166] ci/check-semver: Fix semver failed step (#6535) The semver-check is failing with the following [error](https://github.com/paritytech/polkadot-sdk/actions/runs/11908981132/job/33185572284): ```bash error[E0658]: use of unstable library feature 'error_in_core' --> /usr/local/cargo/registry/src/index.crates.io-6f17d22bba15001f/frame-decode-0.5.0/src/decoding/extrinsic_decoder.rs:56:6 | 56 | impl core::error::Error for ExtrinsicDecodeError {} | ^^^^^^^^^^^^^^^^^^ | = note: see issue #103765 for more information = help: add `#![feature(error_in_core)]` to the crate attributes to enable = note: this compiler was built on 2024-05-31; consider upgrading it if it is out of date ``` This is related to the toolchain nightly version 1.80. In rust, 1.81 the `core::error::Error` is stable. After updating the rust-toolchain, parity-publish crate must be updated as well. The `cargo-semver-checks` dependency of `parity-publish` crate is updated from 0.34 to 0.38. This update enables rustdoc v36 that fixes the following [issue](https://github.com/paritytech/polkadot-sdk/actions/runs/11912689841/job/33196936011): ```bash validating prdocs... checking file changes... checking semver changes... (1/18) building frame-support-HEAD... (2/18) building frame-support-28.0.0... Error: rustdoc format v36 for file /__w/polkadot-sdk/polkadot-sdk/target/doc/frame_support.new is not supported ``` This PR is pending on a release of parity-publish to version 0.9.0 (fixes already on origin/master) --------- Signed-off-by: Alexandru Vasile --- .github/workflows/check-semver.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/check-semver.yml b/.github/workflows/check-semver.yml index 78602410cdf6..8d77b6a31b75 100644 --- a/.github/workflows/check-semver.yml +++ b/.github/workflows/check-semver.yml @@ -11,7 +11,7 @@ concurrency: cancel-in-progress: true env: - TOOLCHAIN: nightly-2024-06-01 + TOOLCHAIN: nightly-2024-10-19 jobs: preflight: @@ -74,7 +74,7 @@ jobs: - name: install parity-publish # Set the target dir to cache the build. - run: CARGO_TARGET_DIR=./target/ cargo install parity-publish@0.8.0 --locked -q + run: CARGO_TARGET_DIR=./target/ cargo install parity-publish@0.10.1 --locked -q - name: check semver run: | From 3c003872178b6ce535e9f26ce52e324f36075ffd Mon Sep 17 00:00:00 2001 From: Egor_P Date: Tue, 26 Nov 2024 14:46:51 +0100 Subject: [PATCH 140/166] [Release|CI/CD] Github pipeline to publish polkadot deb package (#6640) This pipeline should replace a manual action done on the `cleamroom` server to publish the `polkadot` deb package to our apt repo with the pipeline triggered from the new paritytech-release org. Right now, this is done manually by running the [add-packages.sh](https://github.com/paritytech/cleanroom/blob/master/ansible/roles/parity-repos/files/add-packages.sh) script on the `cleanroom` machine. What is done under the hood: - Pipeline downloads `polakdot` deb package from S3, that was prebuilt in the [Build release rc pipeline](https://github.com/paritytech/polkadot-sdk/blob/master/.github/workflows/release-build-rc.yml) - Prepares and syncs local apt repository - Adds and signs deb package to it using `reprepro` - Uploads new deb package to the distributed repo Closes: https://github.com/paritytech/release-engineering/issues/239 --- .github/scripts/common/lib.sh | 33 +++- .github/scripts/release/distributions | 39 +++++ .../release-40_publish-deb-package.yml | 152 ++++++++++++++++++ 3 files changed, 222 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/release/distributions create mode 100644 .github/workflows/release-40_publish-deb-package.yml diff --git a/.github/scripts/common/lib.sh b/.github/scripts/common/lib.sh index e3dd6224f29b..6b8f70a26d7e 100755 --- a/.github/scripts/common/lib.sh +++ b/.github/scripts/common/lib.sh @@ -237,15 +237,44 @@ fetch_release_artifacts() { popd > /dev/null } -# Fetch the release artifacts like binary and signatures from S3. Assumes the ENV are set: +# Fetch deb package from S3. Assumes the ENV are set: # - RELEASE_ID # - GITHUB_TOKEN # - REPO in the form paritytech/polkadot -fetch_release_artifacts_from_s3() { +fetch_debian_package_from_s3() { BINARY=$1 echo "Version : $VERSION" echo "Repo : $REPO" echo "Binary : $BINARY" + echo "Tag : $RELEASE_TAG" + OUTPUT_DIR=${OUTPUT_DIR:-"./release-artifacts/${BINARY}"} + echo "OUTPUT_DIR : $OUTPUT_DIR" + + URL_BASE=$(get_s3_url_base $BINARY) + echo "URL_BASE=$URL_BASE" + + URL=$URL_BASE/$RELEASE_TAG/x86_64-unknown-linux-gnu/${BINARY}_${VERSION}_amd64.deb + + mkdir -p "$OUTPUT_DIR" + pushd "$OUTPUT_DIR" > /dev/null + + echo "Fetching deb package..." + + echo "Fetching %s" "$URL" + curl --progress-bar -LO "$URL" || echo "Missing $URL" + + pwd + ls -al --color + popd > /dev/null + +} + +# Fetch the release artifacts like binary and signatures from S3. Assumes the ENV are set: +# - RELEASE_ID +# - GITHUB_TOKEN +# - REPO in the form paritytech/polkadot +fetch_release_artifacts_from_s3() { + BINARY=$1 OUTPUT_DIR=${OUTPUT_DIR:-"./release-artifacts/${BINARY}"} echo "OUTPUT_DIR : $OUTPUT_DIR" diff --git a/.github/scripts/release/distributions b/.github/scripts/release/distributions new file mode 100644 index 000000000000..a430ec76c6ba --- /dev/null +++ b/.github/scripts/release/distributions @@ -0,0 +1,39 @@ +Origin: Parity +Label: Parity +Codename: release +Architectures: amd64 +Components: main +Description: Apt repository for software made by Parity Technologies Ltd. +SignWith: 90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE + +Origin: Parity +Label: Parity Staging +Codename: staging +Architectures: amd64 +Components: main +Description: Staging distribution for Parity Technologies Ltd. packages +SignWith: 90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE + +Origin: Parity +Label: Parity stable2407 +Codename: stable2407 +Architectures: amd64 +Components: main +Description: Apt repository for software made by Parity Technologies Ltd. +SignWith: 90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE + +Origin: Parity +Label: Parity stable2409 +Codename: stable2409 +Architectures: amd64 +Components: main +Description: Apt repository for software made by Parity Technologies Ltd. +SignWith: 90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE + +Origin: Parity +Label: Parity stable2412 +Codename: stable2412 +Architectures: amd64 +Components: main +Description: Apt repository for software made by Parity Technologies Ltd. +SignWith: 90BD75EBBB8E95CB3DA6078F94A4029AB4B35DAE diff --git a/.github/workflows/release-40_publish-deb-package.yml b/.github/workflows/release-40_publish-deb-package.yml new file mode 100644 index 000000000000..3c5411ab16f0 --- /dev/null +++ b/.github/workflows/release-40_publish-deb-package.yml @@ -0,0 +1,152 @@ +name: Release - Publish polakdot deb package + +on: + workflow_dispatch: + inputs: + tag: + description: Current final release tag in the format polakdot-stableYYMM or polkadot-stable-YYMM-X + default: polkadot-stable2412 + required: true + type: string + + distribution: + description: Distribution where to publish deb package (release, staging, stable2407, etc) + default: staging + required: true + type: string + +jobs: + check-synchronization: + uses: paritytech-release/sync-workflows/.github/workflows/check-syncronization.yml@main + + validate-inputs: + needs: [check-synchronization] + if: ${{ needs.check-synchronization.outputs.checks_passed }} == 'true' + runs-on: ubuntu-latest + outputs: + release_tag: ${{ steps.validate_inputs.outputs.release_tag }} + + steps: + - name: Checkout sources + uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 + + - name: Validate inputs + id: validate_inputs + run: | + . ./.github/scripts/common/lib.sh + + RELEASE_TAG=$(validate_stable_tag ${{ inputs.tag }}) + echo "release_tag=${RELEASE_TAG}" >> $GITHUB_OUTPUT + + + fetch-artifacts-from-s3: + runs-on: ubuntu-latest + needs: [validate-inputs] + env: + REPO: ${{ github.repository }} + RELEASE_TAG: ${{ needs.validate-inputs.outputs.release_tag }} + outputs: + VERSION: ${{ steps.fetch_artifacts_from_s3.outputs.VERSION }} + + steps: + - name: Checkout sources + uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 + + - name: Fetch rc artifacts or release artifacts from s3 based on version + id: fetch_artifacts_from_s3 + run: | + . ./.github/scripts/common/lib.sh + + VERSION="$(get_polkadot_node_version_from_code)" + echo "VERSION=${VERSION}" >> $GITHUB_OUTPUT + + fetch_debian_package_from_s3 polkadot + + - name: Upload artifacts + uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 + with: + name: release-artifacts + path: release-artifacts/polkadot/*.deb + + publish-deb-package: + runs-on: ubuntu-latest + needs: [fetch-artifacts-from-s3] + environment: release + env: + AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }} + AWS_DEB_PATH: "s3://releases-package-repos/deb" + LOCAL_DEB_REPO_PATH: ${{ github.workspace }}/deb + VERSION: ${{ needs.fetch-artifacts-from-s3.outputs.VERSION }} + + steps: + - name: Install pgpkkms + run: | + # Install pgpkms that is used to sign built artifacts + python3 -m pip install "pgpkms @ git+https://github.com/paritytech-release/pgpkms.git@1f8555426662ac93a3849480a35449f683b1c89f" + echo "PGPKMS_REPREPRO_PATH=$(which pgpkms-reprepro)" >> $GITHUB_ENV + + - name: Install awscli + run: | + python3 -m pip install awscli + which aws + + - name: Checkout sources + uses: actions/checkout@d632683dd7b4114ad314bca15554477dd762a938 # v4.2.0 + + - name: Import gpg keys + shell: bash + run: | + . ./.github/scripts/common/lib.sh + + import_gpg_keys + + - name: Download artifacts + uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + with: + name: release-artifacts + path: release-artifacts + + - name: Setup local deb repo + run: | + sudo apt-get install -y reprepro + which reprepro + + sed -i "s|^SignWith:.*|SignWith: ! ${PGPKMS_REPREPRO_PATH}|" ${{ github.workspace }}/.github/scripts/release/distributions + + mkdir -p ${{ github.workspace }}/deb/conf + cp ${{ github.workspace }}/.github/scripts/release/distributions ${{ github.workspace }}/deb/conf/distributions + cat ${{ github.workspace }}/deb/conf/distributions + + - name: Sync local deb repo + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + run: | + # Download the current state of the deb repo + aws s3 sync "$AWS_DEB_PATH/db" "$LOCAL_DEB_REPO_PATH/db" + aws s3 sync "$AWS_DEB_PATH/pool" "$LOCAL_DEB_REPO_PATH/pool" + aws s3 sync "$AWS_DEB_PATH/dists" "$LOCAL_DEB_REPO_PATH/dists" + + - name: Add deb package to local repo + env: + PGP_KMS_KEY: ${{ secrets.PGP_KMS_KEY }} + PGP_KMS_HASH: ${{ secrets.PGP_KMS_HASH }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + run: | + # Add the new deb to the repo + reprepro -b "$LOCAL_DEB_REPO_PATH" includedeb "${{ inputs.distribution }}" "release-artifacts/polkadot_${VERSION}_amd64.deb" + + - name: Upload updated deb repo + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_RELEASE_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_RELEASE_SECRET_ACCESS_KEY }} + run: | + # Upload the updated repo - dists and pool should be publicly readable + aws s3 sync "$LOCAL_DEB_REPO_PATH/pool" "$AWS_DEB_PATH/pool" --acl public-read + aws s3 sync "$LOCAL_DEB_REPO_PATH/dists" "$AWS_DEB_PATH/dists" --acl public-read + aws s3 sync "$LOCAL_DEB_REPO_PATH/db" "$AWS_DEB_PATH/db" + aws s3 sync "$LOCAL_DEB_REPO_PATH/conf" "$AWS_DEB_PATH/conf" + + # Invalidate caches to make sure latest files are served + aws cloudfront create-invalidation --distribution-id E36FKEYWDXAZYJ --paths '/deb/*' From 1c0b610078611dfebc082be52e77109ea4517e48 Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Tue, 26 Nov 2024 15:52:23 +0100 Subject: [PATCH 141/166] xcm: fix local/remote exports when inner routers return `NotApplicable` (#6645) This PR addresses two small fixes: 1. Fixed a typo ("as as") found on the way. 2. Resolved a bug in the `local/remote exporters` used for bridging. Previously, they consumed `dest` and `msg` without returning them when inner routers/exporters failed with `NotApplicable`. This PR ensures compliance with the [`SendXcm`](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/src/v5/traits.rs#L449-L450) and [`ExportXcm`](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/xcm-executor/src/traits/export.rs#L44-L45) traits. --------- Co-authored-by: GitHub Action --- polkadot/grafana/README.md | 2 +- polkadot/grafana/parachains/status.json | 2 +- polkadot/xcm/src/v3/traits.rs | 4 +- polkadot/xcm/src/v4/traits.rs | 4 +- polkadot/xcm/src/v5/traits.rs | 4 +- .../xcm/xcm-builder/src/universal_exports.rs | 265 +++++++++++++++--- .../xcm/xcm-executor/src/traits/export.rs | 4 +- prdoc/pr_6645.prdoc | 14 + .../frame/examples/default-config/src/lib.rs | 4 +- 9 files changed, 248 insertions(+), 55 deletions(-) create mode 100644 prdoc/pr_6645.prdoc diff --git a/polkadot/grafana/README.md b/polkadot/grafana/README.md index e909fdd29a75..0ecb0b70515b 100644 --- a/polkadot/grafana/README.md +++ b/polkadot/grafana/README.md @@ -90,4 +90,4 @@ and issue statement or initiate dispute. - **Assignment delay tranches**. Approval voting is designed such that validators assigned to check a specific candidate are split up into equal delay tranches (0.5 seconds each). All validators checks are ordered by the delay tranche index. Early tranches of validators have the opportunity to check the candidate first before later tranches -that act as as backups in case of no shows. +that act as backups in case of no shows. diff --git a/polkadot/grafana/parachains/status.json b/polkadot/grafana/parachains/status.json index 5942cbdf4479..22250967848d 100644 --- a/polkadot/grafana/parachains/status.json +++ b/polkadot/grafana/parachains/status.json @@ -1405,7 +1405,7 @@ "type": "prometheus", "uid": "$data_source" }, - "description": "Approval voting requires that validators which are assigned to check a specific \ncandidate are split up into delay tranches (0.5s each). Then, all validators checks are ordered by the delay \ntranche index. Early tranches of validators will check the candidate first and later tranches act as as backups in case of no shows.", + "description": "Approval voting requires that validators which are assigned to check a specific \ncandidate are split up into delay tranches (0.5s each). Then, all validators checks are ordered by the delay \ntranche index. Early tranches of validators will check the candidate first and later tranches act as backups in case of no shows.", "gridPos": { "h": 9, "w": 18, diff --git a/polkadot/xcm/src/v3/traits.rs b/polkadot/xcm/src/v3/traits.rs index 1c8620708922..cbf85b454cc6 100644 --- a/polkadot/xcm/src/v3/traits.rs +++ b/polkadot/xcm/src/v3/traits.rs @@ -547,13 +547,13 @@ impl SendXcm for Tuple { } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. pub fn validate_send(dest: MultiLocation, msg: Xcm<()>) -> SendResult { T::validate(&mut Some(dest), &mut Some(msg)) } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. /// /// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message /// could not be sent. diff --git a/polkadot/xcm/src/v4/traits.rs b/polkadot/xcm/src/v4/traits.rs index f32b26fb163d..178093d27177 100644 --- a/polkadot/xcm/src/v4/traits.rs +++ b/polkadot/xcm/src/v4/traits.rs @@ -289,13 +289,13 @@ impl SendXcm for Tuple { } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. pub fn validate_send(dest: Location, msg: Xcm<()>) -> SendResult { T::validate(&mut Some(dest), &mut Some(msg)) } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. /// /// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message /// could not be sent. diff --git a/polkadot/xcm/src/v5/traits.rs b/polkadot/xcm/src/v5/traits.rs index 1f5041ca8d84..dd067b774fcd 100644 --- a/polkadot/xcm/src/v5/traits.rs +++ b/polkadot/xcm/src/v5/traits.rs @@ -502,13 +502,13 @@ impl SendXcm for Tuple { } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. pub fn validate_send(dest: Location, msg: Xcm<()>) -> SendResult { T::validate(&mut Some(dest), &mut Some(msg)) } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. /// /// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message /// could not be sent. diff --git a/polkadot/xcm/xcm-builder/src/universal_exports.rs b/polkadot/xcm/xcm-builder/src/universal_exports.rs index 5c754f01ec0a..aae8438c78d2 100644 --- a/polkadot/xcm/xcm-builder/src/universal_exports.rs +++ b/polkadot/xcm/xcm-builder/src/universal_exports.rs @@ -68,20 +68,28 @@ impl> SendXcm fn validate( dest: &mut Option, - xcm: &mut Option>, + msg: &mut Option>, ) -> SendResult { - let d = dest.take().ok_or(MissingArgument)?; + // This `clone` ensures that `dest` is not consumed in any case. + let d = dest.clone().take().ok_or(MissingArgument)?; let universal_source = UniversalLocation::get(); - let devolved = match ensure_is_remote(universal_source.clone(), d) { - Ok(x) => x, - Err(d) => { - *dest = Some(d); - return Err(NotApplicable) - }, - }; - let (network, destination) = devolved; - let xcm = xcm.take().ok_or(SendError::MissingArgument)?; - validate_export::(network, 0, universal_source, destination, xcm) + let devolved = ensure_is_remote(universal_source.clone(), d).map_err(|_| NotApplicable)?; + let (remote_network, remote_location) = devolved; + let xcm = msg.take().ok_or(MissingArgument)?; + + validate_export::( + remote_network, + 0, + universal_source, + remote_location, + xcm.clone(), + ) + .inspect_err(|err| { + if let NotApplicable = err { + // We need to make sure that msg is not consumed in case of `NotApplicable`. + *msg = Some(xcm); + } + }) } fn deliver(ticket: Exporter::Ticket) -> Result { @@ -95,7 +103,7 @@ pub trait ExporterFor { /// /// The payment is specified from the local context, not the bridge chain. This is the /// total amount to withdraw in to Holding and should cover both payment for the execution on - /// the bridge chain as well as payment for the use of the `ExportMessage` instruction. + /// the bridge chain and payment for the use of the `ExportMessage` instruction. fn exporter_for( network: &NetworkId, remote_location: &InteriorLocation, @@ -205,7 +213,8 @@ impl, msg: &mut Option>, ) -> SendResult { - let d = dest.clone().ok_or(MissingArgument)?; + // This `clone` ensures that `dest` is not consumed in any case. + let d = dest.clone().take().ok_or(MissingArgument)?; let devolved = ensure_is_remote(UniversalLocation::get(), d).map_err(|_| NotApplicable)?; let (remote_network, remote_location) = devolved; let xcm = msg.take().ok_or(MissingArgument)?; @@ -216,7 +225,7 @@ impl(bridge, message) + validate_send::(bridge, message).inspect_err(|err| { + if let NotApplicable = err { + // We need to make sure that msg is not consumed in case of `NotApplicable`. + *msg = Some(xcm); + } + }) } fn deliver(validation: Self::Ticket) -> Result { @@ -272,9 +290,9 @@ impl, msg: &mut Option>, ) -> SendResult { - let d = dest.as_ref().ok_or(MissingArgument)?; - let devolved = - ensure_is_remote(UniversalLocation::get(), d.clone()).map_err(|_| NotApplicable)?; + // This `clone` ensures that `dest` is not consumed in any case. + let d = dest.clone().take().ok_or(MissingArgument)?; + let devolved = ensure_is_remote(UniversalLocation::get(), d).map_err(|_| NotApplicable)?; let (remote_network, remote_location) = devolved; let xcm = msg.take().ok_or(MissingArgument)?; @@ -284,7 +302,7 @@ impl(bridge, message)?; + let (v, mut cost) = validate_send::(bridge, message).inspect_err(|err| { + if let NotApplicable = err { + // We need to make sure that msg is not consumed in case of `NotApplicable`. + *msg = Some(xcm); + } + })?; if let Some(bridge_payment) = maybe_payment { cost.push(bridge_payment); } @@ -476,10 +502,10 @@ impl< let Location { parents, interior: mut junctions } = BridgedNetwork::get(); match junctions.take_first() { Some(GlobalConsensus(network)) => (network, parents), - _ => return Err(SendError::NotApplicable), + _ => return Err(NotApplicable), } }; - ensure!(&network == &bridged_network, SendError::NotApplicable); + ensure!(&network == &bridged_network, NotApplicable); // We don't/can't use the `channel` for this adapter. let dest = destination.take().ok_or(SendError::MissingArgument)?; @@ -496,7 +522,7 @@ impl< }, Err((dest, _)) => { *destination = Some(dest); - return Err(SendError::NotApplicable) + return Err(NotApplicable) }, }; @@ -540,6 +566,10 @@ impl< #[cfg(test)] mod tests { use super::*; + use frame_support::{ + assert_err, assert_ok, + traits::{Contains, Equals}, + }; #[test] fn ensure_is_remote_works() { @@ -564,21 +594,48 @@ mod tests { assert_eq!(x, Err((Parent, Polkadot, Parachain(1000)).into())); } - pub struct OkSender; - impl SendXcm for OkSender { + pub struct OkFor(PhantomData); + impl> SendXcm for OkFor { type Ticket = (); fn validate( - _destination: &mut Option, + destination: &mut Option, _message: &mut Option>, ) -> SendResult { - Ok(((), Assets::new())) + if let Some(d) = destination.as_ref() { + if Filter::contains(&d) { + return Ok(((), Assets::new())) + } + } + Err(NotApplicable) } fn deliver(_ticket: Self::Ticket) -> Result { Ok([0; 32]) } } + impl> ExportXcm for OkFor { + type Ticket = (); + + fn validate( + network: NetworkId, + _: u32, + _: &mut Option, + destination: &mut Option, + _: &mut Option>, + ) -> SendResult { + if let Some(d) = destination.as_ref() { + if Filter::contains(&(network, d.clone())) { + return Ok(((), Assets::new())) + } + } + Err(NotApplicable) + } + + fn deliver(_ticket: Self::Ticket) -> Result { + Ok([1; 32]) + } + } /// Generic test case asserting that dest and msg is not consumed by `validate` implementation /// of `SendXcm` in case of expected result. @@ -598,46 +655,168 @@ mod tests { } #[test] - fn remote_exporters_does_not_consume_dest_or_msg_on_not_applicable() { + fn local_exporters_works() { frame_support::parameter_types! { pub Local: NetworkId = ByGenesis([0; 32]); pub UniversalLocation: InteriorLocation = [GlobalConsensus(Local::get()), Parachain(1234)].into(); pub DifferentRemote: NetworkId = ByGenesis([22; 32]); - // no routers - pub BridgeTable: Vec = vec![]; + pub RemoteDestination: Junction = Parachain(9657); + pub RoutableBridgeFilter: (NetworkId, InteriorLocation) = (DifferentRemote::get(), RemoteDestination::get().into()); } + type RoutableBridgeExporter = OkFor>; + type NotApplicableBridgeExporter = OkFor<()>; + assert_ok!(validate_export::( + DifferentRemote::get(), + 0, + UniversalLocation::get(), + RemoteDestination::get().into(), + Xcm::default() + )); + assert_err!( + validate_export::( + DifferentRemote::get(), + 0, + UniversalLocation::get(), + RemoteDestination::get().into(), + Xcm::default() + ), + NotApplicable + ); - // check with local destination (should be remote) + // 1. check with local destination (should be remote) let local_dest: Location = (Parent, Parachain(5678)).into(); assert!(ensure_is_remote(UniversalLocation::get(), local_dest.clone()).is_err()); + // UnpaidLocalExporter ensure_validate_does_not_consume_dest_or_msg::< - UnpaidRemoteExporter, OkSender, UniversalLocation>, + UnpaidLocalExporter, >(local_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); + // 2. check with not applicable from the inner router (using `NotApplicableBridgeSender`) + let remote_dest: Location = + (Parent, Parent, DifferentRemote::get(), RemoteDestination::get()).into(); + assert!(ensure_is_remote(UniversalLocation::get(), remote_dest.clone()).is_ok()); + + // UnpaidLocalExporter + ensure_validate_does_not_consume_dest_or_msg::< + UnpaidLocalExporter, + >(remote_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); + + // 3. Ok - deliver + // UnpaidRemoteExporter + assert_ok!(send_xcm::>( + remote_dest, + Xcm::default() + )); + } + + #[test] + fn remote_exporters_works() { + frame_support::parameter_types! { + pub Local: NetworkId = ByGenesis([0; 32]); + pub UniversalLocation: InteriorLocation = [GlobalConsensus(Local::get()), Parachain(1234)].into(); + pub DifferentRemote: NetworkId = ByGenesis([22; 32]); + pub RoutableBridge: Location = Location::new(1, Parachain(9657)); + // not routable + pub NotApplicableBridgeTable: Vec = vec![]; + // routable + pub RoutableBridgeTable: Vec = vec![ + NetworkExportTableItem::new( + DifferentRemote::get(), + None, + RoutableBridge::get(), + None + ) + ]; + } + type RoutableBridgeSender = OkFor>; + type NotApplicableBridgeSender = OkFor<()>; + assert_ok!(validate_send::(RoutableBridge::get(), Xcm::default())); + assert_err!( + validate_send::(RoutableBridge::get(), Xcm::default()), + NotApplicable + ); + + // 1. check with local destination (should be remote) + let local_dest: Location = (Parent, Parachain(5678)).into(); + assert!(ensure_is_remote(UniversalLocation::get(), local_dest.clone()).is_err()); + + // UnpaidRemoteExporter + ensure_validate_does_not_consume_dest_or_msg::< + UnpaidRemoteExporter< + NetworkExportTable, + RoutableBridgeSender, + UniversalLocation, + >, + >(local_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); + // SovereignPaidRemoteExporter ensure_validate_does_not_consume_dest_or_msg::< SovereignPaidRemoteExporter< - NetworkExportTable, - OkSender, + NetworkExportTable, + RoutableBridgeSender, UniversalLocation, >, >(local_dest, |result| assert_eq!(Err(NotApplicable), result)); - // check with not applicable destination + // 2. check with not applicable destination (`NotApplicableBridgeTable`) let remote_dest: Location = (Parent, Parent, DifferentRemote::get()).into(); assert!(ensure_is_remote(UniversalLocation::get(), remote_dest.clone()).is_ok()); + // UnpaidRemoteExporter ensure_validate_does_not_consume_dest_or_msg::< - UnpaidRemoteExporter, OkSender, UniversalLocation>, + UnpaidRemoteExporter< + NetworkExportTable, + RoutableBridgeSender, + UniversalLocation, + >, >(remote_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); - + // SovereignPaidRemoteExporter ensure_validate_does_not_consume_dest_or_msg::< SovereignPaidRemoteExporter< - NetworkExportTable, - OkSender, + NetworkExportTable, + RoutableBridgeSender, UniversalLocation, >, >(remote_dest, |result| assert_eq!(Err(NotApplicable), result)); + + // 3. check with not applicable from the inner router (using `NotApplicableBridgeSender`) + let remote_dest: Location = (Parent, Parent, DifferentRemote::get()).into(); + assert!(ensure_is_remote(UniversalLocation::get(), remote_dest.clone()).is_ok()); + + // UnpaidRemoteExporter + ensure_validate_does_not_consume_dest_or_msg::< + UnpaidRemoteExporter< + NetworkExportTable, + NotApplicableBridgeSender, + UniversalLocation, + >, + >(remote_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); + // SovereignPaidRemoteExporter + ensure_validate_does_not_consume_dest_or_msg::< + SovereignPaidRemoteExporter< + NetworkExportTable, + NotApplicableBridgeSender, + UniversalLocation, + >, + >(remote_dest.clone(), |result| assert_eq!(Err(NotApplicable), result)); + + // 4. Ok - deliver + // UnpaidRemoteExporter + assert_ok!(send_xcm::< + UnpaidRemoteExporter< + NetworkExportTable, + RoutableBridgeSender, + UniversalLocation, + >, + >(remote_dest.clone(), Xcm::default())); + // SovereignPaidRemoteExporter + assert_ok!(send_xcm::< + SovereignPaidRemoteExporter< + NetworkExportTable, + RoutableBridgeSender, + UniversalLocation, + >, + >(remote_dest, Xcm::default())); } #[test] diff --git a/polkadot/xcm/xcm-executor/src/traits/export.rs b/polkadot/xcm/xcm-executor/src/traits/export.rs index b356e0da7df7..3e9275edab37 100644 --- a/polkadot/xcm/xcm-executor/src/traits/export.rs +++ b/polkadot/xcm/xcm-executor/src/traits/export.rs @@ -108,7 +108,7 @@ impl ExportXcm for Tuple { } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. pub fn validate_export( network: NetworkId, channel: u32, @@ -120,7 +120,7 @@ pub fn validate_export( } /// Convenience function for using a `SendXcm` implementation. Just interprets the `dest` and wraps -/// both in `Some` before passing them as as mutable references into `T::send_xcm`. +/// both in `Some` before passing them as mutable references into `T::send_xcm`. /// /// Returns either `Ok` with the price of the delivery, or `Err` with the reason why the message /// could not be sent. diff --git a/prdoc/pr_6645.prdoc b/prdoc/pr_6645.prdoc new file mode 100644 index 000000000000..f033cadc0b6e --- /dev/null +++ b/prdoc/pr_6645.prdoc @@ -0,0 +1,14 @@ +title: 'xcm: fix local/remote exports when inner routers return `NotApplicable`' +doc: +- audience: Runtime Dev + description: |- + Resolved a bug in the `local/remote exporters` used for bridging. Previously, they consumed `dest` and `msg` without returning them when inner routers/exporters failed with `NotApplicable`. This PR ensures compliance with the [`SendXcm`](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/src/v5/traits.rs#L449-L450) and [`ExportXcm`](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm/xcm-executor/src/traits/export.rs#L44-L45) traits. +crates: +- name: staging-xcm-builder + bump: patch +- name: polkadot + bump: none +- name: staging-xcm + bump: none +- name: staging-xcm-executor + bump: none diff --git a/substrate/frame/examples/default-config/src/lib.rs b/substrate/frame/examples/default-config/src/lib.rs index ccdcd4968598..f690bffe0998 100644 --- a/substrate/frame/examples/default-config/src/lib.rs +++ b/substrate/frame/examples/default-config/src/lib.rs @@ -62,10 +62,10 @@ pub mod pallet { type OverwrittenDefaultValue: Get; /// An input parameter that relies on `::AccountId`. This can - /// too have a default, as long as as it is present in `frame_system::DefaultConfig`. + /// too have a default, as long as it is present in `frame_system::DefaultConfig`. type CanDeriveDefaultFromSystem: Get; - /// We might chose to declare as one that doesn't have a default, for whatever semantical + /// We might choose to declare as one that doesn't have a default, for whatever semantical /// reason. #[pallet::no_default] type HasNoDefault: Get; From f520adb0aacd51247ed548c7db9bef874c2cca9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dino=20Pa=C4=8Dandi?= <3002868+Dinonard@users.noreply.github.com> Date: Tue, 26 Nov 2024 15:56:02 +0100 Subject: [PATCH 142/166] Zero refund check for FungibleAdapter (#6506) `FungibleAdapter` will now check if the _refund amount_ is zero before calling deposit & emitting an event. Fixes https://github.com/paritytech/polkadot-sdk/issues/6469. --------- Co-authored-by: GitHub Action --- prdoc/pr_6506.prdoc | 10 +++++ .../frame/transaction-payment/src/payment.rs | 17 +++++---- .../frame/transaction-payment/src/tests.rs | 37 +++++++++++++++++++ 3 files changed, 56 insertions(+), 8 deletions(-) create mode 100644 prdoc/pr_6506.prdoc diff --git a/prdoc/pr_6506.prdoc b/prdoc/pr_6506.prdoc new file mode 100644 index 000000000000..7c6164a9959a --- /dev/null +++ b/prdoc/pr_6506.prdoc @@ -0,0 +1,10 @@ +title: Zero refund check for FungibleAdapter +doc: +- audience: Runtime User + description: |- + `FungibleAdapter` will now check if the _refund amount_ is zero before calling deposit & emitting an event. + + Fixes https://github.com/paritytech/polkadot-sdk/issues/6469. +crates: +- name: pallet-transaction-payment + bump: patch diff --git a/substrate/frame/transaction-payment/src/payment.rs b/substrate/frame/transaction-payment/src/payment.rs index 4b39cd3fe53b..b8a047fee3e6 100644 --- a/substrate/frame/transaction-payment/src/payment.rs +++ b/substrate/frame/transaction-payment/src/payment.rs @@ -155,14 +155,15 @@ where if let Some(paid) = already_withdrawn { // Calculate how much refund we should return let refund_amount = paid.peek().saturating_sub(corrected_fee); - // refund to the the account that paid the fees if it exists. otherwise, don't refind - // anything. - let refund_imbalance = if F::total_balance(who) > F::Balance::zero() { - F::deposit(who, refund_amount, Precision::BestEffort) - .unwrap_or_else(|_| Debt::::zero()) - } else { - Debt::::zero() - }; + // Refund to the the account that paid the fees if it exists & refund is non-zero. + // Otherwise, don't refund anything. + let refund_imbalance = + if refund_amount > Zero::zero() && F::total_balance(who) > F::Balance::zero() { + F::deposit(who, refund_amount, Precision::BestEffort) + .unwrap_or_else(|_| Debt::::zero()) + } else { + Debt::::zero() + }; // merge the imbalance caused by paying the fees and refunding parts of it again. let adjusted_paid: Credit = paid .offset(refund_imbalance) diff --git a/substrate/frame/transaction-payment/src/tests.rs b/substrate/frame/transaction-payment/src/tests.rs index 572c1d4961dd..bde1bf64728e 100644 --- a/substrate/frame/transaction-payment/src/tests.rs +++ b/substrate/frame/transaction-payment/src/tests.rs @@ -877,3 +877,40 @@ fn no_fee_and_no_weight_for_other_origins() { assert_eq!(post_info.actual_weight, Some(info.call_weight)); }) } + +#[test] +fn fungible_adapter_no_zero_refund_action() { + type FungibleAdapterT = payment::FungibleAdapter; + + ExtBuilder::default().balance_factor(10).build().execute_with(|| { + System::set_block_number(10); + + let dummy_acc = 1; + let (actual_fee, no_tip) = (10, 0); + let already_paid = >::withdraw_fee( + &dummy_acc, + CALL, + &CALL.get_dispatch_info(), + actual_fee, + no_tip, + ).expect("Account must have enough funds."); + + // Correction action with no expected side effect. + assert!(>::correct_and_deposit_fee( + &dummy_acc, + &CALL.get_dispatch_info(), + &default_post_info(), + actual_fee, + no_tip, + already_paid, + ).is_ok()); + + // Ensure no zero amount deposit event is emitted. + let events = System::events(); + assert!(!events + .iter() + .any(|record| matches!(record.event, RuntimeEvent::Balances(pallet_balances::Event::Deposit { amount, .. }) if amount.is_zero())), + "No zero amount deposit amount event should be emitted.", + ); + }); +} From fc315ac5979e9bf1cc56b58ab6f364b6b2689635 Mon Sep 17 00:00:00 2001 From: Giuseppe Re Date: Tue, 26 Nov 2024 17:26:19 +0100 Subject: [PATCH 143/166] Hide nonce implementation details in metadata (#6562) See https://github.com/polkadot-fellows/runtimes/issues/248 : using `TypeWithDefault` having derived `TypeInfo` for `Nonce` causes a breaking change in metadata for nonce type because it's no longer `u64`. Adding a default implementation of `TypeInfo` for `TypeWithDefault` to restore the original type info in metadata. --------- Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com> --- prdoc/pr_6562.prdoc | 14 +++++++++++ .../runtime/src/type_with_default.rs | 23 +++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 prdoc/pr_6562.prdoc diff --git a/prdoc/pr_6562.prdoc b/prdoc/pr_6562.prdoc new file mode 100644 index 000000000000..250b656aefb5 --- /dev/null +++ b/prdoc/pr_6562.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Hide nonce implementation details in metadata + +doc: + - audience: Runtime Dev + description: | + Use custom implementation of TypeInfo for TypeWithDefault to show inner value's type info. + This should bring back nonce to u64 in metadata. + +crates: +- name: sp-runtime + bump: minor \ No newline at end of file diff --git a/substrate/primitives/runtime/src/type_with_default.rs b/substrate/primitives/runtime/src/type_with_default.rs index 5790e3ab6bf6..b0eca22e5c1a 100644 --- a/substrate/primitives/runtime/src/type_with_default.rs +++ b/substrate/primitives/runtime/src/type_with_default.rs @@ -31,7 +31,7 @@ use num_traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, CheckedShr, CheckedSub, Num, NumCast, PrimInt, Saturating, ToPrimitive, }; -use scale_info::TypeInfo; +use scale_info::{StaticTypeInfo, TypeInfo}; use sp_core::Get; #[cfg(feature = "serde")] @@ -40,7 +40,8 @@ use serde::{Deserialize, Serialize}; /// A type that wraps another type and provides a default value. /// /// Passes through arithmetical and many other operations to the inner value. -#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen)] +/// Type information for metadata is the same as the inner value's type. +#[derive(Encode, Decode, Debug, MaxEncodedLen)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct TypeWithDefault>(T, PhantomData); @@ -50,6 +51,17 @@ impl> TypeWithDefault { } } +// Hides implementation details from the outside (for metadata type information). +// +// The type info showed in metadata is the one of the inner value's type. +impl + 'static> TypeInfo for TypeWithDefault { + type Identity = Self; + + fn type_info() -> scale_info::Type { + T::type_info() + } +} + impl> Clone for TypeWithDefault { fn clone(&self) -> Self { Self(self.0.clone(), PhantomData) @@ -511,6 +523,7 @@ impl> CompactAs for TypeWithDefault { #[cfg(test)] mod tests { use super::TypeWithDefault; + use scale_info::TypeInfo; use sp_arithmetic::traits::{AtLeast16Bit, AtLeast32Bit, AtLeast8Bit}; use sp_core::Get; @@ -565,5 +578,11 @@ mod tests { } type U128WithDefault = TypeWithDefault; impl WrapAtLeast32Bit for U128WithDefault {} + + assert_eq!(U8WithDefault::type_info(), ::type_info()); + assert_eq!(U16WithDefault::type_info(), ::type_info()); + assert_eq!(U32WithDefault::type_info(), ::type_info()); + assert_eq!(U64WithDefault::type_info(), ::type_info()); + assert_eq!(U128WithDefault::type_info(), ::type_info()); } } From 139691b17c66aa074d2b4ae935158d4296068f72 Mon Sep 17 00:00:00 2001 From: Francisco Aguirre Date: Tue, 26 Nov 2024 16:24:43 -0300 Subject: [PATCH 144/166] Fix `XcmPaymentApi::query_weight_to_asset_fee` version conversion (#6459) The `query_weight_to_asset_fee` function was trying to convert versions by using `try_as`, this function [doesn't convert from a versioned to a concrete type](https://github.com/paritytech/polkadot-sdk/blob/0156ca8f959d5cf3787c18113ce48acaaf1a8345/polkadot/xcm/src/lib.rs#L131). This would cause all calls with a lower version to fail. The correct function to use is the good old [try_into](https://github.com/paritytech/polkadot-sdk/blob/0156ca8f959d5cf3787c18113ce48acaaf1a8345/polkadot/xcm/src/lib.rs#L184). Now those calls work :) --------- Co-authored-by: command-bot <> Co-authored-by: Branislav Kontur Co-authored-by: GitHub Action --- Cargo.lock | 13 +++ .../assets/asset-hub-rococo/Cargo.toml | 1 + .../assets/asset-hub-rococo/src/lib.rs | 28 ++--- .../assets/asset-hub-rococo/tests/tests.rs | 24 +++- .../assets/asset-hub-westend/Cargo.toml | 1 + .../assets/asset-hub-westend/src/lib.rs | 29 ++--- .../assets/asset-hub-westend/tests/tests.rs | 18 ++- .../runtimes/assets/common/src/lib.rs | 79 +++++++++---- .../runtimes/assets/test-utils/Cargo.toml | 4 + .../assets/test-utils/src/test_cases.rs | 110 +++++++++++++++++- .../bridge-hubs/bridge-hub-rococo/Cargo.toml | 1 + .../bridge-hubs/bridge-hub-rococo/src/lib.rs | 3 +- .../bridge-hub-rococo/tests/tests.rs | 16 ++- .../bridge-hubs/bridge-hub-westend/Cargo.toml | 1 + .../bridge-hubs/bridge-hub-westend/src/lib.rs | 3 +- .../bridge-hub-westend/tests/tests.rs | 16 ++- .../collectives-westend/Cargo.toml | 1 + .../collectives-westend/src/lib.rs | 3 +- .../collectives-westend/tests/tests.rs | 14 ++- .../coretime/coretime-rococo/Cargo.toml | 4 + .../coretime/coretime-rococo/src/lib.rs | 3 +- .../coretime/coretime-rococo/tests/tests.rs | 14 ++- .../coretime/coretime-westend/Cargo.toml | 3 + .../coretime/coretime-westend/src/lib.rs | 3 +- .../coretime/coretime-westend/tests/tests.rs | 14 ++- .../runtimes/people/people-rococo/Cargo.toml | 3 + .../runtimes/people/people-rococo/src/lib.rs | 3 +- .../people/people-rococo/tests/tests.rs | 14 ++- .../runtimes/people/people-westend/Cargo.toml | 3 + .../runtimes/people/people-westend/src/lib.rs | 3 +- .../people/people-westend/tests/tests.rs | 14 ++- .../parachains/runtimes/test-utils/Cargo.toml | 4 + .../runtimes/test-utils/src/test_cases.rs | 67 ++++++++++- .../xcm-runtime-apis/tests/fee_estimation.rs | 23 ++++ polkadot/xcm/xcm-runtime-apis/tests/mock.rs | 3 +- prdoc/pr_6459.prdoc | 22 ++++ 36 files changed, 483 insertions(+), 82 deletions(-) create mode 100644 prdoc/pr_6459.prdoc diff --git a/Cargo.lock b/Cargo.lock index c2d2eb3e9644..58b8b222cce4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -899,6 +899,7 @@ dependencies = [ "pallet-xcm-benchmarks 7.0.0", "pallet-xcm-bridge-hub-router 0.5.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -1036,6 +1037,7 @@ dependencies = [ "pallet-xcm-benchmarks 7.0.0", "pallet-xcm-bridge-hub-router 0.5.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -1077,6 +1079,7 @@ dependencies = [ "frame-support 28.0.0", "frame-system 28.0.0", "hex-literal", + "pallet-asset-conversion 10.0.0", "pallet-assets 29.1.0", "pallet-balances 28.0.0", "pallet-collator-selection 9.0.0", @@ -1094,6 +1097,7 @@ dependencies = [ "staging-xcm-builder 7.0.0", "staging-xcm-executor 7.0.0", "substrate-wasm-builder 17.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -2578,6 +2582,7 @@ dependencies = [ "pallet-xcm-benchmarks 7.0.0", "pallet-xcm-bridge-hub 0.2.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -2815,6 +2820,7 @@ dependencies = [ "pallet-xcm-benchmarks 7.0.0", "pallet-xcm-bridge-hub 0.2.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -3550,6 +3556,7 @@ dependencies = [ "pallet-utility 28.0.0", "pallet-xcm 7.0.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -3991,6 +3998,7 @@ dependencies = [ "pallet-xcm 7.0.0", "pallet-xcm-benchmarks 7.0.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -4090,6 +4098,7 @@ dependencies = [ "pallet-xcm 7.0.0", "pallet-xcm-benchmarks 7.0.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -16165,6 +16174,7 @@ dependencies = [ "pallet-session 28.0.0", "pallet-timestamp 27.0.0", "pallet-xcm 7.0.0", + "parachains-common 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "sp-consensus-aura 0.32.0", @@ -16176,6 +16186,7 @@ dependencies = [ "staging-xcm 7.0.0", "staging-xcm-executor 7.0.0", "substrate-wasm-builder 17.0.0", + "xcm-runtime-apis 0.1.0", ] [[package]] @@ -16574,6 +16585,7 @@ dependencies = [ "pallet-xcm 7.0.0", "pallet-xcm-benchmarks 7.0.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", @@ -16675,6 +16687,7 @@ dependencies = [ "pallet-xcm 7.0.0", "pallet-xcm-benchmarks 7.0.0", "parachains-common 7.0.0", + "parachains-runtimes-test-utils 7.0.0", "parity-scale-codec", "polkadot-parachain-primitives 6.0.0", "polkadot-runtime-common 7.0.0", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml index 42adaba7a27c..bfe8ed869758 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml @@ -99,6 +99,7 @@ snowbridge-router-primitives = { workspace = true } [dev-dependencies] asset-test-utils = { workspace = true, default-features = true } +parachains-runtimes-test-utils = { workspace = true, default-features = true } [build-dependencies] substrate-wasm-builder = { optional = true, workspace = true, default-features = true } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index bc48c2d805fd..b6f3ccd3901b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -1415,37 +1415,31 @@ impl_runtime_apis! { // We accept the native token to pay fees. let mut acceptable_assets = vec![AssetId(native_token.clone())]; // We also accept all assets in a pool with the native token. - let assets_in_pool_with_native = assets_common::get_assets_in_pool_with::< - Runtime, - xcm::v5::Location - >(&native_token).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?.into_iter(); - acceptable_assets.extend(assets_in_pool_with_native); + acceptable_assets.extend( + assets_common::PoolAdapter::::get_assets_in_pool_with(native_token) + .map_err(|()| XcmPaymentApiError::VersionedConversionFailed)? + ); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { let native_asset = xcm_config::TokenLocation::get(); let fee_in_native = WeightToFee::weight_to_fee(&weight); - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == native_asset => { // for native token Ok(fee_in_native) }, Ok(asset_id) => { - let assets_in_pool_with_this_asset: Vec<_> = assets_common::get_assets_in_pool_with::< - Runtime, - xcm::v5::Location - >(&asset_id.0).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?; - if assets_in_pool_with_this_asset - .into_iter() - .map(|asset_id| asset_id.0) - .any(|location| location == native_asset) { - pallet_asset_conversion::Pallet::::quote_price_tokens_for_exact_tokens( - asset_id.clone().0, + // Try to get current price of `asset_id` in `native_asset`. + if let Ok(Some(swapped_in_native)) = assets_common::PoolAdapter::::quote_price_tokens_for_exact_tokens( + asset_id.0.clone(), native_asset, fee_in_native, true, // We include the fee. - ).ok_or(XcmPaymentApiError::AssetNotFound) + ) { + Ok(swapped_in_native) } else { log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs index 5da8b45417a3..d056405adff8 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs @@ -24,10 +24,10 @@ use asset_hub_rococo_runtime::{ ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger, LocationToAccountId, StakingPot, TokenLocation, TrustBackedAssetsPalletLocation, XcmConfig, }, - AllPalletsWithoutSystem, AssetConversion, AssetDeposit, Assets, Balances, CollatorSelection, - ExistentialDeposit, ForeignAssets, ForeignAssetsInstance, MetadataDepositBase, - MetadataDepositPerByte, ParachainSystem, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - SessionKeys, TrustBackedAssetsInstance, XcmpQueue, + AllPalletsWithoutSystem, AssetConversion, AssetDeposit, Assets, Balances, Block, + CollatorSelection, ExistentialDeposit, ForeignAssets, ForeignAssetsInstance, + MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, Runtime, RuntimeCall, + RuntimeEvent, RuntimeOrigin, SessionKeys, TrustBackedAssetsInstance, XcmpQueue, }; use asset_test_utils::{ test_cases_over_bridge::TestBridgingConfig, CollatorSessionKey, CollatorSessionKeys, @@ -1471,3 +1471,19 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); + asset_test_utils::test_cases::xcm_payment_api_with_pools_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml index d5eaa43ab834..a3eaebb59153 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml @@ -101,6 +101,7 @@ snowbridge-router-primitives = { workspace = true } [dev-dependencies] asset-test-utils = { workspace = true, default-features = true } +parachains-runtimes-test-utils = { workspace = true, default-features = true } [build-dependencies] substrate-wasm-builder = { optional = true, workspace = true, default-features = true } 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 cafea3b6ff8b..f20b6b1fece0 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -1528,38 +1528,31 @@ impl_runtime_apis! { // We accept the native token to pay fees. let mut acceptable_assets = vec![AssetId(native_token.clone())]; // We also accept all assets in a pool with the native token. - let assets_in_pool_with_native = assets_common::get_assets_in_pool_with::< - Runtime, - xcm::v5::Location - >(&native_token).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?.into_iter(); - acceptable_assets.extend(assets_in_pool_with_native); + acceptable_assets.extend( + assets_common::PoolAdapter::::get_assets_in_pool_with(native_token) + .map_err(|()| XcmPaymentApiError::VersionedConversionFailed)? + ); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { let native_asset = xcm_config::WestendLocation::get(); let fee_in_native = WeightToFee::weight_to_fee(&weight); - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == native_asset => { // for native asset Ok(fee_in_native) }, Ok(asset_id) => { - // We recognize assets in a pool with the native one. - let assets_in_pool_with_this_asset: Vec<_> = assets_common::get_assets_in_pool_with::< - Runtime, - xcm::v5::Location - >(&asset_id.0).map_err(|()| XcmPaymentApiError::VersionedConversionFailed)?; - if assets_in_pool_with_this_asset - .into_iter() - .map(|asset_id| asset_id.0) - .any(|location| location == native_asset) { - pallet_asset_conversion::Pallet::::quote_price_tokens_for_exact_tokens( - asset_id.clone().0, + // Try to get current price of `asset_id` in `native_asset`. + if let Ok(Some(swapped_in_native)) = assets_common::PoolAdapter::::quote_price_tokens_for_exact_tokens( + asset_id.0.clone(), native_asset, fee_in_native, true, // We include the fee. - ).ok_or(XcmPaymentApiError::AssetNotFound) + ) { + Ok(swapped_in_native) } else { log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index 5d0f843554a1..109a5dd2c029 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -24,7 +24,7 @@ use asset_hub_westend_runtime::{ ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger, LocationToAccountId, StakingPot, TrustBackedAssetsPalletLocation, WestendLocation, XcmConfig, }, - AllPalletsWithoutSystem, Assets, Balances, ExistentialDeposit, ForeignAssets, + AllPalletsWithoutSystem, Assets, Balances, Block, ExistentialDeposit, ForeignAssets, ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, TrustBackedAssetsInstance, XcmpQueue, @@ -1446,3 +1446,19 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); + asset_test_utils::test_cases::xcm_payment_api_with_pools_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/assets/common/src/lib.rs b/cumulus/parachains/runtimes/assets/common/src/lib.rs index 1d2d45b42c5d..25c2df6b68d1 100644 --- a/cumulus/parachains/runtimes/assets/common/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/common/src/lib.rs @@ -28,7 +28,7 @@ extern crate alloc; use crate::matching::{LocalLocationPattern, ParentLocation}; use alloc::vec::Vec; use codec::{Decode, EncodeLike}; -use core::cmp::PartialEq; +use core::{cmp::PartialEq, marker::PhantomData}; use frame_support::traits::{Equals, EverythingBut}; use parachains_common::{AssetIdForTrustBackedAssets, CollectionId, ItemId}; use sp_runtime::traits::TryConvertInto; @@ -137,24 +137,62 @@ pub type PoolAssetsConvertedConcreteId = TryConvertInto, >; -/// Returns an iterator of all assets in a pool with `asset`. -/// -/// Should only be used in runtime APIs since it iterates over the whole -/// `pallet_asset_conversion::Pools` map. -/// -/// It takes in any version of an XCM Location but always returns the latest one. -/// This is to allow some margin of migrating the pools when updating the XCM version. -/// -/// An error of type `()` is returned if the version conversion fails for XCM locations. -/// This error should be mapped by the caller to a more descriptive one. -pub fn get_assets_in_pool_with< - Runtime: pallet_asset_conversion::Config, - L: TryInto + Clone + Decode + EncodeLike + PartialEq, ->( - asset: &L, -) -> Result, ()> { - pallet_asset_conversion::Pools::::iter_keys() - .filter_map(|(asset_1, asset_2)| { +/// Adapter implementation for accessing pools (`pallet_asset_conversion`) that uses `AssetKind` as +/// a `xcm::v*` which could be different from the `xcm::latest`. +pub struct PoolAdapter(PhantomData); +impl< + Runtime: pallet_asset_conversion::Config, + L: TryFrom + TryInto + Clone + Decode + EncodeLike + PartialEq, + > PoolAdapter +{ + /// Returns a vector of all assets in a pool with `asset`. + /// + /// Should only be used in runtime APIs since it iterates over the whole + /// `pallet_asset_conversion::Pools` map. + /// + /// It takes in any version of an XCM Location but always returns the latest one. + /// This is to allow some margin of migrating the pools when updating the XCM version. + /// + /// An error of type `()` is returned if the version conversion fails for XCM locations. + /// This error should be mapped by the caller to a more descriptive one. + pub fn get_assets_in_pool_with(asset: Location) -> Result, ()> { + // convert latest to the `L` version. + let asset: L = asset.try_into().map_err(|_| ())?; + Self::iter_assets_in_pool_with(&asset) + .map(|location| { + // convert `L` to the latest `AssetId` + location.try_into().map_err(|_| ()).map(AssetId) + }) + .collect::, _>>() + } + + /// Provides a current prices. Wrapper over + /// `pallet_asset_conversion::Pallet::::quote_price_tokens_for_exact_tokens`. + /// + /// An error of type `()` is returned if the version conversion fails for XCM locations. + /// This error should be mapped by the caller to a more descriptive one. + pub fn quote_price_tokens_for_exact_tokens( + asset_1: Location, + asset_2: Location, + amount: Runtime::Balance, + include_fees: bool, + ) -> Result, ()> { + // Convert latest to the `L` version. + let asset_1: L = asset_1.try_into().map_err(|_| ())?; + let asset_2: L = asset_2.try_into().map_err(|_| ())?; + + // Quote swap price. + Ok(pallet_asset_conversion::Pallet::::quote_price_tokens_for_exact_tokens( + asset_1, + asset_2, + amount, + include_fees, + )) + } + + /// Helper function for filtering pool. + pub fn iter_assets_in_pool_with(asset: &L) -> impl Iterator + '_ { + pallet_asset_conversion::Pools::::iter_keys().filter_map(|(asset_1, asset_2)| { if asset_1 == *asset { Some(asset_2) } else if asset_2 == *asset { @@ -163,8 +201,7 @@ pub fn get_assets_in_pool_with< None } }) - .map(|location| location.try_into().map_err(|_| ()).map(AssetId)) - .collect::, _>>() + } } #[cfg(test)] diff --git a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml index 529d6460fc4e..f6b3c13e8102 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml @@ -16,6 +16,7 @@ codec = { features = ["derive", "max-encoded-len"], workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } pallet-balances = { workspace = true } pallet-timestamp = { workspace = true } pallet-session = { workspace = true } @@ -36,6 +37,7 @@ xcm = { workspace = true } xcm-builder = { workspace = true } xcm-executor = { workspace = true } pallet-xcm = { workspace = true } +xcm-runtime-apis = { workspace = true } # Bridges pallet-xcm-bridge-hub-router = { workspace = true } @@ -55,6 +57,7 @@ std = [ "cumulus-primitives-core/std", "frame-support/std", "frame-system/std", + "pallet-asset-conversion/std", "pallet-assets/std", "pallet-balances/std", "pallet-collator-selection/std", @@ -69,5 +72,6 @@ std = [ "sp-runtime/std", "xcm-builder/std", "xcm-executor/std", + "xcm-runtime-apis/std", "xcm/std", ] diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs index 8dc720e27753..aeacc1a5471e 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs @@ -34,11 +34,14 @@ use parachains_runtimes_test_utils::{ CollatorSessionKeys, ExtBuilder, SlotDurations, ValidatorIdOf, XcmReceivedFrom, }; use sp_runtime::{ - traits::{MaybeEquivalence, StaticLookup, Zero}, + traits::{Block as BlockT, MaybeEquivalence, StaticLookup, Zero}, DispatchError, Saturating, }; use xcm::{latest::prelude::*, VersionedAssets}; use xcm_executor::{traits::ConvertLocation, XcmExecutor}; +use xcm_runtime_apis::fees::{ + runtime_decl_for_xcm_payment_api::XcmPaymentApiV1, Error as XcmPaymentApiError, +}; type RuntimeHelper = parachains_runtimes_test_utils::RuntimeHelper; @@ -1584,3 +1587,108 @@ pub fn reserve_transfer_native_asset_to_non_teleport_para_works< ); }) } + +pub fn xcm_payment_api_with_pools_works() +where + Runtime: XcmPaymentApiV1 + + frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + cumulus_pallet_xcmp_queue::Config + + pallet_timestamp::Config + + pallet_assets::Config< + pallet_assets::Instance1, + AssetId = u32, + Balance = ::Balance, + > + pallet_asset_conversion::Config< + AssetKind = xcm::v5::Location, + Balance = ::Balance, + >, + ValidatorIdOf: From>, + RuntimeOrigin: OriginTrait::AccountId>, + <::Lookup as StaticLookup>::Source: + From<::AccountId>, + Block: BlockT, +{ + use xcm::prelude::*; + + ExtBuilder::::default().build().execute_with(|| { + let test_account = AccountId::from([0u8; 32]); + let transfer_amount = 100u128; + let xcm_to_weigh = Xcm::::builder_unsafe() + .withdraw_asset((Here, transfer_amount)) + .buy_execution((Here, transfer_amount), Unlimited) + .deposit_asset(AllCounted(1), [1u8; 32]) + .build(); + let versioned_xcm_to_weigh = VersionedXcm::from(xcm_to_weigh.clone().into()); + + let xcm_weight = Runtime::query_xcm_weight(versioned_xcm_to_weigh); + assert!(xcm_weight.is_ok()); + let native_token: Location = Parent.into(); + let native_token_versioned = VersionedAssetId::from(AssetId(native_token.clone())); + let execution_fees = + Runtime::query_weight_to_asset_fee(xcm_weight.unwrap(), native_token_versioned); + assert!(execution_fees.is_ok()); + + // We need some balance to create an asset. + assert_ok!( + pallet_balances::Pallet::::mint_into(&test_account, 3_000_000_000_000,) + ); + + // Now we try to use an asset that's not in a pool. + let asset_id = 1984u32; // USDT. + let asset_not_in_pool: Location = + (PalletInstance(50), GeneralIndex(asset_id.into())).into(); + assert_ok!(pallet_assets::Pallet::::create( + RuntimeOrigin::signed(test_account.clone()), + asset_id.into(), + test_account.clone().into(), + 1000 + )); + let execution_fees = Runtime::query_weight_to_asset_fee( + xcm_weight.unwrap(), + asset_not_in_pool.clone().into(), + ); + assert_eq!(execution_fees, Err(XcmPaymentApiError::AssetNotFound)); + + // We add it to a pool with native. + assert_ok!(pallet_asset_conversion::Pallet::::create_pool( + RuntimeOrigin::signed(test_account.clone()), + native_token.clone().try_into().unwrap(), + asset_not_in_pool.clone().try_into().unwrap() + )); + let execution_fees = Runtime::query_weight_to_asset_fee( + xcm_weight.unwrap(), + asset_not_in_pool.clone().into(), + ); + // Still not enough because it doesn't have any liquidity. + assert_eq!(execution_fees, Err(XcmPaymentApiError::AssetNotFound)); + + // We mint some of the asset... + assert_ok!(pallet_assets::Pallet::::mint( + RuntimeOrigin::signed(test_account.clone()), + asset_id.into(), + test_account.clone().into(), + 3_000_000_000_000, + )); + // ...so we can add liquidity to the pool. + assert_ok!(pallet_asset_conversion::Pallet::::add_liquidity( + RuntimeOrigin::signed(test_account.clone()), + native_token.try_into().unwrap(), + asset_not_in_pool.clone().try_into().unwrap(), + 1_000_000_000_000, + 2_000_000_000_000, + 0, + 0, + test_account + )); + let execution_fees = + Runtime::query_weight_to_asset_fee(xcm_weight.unwrap(), asset_not_in_pool.into()); + // Now it works! + assert_ok!(execution_fees); + }); +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml index 4af8a9f43850..3eb06e3a18c1 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml @@ -122,6 +122,7 @@ bridge-hub-test-utils = { workspace = true, default-features = true } bridge-runtime-common = { features = ["integrity-test"], workspace = true, default-features = true } pallet-bridge-relayers = { features = ["integrity-test"], workspace = true } snowbridge-runtime-test-common = { workspace = true, default-features = true } +parachains-runtimes-test-utils = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index 3f3316d0be49..598afeddb984 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -847,7 +847,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::TokenLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index 6ca858e961d3..29f9615bff6a 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -20,9 +20,9 @@ use bp_polkadot_core::Signature; use bridge_hub_rococo_runtime::{ bridge_common_config, bridge_to_bulletin_config, bridge_to_westend_config, xcm_config::{RelayNetwork, TokenLocation, XcmConfig}, - AllPalletsWithoutSystem, BridgeRejectObsoleteHeadersAndMessages, Executive, ExistentialDeposit, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, - TransactionPayment, TxExtension, UncheckedExtrinsic, + AllPalletsWithoutSystem, Block, BridgeRejectObsoleteHeadersAndMessages, Executive, + ExistentialDeposit, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeOrigin, SessionKeys, TransactionPayment, TxExtension, UncheckedExtrinsic, }; use bridge_hub_test_utils::SlotDurations; use codec::{Decode, Encode}; @@ -838,3 +838,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml index 637e7c710640..871bf44ec5b2 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml @@ -121,6 +121,7 @@ bridge-hub-test-utils = { workspace = true, default-features = true } bridge-runtime-common = { features = ["integrity-test"], workspace = true, default-features = true } pallet-bridge-relayers = { features = ["integrity-test"], workspace = true } snowbridge-runtime-test-common = { workspace = true, default-features = true } +parachains-runtimes-test-utils = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs index 65e7d291dc37..ae3dbfa06cba 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs @@ -779,7 +779,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::WestendLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index 84025c4cefeb..d7e70ed769b1 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -27,9 +27,9 @@ use bridge_hub_westend_runtime::{ bridge_common_config, bridge_to_rococo_config, bridge_to_rococo_config::RococoGlobalConsensusNetwork, xcm_config::{LocationToAccountId, RelayNetwork, WestendLocation, XcmConfig}, - AllPalletsWithoutSystem, BridgeRejectObsoleteHeadersAndMessages, Executive, ExistentialDeposit, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, - TransactionPayment, TxExtension, UncheckedExtrinsic, + AllPalletsWithoutSystem, Block, BridgeRejectObsoleteHeadersAndMessages, Executive, + ExistentialDeposit, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeOrigin, SessionKeys, TransactionPayment, TxExtension, UncheckedExtrinsic, }; use bridge_to_rococo_config::{ BridgeGrandpaRococoInstance, BridgeHubRococoLocation, BridgeParachainRococoInstance, @@ -525,3 +525,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml index e03fc934ceaf..810abcf572d4 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml @@ -94,6 +94,7 @@ substrate-wasm-builder = { optional = true, workspace = true, default-features = [dev-dependencies] sp-io = { features = ["std"], workspace = true, default-features = true } +parachains-runtimes-test-utils = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index 0ee3a4068718..f4c62f212e8c 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -963,7 +963,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::WndLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/tests/tests.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/tests/tests.rs index 7add10559d84..c9191eba49f6 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/tests/tests.rs @@ -16,7 +16,9 @@ #![cfg(test)] -use collectives_westend_runtime::xcm_config::LocationToAccountId; +use collectives_westend_runtime::{ + xcm_config::LocationToAccountId, Block, Runtime, RuntimeCall, RuntimeOrigin, +}; use parachains_common::AccountId; use sp_core::crypto::Ss58Codec; use xcm::latest::prelude::*; @@ -132,3 +134,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml index a38b7400cfa3..02807827cf92 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml @@ -80,6 +80,9 @@ parachain-info = { workspace = true } parachains-common = { workspace = true } testnet-parachains-constants = { features = ["rococo"], workspace = true } +[dev-dependencies] +parachains-runtimes-test-utils = { workspace = true } + [features] default = ["std"] std = [ @@ -120,6 +123,7 @@ std = [ "pallet-xcm/std", "parachain-info/std", "parachains-common/std", + "parachains-runtimes-test-utils/std", "polkadot-parachain-primitives/std", "polkadot-runtime-common/std", "rococo-runtime-constants/std", diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index 3f3126b749d8..ae3ad93a9e85 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -835,7 +835,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::RocRelayLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/tests/tests.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/tests/tests.rs index 2cabce567b6e..89a593ab0f57 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/tests/tests.rs @@ -16,7 +16,9 @@ #![cfg(test)] -use coretime_rococo_runtime::xcm_config::LocationToAccountId; +use coretime_rococo_runtime::{ + xcm_config::LocationToAccountId, Block, Runtime, RuntimeCall, RuntimeOrigin, +}; use parachains_common::AccountId; use sp_core::crypto::Ss58Codec; use xcm::latest::prelude::*; @@ -132,3 +134,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml index 149fa5d0b045..34353d312b1f 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml @@ -80,6 +80,9 @@ parachain-info = { workspace = true } parachains-common = { workspace = true } testnet-parachains-constants = { features = ["westend"], workspace = true } +[dev-dependencies] +parachains-runtimes-test-utils = { workspace = true, default-features = true } + [features] default = ["std"] std = [ diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index 098a17cc9984..39ea39f25a8b 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -827,7 +827,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::TokenRelayLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/tests/tests.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/tests/tests.rs index e391d71a9ab7..976ce23d6e87 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/tests/tests.rs @@ -16,7 +16,9 @@ #![cfg(test)] -use coretime_westend_runtime::xcm_config::LocationToAccountId; +use coretime_westend_runtime::{ + xcm_config::LocationToAccountId, Block, Runtime, RuntimeCall, RuntimeOrigin, +}; use parachains_common::AccountId; use sp_core::crypto::Ss58Codec; use xcm::latest::prelude::*; @@ -132,3 +134,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml index 34458c2352fb..a55143b62071 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml @@ -77,6 +77,9 @@ parachain-info = { workspace = true } parachains-common = { workspace = true } testnet-parachains-constants = { features = ["rococo"], workspace = true } +[dev-dependencies] +parachains-runtimes-test-utils = { workspace = true, default-features = true } + [features] default = ["std"] std = [ diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs index 7921030f2bb8..dc5f2ac0997c 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs @@ -783,7 +783,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::RelayLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/people/people-rococo/tests/tests.rs b/cumulus/parachains/runtimes/people/people-rococo/tests/tests.rs index 3627d9c40ec2..00fe7781822a 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/tests/tests.rs @@ -17,7 +17,9 @@ #![cfg(test)] use parachains_common::AccountId; -use people_rococo_runtime::xcm_config::LocationToAccountId; +use people_rococo_runtime::{ + xcm_config::LocationToAccountId, Block, Runtime, RuntimeCall, RuntimeOrigin, +}; use sp_core::crypto::Ss58Codec; use xcm::latest::prelude::*; use xcm_runtime_apis::conversions::LocationToAccountHelper; @@ -132,3 +134,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml index 6840b97d8c3f..4d66332e96dd 100644 --- a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml @@ -77,6 +77,9 @@ parachain-info = { workspace = true } parachains-common = { workspace = true } testnet-parachains-constants = { features = ["westend"], workspace = true } +[dev-dependencies] +parachains-runtimes-test-utils = { workspace = true, default-features = true } + [features] default = ["std"] std = [ diff --git a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs index 19a64ab8d6e8..1b9a3b60a2c4 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs @@ -781,7 +781,8 @@ impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == xcm_config::RelayLocation::get() => { // for native token Ok(WeightToFee::weight_to_fee(&weight)) diff --git a/cumulus/parachains/runtimes/people/people-westend/tests/tests.rs b/cumulus/parachains/runtimes/people/people-westend/tests/tests.rs index fa9331952b4b..5cefec44b1cd 100644 --- a/cumulus/parachains/runtimes/people/people-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/people/people-westend/tests/tests.rs @@ -17,7 +17,9 @@ #![cfg(test)] use parachains_common::AccountId; -use people_westend_runtime::xcm_config::LocationToAccountId; +use people_westend_runtime::{ + xcm_config::LocationToAccountId, Block, Runtime, RuntimeCall, RuntimeOrigin, +}; use sp_core::crypto::Ss58Codec; use xcm::latest::prelude::*; use xcm_runtime_apis::conversions::LocationToAccountHelper; @@ -132,3 +134,13 @@ fn location_conversion_works() { assert_eq!(got, expected, "{}", tc.description); } } + +#[test] +fn xcm_payment_api_works() { + parachains_runtimes_test_utils::test_cases::xcm_payment_api_with_native_token_works::< + Runtime, + RuntimeCall, + RuntimeOrigin, + Block, + >(); +} diff --git a/cumulus/parachains/runtimes/test-utils/Cargo.toml b/cumulus/parachains/runtimes/test-utils/Cargo.toml index 01d7fcc2b5c8..e9d666617ee2 100644 --- a/cumulus/parachains/runtimes/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/test-utils/Cargo.toml @@ -29,6 +29,7 @@ cumulus-pallet-parachain-system = { workspace = true } cumulus-pallet-xcmp-queue = { workspace = true } pallet-collator-selection = { workspace = true } parachain-info = { workspace = true } +parachains-common = { workspace = true } cumulus-primitives-core = { workspace = true } cumulus-primitives-parachain-inherent = { workspace = true } cumulus-test-relay-sproof-builder = { workspace = true } @@ -37,6 +38,7 @@ cumulus-test-relay-sproof-builder = { workspace = true } xcm = { workspace = true } xcm-executor = { workspace = true } pallet-xcm = { workspace = true } +xcm-runtime-apis = { workspace = true } polkadot-parachain-primitives = { workspace = true } [dev-dependencies] @@ -62,11 +64,13 @@ std = [ "pallet-timestamp/std", "pallet-xcm/std", "parachain-info/std", + "parachains-common/std", "polkadot-parachain-primitives/std", "sp-consensus-aura/std", "sp-core/std", "sp-io/std", "sp-runtime/std", "xcm-executor/std", + "xcm-runtime-apis/std", "xcm/std", ] diff --git a/cumulus/parachains/runtimes/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/test-utils/src/test_cases.rs index a66163154cf6..6bdf3ef09d1b 100644 --- a/cumulus/parachains/runtimes/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/test-utils/src/test_cases.rs @@ -18,7 +18,15 @@ use crate::{AccountIdOf, CollatorSessionKeys, ExtBuilder, ValidatorIdOf}; use codec::Encode; -use frame_support::{assert_ok, traits::Get}; +use frame_support::{ + assert_ok, + traits::{Get, OriginTrait}, +}; +use parachains_common::AccountId; +use sp_runtime::traits::{Block as BlockT, StaticLookup}; +use xcm_runtime_apis::fees::{ + runtime_decl_for_xcm_payment_api::XcmPaymentApiV1, Error as XcmPaymentApiError, +}; type RuntimeHelper = crate::RuntimeHelper; @@ -128,3 +136,60 @@ pub fn set_storage_keys_by_governance_works( assert_storage(); }); } + +pub fn xcm_payment_api_with_native_token_works() +where + Runtime: XcmPaymentApiV1 + + frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + cumulus_pallet_xcmp_queue::Config + + pallet_timestamp::Config, + ValidatorIdOf: From>, + RuntimeOrigin: OriginTrait::AccountId>, + <::Lookup as StaticLookup>::Source: + From<::AccountId>, + Block: BlockT, +{ + use xcm::prelude::*; + ExtBuilder::::default().build().execute_with(|| { + let transfer_amount = 100u128; + let xcm_to_weigh = Xcm::::builder_unsafe() + .withdraw_asset((Here, transfer_amount)) + .buy_execution((Here, transfer_amount), Unlimited) + .deposit_asset(AllCounted(1), [1u8; 32]) + .build(); + let versioned_xcm_to_weigh = VersionedXcm::from(xcm_to_weigh.clone().into()); + + // We first try calling it with a lower XCM version. + let lower_version_xcm_to_weigh = + versioned_xcm_to_weigh.clone().into_version(XCM_VERSION - 1).unwrap(); + let xcm_weight = Runtime::query_xcm_weight(lower_version_xcm_to_weigh); + assert!(xcm_weight.is_ok()); + let native_token: Location = Parent.into(); + let native_token_versioned = VersionedAssetId::from(AssetId(native_token)); + let lower_version_native_token = + native_token_versioned.clone().into_version(XCM_VERSION - 1).unwrap(); + let execution_fees = + Runtime::query_weight_to_asset_fee(xcm_weight.unwrap(), lower_version_native_token); + assert!(execution_fees.is_ok()); + + // Now we call it with the latest version. + let xcm_weight = Runtime::query_xcm_weight(versioned_xcm_to_weigh); + assert!(xcm_weight.is_ok()); + let execution_fees = + Runtime::query_weight_to_asset_fee(xcm_weight.unwrap(), native_token_versioned); + assert!(execution_fees.is_ok()); + + // If we call it with anything other than the native token it will error. + let non_existent_token: Location = Here.into(); + let non_existent_token_versioned = VersionedAssetId::from(AssetId(non_existent_token)); + let execution_fees = + Runtime::query_weight_to_asset_fee(xcm_weight.unwrap(), non_existent_token_versioned); + assert_eq!(execution_fees, Err(XcmPaymentApiError::AssetNotFound)); + }); +} diff --git a/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs b/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs index 2d14b4e571c6..c3046b134d1f 100644 --- a/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs @@ -353,3 +353,26 @@ fn dry_run_xcm() { ); }); } + +#[test] +fn calling_payment_api_with_a_lower_version_works() { + let transfer_amount = 100u128; + let xcm_to_weigh = Xcm::::builder_unsafe() + .withdraw_asset((Here, transfer_amount)) + .buy_execution((Here, transfer_amount), Unlimited) + .deposit_asset(AllCounted(1), [1u8; 32]) + .build(); + let versioned_xcm_to_weigh = VersionedXcm::from(xcm_to_weigh.clone().into()); + let lower_version_xcm_to_weigh = versioned_xcm_to_weigh.into_version(XCM_VERSION - 1).unwrap(); + let client = TestClient; + let runtime_api = client.runtime_api(); + let xcm_weight = + runtime_api.query_xcm_weight(H256::zero(), lower_version_xcm_to_weigh).unwrap(); + assert!(xcm_weight.is_ok()); + let native_token = VersionedAssetId::from(AssetId(Here.into())); + let lower_version_native_token = native_token.into_version(XCM_VERSION - 1).unwrap(); + let execution_fees = runtime_api + .query_weight_to_asset_fee(H256::zero(), xcm_weight.unwrap(), lower_version_native_token) + .unwrap(); + assert!(execution_fees.is_ok()); +} diff --git a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs index f0a5be908f69..fb5d1ae7c0e5 100644 --- a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs @@ -453,7 +453,8 @@ sp_api::mock_impl_runtime_apis! { } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { - match asset.try_as::() { + let latest_asset_id: Result = asset.clone().try_into(); + match latest_asset_id { Ok(asset_id) if asset_id.0 == HereLocation::get() => { Ok(WeightToFee::weight_to_fee(&weight)) }, diff --git a/prdoc/pr_6459.prdoc b/prdoc/pr_6459.prdoc new file mode 100644 index 000000000000..592ba4c6b29d --- /dev/null +++ b/prdoc/pr_6459.prdoc @@ -0,0 +1,22 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Fix version conversion in XcmPaymentApi::query_weight_to_asset_fee. + +doc: + - audience: Runtime Dev + description: | + The `query_weight_to_asset_fee` function of the `XcmPaymentApi` was trying + to convert versions in the wrong way. + This resulted in all calls made with lower versions failing. + The version conversion is now done correctly and these same calls will now succeed. + +crates: + - name: asset-hub-westend-runtime + bump: patch + - name: asset-hub-rococo-runtime + bump: patch + - name: xcm-runtime-apis + bump: patch + - name: assets-common + bump: patch From 445c1c80d438d5b937c347b04e4daa66ad25d878 Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Wed, 27 Nov 2024 10:28:26 +0100 Subject: [PATCH 145/166] Add stable2412 to target_branches for command-backport.yml (#6666) The backport bot opens PR for `A4-needs-backport` only for stable2407 stable2409, but we have already stable2412. The question is, when should we append a new `stable*` branch here? Should it be done when a new `stable*` branch is created? Can we automate this process somehow? --- .github/workflows/command-backport.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/command-backport.yml b/.github/workflows/command-backport.yml index 8f23bcd75f01..eecf0ac72d2c 100644 --- a/.github/workflows/command-backport.yml +++ b/.github/workflows/command-backport.yml @@ -40,7 +40,7 @@ jobs: uses: korthout/backport-action@v3 id: backport with: - target_branches: stable2407 stable2409 + target_branches: stable2407 stable2409 stable2412 merge_commits: skip github_token: ${{ steps.generate_token.outputs.token }} pull_description: | From 2a0b2680b8df9c18d2543f82629917f759827e1c Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Wed, 27 Nov 2024 13:11:01 +0200 Subject: [PATCH 146/166] litep2p/req-resp: Always provide main protocol name in responses (#6603) Request responses are initialized with a main protocol name, and optional protocol names as a fallback. Running litep2p in kusama as a validator has surfaced a `debug_asserts` coming from the sync component: https://github.com/paritytech/polkadot-sdk/blob/3906c578c96d97a8a099a4bdac4685acbe375a7c/substrate/client/network/sync/src/strategy/chain_sync.rs#L640-L646 The issue is that we initiate a request-response over the main protocol name `/genesis/sync/2` but receive a response over the legacy procotol `ksm/sync/2`. This behavior is correct because litep2p propagates to the higher levels the protocol that responded. In contrast, libp2p provides the main protocol name regardless of negotiating a legacy protocol. Because of this, higher level components assume that only the main protocol name will respond. To not break this assumption, this PR alings litep2p shim layer with the libp2p behavior. Closes: https://github.com/paritytech/polkadot-sdk/issues/6581 --------- Signed-off-by: Alexandru Vasile Co-authored-by: Dmitry Markin --- prdoc/pr_6603.prdoc | 16 ++++++++++++++++ .../src/litep2p/shim/request_response/mod.rs | 7 ++----- 2 files changed, 18 insertions(+), 5 deletions(-) create mode 100644 prdoc/pr_6603.prdoc diff --git a/prdoc/pr_6603.prdoc b/prdoc/pr_6603.prdoc new file mode 100644 index 000000000000..20c5e7294dfa --- /dev/null +++ b/prdoc/pr_6603.prdoc @@ -0,0 +1,16 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Always provide main protocol name in litep2p responses + +doc: + - audience: [ Node Dev, Node Operator ] + description: | + This PR aligns litep2p behavior with libp2p. Previously, litep2p network backend + would provide the actual negotiated request-response protocol that produced a + response message. After this PR, only the main protocol name is reported to other + subsystems. + +crates: + - name: sc-network + bump: patch diff --git a/substrate/client/network/src/litep2p/shim/request_response/mod.rs b/substrate/client/network/src/litep2p/shim/request_response/mod.rs index bfd7a60ef9fe..146f2e4add97 100644 --- a/substrate/client/network/src/litep2p/shim/request_response/mod.rs +++ b/substrate/client/network/src/litep2p/shim/request_response/mod.rs @@ -320,7 +320,7 @@ impl RequestResponseProtocol { &mut self, peer: litep2p::PeerId, request_id: RequestId, - fallback: Option, + _fallback: Option, response: Vec, ) { match self.pending_inbound_responses.remove(&request_id) { @@ -337,10 +337,7 @@ impl RequestResponseProtocol { response.len(), ); - let _ = tx.send(Ok(( - response, - fallback.map_or_else(|| self.protocol.clone(), Into::into), - ))); + let _ = tx.send(Ok((response, self.protocol.clone()))); self.metrics.register_outbound_request_success(started.elapsed()); }, } From 5b1b34db0c03057c7962eb9682b4d581c324ae26 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Wed, 27 Nov 2024 14:10:36 +0200 Subject: [PATCH 147/166] v16: Expose the unstable metadata v16 (#5732) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This PR exposes the *unstable* metadata V16. The metadata is exposed under the unstable u32::MAX number. Developers can start experimenting with the new features of the metadata v16. *Please note that this metadata is under development and expect breaking changes until stabilization.* The `ExtrinsicMetadata` trait receives a breaking change. Its associated type `VERSION` is rename to `VERSIONS` and now supports a constant static list of metadata versions. The versions implemented for `UncheckedExtrinsic` are v4 (legacy version) and v5 (new version). For metadata collection, it is assumed that all `TransactionExtensions` are under version 0. Builds on top of: https://github.com/paritytech/polkadot-sdk/pull/5274 Closes: https://github.com/paritytech/polkadot-sdk/issues/5980 Closes: https://github.com/paritytech/polkadot-sdk/issues/5347 Closes: https://github.com/paritytech/polkadot-sdk/issues/5285 cc @paritytech/subxt-team --------- Signed-off-by: Alexandru Vasile Co-authored-by: Niklas Adolfsson Co-authored-by: Bastian Köcher Co-authored-by: James Wilson Co-authored-by: GitHub Action --- Cargo.lock | 28 ++- Cargo.toml | 4 +- prdoc/pr_5732.prdoc | 29 +++ .../frame/metadata-hash-extension/Cargo.toml | 2 +- substrate/frame/revive/src/evm/runtime.rs | 8 +- substrate/frame/support/Cargo.toml | 1 + .../src/construct_runtime/expand/metadata.rs | 2 +- substrate/frame/support/test/Cargo.toml | 2 +- substrate/frame/support/test/tests/pallet.rs | 8 +- substrate/primitives/metadata-ir/Cargo.toml | 2 +- substrate/primitives/metadata-ir/src/lib.rs | 25 ++- substrate/primitives/metadata-ir/src/types.rs | 6 +- .../primitives/metadata-ir/src/unstable.rs | 211 ++++++++++++++++++ substrate/primitives/metadata-ir/src/v14.rs | 5 +- substrate/primitives/metadata-ir/src/v15.rs | 2 +- .../src/generic/unchecked_extrinsic.rs | 3 +- .../primitives/runtime/src/traits/mod.rs | 6 +- .../src/overhead/remark_builder.rs | 8 +- .../src/overhead/runtime_utilities.rs | 15 +- substrate/utils/wasm-builder/Cargo.toml | 2 +- 20 files changed, 329 insertions(+), 40 deletions(-) create mode 100644 prdoc/pr_5732.prdoc create mode 100644 substrate/primitives/metadata-ir/src/unstable.rs diff --git a/Cargo.lock b/Cargo.lock index 58b8b222cce4..2c938ec17bd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7224,6 +7224,18 @@ dependencies = [ "serde", ] +[[package]] +name = "frame-metadata" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daaf440c68eb2c3d88e5760fe8c7af3f9fee9181fab6c2f2c4e7cc48dcc40bb8" +dependencies = [ + "cfg-if", + "parity-scale-codec", + "scale-info", + "serde", +] + [[package]] name = "frame-metadata-hash-extension" version = "0.1.0" @@ -7231,7 +7243,7 @@ dependencies = [ "array-bytes", "const-hex", "docify", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "frame-support 28.0.0", "frame-system 28.0.0", "log", @@ -7316,7 +7328,7 @@ dependencies = [ "bitflags 1.3.2", "docify", "environmental", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "frame-support-procedural 23.0.0", "frame-system 28.0.0", "impl-trait-for-tuples", @@ -7494,7 +7506,7 @@ version = "3.0.0" dependencies = [ "frame-benchmarking 28.0.0", "frame-executive 28.0.0", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "frame-support 28.0.0", "frame-support-test-pallet", "frame-system 28.0.0", @@ -10520,13 +10532,13 @@ dependencies = [ [[package]] name = "merkleized-metadata" -version = "0.1.0" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f313fcff1d2a4bcaa2deeaa00bf7530d77d5f7bd0467a117dde2e29a75a7a17a" +checksum = "943f6d92804ed0100803d51fa9b21fd9432b5d122ba4c713dc26fe6d2f619cf6" dependencies = [ "array-bytes", "blake3", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "parity-scale-codec", "scale-decode 0.13.1", "scale-info", @@ -26664,7 +26676,7 @@ dependencies = [ name = "sp-metadata-ir" version = "0.6.0" dependencies = [ - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "parity-scale-codec", "scale-info", ] @@ -28601,7 +28613,7 @@ dependencies = [ "cargo_metadata", "console", "filetime", - "frame-metadata 16.0.0", + "frame-metadata 18.0.0", "jobserver", "merkleized-metadata", "parity-scale-codec", diff --git a/Cargo.toml b/Cargo.toml index 53f95406e79a..b1a52712e736 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -779,7 +779,7 @@ frame-benchmarking-pallet-pov = { default-features = false, path = "substrate/fr frame-election-provider-solution-type = { path = "substrate/frame/election-provider-support/solution-type", default-features = false } frame-election-provider-support = { path = "substrate/frame/election-provider-support", default-features = false } frame-executive = { path = "substrate/frame/executive", default-features = false } -frame-metadata = { version = "16.0.0", default-features = false } +frame-metadata = { version = "18.0.0", default-features = false } frame-metadata-hash-extension = { path = "substrate/frame/metadata-hash-extension", default-features = false } frame-support = { path = "substrate/frame/support", default-features = false } frame-support-procedural = { path = "substrate/frame/support/procedural", default-features = false } @@ -854,7 +854,7 @@ macro_magic = { version = "0.5.1" } maplit = { version = "1.0.2" } memmap2 = { version = "0.9.3" } memory-db = { version = "0.32.0", default-features = false } -merkleized-metadata = { version = "0.1.0" } +merkleized-metadata = { version = "0.1.2" } merlin = { version = "3.0", default-features = false } messages-relay = { path = "bridges/relays/messages" } metered = { version = "0.6.1", default-features = false, package = "prioritized-metered-channel" } diff --git a/prdoc/pr_5732.prdoc b/prdoc/pr_5732.prdoc new file mode 100644 index 000000000000..6f3f9b8a1668 --- /dev/null +++ b/prdoc/pr_5732.prdoc @@ -0,0 +1,29 @@ +title: Expose the unstable metadata v16 +doc: +- audience: Node Dev + description: | + This PR exposes the *unstable* metadata V16. The metadata is exposed under the unstable u32::MAX number. + Developers can start experimenting with the new features of the metadata v16. *Please note that this metadata is under development and expect breaking changes until stabilization.* + The `ExtrinsicMetadata` trait receives a breaking change. Its associated type `VERSION` is rename to `VERSIONS` and now supports a constant static list of metadata versions. + The versions implemented for `UncheckedExtrinsic` are v4 (legacy version) and v5 (new version). + For metadata collection, it is assumed that all `TransactionExtensions` are under version 0. + +crates: + - name: sp-metadata-ir + bump: major + - name: frame-support-procedural + bump: patch + - name: frame-support + bump: minor + - name: frame-support-test + bump: major + - name: frame-metadata-hash-extension + bump: patch + - name: substrate-wasm-builder + bump: minor + - name: pallet-revive + bump: minor + - name: sp-runtime + bump: major + - name: frame-benchmarking-cli + bump: patch diff --git a/substrate/frame/metadata-hash-extension/Cargo.toml b/substrate/frame/metadata-hash-extension/Cargo.toml index bca2c3ffb198..8f4ba922984c 100644 --- a/substrate/frame/metadata-hash-extension/Cargo.toml +++ b/substrate/frame/metadata-hash-extension/Cargo.toml @@ -25,7 +25,7 @@ substrate-test-runtime-client = { workspace = true } sp-api = { workspace = true, default-features = true } sp-transaction-pool = { workspace = true, default-features = true } merkleized-metadata = { workspace = true } -frame-metadata = { features = ["current"], workspace = true, default-features = true } +frame-metadata = { features = ["current", "unstable"], workspace = true, default-features = true } sp-tracing = { workspace = true, default-features = true } [features] diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index 40c210304ca2..b5dc9a36065b 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -92,8 +92,12 @@ impl ExtrinsicLike impl ExtrinsicMetadata for UncheckedExtrinsic { - const VERSION: u8 = - generic::UncheckedExtrinsic::, Signature, E::Extension>::VERSION; + const VERSIONS: &'static [u8] = generic::UncheckedExtrinsic::< + Address, + CallOf, + Signature, + E::Extension, + >::VERSIONS; type TransactionExtensions = E::Extension; } diff --git a/substrate/frame/support/Cargo.toml b/substrate/frame/support/Cargo.toml index d7da034b3492..d48c80510581 100644 --- a/substrate/frame/support/Cargo.toml +++ b/substrate/frame/support/Cargo.toml @@ -28,6 +28,7 @@ scale-info = { features = [ ], workspace = true } frame-metadata = { features = [ "current", + "unstable", ], workspace = true } sp-api = { features = [ "frame-metadata", diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs index c12fc20bc8b8..4590a3a7f490 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs @@ -117,7 +117,7 @@ pub fn expand_runtime_metadata( pallets: #scrate::__private::vec![ #(#pallets),* ], extrinsic: #scrate::__private::metadata_ir::ExtrinsicMetadataIR { ty, - version: <#extrinsic as #scrate::sp_runtime::traits::ExtrinsicMetadata>::VERSION, + versions: <#extrinsic as #scrate::sp_runtime::traits::ExtrinsicMetadata>::VERSIONS.into_iter().map(|ref_version| *ref_version).collect(), address_ty, call_ty, signature_ty, diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index 2187ee22b395..17ee3130b741 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -19,7 +19,7 @@ static_assertions = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true } codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } -frame-metadata = { features = ["current"], workspace = true } +frame-metadata = { features = ["current", "unstable"], workspace = true } sp-api = { workspace = true } sp-arithmetic = { workspace = true } sp-io = { workspace = true } diff --git a/substrate/frame/support/test/tests/pallet.rs b/substrate/frame/support/test/tests/pallet.rs index de7f7eb4bc97..9df1f461bba2 100644 --- a/substrate/frame/support/test/tests/pallet.rs +++ b/substrate/frame/support/test/tests/pallet.rs @@ -53,6 +53,9 @@ parameter_types! { /// Latest stable metadata version used for testing. const LATEST_METADATA_VERSION: u32 = 15; +/// Unstable metadata version. +const UNSTABLE_METADATA_VERSION: u32 = u32::MAX; + pub struct SomeType1; impl From for u64 { fn from(_t: SomeType1) -> Self { @@ -1977,7 +1980,10 @@ fn metadata_at_version() { #[test] fn metadata_versions() { - assert_eq!(vec![14, LATEST_METADATA_VERSION], Runtime::metadata_versions()); + assert_eq!( + vec![14, LATEST_METADATA_VERSION, UNSTABLE_METADATA_VERSION], + Runtime::metadata_versions() + ); } #[test] diff --git a/substrate/primitives/metadata-ir/Cargo.toml b/substrate/primitives/metadata-ir/Cargo.toml index d7786347dd02..046441104b88 100644 --- a/substrate/primitives/metadata-ir/Cargo.toml +++ b/substrate/primitives/metadata-ir/Cargo.toml @@ -17,7 +17,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { workspace = true } -frame-metadata = { features = ["current"], workspace = true } +frame-metadata = { features = ["current", "unstable"], workspace = true } scale-info = { features = ["derive"], workspace = true } [features] diff --git a/substrate/primitives/metadata-ir/src/lib.rs b/substrate/primitives/metadata-ir/src/lib.rs index 4bd13b935afd..bf234432a1a6 100644 --- a/substrate/primitives/metadata-ir/src/lib.rs +++ b/substrate/primitives/metadata-ir/src/lib.rs @@ -30,6 +30,7 @@ mod types; use frame_metadata::RuntimeMetadataPrefixed; pub use types::*; +mod unstable; mod v14; mod v15; @@ -39,23 +40,33 @@ const V14: u32 = 14; /// Metadata V15. const V15: u32 = 15; +/// Unstable metadata V16. +const UNSTABLE_V16: u32 = u32::MAX; + /// Transform the IR to the specified version. /// /// Use [`supported_versions`] to find supported versions. pub fn into_version(metadata: MetadataIR, version: u32) -> Option { // Note: Unstable metadata version is `u32::MAX` until stabilized. match version { - // Latest stable version. + // Version V14. This needs to be around until the + // deprecation of the `Metadata_metadata` runtime call in favor of + // `Metadata_metadata_at_version. V14 => Some(into_v14(metadata)), - // Unstable metadata. + + // Version V15 - latest stable. V15 => Some(into_latest(metadata)), + + // Unstable metadata under `u32::MAX`. + UNSTABLE_V16 => Some(into_unstable(metadata)), + _ => None, } } /// Returns the supported metadata versions. pub fn supported_versions() -> alloc::vec::Vec { - alloc::vec![V14, V15] + alloc::vec![V14, V15, UNSTABLE_V16] } /// Transform the IR to the latest stable metadata version. @@ -70,6 +81,12 @@ pub fn into_v14(metadata: MetadataIR) -> RuntimeMetadataPrefixed { latest.into() } +/// Transform the IR to unstable metadata version 16. +pub fn into_unstable(metadata: MetadataIR) -> RuntimeMetadataPrefixed { + let latest: frame_metadata::v16::RuntimeMetadataV16 = metadata.into(); + latest.into() +} + #[cfg(test)] mod test { use super::*; @@ -81,7 +98,7 @@ mod test { pallets: vec![], extrinsic: ExtrinsicMetadataIR { ty: meta_type::<()>(), - version: 0, + versions: vec![0], address_ty: meta_type::<()>(), call_ty: meta_type::<()>(), signature_ty: meta_type::<()>(), diff --git a/substrate/primitives/metadata-ir/src/types.rs b/substrate/primitives/metadata-ir/src/types.rs index 199b692fbd8c..af217ffe16ee 100644 --- a/substrate/primitives/metadata-ir/src/types.rs +++ b/substrate/primitives/metadata-ir/src/types.rs @@ -170,8 +170,8 @@ pub struct ExtrinsicMetadataIR { /// /// Note: Field used for metadata V14 only. pub ty: T::Type, - /// Extrinsic version. - pub version: u8, + /// Extrinsic versions. + pub versions: Vec, /// The type of the address that signs the extrinsic pub address_ty: T::Type, /// The type of the outermost Call enum. @@ -191,7 +191,7 @@ impl IntoPortable for ExtrinsicMetadataIR { fn into_portable(self, registry: &mut Registry) -> Self::Output { ExtrinsicMetadataIR { ty: registry.register_type(&self.ty), - version: self.version, + versions: self.versions, address_ty: registry.register_type(&self.address_ty), call_ty: registry.register_type(&self.call_ty), signature_ty: registry.register_type(&self.signature_ty), diff --git a/substrate/primitives/metadata-ir/src/unstable.rs b/substrate/primitives/metadata-ir/src/unstable.rs new file mode 100644 index 000000000000..d46ce3ec6a7d --- /dev/null +++ b/substrate/primitives/metadata-ir/src/unstable.rs @@ -0,0 +1,211 @@ +// 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. + +//! Convert the IR to V16 metadata. + +use crate::{ + DeprecationInfoIR, DeprecationStatusIR, OuterEnumsIR, PalletAssociatedTypeMetadataIR, + PalletCallMetadataIR, PalletConstantMetadataIR, PalletErrorMetadataIR, PalletEventMetadataIR, + PalletStorageMetadataIR, StorageEntryMetadataIR, +}; + +use super::types::{ + ExtrinsicMetadataIR, MetadataIR, PalletMetadataIR, RuntimeApiMetadataIR, + RuntimeApiMethodMetadataIR, RuntimeApiMethodParamMetadataIR, TransactionExtensionMetadataIR, +}; + +use frame_metadata::v16::{ + CustomMetadata, DeprecationInfo, DeprecationStatus, ExtrinsicMetadata, OuterEnums, + PalletAssociatedTypeMetadata, PalletCallMetadata, PalletConstantMetadata, PalletErrorMetadata, + PalletEventMetadata, PalletMetadata, PalletStorageMetadata, RuntimeApiMetadata, + RuntimeApiMethodMetadata, RuntimeApiMethodParamMetadata, RuntimeMetadataV16, + StorageEntryMetadata, TransactionExtensionMetadata, +}; + +impl From for RuntimeMetadataV16 { + fn from(ir: MetadataIR) -> Self { + RuntimeMetadataV16::new( + ir.pallets.into_iter().map(Into::into).collect(), + ir.extrinsic.into(), + ir.apis.into_iter().map(Into::into).collect(), + ir.outer_enums.into(), + // Substrate does not collect yet the custom metadata fields. + // This allows us to extend the V16 easily. + CustomMetadata { map: Default::default() }, + ) + } +} + +impl From for RuntimeApiMetadata { + fn from(ir: RuntimeApiMetadataIR) -> Self { + RuntimeApiMetadata { + name: ir.name, + methods: ir.methods.into_iter().map(Into::into).collect(), + docs: ir.docs, + deprecation_info: ir.deprecation_info.into(), + } + } +} + +impl From for RuntimeApiMethodMetadata { + fn from(ir: RuntimeApiMethodMetadataIR) -> Self { + RuntimeApiMethodMetadata { + name: ir.name, + inputs: ir.inputs.into_iter().map(Into::into).collect(), + output: ir.output, + docs: ir.docs, + deprecation_info: ir.deprecation_info.into(), + } + } +} + +impl From for RuntimeApiMethodParamMetadata { + fn from(ir: RuntimeApiMethodParamMetadataIR) -> Self { + RuntimeApiMethodParamMetadata { name: ir.name, ty: ir.ty } + } +} + +impl From for PalletMetadata { + fn from(ir: PalletMetadataIR) -> Self { + PalletMetadata { + name: ir.name, + storage: ir.storage.map(Into::into), + calls: ir.calls.map(Into::into), + event: ir.event.map(Into::into), + constants: ir.constants.into_iter().map(Into::into).collect(), + error: ir.error.map(Into::into), + index: ir.index, + docs: ir.docs, + associated_types: ir.associated_types.into_iter().map(Into::into).collect(), + deprecation_info: ir.deprecation_info.into(), + } + } +} + +impl From for PalletStorageMetadata { + fn from(ir: PalletStorageMetadataIR) -> Self { + PalletStorageMetadata { + prefix: ir.prefix, + entries: ir.entries.into_iter().map(Into::into).collect(), + } + } +} + +impl From for StorageEntryMetadata { + fn from(ir: StorageEntryMetadataIR) -> Self { + StorageEntryMetadata { + name: ir.name, + modifier: ir.modifier.into(), + ty: ir.ty.into(), + default: ir.default, + docs: ir.docs, + deprecation_info: ir.deprecation_info.into(), + } + } +} + +impl From for PalletAssociatedTypeMetadata { + fn from(ir: PalletAssociatedTypeMetadataIR) -> Self { + PalletAssociatedTypeMetadata { name: ir.name, ty: ir.ty, docs: ir.docs } + } +} + +impl From for PalletErrorMetadata { + fn from(ir: PalletErrorMetadataIR) -> Self { + PalletErrorMetadata { ty: ir.ty, deprecation_info: ir.deprecation_info.into() } + } +} + +impl From for PalletEventMetadata { + fn from(ir: PalletEventMetadataIR) -> Self { + PalletEventMetadata { ty: ir.ty, deprecation_info: ir.deprecation_info.into() } + } +} + +impl From for PalletCallMetadata { + fn from(ir: PalletCallMetadataIR) -> Self { + PalletCallMetadata { ty: ir.ty, deprecation_info: ir.deprecation_info.into() } + } +} + +impl From for PalletConstantMetadata { + fn from(ir: PalletConstantMetadataIR) -> Self { + PalletConstantMetadata { + name: ir.name, + ty: ir.ty, + value: ir.value, + docs: ir.docs, + deprecation_info: ir.deprecation_info.into(), + } + } +} + +impl From for TransactionExtensionMetadata { + fn from(ir: TransactionExtensionMetadataIR) -> Self { + TransactionExtensionMetadata { identifier: ir.identifier, ty: ir.ty, implicit: ir.implicit } + } +} + +impl From for ExtrinsicMetadata { + fn from(ir: ExtrinsicMetadataIR) -> Self { + // Assume version 0 for all extensions. + let indexes = (0..ir.extensions.len()).map(|index| index as u32).collect(); + let transaction_extensions_by_version = [(0, indexes)].iter().cloned().collect(); + + ExtrinsicMetadata { + versions: ir.versions, + address_ty: ir.address_ty, + signature_ty: ir.signature_ty, + transaction_extensions_by_version, + transaction_extensions: ir.extensions.into_iter().map(Into::into).collect(), + } + } +} + +impl From for OuterEnums { + fn from(ir: OuterEnumsIR) -> Self { + OuterEnums { + call_enum_ty: ir.call_enum_ty, + event_enum_ty: ir.event_enum_ty, + error_enum_ty: ir.error_enum_ty, + } + } +} + +impl From for DeprecationStatus { + fn from(ir: DeprecationStatusIR) -> Self { + match ir { + DeprecationStatusIR::NotDeprecated => DeprecationStatus::NotDeprecated, + DeprecationStatusIR::DeprecatedWithoutNote => DeprecationStatus::DeprecatedWithoutNote, + DeprecationStatusIR::Deprecated { since, note } => + DeprecationStatus::Deprecated { since, note }, + } + } +} + +impl From for DeprecationInfo { + fn from(ir: DeprecationInfoIR) -> Self { + match ir { + DeprecationInfoIR::NotDeprecated => DeprecationInfo::NotDeprecated, + DeprecationInfoIR::ItemDeprecated(status) => + DeprecationInfo::ItemDeprecated(status.into()), + DeprecationInfoIR::VariantsDeprecated(btree) => DeprecationInfo::VariantsDeprecated( + btree.into_iter().map(|(key, value)| (key.0, value.into())).collect(), + ), + } + } +} diff --git a/substrate/primitives/metadata-ir/src/v14.rs b/substrate/primitives/metadata-ir/src/v14.rs index 70e84532add9..f3cb5973f5bd 100644 --- a/substrate/primitives/metadata-ir/src/v14.rs +++ b/substrate/primitives/metadata-ir/src/v14.rs @@ -149,9 +149,12 @@ impl From for SignedExtensionMetadata { impl From for ExtrinsicMetadata { fn from(ir: ExtrinsicMetadataIR) -> Self { + let lowest_supported_version = + ir.versions.iter().min().expect("Metadata V14 supports one version; qed"); + ExtrinsicMetadata { ty: ir.ty, - version: ir.version, + version: *lowest_supported_version, signed_extensions: ir.extensions.into_iter().map(Into::into).collect(), } } diff --git a/substrate/primitives/metadata-ir/src/v15.rs b/substrate/primitives/metadata-ir/src/v15.rs index 4b3b6106d27f..ed315a31e6dc 100644 --- a/substrate/primitives/metadata-ir/src/v15.rs +++ b/substrate/primitives/metadata-ir/src/v15.rs @@ -100,7 +100,7 @@ impl From for SignedExtensionMetadata { impl From for ExtrinsicMetadata { fn from(ir: ExtrinsicMetadataIR) -> Self { ExtrinsicMetadata { - version: ir.version, + version: *ir.versions.iter().min().expect("Metadata V15 supports only one version"), address_ty: ir.address_ty, call_ty: ir.call_ty, signature_ty: ir.signature_ty, diff --git a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs index 91ba37451909..d8510a60a789 100644 --- a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -389,8 +389,7 @@ where impl> ExtrinsicMetadata for UncheckedExtrinsic { - // TODO: Expose both version 4 and version 5 in metadata v16. - const VERSION: u8 = LEGACY_EXTRINSIC_FORMAT_VERSION; + const VERSIONS: &'static [u8] = &[LEGACY_EXTRINSIC_FORMAT_VERSION, EXTRINSIC_FORMAT_VERSION]; type TransactionExtensions = Extension; } diff --git a/substrate/primitives/runtime/src/traits/mod.rs b/substrate/primitives/runtime/src/traits/mod.rs index 02bc7adc8ba5..cfcc3e5a354d 100644 --- a/substrate/primitives/runtime/src/traits/mod.rs +++ b/substrate/primitives/runtime/src/traits/mod.rs @@ -1410,10 +1410,10 @@ impl SignaturePayload for () { /// Implementor is an [`Extrinsic`] and provides metadata about this extrinsic. pub trait ExtrinsicMetadata { - /// The format version of the `Extrinsic`. + /// The format versions of the `Extrinsic`. /// - /// By format is meant the encoded representation of the `Extrinsic`. - const VERSION: u8; + /// By format we mean the encoded representation of the `Extrinsic`. + const VERSIONS: &'static [u8]; /// Transaction extensions attached to this `Extrinsic`. type TransactionExtensions; diff --git a/substrate/utils/frame/benchmarking-cli/src/overhead/remark_builder.rs b/substrate/utils/frame/benchmarking-cli/src/overhead/remark_builder.rs index a1d5f282d9f8..3a2d8776d1e1 100644 --- a/substrate/utils/frame/benchmarking-cli/src/overhead/remark_builder.rs +++ b/substrate/utils/frame/benchmarking-cli/src/overhead/remark_builder.rs @@ -54,13 +54,15 @@ impl> DynamicRemarkBuilder { log::debug!("Found metadata API version {}.", metadata_api_version); let opaque_metadata = if metadata_api_version > 1 { - let Ok(mut supported_metadata_versions) = api.metadata_versions(genesis) else { + let Ok(supported_metadata_versions) = api.metadata_versions(genesis) else { return Err("Unable to fetch metadata versions".to_string().into()); }; let latest = supported_metadata_versions - .pop() - .ok_or("No metadata version supported".to_string())?; + .into_iter() + .filter(|v| *v != u32::MAX) + .max() + .ok_or("No stable metadata versions supported".to_string())?; api.metadata_at_version(genesis, latest) .map_err(|e| format!("Unable to fetch metadata: {:?}", e))? diff --git a/substrate/utils/frame/benchmarking-cli/src/overhead/runtime_utilities.rs b/substrate/utils/frame/benchmarking-cli/src/overhead/runtime_utilities.rs index c498da38afb0..3081197dc033 100644 --- a/substrate/utils/frame/benchmarking-cli/src/overhead/runtime_utilities.rs +++ b/substrate/utils/frame/benchmarking-cli/src/overhead/runtime_utilities.rs @@ -35,14 +35,19 @@ pub fn fetch_latest_metadata_from_code_blob( let opaque_metadata: OpaqueMetadata = match version_result { Ok(supported_versions) => { - let latest_version = Vec::::decode(&mut supported_versions.as_slice()) - .map_err(|e| format!("Unable to decode version list: {e}"))? - .pop() - .ok_or("No metadata versions supported".to_string())?; + let supported_versions = Vec::::decode(&mut supported_versions.as_slice()) + .map_err(|e| format!("Unable to decode version list: {e}"))?; + + let latest_stable = supported_versions + .into_iter() + .filter(|v| *v != u32::MAX) + .max() + .ok_or("No stable metadata versions supported".to_string())?; let encoded = runtime_caller - .call("Metadata_metadata_at_version", latest_version) + .call("Metadata_metadata_at_version", latest_stable) .map_err(|_| "Unable to fetch metadata from blob".to_string())?; + Option::::decode(&mut encoded.as_slice())? .ok_or_else(|| "Metadata not found".to_string())? }, diff --git a/substrate/utils/wasm-builder/Cargo.toml b/substrate/utils/wasm-builder/Cargo.toml index 8f0e8a23e54a..fb15e8619a38 100644 --- a/substrate/utils/wasm-builder/Cargo.toml +++ b/substrate/utils/wasm-builder/Cargo.toml @@ -35,7 +35,7 @@ sc-executor = { optional = true, workspace = true, default-features = true } sp-core = { optional = true, workspace = true, default-features = true } sp-io = { optional = true, workspace = true, default-features = true } sp-version = { optional = true, workspace = true, default-features = true } -frame-metadata = { features = ["current"], optional = true, workspace = true, default-features = true } +frame-metadata = { features = ["current", "unstable"], optional = true, workspace = true, default-features = true } codec = { optional = true, workspace = true, default-features = true } array-bytes = { optional = true, workspace = true, default-features = true } sp-tracing = { optional = true, workspace = true, default-features = true } From afd065fa7267494246a9a8d767dfd030e2681fce Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Wed, 27 Nov 2024 20:12:39 +0200 Subject: [PATCH 148/166] rpc-v2: Implement `archive_unstable_storageDiff` (#5997) This PR implements the `archive_unstable_storageDiff`. The implementation follows the rpc-v2 spec from: - https://github.com/paritytech/json-rpc-interface-spec/pull/159. - builds on top of https://github.com/paritytech/json-rpc-interface-spec/pull/161 cc @paritytech/subxt-team --------- Signed-off-by: Alexandru Vasile Co-authored-by: James Wilson --- Cargo.lock | 7 +- prdoc/pr_5997.prdoc | 18 + substrate/client/rpc-spec-v2/Cargo.toml | 1 + .../client/rpc-spec-v2/src/archive/api.rs | 22 +- .../client/rpc-spec-v2/src/archive/archive.rs | 89 +- .../src/archive/archive_storage.rs | 829 +++++++++++++++++- .../client/rpc-spec-v2/src/archive/tests.rs | 277 +++++- .../client/rpc-spec-v2/src/common/events.rs | 208 ++++- .../client/rpc-spec-v2/src/common/storage.rs | 15 + substrate/client/service/src/builder.rs | 1 + 10 files changed, 1449 insertions(+), 18 deletions(-) create mode 100644 prdoc/pr_5997.prdoc diff --git a/Cargo.lock b/Cargo.lock index 2c938ec17bd0..12e642bc9d06 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20959,7 +20959,7 @@ checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" dependencies = [ "aho-corasick", "memchr", - "regex-automata 0.4.9", + "regex-automata 0.4.8", "regex-syntax 0.8.5", ] @@ -20980,9 +20980,9 @@ checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" [[package]] name = "regex-automata" -version = "0.4.9" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" +checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", @@ -23277,6 +23277,7 @@ dependencies = [ "futures", "futures-util", "hex", + "itertools 0.11.0", "jsonrpsee", "log", "parity-scale-codec", diff --git a/prdoc/pr_5997.prdoc b/prdoc/pr_5997.prdoc new file mode 100644 index 000000000000..6bac36a44586 --- /dev/null +++ b/prdoc/pr_5997.prdoc @@ -0,0 +1,18 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Implement archive_unstable_storageDiff method + +doc: + - audience: Node Dev + description: | + This PR implements the `archive_unstable_storageDiff` rpc-v2 method. + Developers can use this method to fetch the storage differences + between two blocks. This is useful for oracles and archive nodes. + For more details see: https://github.com/paritytech/json-rpc-interface-spec/blob/main/src/api/archive_unstable_storageDiff.md. + +crates: + - name: sc-rpc-spec-v2 + bump: major + - name: sc-service + bump: patch diff --git a/substrate/client/rpc-spec-v2/Cargo.toml b/substrate/client/rpc-spec-v2/Cargo.toml index daa805912fb9..b304bc905925 100644 --- a/substrate/client/rpc-spec-v2/Cargo.toml +++ b/substrate/client/rpc-spec-v2/Cargo.toml @@ -42,6 +42,7 @@ log = { workspace = true, default-features = true } futures-util = { workspace = true } rand = { workspace = true, default-features = true } schnellru = { workspace = true } +itertools = { workspace = true } [dev-dependencies] async-trait = { workspace = true } diff --git a/substrate/client/rpc-spec-v2/src/archive/api.rs b/substrate/client/rpc-spec-v2/src/archive/api.rs index b19738304000..dcfeaecb147b 100644 --- a/substrate/client/rpc-spec-v2/src/archive/api.rs +++ b/substrate/client/rpc-spec-v2/src/archive/api.rs @@ -19,7 +19,10 @@ //! API trait of the archive methods. use crate::{ - common::events::{ArchiveStorageResult, PaginatedStorageQuery}, + common::events::{ + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageResult, + PaginatedStorageQuery, + }, MethodResult, }; use jsonrpsee::{core::RpcResult, proc_macros::rpc}; @@ -104,4 +107,21 @@ pub trait ArchiveApi { items: Vec>, child_trie: Option, ) -> RpcResult; + + /// Returns the storage difference between two blocks. + /// + /// # Unstable + /// + /// This method is unstable and can change in minor or patch releases. + #[subscription( + name = "archive_unstable_storageDiff" => "archive_unstable_storageDiffEvent", + unsubscribe = "archive_unstable_storageDiff_stopStorageDiff", + item = ArchiveStorageDiffEvent, + )] + fn archive_unstable_storage_diff( + &self, + hash: Hash, + items: Vec>, + previous_hash: Option, + ); } diff --git a/substrate/client/rpc-spec-v2/src/archive/archive.rs b/substrate/client/rpc-spec-v2/src/archive/archive.rs index dd6c566a76ed..55054d91d85d 100644 --- a/substrate/client/rpc-spec-v2/src/archive/archive.rs +++ b/substrate/client/rpc-spec-v2/src/archive/archive.rs @@ -19,17 +19,29 @@ //! API implementation for `archive`. use crate::{ - archive::{error::Error as ArchiveError, ArchiveApiServer}, - common::events::{ArchiveStorageResult, PaginatedStorageQuery}, - hex_string, MethodResult, + archive::{ + archive_storage::{ArchiveStorage, ArchiveStorageDiff}, + error::Error as ArchiveError, + ArchiveApiServer, + }, + common::events::{ + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageResult, + PaginatedStorageQuery, + }, + hex_string, MethodResult, SubscriptionTaskExecutor, }; use codec::Encode; -use jsonrpsee::core::{async_trait, RpcResult}; +use futures::FutureExt; +use jsonrpsee::{ + core::{async_trait, RpcResult}, + PendingSubscriptionSink, +}; use sc_client_api::{ Backend, BlockBackend, BlockchainEvents, CallExecutor, ChildInfo, ExecutorProvider, StorageKey, StorageProvider, }; +use sc_rpc::utils::Subscription; use sp_api::{CallApiAt, CallContext}; use sp_blockchain::{ Backend as BlockChainBackend, Error as BlockChainError, HeaderBackend, HeaderMetadata, @@ -41,7 +53,9 @@ use sp_runtime::{ }; use std::{collections::HashSet, marker::PhantomData, sync::Arc}; -use super::archive_storage::ArchiveStorage; +use tokio::sync::mpsc; + +pub(crate) const LOG_TARGET: &str = "rpc-spec-v2::archive"; /// The configuration of [`Archive`]. pub struct ArchiveConfig { @@ -64,6 +78,12 @@ const MAX_DESCENDANT_RESPONSES: usize = 5; /// `MAX_DESCENDANT_RESPONSES`. const MAX_QUERIED_ITEMS: usize = 8; +/// The buffer capacity for each storage query. +/// +/// This is small because the underlying JSON-RPC server has +/// its down buffer capacity per connection as well. +const STORAGE_QUERY_BUF: usize = 16; + impl Default for ArchiveConfig { fn default() -> Self { Self { @@ -79,6 +99,8 @@ pub struct Archive, Block: BlockT, Client> { client: Arc, /// Backend of the chain. backend: Arc, + /// Executor to spawn subscriptions. + executor: SubscriptionTaskExecutor, /// The hexadecimal encoded hash of the genesis block. genesis_hash: String, /// The maximum number of items the `archive_storage` can return for a descendant query before @@ -96,12 +118,14 @@ impl, Block: BlockT, Client> Archive { client: Arc, backend: Arc, genesis_hash: GenesisHash, + executor: SubscriptionTaskExecutor, config: ArchiveConfig, ) -> Self { let genesis_hash = hex_string(&genesis_hash.as_ref()); Self { client, backend, + executor, genesis_hash, storage_max_descendant_responses: config.max_descendant_responses, storage_max_queried_items: config.max_queried_items, @@ -278,4 +302,59 @@ where Ok(storage_client.handle_query(hash, items, child_trie)) } + + fn archive_unstable_storage_diff( + &self, + pending: PendingSubscriptionSink, + hash: Block::Hash, + items: Vec>, + previous_hash: Option, + ) { + let storage_client = ArchiveStorageDiff::new(self.client.clone()); + let client = self.client.clone(); + + log::trace!(target: LOG_TARGET, "Storage diff subscription started"); + + let fut = async move { + let Ok(mut sink) = pending.accept().await.map(Subscription::from) else { return }; + + let previous_hash = if let Some(previous_hash) = previous_hash { + previous_hash + } else { + let Ok(Some(current_header)) = client.header(hash) else { + let message = format!("Block header is not present: {hash}"); + let _ = sink.send(&ArchiveStorageDiffEvent::err(message)).await; + return + }; + *current_header.parent_hash() + }; + + let (tx, mut rx) = tokio::sync::mpsc::channel(STORAGE_QUERY_BUF); + let storage_fut = + storage_client.handle_trie_queries(hash, items, previous_hash, tx.clone()); + + // We don't care about the return value of this join: + // - process_events might encounter an error (if the client disconnected) + // - storage_fut might encounter an error while processing a trie queries and + // the error is propagated via the sink. + let _ = futures::future::join(storage_fut, process_events(&mut rx, &mut sink)).await; + }; + + self.executor.spawn("substrate-rpc-subscription", Some("rpc"), fut.boxed()); + } +} + +/// Sends all the events to the sink. +async fn process_events(rx: &mut mpsc::Receiver, sink: &mut Subscription) { + while let Some(event) = rx.recv().await { + if event.is_done() { + log::debug!(target: LOG_TARGET, "Finished processing partial trie query"); + } else if event.is_err() { + log::debug!(target: LOG_TARGET, "Error encountered while processing partial trie query"); + } + + if sink.send(&event).await.is_err() { + return + } + } } diff --git a/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs b/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs index 26e7c299de41..5a3920882f00 100644 --- a/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs +++ b/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs @@ -18,15 +18,28 @@ //! Implementation of the `archive_storage` method. -use std::sync::Arc; +use std::{ + collections::{hash_map::Entry, HashMap}, + sync::Arc, +}; +use itertools::Itertools; use sc_client_api::{Backend, ChildInfo, StorageKey, StorageProvider}; use sp_runtime::traits::Block as BlockT; -use crate::common::{ - events::{ArchiveStorageResult, PaginatedStorageQuery, StorageQueryType}, - storage::{IterQueryType, QueryIter, Storage}, +use super::error::Error as ArchiveError; +use crate::{ + archive::archive::LOG_TARGET, + common::{ + events::{ + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageDiffOperationType, + ArchiveStorageDiffResult, ArchiveStorageDiffType, ArchiveStorageResult, + PaginatedStorageQuery, StorageQueryType, StorageResult, + }, + storage::{IterQueryType, QueryIter, Storage}, + }, }; +use tokio::sync::mpsc; /// Generates the events of the `archive_storage` method. pub struct ArchiveStorage { @@ -127,3 +140,811 @@ where ArchiveStorageResult::ok(storage_results, discarded_items) } } + +/// Parse hex-encoded string parameter as raw bytes. +/// +/// If the parsing fails, returns an error propagated to the RPC method. +pub fn parse_hex_param(param: String) -> Result, ArchiveError> { + // Methods can accept empty parameters. + if param.is_empty() { + return Ok(Default::default()) + } + + array_bytes::hex2bytes(¶m).map_err(|_| ArchiveError::InvalidParam(param)) +} + +#[derive(Debug, PartialEq, Clone)] +pub struct DiffDetails { + key: StorageKey, + return_type: ArchiveStorageDiffType, + child_trie_key: Option, + child_trie_key_string: Option, +} + +/// The type of storage query. +#[derive(Debug, PartialEq, Clone, Copy)] +enum FetchStorageType { + /// Only fetch the value. + Value, + /// Only fetch the hash. + Hash, + /// Fetch both the value and the hash. + Both, +} + +/// The return value of the `fetch_storage` method. +#[derive(Debug, PartialEq, Clone)] +enum FetchedStorage { + /// Storage value under a key. + Value(StorageResult), + /// Storage hash under a key. + Hash(StorageResult), + /// Both storage value and hash under a key. + Both { value: StorageResult, hash: StorageResult }, +} + +pub struct ArchiveStorageDiff { + client: Storage, +} + +impl ArchiveStorageDiff { + pub fn new(client: Arc) -> Self { + Self { client: Storage::new(client) } + } +} + +impl ArchiveStorageDiff +where + Block: BlockT + 'static, + BE: Backend + 'static, + Client: StorageProvider + Send + Sync + 'static, +{ + /// Fetch the storage from the given key. + fn fetch_storage( + &self, + hash: Block::Hash, + key: StorageKey, + maybe_child_trie: Option, + ty: FetchStorageType, + ) -> Result, String> { + match ty { + FetchStorageType::Value => { + let result = self.client.query_value(hash, &key, maybe_child_trie.as_ref())?; + + Ok(result.map(FetchedStorage::Value)) + }, + + FetchStorageType::Hash => { + let result = self.client.query_hash(hash, &key, maybe_child_trie.as_ref())?; + + Ok(result.map(FetchedStorage::Hash)) + }, + + FetchStorageType::Both => { + let Some(value) = self.client.query_value(hash, &key, maybe_child_trie.as_ref())? + else { + return Ok(None); + }; + + let Some(hash) = self.client.query_hash(hash, &key, maybe_child_trie.as_ref())? + else { + return Ok(None); + }; + + Ok(Some(FetchedStorage::Both { value, hash })) + }, + } + } + + /// Check if the key belongs to the provided query items. + /// + /// A key belongs to the query items when: + /// - the provided key is a prefix of the key in the query items. + /// - the query items are empty. + /// + /// Returns an optional `FetchStorageType` based on the query items. + /// If the key does not belong to the query items, returns `None`. + fn belongs_to_query(key: &StorageKey, items: &[DiffDetails]) -> Option { + // User has requested all keys, by default this fallbacks to fetching the value. + if items.is_empty() { + return Some(FetchStorageType::Value) + } + + let mut value = false; + let mut hash = false; + + for item in items { + if key.as_ref().starts_with(&item.key.as_ref()) { + match item.return_type { + ArchiveStorageDiffType::Value => value = true, + ArchiveStorageDiffType::Hash => hash = true, + } + } + } + + match (value, hash) { + (true, true) => Some(FetchStorageType::Both), + (true, false) => Some(FetchStorageType::Value), + (false, true) => Some(FetchStorageType::Hash), + (false, false) => None, + } + } + + /// Send the provided result to the `tx` sender. + /// + /// Returns `false` if the sender has been closed. + fn send_result( + tx: &mpsc::Sender, + result: FetchedStorage, + operation_type: ArchiveStorageDiffOperationType, + child_trie_key: Option, + ) -> bool { + let items = match result { + FetchedStorage::Value(storage_result) | FetchedStorage::Hash(storage_result) => + vec![storage_result], + FetchedStorage::Both { value, hash } => vec![value, hash], + }; + + for item in items { + let res = ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: item.key, + result: item.result, + operation_type, + child_trie_key: child_trie_key.clone(), + }); + if tx.blocking_send(res).is_err() { + return false + } + } + + true + } + + fn handle_trie_queries_inner( + &self, + hash: Block::Hash, + previous_hash: Block::Hash, + items: Vec, + tx: &mpsc::Sender, + ) -> Result<(), String> { + // Parse the child trie key as `ChildInfo` and `String`. + let maybe_child_trie = items.first().and_then(|item| item.child_trie_key.clone()); + let maybe_child_trie_str = + items.first().and_then(|item| item.child_trie_key_string.clone()); + + // Iterator over the current block and previous block + // at the same time to compare the keys. This approach effectively + // leverages backpressure to avoid memory consumption. + let keys_iter = self.client.raw_keys_iter(hash, maybe_child_trie.clone())?; + let previous_keys_iter = + self.client.raw_keys_iter(previous_hash, maybe_child_trie.clone())?; + + let mut diff_iter = lexicographic_diff(keys_iter, previous_keys_iter); + + while let Some(item) = diff_iter.next() { + let (operation_type, key) = match item { + Diff::Added(key) => (ArchiveStorageDiffOperationType::Added, key), + Diff::Deleted(key) => (ArchiveStorageDiffOperationType::Deleted, key), + Diff::Equal(key) => (ArchiveStorageDiffOperationType::Modified, key), + }; + + let Some(fetch_type) = Self::belongs_to_query(&key, &items) else { + // The key does not belong the the query items. + continue; + }; + + let maybe_result = match operation_type { + ArchiveStorageDiffOperationType::Added => + self.fetch_storage(hash, key.clone(), maybe_child_trie.clone(), fetch_type)?, + ArchiveStorageDiffOperationType::Deleted => self.fetch_storage( + previous_hash, + key.clone(), + maybe_child_trie.clone(), + fetch_type, + )?, + ArchiveStorageDiffOperationType::Modified => { + let Some(storage_result) = self.fetch_storage( + hash, + key.clone(), + maybe_child_trie.clone(), + fetch_type, + )? + else { + continue + }; + + let Some(previous_storage_result) = self.fetch_storage( + previous_hash, + key.clone(), + maybe_child_trie.clone(), + fetch_type, + )? + else { + continue + }; + + // For modified records we need to check the actual storage values. + if storage_result == previous_storage_result { + continue + } + + Some(storage_result) + }, + }; + + if let Some(storage_result) = maybe_result { + if !Self::send_result( + &tx, + storage_result, + operation_type, + maybe_child_trie_str.clone(), + ) { + return Ok(()) + } + } + } + + Ok(()) + } + + /// This method will iterate over the keys of the main trie or a child trie and fetch the + /// given keys. The fetched keys will be sent to the provided `tx` sender to leverage + /// the backpressure mechanism. + pub async fn handle_trie_queries( + &self, + hash: Block::Hash, + items: Vec>, + previous_hash: Block::Hash, + tx: mpsc::Sender, + ) -> Result<(), tokio::task::JoinError> { + let this = ArchiveStorageDiff { client: self.client.clone() }; + + tokio::task::spawn_blocking(move || { + // Deduplicate the items. + let mut trie_items = match deduplicate_storage_diff_items(items) { + Ok(items) => items, + Err(error) => { + let _ = tx.blocking_send(ArchiveStorageDiffEvent::err(error.to_string())); + return + }, + }; + // Default to using the main storage trie if no items are provided. + if trie_items.is_empty() { + trie_items.push(Vec::new()); + } + log::trace!(target: LOG_TARGET, "Storage diff deduplicated items: {:?}", trie_items); + + for items in trie_items { + log::trace!( + target: LOG_TARGET, + "handle_trie_queries: hash={:?}, previous_hash={:?}, items={:?}", + hash, + previous_hash, + items + ); + + let result = this.handle_trie_queries_inner(hash, previous_hash, items, &tx); + + if let Err(error) = result { + log::trace!( + target: LOG_TARGET, + "handle_trie_queries: sending error={:?}", + error, + ); + + let _ = tx.blocking_send(ArchiveStorageDiffEvent::err(error)); + + return + } else { + log::trace!( + target: LOG_TARGET, + "handle_trie_queries: sending storage diff done", + ); + } + } + + let _ = tx.blocking_send(ArchiveStorageDiffEvent::StorageDiffDone); + }) + .await?; + + Ok(()) + } +} + +/// The result of the `lexicographic_diff` method. +#[derive(Debug, PartialEq)] +enum Diff { + Added(T), + Deleted(T), + Equal(T), +} + +/// Compare two iterators lexicographically and return the differences. +fn lexicographic_diff( + mut left: LeftIter, + mut right: RightIter, +) -> impl Iterator> +where + T: Ord, + LeftIter: Iterator, + RightIter: Iterator, +{ + let mut a = left.next(); + let mut b = right.next(); + + core::iter::from_fn(move || match (a.take(), b.take()) { + (Some(a_value), Some(b_value)) => + if a_value < b_value { + b = Some(b_value); + a = left.next(); + + Some(Diff::Added(a_value)) + } else if a_value > b_value { + a = Some(a_value); + b = right.next(); + + Some(Diff::Deleted(b_value)) + } else { + a = left.next(); + b = right.next(); + + Some(Diff::Equal(a_value)) + }, + (Some(a_value), None) => { + a = left.next(); + Some(Diff::Added(a_value)) + }, + (None, Some(b_value)) => { + b = right.next(); + Some(Diff::Deleted(b_value)) + }, + (None, None) => None, + }) +} + +/// Deduplicate the provided items and return a list of `DiffDetails`. +/// +/// Each list corresponds to a single child trie or the main trie. +fn deduplicate_storage_diff_items( + items: Vec>, +) -> Result>, ArchiveError> { + let mut deduplicated: HashMap, Vec> = HashMap::new(); + + for diff_item in items { + // Ensure the provided hex keys are valid before deduplication. + let key = StorageKey(parse_hex_param(diff_item.key)?); + let child_trie_key_string = diff_item.child_trie_key.clone(); + let child_trie_key = diff_item + .child_trie_key + .map(|child_trie_key| parse_hex_param(child_trie_key)) + .transpose()? + .map(ChildInfo::new_default_from_vec); + + let diff_item = DiffDetails { + key, + return_type: diff_item.return_type, + child_trie_key: child_trie_key.clone(), + child_trie_key_string, + }; + + match deduplicated.entry(child_trie_key.clone()) { + Entry::Occupied(mut entry) => { + let mut should_insert = true; + + for existing in entry.get() { + // This points to a different return type. + if existing.return_type != diff_item.return_type { + continue + } + // Keys and return types are identical. + if existing.key == diff_item.key { + should_insert = false; + break + } + + // The following two conditions ensure that we keep the shortest key. + + // The current key is a longer prefix of the existing key. + if diff_item.key.as_ref().starts_with(&existing.key.as_ref()) { + should_insert = false; + break + } + + // The existing key is a longer prefix of the current key. + // We need to keep the current key and remove the existing one. + if existing.key.as_ref().starts_with(&diff_item.key.as_ref()) { + let to_remove = existing.clone(); + entry.get_mut().retain(|item| item != &to_remove); + break; + } + } + + if should_insert { + entry.get_mut().push(diff_item); + } + }, + Entry::Vacant(entry) => { + entry.insert(vec![diff_item]); + }, + } + } + + Ok(deduplicated + .into_iter() + .sorted_by_key(|(child_trie_key, _)| child_trie_key.clone()) + .map(|(_, values)| values) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dedup_empty() { + let items = vec![]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert!(result.is_empty()); + } + + #[test] + fn dedup_single() { + let items = vec![ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 1); + + let expected = DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }; + assert_eq!(result[0][0], expected); + } + + #[test] + fn dedup_with_different_keys() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x02".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 2); + + let expected = vec![ + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }, + DiffDetails { + key: StorageKey(vec![2]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }, + ]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_with_same_keys() { + // Identical keys. + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 1); + + let expected = vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_with_same_prefix() { + // Identical keys. + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x01ff".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 1); + + let expected = vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_with_different_return_types() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: None, + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 2); + + let expected = vec![ + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }, + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: None, + child_trie_key_string: None, + }, + ]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_with_different_child_tries() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x01".into()), + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x02".into()), + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 2); + assert_eq!(result[0].len(), 1); + assert_eq!(result[1].len(), 1); + + let expected = vec![ + vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![1])), + child_trie_key_string: Some("0x01".into()), + }], + vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![2])), + child_trie_key_string: Some("0x02".into()), + }], + ]; + assert_eq!(result, expected); + } + + #[test] + fn dedup_with_same_child_tries() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x01".into()), + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x01".into()), + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 1); + + let expected = vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![1])), + child_trie_key_string: Some("0x01".into()), + }]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_with_shorter_key_reverse_order() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x01ff".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ]; + let result = deduplicate_storage_diff_items(items).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].len(), 1); + + let expected = vec![DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }]; + assert_eq!(result[0], expected); + } + + #[test] + fn dedup_multiple_child_tries() { + let items = vec![ + ArchiveStorageDiffItem { + key: "0x02".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x01".into()), + }, + ArchiveStorageDiffItem { + key: "0x02".into(), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: Some("0x01".into()), + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x02".into()), + }, + ArchiveStorageDiffItem { + key: "0x01".into(), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: Some("0x02".into()), + }, + ArchiveStorageDiffItem { + key: "0x01ff".into(), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x02".into()), + }, + ]; + + let result = deduplicate_storage_diff_items(items).unwrap(); + + let expected = vec![ + vec![DiffDetails { + key: StorageKey(vec![2]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + child_trie_key_string: None, + }], + vec![ + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![1])), + child_trie_key_string: Some("0x01".into()), + }, + DiffDetails { + key: StorageKey(vec![2]), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![1])), + child_trie_key_string: Some("0x01".into()), + }, + ], + vec![ + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![2])), + child_trie_key_string: Some("0x02".into()), + }, + DiffDetails { + key: StorageKey(vec![1]), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: Some(ChildInfo::new_default_from_vec(vec![2])), + child_trie_key_string: Some("0x02".into()), + }, + ], + ]; + + assert_eq!(result, expected); + } + + #[test] + fn test_lexicographic_diff() { + let left = vec![1, 2, 3, 4, 5]; + let right = vec![2, 3, 4, 5, 6]; + + let diff = lexicographic_diff(left.into_iter(), right.into_iter()).collect::>(); + let expected = vec![ + Diff::Added(1), + Diff::Equal(2), + Diff::Equal(3), + Diff::Equal(4), + Diff::Equal(5), + Diff::Deleted(6), + ]; + assert_eq!(diff, expected); + } + + #[test] + fn test_lexicographic_diff_one_side_empty() { + let left = vec![]; + let right = vec![1, 2, 3, 4, 5, 6]; + + let diff = lexicographic_diff(left.into_iter(), right.into_iter()).collect::>(); + let expected = vec![ + Diff::Deleted(1), + Diff::Deleted(2), + Diff::Deleted(3), + Diff::Deleted(4), + Diff::Deleted(5), + Diff::Deleted(6), + ]; + assert_eq!(diff, expected); + + let left = vec![1, 2, 3, 4, 5, 6]; + let right = vec![]; + + let diff = lexicographic_diff(left.into_iter(), right.into_iter()).collect::>(); + let expected = vec![ + Diff::Added(1), + Diff::Added(2), + Diff::Added(3), + Diff::Added(4), + Diff::Added(5), + Diff::Added(6), + ]; + assert_eq!(diff, expected); + } +} diff --git a/substrate/client/rpc-spec-v2/src/archive/tests.rs b/substrate/client/rpc-spec-v2/src/archive/tests.rs index 078016f5b3e2..994c5d28bd61 100644 --- a/substrate/client/rpc-spec-v2/src/archive/tests.rs +++ b/substrate/client/rpc-spec-v2/src/archive/tests.rs @@ -18,8 +18,9 @@ use crate::{ common::events::{ - ArchiveStorageMethodOk, ArchiveStorageResult, PaginatedStorageQuery, StorageQueryType, - StorageResultType, + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageDiffOperationType, + ArchiveStorageDiffResult, ArchiveStorageDiffType, ArchiveStorageMethodOk, + ArchiveStorageResult, PaginatedStorageQuery, StorageQueryType, StorageResultType, }, hex_string, MethodResult, }; @@ -32,10 +33,13 @@ use super::{ use assert_matches::assert_matches; use codec::{Decode, Encode}; use jsonrpsee::{ - core::EmptyServerParams as EmptyParams, rpc_params, MethodsError as Error, RpcModule, + core::{server::Subscription as RpcSubscription, EmptyServerParams as EmptyParams}, + rpc_params, MethodsError as Error, RpcModule, }; + use sc_block_builder::BlockBuilderBuilder; use sc_client_api::ChildInfo; +use sc_rpc::testing::TokioTestExecutor; use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; use sp_core::{Blake2Hasher, Hasher}; @@ -78,6 +82,7 @@ fn setup_api( client.clone(), backend, CHAIN_GENESIS, + Arc::new(TokioTestExecutor::default()), ArchiveConfig { max_descendant_responses, max_queried_items }, ) .into_rpc(); @@ -85,6 +90,15 @@ fn setup_api( (client, api) } +async fn get_next_event(sub: &mut RpcSubscription) -> T { + let (event, _sub_id) = tokio::time::timeout(std::time::Duration::from_secs(60), sub.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + event +} + #[tokio::test] async fn archive_genesis() { let (_client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); @@ -838,3 +852,260 @@ async fn archive_storage_discarded_items() { _ => panic!("Unexpected result"), }; } + +#[tokio::test] +async fn archive_storage_diff_main_trie() { + let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(client.chain_info().genesis_hash) + .with_parent_block_number(0) + .build() + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"B".to_vec())).unwrap(); + builder.push_storage_change(b":AA".to_vec(), Some(b"BB".to_vec())).unwrap(); + let prev_block = builder.build().unwrap().block; + let prev_hash = format!("{:?}", prev_block.header.hash()); + client.import(BlockOrigin::Own, prev_block.clone()).await.unwrap(); + + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(prev_block.hash()) + .with_parent_block_number(1) + .build() + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"11".to_vec())).unwrap(); + builder.push_storage_change(b":AA".to_vec(), Some(b"22".to_vec())).unwrap(); + builder.push_storage_change(b":AAA".to_vec(), Some(b"222".to_vec())).unwrap(); + let block = builder.build().unwrap().block; + let block_hash = format!("{:?}", block.header.hash()); + client.import(BlockOrigin::Own, block.clone()).await.unwrap(); + + // Search for items in the main trie: + // - values of keys under ":A" + // - hashes of keys under ":AA" + let items = vec![ + ArchiveStorageDiffItem:: { + key: hex_string(b":A"), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }, + ArchiveStorageDiffItem:: { + key: hex_string(b":AA"), + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: None, + }, + ]; + let mut sub = api + .subscribe_unbounded( + "archive_unstable_storageDiff", + rpc_params![&block_hash, items.clone(), &prev_hash], + ) + .await + .unwrap(); + + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":A"), + result: StorageResultType::Value(hex_string(b"11")), + operation_type: ArchiveStorageDiffOperationType::Modified, + child_trie_key: None, + }), + event, + ); + + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":AA"), + result: StorageResultType::Value(hex_string(b"22")), + operation_type: ArchiveStorageDiffOperationType::Modified, + child_trie_key: None, + }), + event, + ); + + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":AA"), + result: StorageResultType::Hash(format!("{:?}", Blake2Hasher::hash(b"22"))), + operation_type: ArchiveStorageDiffOperationType::Modified, + child_trie_key: None, + }), + event, + ); + + // Added key. + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":AAA"), + result: StorageResultType::Value(hex_string(b"222")), + operation_type: ArchiveStorageDiffOperationType::Added, + child_trie_key: None, + }), + event, + ); + + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":AAA"), + result: StorageResultType::Hash(format!("{:?}", Blake2Hasher::hash(b"222"))), + operation_type: ArchiveStorageDiffOperationType::Added, + child_trie_key: None, + }), + event, + ); + + let event = get_next_event::(&mut sub).await; + assert_eq!(ArchiveStorageDiffEvent::StorageDiffDone, event); +} + +#[tokio::test] +async fn archive_storage_diff_no_changes() { + let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + + // Build 2 identical blocks. + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(client.chain_info().genesis_hash) + .with_parent_block_number(0) + .build() + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"B".to_vec())).unwrap(); + builder.push_storage_change(b":AA".to_vec(), Some(b"BB".to_vec())).unwrap(); + builder.push_storage_change(b":B".to_vec(), Some(b"CC".to_vec())).unwrap(); + builder.push_storage_change(b":BA".to_vec(), Some(b"CC".to_vec())).unwrap(); + let prev_block = builder.build().unwrap().block; + let prev_hash = format!("{:?}", prev_block.header.hash()); + client.import(BlockOrigin::Own, prev_block.clone()).await.unwrap(); + + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(prev_block.hash()) + .with_parent_block_number(1) + .build() + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"B".to_vec())).unwrap(); + builder.push_storage_change(b":AA".to_vec(), Some(b"BB".to_vec())).unwrap(); + let block = builder.build().unwrap().block; + let block_hash = format!("{:?}", block.header.hash()); + client.import(BlockOrigin::Own, block.clone()).await.unwrap(); + + // Search for items in the main trie with keys prefixed with ":A". + let items = vec![ArchiveStorageDiffItem:: { + key: hex_string(b":A"), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }]; + let mut sub = api + .subscribe_unbounded( + "archive_unstable_storageDiff", + rpc_params![&block_hash, items.clone(), &prev_hash], + ) + .await + .unwrap(); + + let event = get_next_event::(&mut sub).await; + assert_eq!(ArchiveStorageDiffEvent::StorageDiffDone, event); +} + +#[tokio::test] +async fn archive_storage_diff_deleted_changes() { + let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + + // Blocks are imported as forks. + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(client.chain_info().genesis_hash) + .with_parent_block_number(0) + .build() + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"B".to_vec())).unwrap(); + builder.push_storage_change(b":AA".to_vec(), Some(b"BB".to_vec())).unwrap(); + builder.push_storage_change(b":B".to_vec(), Some(b"CC".to_vec())).unwrap(); + builder.push_storage_change(b":BA".to_vec(), Some(b"CC".to_vec())).unwrap(); + let prev_block = builder.build().unwrap().block; + let prev_hash = format!("{:?}", prev_block.header.hash()); + client.import(BlockOrigin::Own, prev_block.clone()).await.unwrap(); + + let mut builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(client.chain_info().genesis_hash) + .with_parent_block_number(0) + .build() + .unwrap(); + builder + .push_transfer(Transfer { + from: AccountKeyring::Alice.into(), + to: AccountKeyring::Ferdie.into(), + amount: 41, + nonce: 0, + }) + .unwrap(); + builder.push_storage_change(b":A".to_vec(), Some(b"B".to_vec())).unwrap(); + let block = builder.build().unwrap().block; + let block_hash = format!("{:?}", block.header.hash()); + client.import(BlockOrigin::Own, block.clone()).await.unwrap(); + + // Search for items in the main trie with keys prefixed with ":A". + let items = vec![ArchiveStorageDiffItem:: { + key: hex_string(b":A"), + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }]; + + let mut sub = api + .subscribe_unbounded( + "archive_unstable_storageDiff", + rpc_params![&block_hash, items.clone(), &prev_hash], + ) + .await + .unwrap(); + + let event = get_next_event::(&mut sub).await; + assert_eq!( + ArchiveStorageDiffEvent::StorageDiff(ArchiveStorageDiffResult { + key: hex_string(b":AA"), + result: StorageResultType::Value(hex_string(b"BB")), + operation_type: ArchiveStorageDiffOperationType::Deleted, + child_trie_key: None, + }), + event, + ); + + let event = get_next_event::(&mut sub).await; + assert_eq!(ArchiveStorageDiffEvent::StorageDiffDone, event); +} + +#[tokio::test] +async fn archive_storage_diff_invalid_params() { + let invalid_hash = hex_string(&INVALID_HASH); + let (_, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + + // Invalid shape for parameters. + let items: Vec> = Vec::new(); + let err = api + .subscribe_unbounded( + "archive_unstable_storageDiff", + rpc_params!["123", items.clone(), &invalid_hash], + ) + .await + .unwrap_err(); + assert_matches!(err, + Error::JsonRpc(ref err) if err.code() == crate::chain_head::error::json_rpc_spec::INVALID_PARAM_ERROR && err.message() == "Invalid params" + ); + + // The shape is right, but the block hash is invalid. + let items: Vec> = Vec::new(); + let mut sub = api + .subscribe_unbounded( + "archive_unstable_storageDiff", + rpc_params![&invalid_hash, items.clone(), &invalid_hash], + ) + .await + .unwrap(); + + let event = get_next_event::(&mut sub).await; + assert_matches!(event, + ArchiveStorageDiffEvent::StorageDiffError(ref err) if err.error.contains("Header was not found") + ); +} diff --git a/substrate/client/rpc-spec-v2/src/common/events.rs b/substrate/client/rpc-spec-v2/src/common/events.rs index b1627d74c844..198a60bf4cac 100644 --- a/substrate/client/rpc-spec-v2/src/common/events.rs +++ b/substrate/client/rpc-spec-v2/src/common/events.rs @@ -81,7 +81,7 @@ pub struct StorageResult { } /// The type of the storage query. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum StorageResultType { /// Fetch the value of the provided key. @@ -136,17 +136,221 @@ pub struct ArchiveStorageMethodOk { } /// The error of a storage call. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ArchiveStorageMethodErr { /// Reported error. pub error: String, } +/// The type of the archive storage difference query. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ArchiveStorageDiffType { + /// The result is provided as value of the key. + Value, + /// The result the hash of the value of the key. + Hash, +} + +/// The storage item to query. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchiveStorageDiffItem { + /// The provided key. + pub key: Key, + /// The type of the storage query. + pub return_type: ArchiveStorageDiffType, + /// The child trie key if provided. + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub child_trie_key: Option, +} + +/// The result of a storage difference call. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchiveStorageDiffMethodResult { + /// Reported results. + pub result: Vec, +} + +/// The result of a storage difference call operation type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ArchiveStorageDiffOperationType { + /// The key is added. + Added, + /// The key is modified. + Modified, + /// The key is removed. + Deleted, +} + +/// The result of an individual storage difference key. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ArchiveStorageDiffResult { + /// The hex-encoded key of the result. + pub key: String, + /// The result of the query. + #[serde(flatten)] + pub result: StorageResultType, + /// The operation type. + #[serde(rename = "type")] + pub operation_type: ArchiveStorageDiffOperationType, + /// The child trie key if provided. + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub child_trie_key: Option, +} + +/// The event generated by the `archive_storageDiff` method. +/// +/// The `archive_storageDiff` can generate the following events: +/// - `storageDiff` event - generated when a `ArchiveStorageDiffResult` is produced. +/// - `storageDiffError` event - generated when an error is produced. +/// - `storageDiffDone` event - generated when the `archive_storageDiff` method completed. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "event")] +pub enum ArchiveStorageDiffEvent { + /// The `storageDiff` event. + StorageDiff(ArchiveStorageDiffResult), + /// The `storageDiffError` event. + StorageDiffError(ArchiveStorageMethodErr), + /// The `storageDiffDone` event. + StorageDiffDone, +} + +impl ArchiveStorageDiffEvent { + /// Create a new `ArchiveStorageDiffEvent::StorageDiffError` event. + pub fn err(error: String) -> Self { + Self::StorageDiffError(ArchiveStorageMethodErr { error }) + } + + /// Checks if the event is a `StorageDiffDone` event. + pub fn is_done(&self) -> bool { + matches!(self, Self::StorageDiffDone) + } + + /// Checks if the event is a `StorageDiffError` event. + pub fn is_err(&self) -> bool { + matches!(self, Self::StorageDiffError(_)) + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn archive_diff_input() { + // Item with Value. + let item = ArchiveStorageDiffItem { + key: "0x1", + return_type: ArchiveStorageDiffType::Value, + child_trie_key: None, + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","returnType":"value"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffItem<&str> = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + + // Item with Hash. + let item = ArchiveStorageDiffItem { + key: "0x1", + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: None, + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","returnType":"hash"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffItem<&str> = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + + // Item with Value and child trie key. + let item = ArchiveStorageDiffItem { + key: "0x1", + return_type: ArchiveStorageDiffType::Value, + child_trie_key: Some("0x2"), + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","returnType":"value","childTrieKey":"0x2"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffItem<&str> = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + + // Item with Hash and child trie key. + let item = ArchiveStorageDiffItem { + key: "0x1", + return_type: ArchiveStorageDiffType::Hash, + child_trie_key: Some("0x2"), + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","returnType":"hash","childTrieKey":"0x2"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffItem<&str> = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + } + + #[test] + fn archive_diff_output() { + // Item with Value. + let item = ArchiveStorageDiffResult { + key: "0x1".into(), + result: StorageResultType::Value("res".into()), + operation_type: ArchiveStorageDiffOperationType::Added, + child_trie_key: None, + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","value":"res","type":"added"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffResult = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + + // Item with Hash. + let item = ArchiveStorageDiffResult { + key: "0x1".into(), + result: StorageResultType::Hash("res".into()), + operation_type: ArchiveStorageDiffOperationType::Modified, + child_trie_key: None, + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","hash":"res","type":"modified"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffResult = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + + // Item with Hash, child trie key and removed. + let item = ArchiveStorageDiffResult { + key: "0x1".into(), + result: StorageResultType::Hash("res".into()), + operation_type: ArchiveStorageDiffOperationType::Deleted, + child_trie_key: Some("0x2".into()), + }; + // Encode + let ser = serde_json::to_string(&item).unwrap(); + let exp = r#"{"key":"0x1","hash":"res","type":"deleted","childTrieKey":"0x2"}"#; + assert_eq!(ser, exp); + // Decode + let dec: ArchiveStorageDiffResult = serde_json::from_str(exp).unwrap(); + assert_eq!(dec, item); + } + #[test] fn storage_result() { // Item with Value. diff --git a/substrate/client/rpc-spec-v2/src/common/storage.rs b/substrate/client/rpc-spec-v2/src/common/storage.rs index 2e24a8da8ca8..673e20b2bc78 100644 --- a/substrate/client/rpc-spec-v2/src/common/storage.rs +++ b/substrate/client/rpc-spec-v2/src/common/storage.rs @@ -248,4 +248,19 @@ where }); Ok((ret, maybe_next_query)) } + + /// Raw iterator over the keys. + pub fn raw_keys_iter( + &self, + hash: Block::Hash, + child_key: Option, + ) -> Result, String> { + let keys_iter = if let Some(child_key) = child_key { + self.client.child_storage_keys(hash, child_key, None, None) + } else { + self.client.storage_keys(hash, None, None) + }; + + keys_iter.map_err(|err| err.to_string()) + } } diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index ac9371a8941b..027a444012af 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -755,6 +755,7 @@ where client.clone(), backend.clone(), genesis_hash, + task_executor.clone(), // Defaults to sensible limits for the `Archive`. sc_rpc_spec_v2::archive::ArchiveConfig::default(), ) From 2ef2723126584dfcd6d2a9272282ee78375dbcd3 Mon Sep 17 00:00:00 2001 From: Michal Kucharczyk <1728078+michalkucharczyk@users.noreply.github.com> Date: Wed, 27 Nov 2024 21:40:23 +0100 Subject: [PATCH 149/166] chain-spec-guide-runtime: path to wasm blob fixed (#6673) In `chain-spec-guide-runtime` crate's tests, there was assumption that release version of wasm blob exists. This PR uses `chain_spec_guide_runtime::runtime::WASM_BINARY_PATH` const to use correct path to runtime blob. --------- Co-authored-by: GitHub Action --- .../tests/chain_spec_builder_tests.rs | 14 ++++++++------ prdoc/pr_6673.prdoc | 7 +++++++ 2 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 prdoc/pr_6673.prdoc diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/tests/chain_spec_builder_tests.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/tests/chain_spec_builder_tests.rs index c2fe5a6727e6..df400b68f79d 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/tests/chain_spec_builder_tests.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/tests/chain_spec_builder_tests.rs @@ -1,8 +1,10 @@ use serde_json::{json, Value}; use std::{process::Command, str}; -const WASM_FILE_PATH: &str = - "../../../../../target/release/wbuild/chain-spec-guide-runtime/chain_spec_guide_runtime.wasm"; +fn wasm_file_path() -> &'static str { + chain_spec_guide_runtime::runtime::WASM_BINARY_PATH + .expect("chain_spec_guide_runtime wasm should exist. qed") +} const CHAIN_SPEC_BUILDER_PATH: &str = "../../../../../target/release/chain-spec-builder"; @@ -26,7 +28,7 @@ fn list_presets() { let output = Command::new(get_chain_spec_builder_path()) .arg("list-presets") .arg("-r") - .arg(WASM_FILE_PATH) + .arg(wasm_file_path()) .output() .expect("Failed to execute command"); @@ -50,7 +52,7 @@ fn get_preset() { let output = Command::new(get_chain_spec_builder_path()) .arg("display-preset") .arg("-r") - .arg(WASM_FILE_PATH) + .arg(wasm_file_path()) .arg("-p") .arg("preset_2") .output() @@ -83,7 +85,7 @@ fn generate_chain_spec() { .arg("/dev/stdout") .arg("create") .arg("-r") - .arg(WASM_FILE_PATH) + .arg(wasm_file_path()) .arg("named-preset") .arg("preset_2") .output() @@ -140,7 +142,7 @@ fn generate_para_chain_spec() { .arg("-p") .arg("1000") .arg("-r") - .arg(WASM_FILE_PATH) + .arg(wasm_file_path()) .arg("named-preset") .arg("preset_2") .output() diff --git a/prdoc/pr_6673.prdoc b/prdoc/pr_6673.prdoc new file mode 100644 index 000000000000..d2ca3c61ff39 --- /dev/null +++ b/prdoc/pr_6673.prdoc @@ -0,0 +1,7 @@ +title: 'chain-spec-guide-runtime: path to wasm blob fixed' +doc: +- audience: Runtime Dev + description: In `chain-spec-guide-runtime` crate's tests, there was assumption that + release version of wasm blob exists. This PR uses `chain_spec_guide_runtime::runtime::WASM_BINARY_PATH` + const to use correct path to runtime blob. +crates: [] From 51c3e95a05c528b3869ad267aeb5c356551e38db Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Thu, 28 Nov 2024 11:16:06 +0200 Subject: [PATCH 150/166] chore: Update litep2p to v0.8.2 (#6677) This includes a critical fix for debug release versions of litep2p (which are running in Kusama as validators). While at it, have stopped the oncall pain of alerts around `incoming_connections_total`. We can rethink the metric expose of litep2p in Q1. ## [0.8.2] - 2024-11-27 This release ensures that the provided peer identity is verified at the crypto/noise protocol level, enhancing security and preventing potential misuses. The release also includes a fix that caused `TransportService` component to panic on debug builds. ### Fixed - req-resp: Fix panic on connection closed for substream open failure ([#291](https://github.com/paritytech/litep2p/pull/291)) - crypto/noise: Verify crypto/noise signature payload ([#278](https://github.com/paritytech/litep2p/pull/278)) ### Changed - transport_service/logs: Provide less details for trace logs ([#292](https://github.com/paritytech/litep2p/pull/292)) ## Testing Done This has been extensively tested in Kusama on all validators, that are now running litep2p. Deployed PR: https://github.com/paritytech/polkadot-sdk/pull/6638 ### Litep2p Dashboards ![Screenshot 2024-11-26 at 19 19 41](https://github.com/user-attachments/assets/e00b2b2b-7e64-4d96-ab26-165e2b8d0dc9) ### Libp2p vs Litep2p CPU usage After deploying litep2p we have reduced CPU usage from around 300-400% to 200%, this is a significant boost in performance, freeing resources for other subcomponents to function more optimally. ![image(1)](https://github.com/user-attachments/assets/fa793df5-4d58-4601-963d-246e56dd2a26) cc @paritytech/sdk-node --------- Signed-off-by: Alexandru Vasile Co-authored-by: GitHub Action --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- prdoc/pr_6677.prdoc | 11 +++++++++++ substrate/client/network/src/litep2p/mod.rs | 11 ++++++++++- 4 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 prdoc/pr_6677.prdoc diff --git a/Cargo.lock b/Cargo.lock index 12e642bc9d06..84477cd05416 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10216,9 +10216,9 @@ dependencies = [ [[package]] name = "litep2p" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b67484b8ac41e1cfdf012f65fa81e88c2ef5f8a7d6dec0e2678c2d06dc04530" +checksum = "569e7dbec8a0d4b08d30f4942cd579cfe8db5d3f83f8604abe61697c38d17e73" dependencies = [ "async-trait", "bs58", diff --git a/Cargo.toml b/Cargo.toml index b1a52712e736..964964908a9b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -848,7 +848,7 @@ linked-hash-map = { version = "0.5.4" } linked_hash_set = { version = "0.1.4" } linregress = { version = "0.5.1" } lite-json = { version = "0.2.0", default-features = false } -litep2p = { version = "0.8.1", features = ["websocket"] } +litep2p = { version = "0.8.2", features = ["websocket"] } log = { version = "0.4.22", default-features = false } macro_magic = { version = "0.5.1" } maplit = { version = "1.0.2" } diff --git a/prdoc/pr_6677.prdoc b/prdoc/pr_6677.prdoc new file mode 100644 index 000000000000..c6766889e68d --- /dev/null +++ b/prdoc/pr_6677.prdoc @@ -0,0 +1,11 @@ +title: 'chore: Update litep2p to v0.8.2' +doc: +- audience: Node Dev + description: |- + This includes a critical fix for debug release versions of litep2p (which are running in Kusama as validators). + + While at it, have stopped the oncall pain of alerts around `incoming_connections_total`. We can rethink the metric expose of litep2p in Q1. + +crates: +- name: sc-network + bump: minor diff --git a/substrate/client/network/src/litep2p/mod.rs b/substrate/client/network/src/litep2p/mod.rs index 10cf9f4da36d..6d3575fc2b6b 100644 --- a/substrate/client/network/src/litep2p/mod.rs +++ b/substrate/client/network/src/litep2p/mod.rs @@ -986,7 +986,15 @@ impl NetworkBackend for Litep2pNetworkBac let direction = match endpoint { Endpoint::Dialer { .. } => "out", - Endpoint::Listener { .. } => "in", + Endpoint::Listener { .. } => { + // Increment incoming connections counter. + // + // Note: For litep2p these are represented by established negotiated connections, + // while for libp2p (legacy) these represent not-yet-negotiated connections. + metrics.incoming_connections_total.inc(); + + "in" + }, }; metrics.connections_opened_total.with_label_values(&[direction]).inc(); @@ -1058,6 +1066,7 @@ impl NetworkBackend for Litep2pNetworkBac NegotiationError::ParseError(_) => "parse-error", NegotiationError::IoError(_) => "io-error", NegotiationError::WebSocket(_) => "webscoket-error", + NegotiationError::BadSignature => "bad-signature", } }; From 9ec8009c5a8fdf89499fcd2a40df0292d3950efa Mon Sep 17 00:00:00 2001 From: Branislav Kontur Date: Thu, 28 Nov 2024 12:41:09 +0100 Subject: [PATCH 151/166] Multiple instances for pallet-bridge-relayers fix (#6684) Previously, we added multi-instance pallet support for `pallet-bridge-relayers`, but missed fixing it in this one place. --------- Co-authored-by: GitHub Action Co-authored-by: Adrian Catangiu --- bridges/modules/relayers/src/extension/mod.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/bridges/modules/relayers/src/extension/mod.rs b/bridges/modules/relayers/src/extension/mod.rs index 34d280d26d6e..d562ed9bcd0e 100644 --- a/bridges/modules/relayers/src/extension/mod.rs +++ b/bridges/modules/relayers/src/extension/mod.rs @@ -129,7 +129,7 @@ pub struct BridgeRelayersTransactionExtension( impl BridgeRelayersTransactionExtension where Self: 'static + Send + Sync, - R: RelayersConfig + R: RelayersConfig + BridgeMessagesConfig + TransactionPaymentConfig, C: ExtensionConfig, @@ -250,7 +250,7 @@ where // let's also replace the weight of slashing relayer with the weight of rewarding relayer if call_info.is_receive_messages_proof_call() { post_info_weight = post_info_weight.saturating_sub( - ::WeightInfo::extra_weight_of_successful_receive_messages_proof_call(), + >::WeightInfo::extra_weight_of_successful_receive_messages_proof_call(), ); } @@ -278,7 +278,7 @@ impl TransactionExtension for BridgeRelayersTransactionExtension where Self: 'static + Send + Sync, - R: RelayersConfig + R: RelayersConfig + BridgeMessagesConfig + TransactionPaymentConfig, C: ExtensionConfig, @@ -326,7 +326,9 @@ where }; // we only boost priority if relayer has staked required balance - if !RelayersPallet::::is_registration_active(&data.relayer) { + if !RelayersPallet::::is_registration_active( + &data.relayer, + ) { return Ok((Default::default(), Some(data), origin)) } @@ -382,7 +384,11 @@ where match call_result { RelayerAccountAction::None => (), RelayerAccountAction::Reward(relayer, reward_account, reward) => { - RelayersPallet::::register_relayer_reward(reward_account, &relayer, reward); + RelayersPallet::::register_relayer_reward( + reward_account, + &relayer, + reward, + ); log::trace!( target: LOG_TARGET, @@ -394,7 +400,7 @@ where ); }, RelayerAccountAction::Slash(relayer, slash_account) => - RelayersPallet::::slash_and_deregister( + RelayersPallet::::slash_and_deregister( &relayer, ExplicitOrAccountParams::Params(slash_account), ), From 23369acd34411cfae924718a2834df1a7ea8bc05 Mon Sep 17 00:00:00 2001 From: Ludovic_Domingues Date: Thu, 28 Nov 2024 15:27:49 +0100 Subject: [PATCH 152/166] Migrating pallet-xcm-benchmarks to V2 (#6618) # Description Migrated pallet-xcm-benchmarks to benchmaking syntax V2 This is part of #6202 --------- Co-authored-by: Giuseppe Re --- .../src/generic/benchmarking.rs | 652 +++++++++++------- 1 file changed, 394 insertions(+), 258 deletions(-) diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 87bf27e4ff18..f4836b7cdde1 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -13,12 +13,13 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +#![cfg(feature = "runtime-benchmarks")] use super::*; use crate::{account_and_location, new_executor, EnsureDelivery, XcmCallOf}; use alloc::{vec, vec::Vec}; use codec::Encode; -use frame_benchmarking::{benchmarks, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::traits::fungible::Inspect; use xcm::{ latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight, MAX_ITEMS_IN_ASSETS}, @@ -29,16 +30,21 @@ use xcm_executor::{ ExecutorError, FeesMode, }; -benchmarks! { - report_holding { +#[benchmarks] +mod benchmarks { + use super::*; + + #[benchmark] + fn report_holding() -> Result<(), BenchmarkError> { let (sender_account, sender_location) = account_and_location::(1); let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &sender_location, - &destination, - FeeReason::Report, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); // generate holding and add possible required fees @@ -64,21 +70,33 @@ benchmarks! { query_id: Default::default(), max_weight: Weight::MAX, }, - // Worst case is looking through all holdings for every asset explicitly - respecting the limit `MAX_ITEMS_IN_ASSETS`. - assets: Definite(holding.into_inner().into_iter().take(MAX_ITEMS_IN_ASSETS).collect::>().into()), + // Worst case is looking through all holdings for every asset explicitly - respecting + // the limit `MAX_ITEMS_IN_ASSETS`. + assets: Definite( + holding + .into_inner() + .into_iter() + .take(MAX_ITEMS_IN_ASSETS) + .collect::>() + .into(), + ), }; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); + + Ok(()) } // This benchmark does not use any additional orders or instructions. This should be managed // by the `deep` and `shallow` implementation. - buy_execution { + #[benchmark] + fn buy_execution() -> Result<(), BenchmarkError> { let holding = T::worst_case_holding(0).into(); let mut executor = new_executor::(Default::default()); @@ -92,13 +110,16 @@ benchmarks! { }; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } + Ok(()) } - pay_fees { + #[benchmark] + fn pay_fees() -> Result<(), BenchmarkError> { let holding = T::worst_case_holding(0).into(); let mut executor = new_executor::(Default::default()); @@ -111,40 +132,53 @@ benchmarks! { let instruction = Instruction::>::PayFees { asset: fee_asset }; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify {} + #[block] + { + executor.bench_process(xcm)?; + } + Ok(()) + } - set_asset_claimer { + #[benchmark] + fn set_asset_claimer() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let (_, sender_location) = account_and_location::(1); - let instruction = Instruction::SetAssetClaimer{ location:sender_location.clone() }; + let instruction = Instruction::SetAssetClaimer { location: sender_location.clone() }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.asset_claimer(), Some(sender_location.clone())); + + Ok(()) } - query_response { + #[benchmark] + fn query_response() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let (query_id, response) = T::worst_case_response(); let max_weight = Weight::MAX; let querier: Option = Some(Here.into()); let instruction = Instruction::QueryResponse { query_id, response, max_weight, querier }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + + #[block] + { + executor.bench_process(xcm)?; + } // The assert above is enough to show this XCM succeeded + + Ok(()) } // We don't care about the call itself, since that is accounted for in the weight parameter // and included in the final weight calculation. So this is just the overhead of submitting // a noop call. - transact { + #[benchmark] + fn transact() -> Result<(), BenchmarkError> { let (origin, noop_call) = T::transact_origin_and_runtime_call()?; let mut executor = new_executor::(origin); let double_encoded_noop_call: DoubleEncoded<_> = noop_call.encode().into(); @@ -154,119 +188,145 @@ benchmarks! { call: double_encoded_noop_call, }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // TODO Make the assertion configurable? + + Ok(()) } - refund_surplus { + #[benchmark] + fn refund_surplus() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let holding_assets = T::worst_case_holding(1); // We can already buy execution since we'll load the holding register manually let asset_for_fees = T::fee_asset().unwrap(); - let previous_xcm = Xcm(vec![BuyExecution { fees: asset_for_fees, weight_limit: Limited(Weight::from_parts(1337, 1337)) }]); + let previous_xcm = Xcm(vec![BuyExecution { + fees: asset_for_fees, + weight_limit: Limited(Weight::from_parts(1337, 1337)), + }]); executor.set_holding(holding_assets.into()); executor.set_total_surplus(Weight::from_parts(1337, 1337)); executor.set_total_refunded(Weight::zero()); - executor.bench_process(previous_xcm).expect("Holding has been loaded, so we can buy execution here"); + executor + .bench_process(previous_xcm) + .expect("Holding has been loaded, so we can buy execution here"); let instruction = Instruction::>::RefundSurplus; let xcm = Xcm(vec![instruction]); - } : { - let result = executor.bench_process(xcm)?; - } verify { + #[block] + { + let _result = executor.bench_process(xcm)?; + } assert_eq!(executor.total_surplus(), &Weight::from_parts(1337, 1337)); assert_eq!(executor.total_refunded(), &Weight::from_parts(1337, 1337)); + + Ok(()) } - set_error_handler { + #[benchmark] + fn set_error_handler() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let instruction = Instruction::>::SetErrorHandler(Xcm(vec![])); let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.error_handler(), &Xcm(vec![])); + + Ok(()) } - set_appendix { + #[benchmark] + fn set_appendix() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let appendix = Xcm(vec![]); let instruction = Instruction::>::SetAppendix(appendix); let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.appendix(), &Xcm(vec![])); + Ok(()) } - clear_error { + #[benchmark] + fn clear_error() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_error(Some((5u32, XcmError::Overflow))); let instruction = Instruction::>::ClearError; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { - assert!(executor.error().is_none()) + #[block] + { + executor.bench_process(xcm)?; + } + assert!(executor.error().is_none()); + Ok(()) } - descend_origin { + #[benchmark] + fn descend_origin() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let who = Junctions::from([OnlyChild, OnlyChild]); let instruction = Instruction::DescendOrigin(who.clone()); let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { - assert_eq!( - executor.origin(), - &Some(Location { - parents: 0, - interior: who, - }), - ); + #[block] + { + executor.bench_process(xcm)?; + } + assert_eq!(executor.origin(), &Some(Location { parents: 0, interior: who }),); + + Ok(()) } - execute_with_origin { + #[benchmark] + fn execute_with_origin() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let who: Junctions = Junctions::from([AccountId32 { id: [0u8; 32], network: None }]); - let instruction = Instruction::ExecuteWithOrigin { descendant_origin: Some(who.clone()), xcm: Xcm(vec![]) }; + let instruction = Instruction::ExecuteWithOrigin { + descendant_origin: Some(who.clone()), + xcm: Xcm(vec![]), + }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { - assert_eq!( - executor.origin(), - &Some(Location { - parents: 0, - interior: Here, - }), - ); + #[block] + { + executor.bench_process(xcm)?; + } + assert_eq!(executor.origin(), &Some(Location { parents: 0, interior: Here }),); + + Ok(()) } - clear_origin { + #[benchmark] + fn clear_origin() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let instruction = Instruction::ClearOrigin; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.origin(), &None); + Ok(()) } - report_error { + #[benchmark] + fn report_error() -> Result<(), BenchmarkError> { let (sender_account, sender_location) = account_and_location::(1); let query_id = Default::default(); let max_weight = Default::default(); let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &sender_location, - &destination, - FeeReason::Report, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); let mut executor = new_executor::(sender_location); @@ -278,18 +338,21 @@ benchmarks! { } executor.set_error(Some((0u32, XcmError::Unimplemented))); - let instruction = Instruction::ReportError(QueryResponseInfo { - query_id, destination, max_weight - }); + let instruction = + Instruction::ReportError(QueryResponseInfo { query_id, destination, max_weight }); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); + + Ok(()) } - claim_asset { + #[benchmark] + fn claim_asset() -> Result<(), BenchmarkError> { use xcm_executor::traits::DropAssets; let (origin, ticket, assets) = T::claimable_asset()?; @@ -298,11 +361,7 @@ benchmarks! { ::AssetTrap::drop_assets( &origin, assets.clone().into(), - &XcmContext { - origin: Some(origin.clone()), - message_id: [0; 32], - topic: None, - }, + &XcmContext { origin: Some(origin.clone()), message_id: [0; 32], topic: None }, ); // Assets should be in the trap now. @@ -310,28 +369,32 @@ benchmarks! { let mut executor = new_executor::(origin); let instruction = Instruction::ClaimAsset { assets: assets.clone(), ticket }; let xcm = Xcm(vec![instruction]); - } :{ - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert!(executor.holding().ensure_contains(&assets).is_ok()); + Ok(()) } - trap { + #[benchmark] + fn trap() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let instruction = Instruction::Trap(10); let xcm = Xcm(vec![instruction]); // In order to access result in the verification below, it needs to be defined here. - let mut _result = Ok(()); - } : { - _result = executor.bench_process(xcm); - } verify { - assert!(matches!(_result, Err(ExecutorError { - xcm_error: XcmError::Trap(10), - .. - }))); + let result; + #[block] + { + result = executor.bench_process(xcm); + } + assert!(matches!(result, Err(ExecutorError { xcm_error: XcmError::Trap(10), .. }))); + + Ok(()) } - subscribe_version { + #[benchmark] + fn subscribe_version() -> Result<(), BenchmarkError> { use xcm_executor::traits::VersionChangeNotifier; let origin = T::subscribe_origin()?; let query_id = Default::default(); @@ -339,13 +402,18 @@ benchmarks! { let mut executor = new_executor::(origin.clone()); let instruction = Instruction::SubscribeVersion { query_id, max_response_weight }; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { - assert!(::SubscriptionService::is_subscribed(&origin)); + #[block] + { + executor.bench_process(xcm)?; + } + assert!(::SubscriptionService::is_subscribed( + &origin + )); + Ok(()) } - unsubscribe_version { + #[benchmark] + fn unsubscribe_version() -> Result<(), BenchmarkError> { use xcm_executor::traits::VersionChangeNotifier; // First we need to subscribe to notifications. let (origin, _) = T::transact_origin_and_runtime_call()?; @@ -355,24 +423,28 @@ benchmarks! { &origin, query_id, max_response_weight, - &XcmContext { - origin: Some(origin.clone()), - message_id: [0; 32], - topic: None, - }, - ).map_err(|_| "Could not start subscription")?; - assert!(::SubscriptionService::is_subscribed(&origin)); + &XcmContext { origin: Some(origin.clone()), message_id: [0; 32], topic: None }, + ) + .map_err(|_| "Could not start subscription")?; + assert!(::SubscriptionService::is_subscribed( + &origin + )); let mut executor = new_executor::(origin.clone()); let instruction = Instruction::UnsubscribeVersion; let xcm = Xcm(vec![instruction]); - } : { - executor.bench_process(xcm)?; - } verify { - assert!(!::SubscriptionService::is_subscribed(&origin)); + #[block] + { + executor.bench_process(xcm)?; + } + assert!(!::SubscriptionService::is_subscribed( + &origin + )); + Ok(()) } - burn_asset { + #[benchmark] + fn burn_asset() -> Result<(), BenchmarkError> { let holding = T::worst_case_holding(0); let assets = holding.clone(); @@ -381,13 +453,16 @@ benchmarks! { let instruction = Instruction::BurnAsset(assets.into()); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert!(executor.holding().is_empty()); + Ok(()) } - expect_asset { + #[benchmark] + fn expect_asset() -> Result<(), BenchmarkError> { let holding = T::worst_case_holding(0); let assets = holding.clone(); @@ -396,71 +471,86 @@ benchmarks! { let instruction = Instruction::ExpectAsset(assets.into()); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // `execute` completing successfully is as good as we can check. + + Ok(()) } - expect_origin { + #[benchmark] + fn expect_origin() -> Result<(), BenchmarkError> { let expected_origin = Parent.into(); let mut executor = new_executor::(Default::default()); let instruction = Instruction::ExpectOrigin(Some(expected_origin)); let xcm = Xcm(vec![instruction]); let mut _result = Ok(()); - }: { - _result = executor.bench_process(xcm); - } verify { - assert!(matches!(_result, Err(ExecutorError { - xcm_error: XcmError::ExpectationFalse, - .. - }))); + #[block] + { + _result = executor.bench_process(xcm); + } + assert!(matches!( + _result, + Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, .. }) + )); + + Ok(()) } - expect_error { + #[benchmark] + fn expect_error() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_error(Some((3u32, XcmError::Overflow))); let instruction = Instruction::ExpectError(None); let xcm = Xcm(vec![instruction]); let mut _result = Ok(()); - }: { - _result = executor.bench_process(xcm); - } verify { - assert!(matches!(_result, Err(ExecutorError { - xcm_error: XcmError::ExpectationFalse, - .. - }))); + #[block] + { + _result = executor.bench_process(xcm); + } + assert!(matches!( + _result, + Err(ExecutorError { xcm_error: XcmError::ExpectationFalse, .. }) + )); + + Ok(()) } - expect_transact_status { + #[benchmark] + fn expect_transact_status() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); - let worst_error = || -> MaybeErrorCode { - vec![0; MaxDispatchErrorLen::get() as usize].into() - }; + let worst_error = + || -> MaybeErrorCode { vec![0; MaxDispatchErrorLen::get() as usize].into() }; executor.set_transact_status(worst_error()); let instruction = Instruction::ExpectTransactStatus(worst_error()); let xcm = Xcm(vec![instruction]); let mut _result = Ok(()); - }: { - _result = executor.bench_process(xcm); - } verify { + #[block] + { + _result = executor.bench_process(xcm); + } assert!(matches!(_result, Ok(..))); + Ok(()) } - query_pallet { + #[benchmark] + fn query_pallet() -> Result<(), BenchmarkError> { let (sender_account, sender_location) = account_and_location::(1); let query_id = Default::default(); let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; let max_weight = Default::default(); - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &sender_location, - &destination, - FeeReason::QueryPallet, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::QueryPallet, + ); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); let mut executor = new_executor::(sender_location); if let Some(expected_fees_mode) = expected_fees_mode { @@ -476,15 +566,19 @@ benchmarks! { response_info: QueryResponseInfo { destination, query_id, max_weight }, }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + + Ok(()) } - expect_pallet { + #[benchmark] + fn expect_pallet() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let valid_pallet = T::valid_pallet(); let instruction = Instruction::ExpectPallet { @@ -495,23 +589,27 @@ benchmarks! { min_crate_minor: valid_pallet.crate_version.minor.into(), }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // the execution succeeding is all we need to verify this xcm was successful + Ok(()) } - report_transact_status { + #[benchmark] + fn report_transact_status() -> Result<(), BenchmarkError> { let (sender_account, sender_location) = account_and_location::(1); let query_id = Default::default(); let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; let max_weight = Default::default(); - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &sender_location, - &destination, - FeeReason::Report, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); let mut executor = new_executor::(sender_location); @@ -529,84 +627,102 @@ benchmarks! { max_weight, }); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + Ok(()) } - clear_transact_status { + #[benchmark] + fn clear_transact_status() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_transact_status(b"MyError".to_vec().into()); let instruction = Instruction::ClearTransactStatus; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.transact_status(), &MaybeErrorCode::Success); + Ok(()) } - set_topic { + #[benchmark] + fn set_topic() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); let instruction = Instruction::SetTopic([1; 32]); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.topic(), &Some([1; 32])); + Ok(()) } - clear_topic { + #[benchmark] + fn clear_topic() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_topic(Some([2; 32])); let instruction = Instruction::ClearTopic; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.topic(), &None); + Ok(()) } - exchange_asset { + #[benchmark] + fn exchange_asset() -> Result<(), BenchmarkError> { let (give, want) = T::worst_case_asset_exchange().map_err(|_| BenchmarkError::Skip)?; let assets = give.clone(); let mut executor = new_executor::(Default::default()); executor.set_holding(give.into()); - let instruction = Instruction::ExchangeAsset { - give: assets.into(), - want: want.clone(), - maximal: true, - }; + let instruction = + Instruction::ExchangeAsset { give: assets.into(), want: want.clone(), maximal: true }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.holding(), &want.into()); + Ok(()) } - universal_origin { + #[benchmark] + fn universal_origin() -> Result<(), BenchmarkError> { let (origin, alias) = T::universal_alias().map_err(|_| BenchmarkError::Skip)?; let mut executor = new_executor::(origin); let instruction = Instruction::UniversalOrigin(alias); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } use frame_support::traits::Get; let universal_location = ::UniversalLocation::get(); - assert_eq!(executor.origin(), &Some(Junctions::from([alias]).relative_to(&universal_location))); + assert_eq!( + executor.origin(), + &Some(Junctions::from([alias]).relative_to(&universal_location)) + ); + + Ok(()) } - export_message { - let x in 1 .. 1000; + #[benchmark] + fn export_message(x: Linear<1, 1000>) -> Result<(), BenchmarkError> { // The `inner_xcm` influences `ExportMessage` total weight based on // `inner_xcm.encoded_size()`, so for this benchmark use smallest encoded instruction // to approximate weight per "unit" of encoded size; then actual weight can be estimated @@ -616,11 +732,12 @@ benchmarks! { // Get `origin`, `network` and `destination` from configured runtime. let (origin, network, destination) = T::export_message_origin_and_destination()?; - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &origin, - &destination.clone().into(), - FeeReason::Export { network, destination: destination.clone() }, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &origin, + &destination.clone().into(), + FeeReason::Export { network, destination: destination.clone() }, + ); let sender_account = T::AccountIdConverter::convert_location(&origin).unwrap(); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); @@ -631,37 +748,39 @@ benchmarks! { if let Some(expected_assets_in_holding) = expected_assets_in_holding { executor.set_holding(expected_assets_in_holding.into()); } - let xcm = Xcm(vec![ExportMessage { - network, destination: destination.clone(), xcm: inner_xcm, - }]); - }: { - executor.bench_process(xcm)?; - } verify { + let xcm = + Xcm(vec![ExportMessage { network, destination: destination.clone(), xcm: inner_xcm }]); + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + Ok(()) } - set_fees_mode { + #[benchmark] + fn set_fees_mode() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_fees_mode(FeesMode { jit_withdraw: false }); let instruction = Instruction::SetFeesMode { jit_withdraw: true }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.fees_mode(), &FeesMode { jit_withdraw: true }); + Ok(()) } - lock_asset { + #[benchmark] + fn lock_asset() -> Result<(), BenchmarkError> { let (unlocker, owner, asset) = T::unlockable_asset()?; - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &owner, - &unlocker, - FeeReason::LockAsset, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery(&owner, &unlocker, FeeReason::LockAsset); let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap(); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); @@ -681,15 +800,18 @@ benchmarks! { let instruction = Instruction::LockAsset { asset, unlocker }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + Ok(()) } - unlock_asset { + #[benchmark] + fn unlock_asset() -> Result<(), BenchmarkError> { use xcm_executor::traits::{AssetLock, Enact}; let (unlocker, owner, asset) = T::unlockable_asset()?; @@ -709,13 +831,15 @@ benchmarks! { // ... then unlock them with the UnlockAsset instruction. let instruction = Instruction::UnlockAsset { asset, target: owner }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { - + #[block] + { + executor.bench_process(xcm)?; + } + Ok(()) } - note_unlockable { + #[benchmark] + fn note_unlockable() -> Result<(), BenchmarkError> { use xcm_executor::traits::{AssetLock, Enact}; let (unlocker, owner, asset) = T::unlockable_asset()?; @@ -735,13 +859,15 @@ benchmarks! { // ... then note them as unlockable with the NoteUnlockable instruction. let instruction = Instruction::NoteUnlockable { asset, owner }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { - + #[block] + { + executor.bench_process(xcm)?; + } + Ok(()) } - request_unlock { + #[benchmark] + fn request_unlock() -> Result<(), BenchmarkError> { use xcm_executor::traits::{AssetLock, Enact}; let (locker, owner, asset) = T::unlockable_asset()?; @@ -756,11 +882,12 @@ benchmarks! { .enact() .map_err(|_| BenchmarkError::Skip)?; - let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( - &owner, - &locker, - FeeReason::RequestUnlock, - ); + let (expected_fees_mode, expected_assets_in_holding) = + T::DeliveryHelper::ensure_successful_delivery( + &owner, + &locker, + FeeReason::RequestUnlock, + ); let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap(); let sender_account_balance_before = T::TransactAsset::balance(&sender_account); @@ -774,15 +901,18 @@ benchmarks! { } let instruction = Instruction::RequestUnlock { asset, locker }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } // Check we charged the delivery fees assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + Ok(()) } - unpaid_execution { + #[benchmark] + fn unpaid_execution() -> Result<(), BenchmarkError> { let mut executor = new_executor::(Default::default()); executor.set_origin(Some(Here.into())); @@ -792,21 +922,27 @@ benchmarks! { }; let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; + #[block] + { + executor.bench_process(xcm)?; + } + Ok(()) } - alias_origin { + #[benchmark] + fn alias_origin() -> Result<(), BenchmarkError> { let (origin, target) = T::alias_origin().map_err(|_| BenchmarkError::Skip)?; let mut executor = new_executor::(origin); let instruction = Instruction::AliasOrigin(target.clone()); let xcm = Xcm(vec![instruction]); - }: { - executor.bench_process(xcm)?; - } verify { + #[block] + { + executor.bench_process(xcm)?; + } assert_eq!(executor.origin(), &Some(target)); + Ok(()) } impl_benchmark_test_suite!( From fdb264d0df6fdbed32f001ba43c3282a01dd3d65 Mon Sep 17 00:00:00 2001 From: Ludovic_Domingues Date: Thu, 28 Nov 2024 17:18:30 +0100 Subject: [PATCH 153/166] Migrating pallet-state-trie-migration to benchmarking V2 (#6617) # Description Migrated pallet-state-trie-migration benchmarking to the new benchmarking syntax v2. This is part of #6202 Co-authored-by: Shawn Tabrizi Co-authored-by: Giuseppe Re --- .../frame/state-trie-migration/src/lib.rs | 176 +++++++++++------- 1 file changed, 108 insertions(+), 68 deletions(-) diff --git a/substrate/frame/state-trie-migration/src/lib.rs b/substrate/frame/state-trie-migration/src/lib.rs index 3fe5abb81031..61323b70b33d 100644 --- a/substrate/frame/state-trie-migration/src/lib.rs +++ b/substrate/frame/state-trie-migration/src/lib.rs @@ -249,13 +249,13 @@ pub mod pallet { if limits.item.is_zero() || limits.size.is_zero() { // handle this minor edge case, else we would call `migrate_tick` at least once. log!(warn, "limits are zero. stopping"); - return Ok(()) + return Ok(()); } while !self.exhausted(limits) && !self.finished() { if let Err(e) = self.migrate_tick() { log!(error, "migrate_until_exhaustion failed: {:?}", e); - return Err(e) + return Err(e); } } @@ -332,7 +332,7 @@ pub mod pallet { _ => { // defensive: there must be an ongoing top migration. frame_support::defensive!("cannot migrate child key."); - return Ok(()) + return Ok(()); }, }; @@ -374,7 +374,7 @@ pub mod pallet { Progress::Complete => { // defensive: there must be an ongoing top migration. frame_support::defensive!("cannot migrate top key."); - return Ok(()) + return Ok(()); }, }; @@ -669,7 +669,7 @@ pub mod pallet { // ensure that the migration witness data was correct. if real_size_upper < task.dyn_size { Self::slash(who, deposit)?; - return Ok(().into()) + return Ok(().into()); } Self::deposit_event(Event::::Migrated { @@ -957,6 +957,7 @@ pub mod pallet { mod benchmarks { use super::{pallet::Pallet as StateTrieMigration, *}; use alloc::vec; + use frame_benchmarking::v2::*; use frame_support::traits::fungible::{Inspect, Mutate}; // The size of the key seemingly makes no difference in the read/write time, so we make it @@ -970,8 +971,12 @@ mod benchmarks { stash } - frame_benchmarking::benchmarks! { - continue_migrate { + #[benchmarks] + mod inner_benchmarks { + use super::*; + + #[benchmark] + fn continue_migrate() -> Result<(), BenchmarkError> { // note that this benchmark should migrate nothing, as we only want the overhead weight // of the bookkeeping, and the migration cost itself is noted via the `dynamic_weight` // function. @@ -980,116 +985,151 @@ mod benchmarks { let stash = set_balance_for_deposit::(&caller, null.item); // Allow signed migrations. SignedMigrationMaxLimits::::put(MigrationLimits { size: 1024, item: 5 }); - }: _(frame_system::RawOrigin::Signed(caller.clone()), null, 0, StateTrieMigration::::migration_process()) - verify { + + #[extrinsic_call] + _( + frame_system::RawOrigin::Signed(caller.clone()), + null, + 0, + StateTrieMigration::::migration_process(), + ); + assert_eq!(StateTrieMigration::::migration_process(), Default::default()); - assert_eq!(T::Currency::balance(&caller), stash) + assert_eq!(T::Currency::balance(&caller), stash); + + Ok(()) } - continue_migrate_wrong_witness { + #[benchmark] + fn continue_migrate_wrong_witness() -> Result<(), BenchmarkError> { let null = MigrationLimits::default(); let caller = frame_benchmarking::whitelisted_caller(); - let bad_witness = MigrationTask { progress_top: Progress::LastKey(vec![1u8].try_into().unwrap()), ..Default::default() }; - }: { - assert!( - StateTrieMigration::::continue_migrate( + let bad_witness = MigrationTask { + progress_top: Progress::LastKey(vec![1u8].try_into().unwrap()), + ..Default::default() + }; + #[block] + { + assert!(StateTrieMigration::::continue_migrate( frame_system::RawOrigin::Signed(caller).into(), null, 0, bad_witness, ) - .is_err() - ) - } - verify { - assert_eq!(StateTrieMigration::::migration_process(), Default::default()) + .is_err()); + } + + assert_eq!(StateTrieMigration::::migration_process(), Default::default()); + + Ok(()) } - migrate_custom_top_success { + #[benchmark] + fn migrate_custom_top_success() -> Result<(), BenchmarkError> { let null = MigrationLimits::default(); let caller: T::AccountId = frame_benchmarking::whitelisted_caller(); let stash = set_balance_for_deposit::(&caller, null.item); - }: migrate_custom_top(frame_system::RawOrigin::Signed(caller.clone()), Default::default(), 0) - verify { + #[extrinsic_call] + migrate_custom_top( + frame_system::RawOrigin::Signed(caller.clone()), + Default::default(), + 0, + ); + assert_eq!(StateTrieMigration::::migration_process(), Default::default()); - assert_eq!(T::Currency::balance(&caller), stash) + assert_eq!(T::Currency::balance(&caller), stash); + Ok(()) } - migrate_custom_top_fail { + #[benchmark] + fn migrate_custom_top_fail() -> Result<(), BenchmarkError> { let null = MigrationLimits::default(); let caller: T::AccountId = frame_benchmarking::whitelisted_caller(); let stash = set_balance_for_deposit::(&caller, null.item); // for tests, we need to make sure there is _something_ in storage that is being // migrated. - sp_io::storage::set(b"foo", vec![1u8;33].as_ref()); - }: { - assert!( - StateTrieMigration::::migrate_custom_top( + sp_io::storage::set(b"foo", vec![1u8; 33].as_ref()); + #[block] + { + assert!(StateTrieMigration::::migrate_custom_top( frame_system::RawOrigin::Signed(caller.clone()).into(), vec![b"foo".to_vec()], 1, - ).is_ok() - ); + ) + .is_ok()); + + frame_system::Pallet::::assert_last_event( + ::RuntimeEvent::from(crate::Event::Slashed { + who: caller.clone(), + amount: StateTrieMigration::::calculate_deposit_for(1u32), + }) + .into(), + ); + } - frame_system::Pallet::::assert_last_event( - ::RuntimeEvent::from(crate::Event::Slashed { - who: caller.clone(), - amount: StateTrieMigration::::calculate_deposit_for(1u32), - }).into(), - ); - } - verify { assert_eq!(StateTrieMigration::::migration_process(), Default::default()); // must have gotten slashed - assert!(T::Currency::balance(&caller) < stash) + assert!(T::Currency::balance(&caller) < stash); + + Ok(()) } - migrate_custom_child_success { + #[benchmark] + fn migrate_custom_child_success() -> Result<(), BenchmarkError> { let caller: T::AccountId = frame_benchmarking::whitelisted_caller(); let stash = set_balance_for_deposit::(&caller, 0); - }: migrate_custom_child( - frame_system::RawOrigin::Signed(caller.clone()), - StateTrieMigration::::childify(Default::default()), - Default::default(), - 0 - ) - verify { + + #[extrinsic_call] + migrate_custom_child( + frame_system::RawOrigin::Signed(caller.clone()), + StateTrieMigration::::childify(Default::default()), + Default::default(), + 0, + ); + assert_eq!(StateTrieMigration::::migration_process(), Default::default()); assert_eq!(T::Currency::balance(&caller), stash); + + Ok(()) } - migrate_custom_child_fail { + #[benchmark] + fn migrate_custom_child_fail() -> Result<(), BenchmarkError> { let caller: T::AccountId = frame_benchmarking::whitelisted_caller(); let stash = set_balance_for_deposit::(&caller, 1); // for tests, we need to make sure there is _something_ in storage that is being // migrated. - sp_io::default_child_storage::set(b"top", b"foo", vec![1u8;33].as_ref()); - }: { - assert!( - StateTrieMigration::::migrate_custom_child( + sp_io::default_child_storage::set(b"top", b"foo", vec![1u8; 33].as_ref()); + + #[block] + { + assert!(StateTrieMigration::::migrate_custom_child( frame_system::RawOrigin::Signed(caller.clone()).into(), StateTrieMigration::::childify("top"), vec![b"foo".to_vec()], 1, - ).is_ok() - ) - } - verify { + ) + .is_ok()); + } assert_eq!(StateTrieMigration::::migration_process(), Default::default()); // must have gotten slashed - assert!(T::Currency::balance(&caller) < stash) + assert!(T::Currency::balance(&caller) < stash); + Ok(()) } - process_top_key { - let v in 1 .. (4 * 1024 * 1024); - + #[benchmark] + fn process_top_key(v: Linear<1, { 4 * 1024 * 1024 }>) -> Result<(), BenchmarkError> { let value = alloc::vec![1u8; v as usize]; sp_io::storage::set(KEY, &value); - }: { - let data = sp_io::storage::get(KEY).unwrap(); - sp_io::storage::set(KEY, &data); - let _next = sp_io::storage::next_key(KEY); - assert_eq!(data, value); + #[block] + { + let data = sp_io::storage::get(KEY).unwrap(); + sp_io::storage::set(KEY, &data); + let _next = sp_io::storage::next_key(KEY); + assert_eq!(data, value); + } + + Ok(()) } impl_benchmark_test_suite!( @@ -1741,7 +1781,7 @@ pub(crate) mod remote_tests { let ((finished, weight), proof) = ext.execute_and_prove(|| { let weight = run_to_block::(now + One::one()).1; if StateTrieMigration::::migration_process().finished() { - return (true, weight) + return (true, weight); } duration += One::one(); now += One::one(); @@ -1768,7 +1808,7 @@ pub(crate) mod remote_tests { ext.commit_all().unwrap(); if finished { - break + break; } } From 6416b280a7d0032ba3c265e4506504c6d6536637 Mon Sep 17 00:00:00 2001 From: Cyrill Leutwiler Date: Thu, 28 Nov 2024 19:01:41 +0100 Subject: [PATCH 154/166] [pallet-revive] bugfix decoding 64bit args in the decoder (#6695) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The argument index of the next argument is dictated by the size of the current one. --------- Signed-off-by: xermicus Co-authored-by: GitHub Action Co-authored-by: Alexander Theißen --- prdoc/pr_6695.prdoc | 8 ++++++++ substrate/frame/revive/proc-macro/src/lib.rs | 4 +++- 2 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 prdoc/pr_6695.prdoc diff --git a/prdoc/pr_6695.prdoc b/prdoc/pr_6695.prdoc new file mode 100644 index 000000000000..7a950e8546cd --- /dev/null +++ b/prdoc/pr_6695.prdoc @@ -0,0 +1,8 @@ +title: '[pallet-revive] bugfix decoding 64bit args in the decoder' +doc: +- audience: Runtime Dev + description: The argument index of the next argument is dictated by the size of + the current one. +crates: +- name: pallet-revive-proc-macro + bump: patch diff --git a/substrate/frame/revive/proc-macro/src/lib.rs b/substrate/frame/revive/proc-macro/src/lib.rs index 012b4bfab9a9..7232c6342824 100644 --- a/substrate/frame/revive/proc-macro/src/lib.rs +++ b/substrate/frame/revive/proc-macro/src/lib.rs @@ -342,7 +342,8 @@ where const ALLOWED_REGISTERS: u32 = 6; let mut registers_used = 0; let mut bindings = vec![]; - for (idx, (name, ty)) in param_names.clone().zip(param_types.clone()).enumerate() { + let mut idx = 0; + for (name, ty) in param_names.clone().zip(param_types.clone()) { let syn::Type::Path(path) = &**ty else { panic!("Type needs to be path"); }; @@ -380,6 +381,7 @@ where } }; bindings.push(binding); + idx += size; } quote! { #( #bindings )* From 72fb8bd3cd4a5051bb855415b360657d7ce247fb Mon Sep 17 00:00:00 2001 From: Rodrigo Quelhas <22591718+RomarQ@users.noreply.github.com> Date: Fri, 29 Nov 2024 10:33:46 +0000 Subject: [PATCH 155/166] Expose types from `sc-service` (#5855) # Description At moonbeam we have worked on a `lazy-loading` feature which is a client mode that forks a live parachain and fetches its state on-demand, we have been able to do this by duplicating some code from `sc_service::client`. The objective of this PR is to simplify the implementation by making public some types in polkadot-sdk. - Modules: - `sc_service::client` **I do not see a point to only expose this type when `test-helpers` feature is enabled** ## Integration Not applicable, the PR just makes some types public. ## Review Notes The changes included in this PR give more flexibility for client developers by exposing important types. --- prdoc/pr_5855.prdoc | 15 +++++++ substrate/bin/node/testing/Cargo.toml | 2 +- substrate/client/network/test/Cargo.toml | 2 +- substrate/client/rpc-spec-v2/Cargo.toml | 2 +- .../src/chain_head/subscription/inner.rs | 6 +-- .../rpc-spec-v2/src/chain_head/tests.rs | 6 +-- substrate/client/service/Cargo.toml | 2 - substrate/client/service/src/client/client.rs | 40 +------------------ substrate/client/service/src/client/mod.rs | 3 +- substrate/client/service/src/lib.rs | 5 +-- substrate/client/service/test/Cargo.toml | 2 +- .../client/service/test/src/client/mod.rs | 6 +-- substrate/test-utils/client/Cargo.toml | 4 +- substrate/test-utils/runtime/Cargo.toml | 2 +- 14 files changed, 34 insertions(+), 63 deletions(-) create mode 100644 prdoc/pr_5855.prdoc diff --git a/prdoc/pr_5855.prdoc b/prdoc/pr_5855.prdoc new file mode 100644 index 000000000000..7735cfee9f37 --- /dev/null +++ b/prdoc/pr_5855.prdoc @@ -0,0 +1,15 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Remove feature `test-helpers` from sc-service + +doc: + - audience: Node Dev + description: | + Removes feature `test-helpers` from sc-service. + +crates: + - name: sc-service + bump: major + - name: sc-rpc-spec-v2 + bump: major diff --git a/substrate/bin/node/testing/Cargo.toml b/substrate/bin/node/testing/Cargo.toml index 16112386ad7c..1972c03a368b 100644 --- a/substrate/bin/node/testing/Cargo.toml +++ b/substrate/bin/node/testing/Cargo.toml @@ -37,7 +37,7 @@ sc-client-api = { workspace = true, default-features = true } sc-client-db = { features = ["rocksdb"], workspace = true, default-features = true } sc-consensus = { workspace = true, default-features = true } sc-executor = { workspace = true, default-features = true } -sc-service = { features = ["rocksdb", "test-helpers"], workspace = true, default-features = true } +sc-service = { features = ["rocksdb"], workspace = true, default-features = true } sp-api = { workspace = true, default-features = true } sp-block-builder = { workspace = true, default-features = true } sp-blockchain = { workspace = true, default-features = true } diff --git a/substrate/client/network/test/Cargo.toml b/substrate/client/network/test/Cargo.toml index ebece1762f29..6340d1dfb2f4 100644 --- a/substrate/client/network/test/Cargo.toml +++ b/substrate/client/network/test/Cargo.toml @@ -33,7 +33,7 @@ sc-network-types = { workspace = true, default-features = true } sc-utils = { workspace = true, default-features = true } sc-network-light = { workspace = true, default-features = true } sc-network-sync = { workspace = true, default-features = true } -sc-service = { features = ["test-helpers"], workspace = true } +sc-service = { workspace = true } sp-blockchain = { workspace = true, default-features = true } sp-consensus = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } diff --git a/substrate/client/rpc-spec-v2/Cargo.toml b/substrate/client/rpc-spec-v2/Cargo.toml index b304bc905925..70f68436767f 100644 --- a/substrate/client/rpc-spec-v2/Cargo.toml +++ b/substrate/client/rpc-spec-v2/Cargo.toml @@ -56,7 +56,7 @@ sp-consensus = { workspace = true, default-features = true } sp-externalities = { workspace = true, default-features = true } sp-maybe-compressed-blob = { workspace = true, default-features = true } sc-block-builder = { workspace = true, default-features = true } -sc-service = { features = ["test-helpers"], workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } sc-rpc = { workspace = true, default-features = true, features = ["test-helpers"] } assert_matches = { workspace = true } pretty_assertions = { workspace = true } diff --git a/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs b/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs index 95a7c7fe1832..3e1bd23776d3 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs @@ -784,7 +784,7 @@ mod tests { use super::*; use jsonrpsee::ConnectionId; use sc_block_builder::BlockBuilderBuilder; - use sc_service::client::new_in_mem; + use sc_service::client::new_with_backend; use sp_consensus::BlockOrigin; use sp_core::{testing::TaskExecutor, H256}; use substrate_test_runtime_client::{ @@ -811,13 +811,13 @@ mod tests { ) .unwrap(); let client = Arc::new( - new_in_mem::<_, Block, _, RuntimeApi>( + new_with_backend::<_, _, Block, _, RuntimeApi>( backend.clone(), executor, genesis_block_builder, + Box::new(TaskExecutor::new()), None, None, - Box::new(TaskExecutor::new()), client_config, ) .unwrap(), diff --git a/substrate/client/rpc-spec-v2/src/chain_head/tests.rs b/substrate/client/rpc-spec-v2/src/chain_head/tests.rs index c505566d887d..21e8365622a1 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/tests.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/tests.rs @@ -34,7 +34,7 @@ use jsonrpsee::{ use sc_block_builder::BlockBuilderBuilder; use sc_client_api::ChildInfo; use sc_rpc::testing::TokioTestExecutor; -use sc_service::client::new_in_mem; +use sc_service::client::new_with_backend; use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; use sp_core::{ @@ -2547,13 +2547,13 @@ async fn pin_block_references() { .unwrap(); let client = Arc::new( - new_in_mem::<_, Block, _, RuntimeApi>( + new_with_backend::<_, _, Block, _, RuntimeApi>( backend.clone(), executor, genesis_block_builder, + Box::new(TokioTestExecutor::default()), None, None, - Box::new(TokioTestExecutor::default()), client_config, ) .unwrap(), diff --git a/substrate/client/service/Cargo.toml b/substrate/client/service/Cargo.toml index f2fc65ef2439..3981395d9768 100644 --- a/substrate/client/service/Cargo.toml +++ b/substrate/client/service/Cargo.toml @@ -20,8 +20,6 @@ default = ["rocksdb"] # The RocksDB feature activates the RocksDB database backend. If it is not activated, and you pass # a path to a database, an error will be produced at runtime. rocksdb = ["sc-client-db/rocksdb"] -# exposes the client type -test-helpers = [] runtime-benchmarks = [ "sc-client-db/runtime-benchmarks", "sp-runtime/runtime-benchmarks", diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index ce5b92551bf2..eddbb9260c05 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -85,10 +85,8 @@ use std::{ sync::Arc, }; -#[cfg(feature = "test-helpers")] -use { - super::call_executor::LocalCallExecutor, sc_client_api::in_mem, sp_core::traits::CodeExecutor, -}; +use super::call_executor::LocalCallExecutor; +use sp_core::traits::CodeExecutor; type NotificationSinks = Mutex>>; @@ -152,39 +150,6 @@ enum PrepareStorageChangesResult { Discard(ImportResult), Import(Option>), } - -/// Create an instance of in-memory client. -#[cfg(feature = "test-helpers")] -pub fn new_in_mem( - backend: Arc>, - executor: E, - genesis_block_builder: G, - prometheus_registry: Option, - telemetry: Option, - spawn_handle: Box, - config: ClientConfig, -) -> sp_blockchain::Result< - Client, LocalCallExecutor, E>, Block, RA>, -> -where - E: CodeExecutor + sc_executor::RuntimeVersionOf, - Block: BlockT, - G: BuildGenesisBlock< - Block, - BlockImportOperation = as backend::Backend>::BlockImportOperation, - >, -{ - new_with_backend( - backend, - executor, - genesis_block_builder, - spawn_handle, - prometheus_registry, - telemetry, - config, - ) -} - /// Client configuration items. #[derive(Debug, Clone)] pub struct ClientConfig { @@ -218,7 +183,6 @@ impl Default for ClientConfig { /// Create a client with the explicitly provided backend. /// This is useful for testing backend implementations. -#[cfg(feature = "test-helpers")] pub fn new_with_backend( backend: Arc, executor: E, diff --git a/substrate/client/service/src/client/mod.rs b/substrate/client/service/src/client/mod.rs index ec77a92f162f..3020b3d296f4 100644 --- a/substrate/client/service/src/client/mod.rs +++ b/substrate/client/service/src/client/mod.rs @@ -56,5 +56,4 @@ pub use call_executor::LocalCallExecutor; pub use client::{Client, ClientConfig}; pub(crate) use code_provider::CodeProvider; -#[cfg(feature = "test-helpers")] -pub use self::client::{new_in_mem, new_with_backend}; +pub use self::client::new_with_backend; diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 9c01d7288a81..b5a38d875e3b 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -23,14 +23,11 @@ #![recursion_limit = "1024"] pub mod chain_ops; +pub mod client; pub mod config; pub mod error; mod builder; -#[cfg(feature = "test-helpers")] -pub mod client; -#[cfg(not(feature = "test-helpers"))] -mod client; mod metrics; mod task_manager; diff --git a/substrate/client/service/test/Cargo.toml b/substrate/client/service/test/Cargo.toml index 0edfc5b19314..632b98104f6b 100644 --- a/substrate/client/service/test/Cargo.toml +++ b/substrate/client/service/test/Cargo.toml @@ -31,7 +31,7 @@ sc-consensus = { workspace = true, default-features = true } sc-executor = { workspace = true, default-features = true } sc-network = { workspace = true, default-features = true } sc-network-sync = { workspace = true, default-features = true } -sc-service = { features = ["test-helpers"], workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } sc-transaction-pool-api = { workspace = true, default-features = true } sp-api = { workspace = true, default-features = true } sp-blockchain = { workspace = true, default-features = true } diff --git a/substrate/client/service/test/src/client/mod.rs b/substrate/client/service/test/src/client/mod.rs index 55bbfcdd8594..ead90c4c65d8 100644 --- a/substrate/client/service/test/src/client/mod.rs +++ b/substrate/client/service/test/src/client/mod.rs @@ -29,7 +29,7 @@ use sc_consensus::{ BlockCheckParams, BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, }; use sc_executor::WasmExecutor; -use sc_service::client::{new_in_mem, Client, LocalCallExecutor}; +use sc_service::client::{new_with_backend, Client, LocalCallExecutor}; use sp_api::ProvideRuntimeApi; use sp_consensus::{BlockOrigin, Error as ConsensusError, SelectChain}; use sp_core::{testing::TaskExecutor, traits::CallContext, H256}; @@ -2087,13 +2087,13 @@ fn cleans_up_closed_notification_sinks_on_block_import() { // NOTE: we need to build the client here instead of using the client // provided by test_runtime_client otherwise we can't access the private // `import_notification_sinks` and `finality_notification_sinks` fields. - let mut client = new_in_mem::<_, Block, _, RuntimeApi>( + let mut client = new_with_backend::<_, _, Block, _, RuntimeApi>( backend, executor, genesis_block_builder, + Box::new(TaskExecutor::new()), None, None, - Box::new(TaskExecutor::new()), client_config, ) .unwrap(); diff --git a/substrate/test-utils/client/Cargo.toml b/substrate/test-utils/client/Cargo.toml index ebd1eab5980d..a67c91fc5f79 100644 --- a/substrate/test-utils/client/Cargo.toml +++ b/substrate/test-utils/client/Cargo.toml @@ -29,9 +29,7 @@ sc-client-db = { features = [ sc-consensus = { workspace = true, default-features = true } sc-executor = { workspace = true, default-features = true } sc-offchain = { workspace = true, default-features = true } -sc-service = { features = [ - "test-helpers", -], workspace = true } +sc-service = { workspace = true } sp-blockchain = { workspace = true, default-features = true } sp-consensus = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } diff --git a/substrate/test-utils/runtime/Cargo.toml b/substrate/test-utils/runtime/Cargo.toml index 1c82c73072bc..96a888052876 100644 --- a/substrate/test-utils/runtime/Cargo.toml +++ b/substrate/test-utils/runtime/Cargo.toml @@ -45,7 +45,7 @@ sp-consensus-grandpa = { features = ["serde"], workspace = true } sp-trie = { workspace = true } sp-transaction-pool = { workspace = true } trie-db = { workspace = true } -sc-service = { features = ["test-helpers"], optional = true, workspace = true } +sc-service = { optional = true, workspace = true } sp-state-machine = { workspace = true } sp-externalities = { workspace = true } From 1dd21bcc1406e0f07f70e604f9cef4dc2115c989 Mon Sep 17 00:00:00 2001 From: Alexander Samusev <41779041+alvicsam@users.noreply.github.com> Date: Fri, 29 Nov 2024 12:00:52 +0100 Subject: [PATCH 156/166] ci: update nightly in ci-unified to 2024-11-19 (#6691) cc https://github.com/paritytech/ci_cd/issues/1088 --- .github/env | 2 +- .gitlab-ci.yml | 2 +- docs/contributor/container.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/env b/.github/env index bb61e1f4cd99..730c37f1db80 100644 --- a/.github/env +++ b/.github/env @@ -1 +1 @@ -IMAGE="docker.io/paritytech/ci-unified:bullseye-1.81.0-2024-09-11-v202409111034" +IMAGE="docker.io/paritytech/ci-unified:bullseye-1.81.0-2024-11-19-v202411281558" diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f508404f1efa..42a7e87bda43 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -22,7 +22,7 @@ workflow: variables: # CI_IMAGE: !reference [ .ci-unified, variables, CI_IMAGE ] - CI_IMAGE: "docker.io/paritytech/ci-unified:bullseye-1.81.0-2024-09-11-v202409111034" + CI_IMAGE: "docker.io/paritytech/ci-unified:bullseye-1.81.0-2024-11-19-v202411281558" # BUILDAH_IMAGE is defined in group variables BUILDAH_COMMAND: "buildah --storage-driver overlay2" RELENG_SCRIPTS_BRANCH: "master" diff --git a/docs/contributor/container.md b/docs/contributor/container.md index ec51b8b9d7cc..e387f568d7b5 100644 --- a/docs/contributor/container.md +++ b/docs/contributor/container.md @@ -24,7 +24,7 @@ The command below allows building a Linux binary without having to even install docker run --rm -it \ -w /polkadot-sdk \ -v $(pwd):/polkadot-sdk \ - docker.io/paritytech/ci-unified:bullseye-1.77.0-2024-04-10-v20240408 \ + docker.io/paritytech/ci-unified:bullseye-1.81.0-2024-11-19-v202411281558 \ cargo build --release --locked -p polkadot-parachain-bin --bin polkadot-parachain sudo chown -R $(id -u):$(id -g) target/ ``` From b3ab312724ee8c3a0c7f3d9b5ea6c98513b5c951 Mon Sep 17 00:00:00 2001 From: Xavier Lau Date: Fri, 29 Nov 2024 20:02:59 +0800 Subject: [PATCH 157/166] Migrate pallet-preimage to benchmark v2 (#6277) Part of: - #6202. --------- Co-authored-by: Giuseppe Re Co-authored-by: command-bot <> --- substrate/frame/preimage/src/benchmarking.rs | 296 ++++++++++--------- substrate/frame/preimage/src/weights.rs | 150 +++++----- 2 files changed, 231 insertions(+), 215 deletions(-) diff --git a/substrate/frame/preimage/src/benchmarking.rs b/substrate/frame/preimage/src/benchmarking.rs index 3d0c5b900579..ea635bf3ef77 100644 --- a/substrate/frame/preimage/src/benchmarking.rs +++ b/substrate/frame/preimage/src/benchmarking.rs @@ -17,14 +17,13 @@ //! Preimage pallet benchmarking. -use super::*; use alloc::vec; -use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; +use frame_benchmarking::v2::*; use frame_support::assert_ok; use frame_system::RawOrigin; use sp_runtime::traits::Bounded; -use crate::Pallet as Preimage; +use crate::*; fn funded_account() -> T::AccountId { let caller: T::AccountId = whitelisted_caller(); @@ -43,206 +42,225 @@ fn sized_preimage_and_hash(size: u32) -> (Vec, T::Hash) { (preimage, hash) } -benchmarks! { +fn insert_old_unrequested(s: u32) -> ::Hash { + let acc = account("old", s, 0); + T::Currency::make_free_balance_be(&acc, BalanceOf::::max_value() / 2u32.into()); + + // The preimage size does not matter here as it is not touched. + let preimage = s.to_le_bytes(); + let hash = ::Hashing::hash(&preimage[..]); + + #[allow(deprecated)] + StatusFor::::insert( + &hash, + OldRequestStatus::Unrequested { deposit: (acc, 123u32.into()), len: preimage.len() as u32 }, + ); + hash +} + +#[benchmarks] +mod benchmarks { + use super::*; + // Expensive note - will reserve. - note_preimage { - let s in 0 .. MAX_SIZE; + #[benchmark] + fn note_preimage(s: Linear<0, MAX_SIZE>) { let caller = funded_account::(); let (preimage, hash) = sized_preimage_and_hash::(s); - }: _(RawOrigin::Signed(caller), preimage) - verify { - assert!(Preimage::::have_preimage(&hash)); + + #[extrinsic_call] + _(RawOrigin::Signed(caller), preimage); + + assert!(Pallet::::have_preimage(&hash)); } + // Cheap note - will not reserve since it was requested. - note_requested_preimage { - let s in 0 .. MAX_SIZE; + #[benchmark] + fn note_requested_preimage(s: Linear<0, MAX_SIZE>) { let caller = funded_account::(); let (preimage, hash) = sized_preimage_and_hash::(s); - assert_ok!(Preimage::::request_preimage( + assert_ok!(Pallet::::request_preimage( T::ManagerOrigin::try_successful_origin() .expect("ManagerOrigin has no successful origin required for the benchmark"), hash, )); - }: note_preimage(RawOrigin::Signed(caller), preimage) - verify { - assert!(Preimage::::have_preimage(&hash)); + + #[extrinsic_call] + note_preimage(RawOrigin::Signed(caller), preimage); + + assert!(Pallet::::have_preimage(&hash)); } + // Cheap note - will not reserve since it's the manager. - note_no_deposit_preimage { - let s in 0 .. MAX_SIZE; + #[benchmark] + fn note_no_deposit_preimage(s: Linear<0, MAX_SIZE>) { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (preimage, hash) = sized_preimage_and_hash::(s); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - }: note_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - preimage - ) verify { - assert!(Preimage::::have_preimage(&hash)); + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + + #[extrinsic_call] + note_preimage(o as T::RuntimeOrigin, preimage); + + assert!(Pallet::::have_preimage(&hash)); } // Expensive unnote - will unreserve. - unnote_preimage { + #[benchmark] + fn unnote_preimage() { let caller = funded_account::(); let (preimage, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::note_preimage(RawOrigin::Signed(caller.clone()).into(), preimage)); - }: _(RawOrigin::Signed(caller), hash) - verify { - assert!(!Preimage::::have_preimage(&hash)); + assert_ok!(Pallet::::note_preimage(RawOrigin::Signed(caller.clone()).into(), preimage)); + + #[extrinsic_call] + _(RawOrigin::Signed(caller), hash); + + assert!(!Pallet::::have_preimage(&hash)); } + // Cheap unnote - will not unreserve since there's no deposit held. - unnote_no_deposit_preimage { + #[benchmark] + fn unnote_no_deposit_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (preimage, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::note_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - preimage, - )); - }: unnote_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { - assert!(!Preimage::::have_preimage(&hash)); + assert_ok!(Pallet::::note_preimage(o.clone(), preimage,)); + + #[extrinsic_call] + unnote_preimage(o as T::RuntimeOrigin, hash); + + assert!(!Pallet::::have_preimage(&hash)); } // Expensive request - will unreserve the noter's deposit. - request_preimage { + #[benchmark] + fn request_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (preimage, hash) = preimage_and_hash::(); let noter = funded_account::(); - assert_ok!(Preimage::::note_preimage(RawOrigin::Signed(noter.clone()).into(), preimage)); - }: _( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { - let ticket = TicketOf::::new(¬er, Footprint { count: 1, size: MAX_SIZE as u64 }).unwrap(); - let s = RequestStatus::Requested { maybe_ticket: Some((noter, ticket)), count: 1, maybe_len: Some(MAX_SIZE) }; + assert_ok!(Pallet::::note_preimage(RawOrigin::Signed(noter.clone()).into(), preimage)); + + #[extrinsic_call] + _(o as T::RuntimeOrigin, hash); + + let ticket = + TicketOf::::new(¬er, Footprint { count: 1, size: MAX_SIZE as u64 }).unwrap(); + let s = RequestStatus::Requested { + maybe_ticket: Some((noter, ticket)), + count: 1, + maybe_len: Some(MAX_SIZE), + }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } + // Cheap request - would unreserve the deposit but none was held. - request_no_deposit_preimage { + #[benchmark] + fn request_no_deposit_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (preimage, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::note_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - preimage, - )); - }: request_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { - let s = RequestStatus::Requested { maybe_ticket: None, count: 2, maybe_len: Some(MAX_SIZE) }; + assert_ok!(Pallet::::note_preimage(o.clone(), preimage,)); + + #[extrinsic_call] + request_preimage(o as T::RuntimeOrigin, hash); + + let s = + RequestStatus::Requested { maybe_ticket: None, count: 2, maybe_len: Some(MAX_SIZE) }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } + // Cheap request - the preimage is not yet noted, so deposit to unreserve. - request_unnoted_preimage { + #[benchmark] + fn request_unnoted_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (_, hash) = preimage_and_hash::(); - }: request_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { + + #[extrinsic_call] + request_preimage(o as T::RuntimeOrigin, hash); + let s = RequestStatus::Requested { maybe_ticket: None, count: 1, maybe_len: None }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } + // Cheap request - the preimage is already requested, so just a counter bump. - request_requested_preimage { + #[benchmark] + fn request_requested_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - }: request_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + + #[extrinsic_call] + request_preimage(o as T::RuntimeOrigin, hash); + let s = RequestStatus::Requested { maybe_ticket: None, count: 2, maybe_len: None }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } // Expensive unrequest - last reference and it's noted, so will destroy the preimage. - unrequest_preimage { + #[benchmark] + fn unrequest_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (preimage, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - assert_ok!(Preimage::::note_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - preimage, - )); - }: _( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + assert_ok!(Pallet::::note_preimage(o.clone(), preimage)); + + #[extrinsic_call] + _(o as T::RuntimeOrigin, hash); + assert_eq!(RequestStatusFor::::get(&hash), None); } + // Cheap unrequest - last reference, but it's not noted. - unrequest_unnoted_preimage { + #[benchmark] + fn unrequest_unnoted_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - }: unrequest_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + + #[extrinsic_call] + unrequest_preimage(o as T::RuntimeOrigin, hash); + assert_eq!(RequestStatusFor::::get(&hash), None); } + // Cheap unrequest - not the last reference. - unrequest_multi_referenced_preimage { + #[benchmark] + fn unrequest_multi_referenced_preimage() { + let o = T::ManagerOrigin::try_successful_origin() + .expect("ManagerOrigin has no successful origin required for the benchmark"); let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - assert_ok!(Preimage::::request_preimage( - T::ManagerOrigin::try_successful_origin() - .expect("ManagerOrigin has no successful origin required for the benchmark"), - hash, - )); - }: unrequest_preimage( - T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, - hash - ) verify { + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + assert_ok!(Pallet::::request_preimage(o.clone(), hash,)); + + #[extrinsic_call] + unrequest_preimage(o as T::RuntimeOrigin, hash); + let s = RequestStatus::Requested { maybe_ticket: None, count: 1, maybe_len: None }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } - ensure_updated { - let n in 1..MAX_HASH_UPGRADE_BULK_COUNT; - + #[benchmark] + fn ensure_updated(n: Linear<1, MAX_HASH_UPGRADE_BULK_COUNT>) { let caller = funded_account::(); let hashes = (0..n).map(|i| insert_old_unrequested::(i)).collect::>(); - }: _(RawOrigin::Signed(caller), hashes) - verify { + + #[extrinsic_call] + _(RawOrigin::Signed(caller), hashes); + assert_eq!(RequestStatusFor::::iter_keys().count(), n as usize); #[allow(deprecated)] let c = StatusFor::::iter_keys().count(); assert_eq!(c, 0); } - impl_benchmark_test_suite!(Preimage, crate::mock::new_test_ext(), crate::mock::Test); -} - -fn insert_old_unrequested(s: u32) -> ::Hash { - let acc = account("old", s, 0); - T::Currency::make_free_balance_be(&acc, BalanceOf::::max_value() / 2u32.into()); - - // The preimage size does not matter here as it is not touched. - let preimage = s.to_le_bytes(); - let hash = ::Hashing::hash(&preimage[..]); - - #[allow(deprecated)] - StatusFor::::insert( - &hash, - OldRequestStatus::Unrequested { deposit: (acc, 123u32.into()), len: preimage.len() as u32 }, - ); - hash + impl_benchmark_test_suite! { + Pallet, + mock::new_test_ext(), + mock::Test + } } diff --git a/substrate/frame/preimage/src/weights.rs b/substrate/frame/preimage/src/weights.rs index edb2eed9c75a..a3aec7e7546e 100644 --- a/substrate/frame/preimage/src/weights.rs +++ b/substrate/frame/preimage/src/weights.rs @@ -18,27 +18,25 @@ //! Autogenerated weights for `pallet_preimage` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-11-08, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-11-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-wiukf8gn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: -// ./target/production/substrate-node +// target/production/substrate-node // benchmark // pallet -// --chain=dev // --steps=50 // --repeat=20 -// --pallet=pallet_preimage -// --no-storage-info -// --no-median-slopes -// --no-min-squares // --extrinsic=* // --wasm-execution=compiled // --heap-pages=4096 -// --output=./substrate/frame/preimage/src/weights.rs +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_preimage +// --chain=dev // --header=./substrate/HEADER-APACHE2 +// --output=./substrate/frame/preimage/src/weights.rs // --template=./substrate/.maintain/frame-weight-template.hbs #![cfg_attr(rustfmt, rustfmt_skip)] @@ -84,10 +82,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `7` // Estimated: `6012` - // Minimum execution time: 51_981_000 picoseconds. - Weight::from_parts(52_228_000, 6012) - // Standard Error: 6 - .saturating_add(Weight::from_parts(2_392, 0).saturating_mul(s.into())) + // Minimum execution time: 51_305_000 picoseconds. + Weight::from_parts(51_670_000, 6012) + // Standard Error: 5 + .saturating_add(Weight::from_parts(2_337, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -102,10 +100,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_835_000 picoseconds. - Weight::from_parts(16_429_000, 3556) - // Standard Error: 8 - .saturating_add(Weight::from_parts(2_647, 0).saturating_mul(s.into())) + // Minimum execution time: 16_204_000 picoseconds. + Weight::from_parts(16_613_000, 3556) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_503, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -120,10 +118,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_263_000 picoseconds. - Weight::from_parts(15_578_000, 3556) - // Standard Error: 7 - .saturating_add(Weight::from_parts(2_598, 0).saturating_mul(s.into())) + // Minimum execution time: 15_118_000 picoseconds. + Weight::from_parts(15_412_000, 3556) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_411, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -139,8 +137,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `206` // Estimated: `3820` - // Minimum execution time: 64_189_000 picoseconds. - Weight::from_parts(70_371_000, 3820) + // Minimum execution time: 57_218_000 picoseconds. + Weight::from_parts(61_242_000, 3820) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -154,8 +152,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 27_582_000 picoseconds. - Weight::from_parts(31_256_000, 3556) + // Minimum execution time: 25_140_000 picoseconds. + Weight::from_parts(27_682_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -167,8 +165,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `150` // Estimated: `3556` - // Minimum execution time: 27_667_000 picoseconds. - Weight::from_parts(32_088_000, 3556) + // Minimum execution time: 25_296_000 picoseconds. + Weight::from_parts(27_413_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -180,8 +178,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 16_065_000 picoseconds. - Weight::from_parts(20_550_000, 3556) + // Minimum execution time: 15_011_000 picoseconds. + Weight::from_parts(16_524_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -193,8 +191,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `4` // Estimated: `3556` - // Minimum execution time: 13_638_000 picoseconds. - Weight::from_parts(16_979_000, 3556) + // Minimum execution time: 14_649_000 picoseconds. + Weight::from_parts(15_439_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -206,8 +204,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 11_383_000 picoseconds. - Weight::from_parts(12_154_000, 3556) + // Minimum execution time: 10_914_000 picoseconds. + Weight::from_parts(11_137_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -221,8 +219,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 22_832_000 picoseconds. - Weight::from_parts(30_716_000, 3556) + // Minimum execution time: 22_512_000 picoseconds. + Weight::from_parts(24_376_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -234,8 +232,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_685_000 picoseconds. - Weight::from_parts(12_129_000, 3556) + // Minimum execution time: 10_571_000 picoseconds. + Weight::from_parts(10_855_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -247,8 +245,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_394_000 picoseconds. - Weight::from_parts(10_951_000, 3556) + // Minimum execution time: 10_312_000 picoseconds. + Weight::from_parts(10_653_000, 3556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -267,10 +265,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0 + n * (227 ±0)` // Estimated: `6012 + n * (2830 ±0)` - // Minimum execution time: 62_203_000 picoseconds. - Weight::from_parts(63_735_000, 6012) - // Standard Error: 59_589 - .saturating_add(Weight::from_parts(59_482_352, 0).saturating_mul(n.into())) + // Minimum execution time: 61_990_000 picoseconds. + Weight::from_parts(62_751_000, 6012) + // Standard Error: 44_079 + .saturating_add(Weight::from_parts(57_343_378, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes((4_u64).saturating_mul(n.into()))) @@ -295,10 +293,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `7` // Estimated: `6012` - // Minimum execution time: 51_981_000 picoseconds. - Weight::from_parts(52_228_000, 6012) - // Standard Error: 6 - .saturating_add(Weight::from_parts(2_392, 0).saturating_mul(s.into())) + // Minimum execution time: 51_305_000 picoseconds. + Weight::from_parts(51_670_000, 6012) + // Standard Error: 5 + .saturating_add(Weight::from_parts(2_337, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -313,10 +311,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_835_000 picoseconds. - Weight::from_parts(16_429_000, 3556) - // Standard Error: 8 - .saturating_add(Weight::from_parts(2_647, 0).saturating_mul(s.into())) + // Minimum execution time: 16_204_000 picoseconds. + Weight::from_parts(16_613_000, 3556) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_503, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -331,10 +329,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 15_263_000 picoseconds. - Weight::from_parts(15_578_000, 3556) - // Standard Error: 7 - .saturating_add(Weight::from_parts(2_598, 0).saturating_mul(s.into())) + // Minimum execution time: 15_118_000 picoseconds. + Weight::from_parts(15_412_000, 3556) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_411, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -350,8 +348,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `206` // Estimated: `3820` - // Minimum execution time: 64_189_000 picoseconds. - Weight::from_parts(70_371_000, 3820) + // Minimum execution time: 57_218_000 picoseconds. + Weight::from_parts(61_242_000, 3820) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -365,8 +363,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 27_582_000 picoseconds. - Weight::from_parts(31_256_000, 3556) + // Minimum execution time: 25_140_000 picoseconds. + Weight::from_parts(27_682_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -378,8 +376,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `150` // Estimated: `3556` - // Minimum execution time: 27_667_000 picoseconds. - Weight::from_parts(32_088_000, 3556) + // Minimum execution time: 25_296_000 picoseconds. + Weight::from_parts(27_413_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -391,8 +389,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 16_065_000 picoseconds. - Weight::from_parts(20_550_000, 3556) + // Minimum execution time: 15_011_000 picoseconds. + Weight::from_parts(16_524_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -404,8 +402,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `4` // Estimated: `3556` - // Minimum execution time: 13_638_000 picoseconds. - Weight::from_parts(16_979_000, 3556) + // Minimum execution time: 14_649_000 picoseconds. + Weight::from_parts(15_439_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -417,8 +415,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 11_383_000 picoseconds. - Weight::from_parts(12_154_000, 3556) + // Minimum execution time: 10_914_000 picoseconds. + Weight::from_parts(11_137_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -432,8 +430,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `106` // Estimated: `3556` - // Minimum execution time: 22_832_000 picoseconds. - Weight::from_parts(30_716_000, 3556) + // Minimum execution time: 22_512_000 picoseconds. + Weight::from_parts(24_376_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -445,8 +443,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_685_000 picoseconds. - Weight::from_parts(12_129_000, 3556) + // Minimum execution time: 10_571_000 picoseconds. + Weight::from_parts(10_855_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -458,8 +456,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `68` // Estimated: `3556` - // Minimum execution time: 10_394_000 picoseconds. - Weight::from_parts(10_951_000, 3556) + // Minimum execution time: 10_312_000 picoseconds. + Weight::from_parts(10_653_000, 3556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -478,10 +476,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0 + n * (227 ±0)` // Estimated: `6012 + n * (2830 ±0)` - // Minimum execution time: 62_203_000 picoseconds. - Weight::from_parts(63_735_000, 6012) - // Standard Error: 59_589 - .saturating_add(Weight::from_parts(59_482_352, 0).saturating_mul(n.into())) + // Minimum execution time: 61_990_000 picoseconds. + Weight::from_parts(62_751_000, 6012) + // Standard Error: 44_079 + .saturating_add(Weight::from_parts(57_343_378, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((3_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes((4_u64).saturating_mul(n.into()))) From 447902eff4a574e66894ad60cb41999b05bf5e84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Thei=C3=9Fen?= Date: Fri, 29 Nov 2024 13:46:31 +0100 Subject: [PATCH 158/166] pallet_revive: Switch to 64bit RISC-V (#6565) This PR updates pallet_revive to the newest PolkaVM version and adapts the test fixtures and syscall interface to work under 64bit. Please note that after this PR no 32bit contracts can be deployed (they will be rejected at deploy time). Pre-deployed 32bit contracts are now considered defunct since we changes how parameters are passed for functions with more than 6 arguments. ## Fixtures The fixtures are now built for the 64bit target. I also removed the temporary directory mechanism that triggered a full rebuild every time. It also makes it easier to find the compiled fixtures since they are now always in `target/pallet-revive-fixtures`. ## Syscall interface ### Passing pointer Registers and pointers are now 64bit wide. This allows us to pass u64 arguments in a single register. Before we needed two registers to pass them. This means that just as before we need one register per pointer we pass. We keep pointers as `u32` argument by truncating the register. This is done since the memory space of PolkaVM is 32bit. ### Functions with more than 6 arguments We only have 6 registers to pass arguments. This is why we pass a pointer to a struct when we need more than 6. Before this PR we expected a packed struct and interpreted it as SCALE encoded tuple. However, this was buggy because the `MaxEncodedLen` returned something that was larger than the packed size of the structure. This wasn't a problem before. But now the memory space changed in a way that things were placed at the edges of the memory space and those extra bytes lead to an out of bound access. This is why this PR drops SCALE and expects the arguments to be passed as a pointer to a `C` aligned struct. This avoids unaligned accesses. However, revive needs to adapt its codegen to properly align the structure fields. ## TODO - [ ] Add multi block migration that wipes all existing contracts as we made breaking changes to the syscall interface --------- Co-authored-by: GitHub Action --- .github/workflows/checks-quick.yml | 1 - Cargo.lock | 72 +++++++------- prdoc/pr_6565.prdoc | 35 +++++++ substrate/frame/revive/Cargo.toml | 2 +- substrate/frame/revive/fixtures/Cargo.toml | 4 +- substrate/frame/revive/fixtures/build.rs | 96 +++++++++++++------ .../build/{Cargo.toml => _Cargo.toml} | 5 +- .../fixtures/build/_rust-toolchain.toml | 4 + .../riscv32emac-unknown-none-polkavm.json | 26 ----- substrate/frame/revive/fixtures/src/lib.rs | 13 +-- substrate/frame/revive/proc-macro/src/lib.rs | 91 ++++++++++-------- substrate/frame/revive/rpc/src/tests.rs | 6 ++ substrate/frame/revive/src/chain_extension.rs | 12 +-- substrate/frame/revive/src/limits.rs | 21 +++- substrate/frame/revive/src/wasm/mod.rs | 20 +++- substrate/frame/revive/src/wasm/runtime.rs | 33 ++----- substrate/frame/revive/uapi/Cargo.toml | 6 +- substrate/frame/revive/uapi/src/host.rs | 4 +- .../uapi/src/host/{riscv32.rs => riscv64.rs} | 86 ++++++++--------- substrate/frame/revive/uapi/src/lib.rs | 6 ++ 20 files changed, 309 insertions(+), 234 deletions(-) create mode 100644 prdoc/pr_6565.prdoc rename substrate/frame/revive/fixtures/build/{Cargo.toml => _Cargo.toml} (80%) create mode 100644 substrate/frame/revive/fixtures/build/_rust-toolchain.toml delete mode 100644 substrate/frame/revive/fixtures/riscv32emac-unknown-none-polkavm.json rename substrate/frame/revive/uapi/src/host/{riscv32.rs => riscv64.rs} (93%) diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index c733a2517cb8..4c26b85a6303 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -97,7 +97,6 @@ jobs: --exclude "substrate/frame/contracts/fixtures/build" "substrate/frame/contracts/fixtures/contracts/common" - "substrate/frame/revive/fixtures/build" "substrate/frame/revive/fixtures/contracts/common" - name: deny git deps run: python3 .github/scripts/deny-git-deps.py . diff --git a/Cargo.lock b/Cargo.lock index 84477cd05416..e1abeea49283 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5975,6 +5975,15 @@ dependencies = [ "dirs-sys-next", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs-sys" version = "0.4.1" @@ -14646,7 +14655,7 @@ dependencies = [ "pallet-utility 28.0.0", "parity-scale-codec", "paste", - "polkavm 0.13.0", + "polkavm 0.17.0", "pretty_assertions", "rlp 0.6.1", "scale-info", @@ -14742,12 +14751,10 @@ dependencies = [ "anyhow", "frame-system 28.0.0", "log", - "parity-wasm", - "polkavm-linker 0.14.0", + "polkavm-linker 0.17.0", "sp-core 28.0.0", "sp-io 30.0.0", "sp-runtime 31.0.1", - "tempfile", "toml 0.8.12", ] @@ -14864,7 +14871,7 @@ dependencies = [ "bitflags 1.3.2", "parity-scale-codec", "paste", - "polkavm-derive 0.14.0", + "polkavm-derive 0.17.0", "scale-info", ] @@ -19699,15 +19706,15 @@ dependencies = [ [[package]] name = "polkavm" -version = "0.13.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57e79a14b15ed38cb5b9a1e38d02e933f19e3d180ae5b325fed606c5e5b9177e" +checksum = "84979be196ba2855f73616413e7b1d18258128aa396b3dc23f520a00a807720e" dependencies = [ "libc", "log", - "polkavm-assembler 0.13.0", - "polkavm-common 0.13.0", - "polkavm-linux-raw 0.13.0", + "polkavm-assembler 0.17.0", + "polkavm-common 0.17.0", + "polkavm-linux-raw 0.17.0", ] [[package]] @@ -19730,9 +19737,9 @@ dependencies = [ [[package]] name = "polkavm-assembler" -version = "0.13.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e8da55465000feb0a61bbf556ed03024db58f3420eca37721fc726b3b2136bf" +checksum = "0ba7b434ff630b0f73a1560e8baea807246ca22098abe49f97821e0e2d2accc4" dependencies = [ "log", ] @@ -19764,20 +19771,14 @@ dependencies = [ [[package]] name = "polkavm-common" -version = "0.13.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "084b4339aae7dfdaaa5aa7d634110afd95970e0737b6fb2a0cb10db8b56b753c" +checksum = "8f0dbafef4ab6ceecb4982ac3b550df430ef4f9fdbf07c108b7d4f91a0682fce" dependencies = [ "log", - "polkavm-assembler 0.13.0", + "polkavm-assembler 0.17.0", ] -[[package]] -name = "polkavm-common" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711952a783e9c5ad407cdacb1ed147f36d37c5d43417c1091d86456d2999417b" - [[package]] name = "polkavm-derive" version = "0.8.0" @@ -19807,11 +19808,11 @@ dependencies = [ [[package]] name = "polkavm-derive" -version = "0.14.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4832a0aebf6cefc988bb7b2d74ea8c86c983164672e2fc96300f356a1babfc1" +checksum = "c0c3dbb6c8c7bd3e5f5b05aa7fc9355acf14df7ce5d392911e77d01090a38d0d" dependencies = [ - "polkavm-derive-impl-macro 0.14.0", + "polkavm-derive-impl-macro 0.17.0", ] [[package]] @@ -19852,11 +19853,11 @@ dependencies = [ [[package]] name = "polkavm-derive-impl" -version = "0.14.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e339fc7c11310fe5adf711d9342278ac44a75c9784947937cce12bd4f30842f2" +checksum = "42565aed4adbc4034612d0b17dea8db3681fb1bd1aed040d6edc5455a9f478a1" dependencies = [ - "polkavm-common 0.14.0", + "polkavm-common 0.17.0", "proc-macro2 1.0.86", "quote 1.0.37", "syn 2.0.87", @@ -19894,11 +19895,11 @@ dependencies = [ [[package]] name = "polkavm-derive-impl-macro" -version = "0.14.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b569754b15060d03000c09e3bf11509d527f60b75d79b4c30c3625b5071d9702" +checksum = "86d9838e95241b0bce4fe269cdd4af96464160505840ed5a8ac8536119ba19e2" dependencies = [ - "polkavm-derive-impl 0.14.0", + "polkavm-derive-impl 0.17.0", "syn 2.0.87", ] @@ -19934,15 +19935,16 @@ dependencies = [ [[package]] name = "polkavm-linker" -version = "0.14.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0959ac3b0f4fd5caf5c245c637705f19493efe83dba31a83bbba928b93b0116a" +checksum = "d359dc721d2cc9b555ebb3558c305112ddc5bdac09d26f95f2f7b49c1f2db7e9" dependencies = [ + "dirs", "gimli 0.31.1", "hashbrown 0.14.5", "log", "object 0.36.1", - "polkavm-common 0.14.0", + "polkavm-common 0.17.0", "regalloc2 0.9.3", "rustc-demangle", ] @@ -19961,9 +19963,9 @@ checksum = "26e45fa59c7e1bb12ef5289080601e9ec9b31435f6e32800a5c90c132453d126" [[package]] name = "polkavm-linux-raw" -version = "0.13.0" +version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "686c4dd9c9c16cc22565b51bdbb269792318d0fd2e6b966b5f6c788534cad0e9" +checksum = "e64c3d93a58ffbc3099d1227f0da9675a025a9ea6c917038f266920c1de1e568" [[package]] name = "polling" diff --git a/prdoc/pr_6565.prdoc b/prdoc/pr_6565.prdoc new file mode 100644 index 000000000000..f9a75a16a6a7 --- /dev/null +++ b/prdoc/pr_6565.prdoc @@ -0,0 +1,35 @@ +title: 'pallet_revive: Switch to 64bit RISC-V' +doc: +- audience: Runtime Dev + description: |- + This PR updates pallet_revive to the newest PolkaVM version and adapts the test fixtures and syscall interface to work under 64bit. + + Please note that after this PR no 32bit contracts can be deployed (they will be rejected at deploy time). Pre-deployed 32bit contracts are now considered defunct since we changes how parameters are passed for functions with more than 6 arguments. + + ## Fixtures + + The fixtures are now built for the 64bit target. I also removed the temporary directory mechanism that triggered a full rebuild every time. It also makes it easier to find the compiled fixtures since they are now always in `target/pallet-revive-fixtures`. + + ## Syscall interface + + ### Passing pointer + + Registers and pointers are now 64bit wide. This allows us to pass u64 arguments in a single register. Before we needed two registers to pass them. This means that just as before we need one register per pointer we pass. We keep pointers as `u32` argument by truncating the register. This is done since the memory space of PolkaVM is 32bit. + + ### Functions with more than 6 arguments + + We only have 6 registers to pass arguments. This is why we pass a pointer to a struct when we need more than 6. Before this PR we expected a packed struct and interpreted it as SCALE encoded tuple. However, this was buggy because the `MaxEncodedLen` returned something that was larger than the packed size of the structure. This wasn't a problem before. But now the memory space changed in a way that things were placed at the edges of the memory space and those extra bytes lead to an out of bound access. + + This is why this PR drops SCALE and expects the arguments to be passed as a pointer to a `C` aligned struct. This avoids unaligned accesses. However, revive needs to adapt its codegen to properly align the structure fields. + + ## TODO + - [ ] Add multi block migration that wipes all existing contracts as we made breaking changes to the syscall interface +crates: +- name: pallet-revive + bump: major +- name: pallet-revive-fixtures + bump: major +- name: pallet-revive-proc-macro + bump: major +- name: pallet-revive-uapi + bump: major diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index 81fbbc8cf38e..677ef0e1367f 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -19,7 +19,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] environmental = { workspace = true } paste = { workspace = true } -polkavm = { version = "0.13.0", default-features = false } +polkavm = { version = "0.17.0", default-features = false } bitflags = { workspace = true } codec = { features = ["derive", "max-encoded-len"], workspace = true } scale-info = { features = ["derive"], workspace = true } diff --git a/substrate/frame/revive/fixtures/Cargo.toml b/substrate/frame/revive/fixtures/Cargo.toml index 7a5452853d65..798ed8c75a5a 100644 --- a/substrate/frame/revive/fixtures/Cargo.toml +++ b/substrate/frame/revive/fixtures/Cargo.toml @@ -18,10 +18,8 @@ anyhow = { workspace = true, default-features = true, optional = true } log = { workspace = true } [build-dependencies] -parity-wasm = { workspace = true } -tempfile = { workspace = true } toml = { workspace = true } -polkavm-linker = { version = "0.14.0" } +polkavm-linker = { version = "0.17.0" } anyhow = { workspace = true, default-features = true } [features] diff --git a/substrate/frame/revive/fixtures/build.rs b/substrate/frame/revive/fixtures/build.rs index 3472e0846efd..46cd5760ca4e 100644 --- a/substrate/frame/revive/fixtures/build.rs +++ b/substrate/frame/revive/fixtures/build.rs @@ -20,7 +20,8 @@ use anyhow::Result; use anyhow::{bail, Context}; use std::{ - cfg, env, fs, + env, fs, + io::Write, path::{Path, PathBuf}, process::Command, }; @@ -82,7 +83,7 @@ fn create_cargo_toml<'a>( entries: impl Iterator, output_dir: &Path, ) -> Result<()> { - let mut cargo_toml: toml::Value = toml::from_str(include_str!("./build/Cargo.toml"))?; + let mut cargo_toml: toml::Value = toml::from_str(include_str!("./build/_Cargo.toml"))?; let mut set_dep = |name, path| -> Result<()> { cargo_toml["dependencies"][name]["path"] = toml::Value::String( fixtures_dir.join(path).canonicalize()?.to_str().unwrap().to_string(), @@ -108,21 +109,24 @@ fn create_cargo_toml<'a>( let cargo_toml = toml::to_string_pretty(&cargo_toml)?; fs::write(output_dir.join("Cargo.toml"), cargo_toml.clone()) .with_context(|| format!("Failed to write {cargo_toml:?}"))?; + fs::copy( + fixtures_dir.join("build/_rust-toolchain.toml"), + output_dir.join("rust-toolchain.toml"), + ) + .context("Failed to write toolchain file")?; Ok(()) } -fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { +fn invoke_build(current_dir: &Path) -> Result<()> { let encoded_rustflags = ["-Dwarnings"].join("\x1f"); - let mut build_command = Command::new(env::var("CARGO")?); + let mut build_command = Command::new("cargo"); build_command .current_dir(current_dir) .env_clear() .env("PATH", env::var("PATH").unwrap_or_default()) .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) - .env("RUSTC_BOOTSTRAP", "1") .env("RUSTUP_HOME", env::var("RUSTUP_HOME").unwrap_or_default()) - .env("RUSTUP_TOOLCHAIN", env::var("RUSTUP_TOOLCHAIN").unwrap_or_default()) .args([ "build", "--release", @@ -130,7 +134,7 @@ fn invoke_build(target: &Path, current_dir: &Path) -> Result<()> { "-Zbuild-std-features=panic_immediate_abort", ]) .arg("--target") - .arg(target); + .arg(polkavm_linker::target_json_64_path().unwrap()); if let Ok(toolchain) = env::var(OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR) { build_command.env("RUSTUP_TOOLCHAIN", &toolchain); @@ -168,7 +172,7 @@ fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result for entry in entries { post_process( &build_dir - .join("target/riscv32emac-unknown-none-polkavm/release") + .join("target/riscv64emac-unknown-none-polkavm/release") .join(entry.name()), &out_dir.join(entry.out_filename()), )?; @@ -177,11 +181,61 @@ fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result Ok(()) } +/// Create a directory in the `target` as output directory +fn create_out_dir() -> Result { + let temp_dir: PathBuf = env::var("OUT_DIR")?.into(); + + // this is set in case the user has overriden the target directory + let out_dir = if let Ok(path) = env::var("CARGO_TARGET_DIR") { + path.into() + } else { + // otherwise just traverse up from the out dir + let mut out_dir: PathBuf = temp_dir.clone(); + loop { + if !out_dir.pop() { + bail!("Cannot find project root.") + } + if out_dir.join("Cargo.lock").exists() { + break; + } + } + out_dir.join("target") + } + .join("pallet-revive-fixtures"); + + // clean up some leftover symlink from previous versions of this script + if out_dir.exists() && !out_dir.is_dir() { + fs::remove_file(&out_dir)?; + } + fs::create_dir_all(&out_dir).context("Failed to create output directory")?; + + // write the location of the out dir so it can be found later + let mut file = fs::File::create(temp_dir.join("fixture_location.rs")) + .context("Failed to create fixture_location.rs")?; + write!( + file, + r#" + #[allow(dead_code)] + const FIXTURE_DIR: &str = "{0}"; + macro_rules! fixture {{ + ($name: literal) => {{ + include_bytes!(concat!("{0}", "/", $name, ".polkavm")) + }}; + }} + "#, + out_dir.display() + ) + .context("Failed to write to fixture_location.rs")?; + + Ok(out_dir) +} + pub fn main() -> Result<()> { let fixtures_dir: PathBuf = env::var("CARGO_MANIFEST_DIR")?.into(); let contracts_dir = fixtures_dir.join("contracts"); - let out_dir: PathBuf = env::var("OUT_DIR")?.into(); - let target = fixtures_dir.join("riscv32emac-unknown-none-polkavm.json"); + let out_dir = create_out_dir().context("Cannot determine output directory")?; + let build_dir = out_dir.join("build"); + fs::create_dir_all(&build_dir).context("Failed to create build directory")?; println!("cargo::rerun-if-env-changed={OVERRIDE_RUSTUP_TOOLCHAIN_ENV_VAR}"); println!("cargo::rerun-if-env-changed={OVERRIDE_STRIP_ENV_VAR}"); @@ -199,25 +253,9 @@ pub fn main() -> Result<()> { return Ok(()) } - let tmp_dir = tempfile::tempdir()?; - let tmp_dir_path = tmp_dir.path(); - - create_cargo_toml(&fixtures_dir, entries.iter(), tmp_dir.path())?; - invoke_build(&target, tmp_dir_path)?; - - write_output(tmp_dir_path, &out_dir, entries)?; - - #[cfg(unix)] - if let Ok(symlink_dir) = env::var("CARGO_WORKSPACE_ROOT_DIR") { - let symlink_dir: PathBuf = symlink_dir.into(); - let symlink_dir: PathBuf = symlink_dir.join("target").join("pallet-revive-fixtures"); - if symlink_dir.is_symlink() { - fs::remove_file(&symlink_dir) - .with_context(|| format!("Failed to remove_file {symlink_dir:?}"))?; - } - std::os::unix::fs::symlink(&out_dir, &symlink_dir) - .with_context(|| format!("Failed to symlink {out_dir:?} -> {symlink_dir:?}"))?; - } + create_cargo_toml(&fixtures_dir, entries.iter(), &build_dir)?; + invoke_build(&build_dir)?; + write_output(&build_dir, &out_dir, entries)?; Ok(()) } diff --git a/substrate/frame/revive/fixtures/build/Cargo.toml b/substrate/frame/revive/fixtures/build/_Cargo.toml similarity index 80% rename from substrate/frame/revive/fixtures/build/Cargo.toml rename to substrate/frame/revive/fixtures/build/_Cargo.toml index 5d0e256e2e73..beaabd83403e 100644 --- a/substrate/frame/revive/fixtures/build/Cargo.toml +++ b/substrate/frame/revive/fixtures/build/_Cargo.toml @@ -4,6 +4,9 @@ publish = false version = "1.0.0" edition = "2021" +# Make sure this is not included into the workspace +[workspace] + # Binary targets are injected dynamically by the build script. [[bin]] @@ -11,7 +14,7 @@ edition = "2021" [dependencies] uapi = { package = 'pallet-revive-uapi', path = "", default-features = false } common = { package = 'pallet-revive-fixtures-common', path = "" } -polkavm-derive = { version = "0.14.0" } +polkavm-derive = { version = "0.17.0" } [profile.release] opt-level = 3 diff --git a/substrate/frame/revive/fixtures/build/_rust-toolchain.toml b/substrate/frame/revive/fixtures/build/_rust-toolchain.toml new file mode 100644 index 000000000000..4c757c708d58 --- /dev/null +++ b/substrate/frame/revive/fixtures/build/_rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "nightly-2024-11-19" +components = ["rust-src"] +profile = "minimal" diff --git a/substrate/frame/revive/fixtures/riscv32emac-unknown-none-polkavm.json b/substrate/frame/revive/fixtures/riscv32emac-unknown-none-polkavm.json deleted file mode 100644 index bbd54cdefbac..000000000000 --- a/substrate/frame/revive/fixtures/riscv32emac-unknown-none-polkavm.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "arch": "riscv32", - "cpu": "generic-rv32", - "crt-objects-fallback": "false", - "data-layout": "e-m:e-p:32:32-i64:64-n32-S32", - "eh-frame-header": false, - "emit-debug-gdb-scripts": false, - "features": "+e,+m,+a,+c,+lui-addi-fusion,+fast-unaligned-access,+xtheadcondmov", - "linker": "rust-lld", - "linker-flavor": "ld.lld", - "llvm-abiname": "ilp32e", - "llvm-target": "riscv32", - "max-atomic-width": 32, - "panic-strategy": "abort", - "relocation-model": "pie", - "target-pointer-width": "32", - "singlethread": true, - "pre-link-args": { - "ld": [ - "--emit-relocs", - "--unique", - "--relocatable" - ] - }, - "env": "polkavm" -} diff --git a/substrate/frame/revive/fixtures/src/lib.rs b/substrate/frame/revive/fixtures/src/lib.rs index cc84daec9b59..24f6ee547dc7 100644 --- a/substrate/frame/revive/fixtures/src/lib.rs +++ b/substrate/frame/revive/fixtures/src/lib.rs @@ -19,10 +19,13 @@ extern crate alloc; +// generated file that tells us where to find the fixtures +include!(concat!(env!("OUT_DIR"), "/fixture_location.rs")); + /// Load a given wasm module and returns a wasm binary contents along with it's hash. #[cfg(feature = "std")] pub fn compile_module(fixture_name: &str) -> anyhow::Result<(Vec, sp_core::H256)> { - let out_dir: std::path::PathBuf = env!("OUT_DIR").into(); + let out_dir: std::path::PathBuf = FIXTURE_DIR.into(); let fixture_path = out_dir.join(format!("{fixture_name}.polkavm")); log::debug!("Loading fixture from {fixture_path:?}"); let binary = std::fs::read(fixture_path)?; @@ -36,12 +39,6 @@ pub fn compile_module(fixture_name: &str) -> anyhow::Result<(Vec, sp_core::H /// available in no-std environments (runtime benchmarks). pub mod bench { use alloc::vec::Vec; - - macro_rules! fixture { - ($name: literal) => { - include_bytes!(concat!(env!("OUT_DIR"), "/", $name, ".polkavm")) - }; - } pub const DUMMY: &[u8] = fixture!("dummy"); pub const NOOP: &[u8] = fixture!("noop"); pub const INSTR: &[u8] = fixture!("instr_benchmark"); @@ -61,7 +58,7 @@ pub mod bench { mod test { #[test] fn out_dir_should_have_compiled_mocks() { - let out_dir: std::path::PathBuf = env!("OUT_DIR").into(); + let out_dir: std::path::PathBuf = crate::FIXTURE_DIR.into(); assert!(out_dir.join("dummy.polkavm").exists()); } } diff --git a/substrate/frame/revive/proc-macro/src/lib.rs b/substrate/frame/revive/proc-macro/src/lib.rs index 7232c6342824..6814add128d9 100644 --- a/substrate/frame/revive/proc-macro/src/lib.rs +++ b/substrate/frame/revive/proc-macro/src/lib.rs @@ -79,6 +79,7 @@ use syn::{parse_quote, punctuated::Punctuated, spanned::Spanned, token::Comma, F /// - `Result<(), TrapReason>`, /// - `Result`, /// - `Result`. +/// - `Result`. /// /// The macro expands to `pub struct Env` declaration, with the following traits implementations: /// - `pallet_revive::wasm::Environment> where E: Ext` @@ -127,6 +128,7 @@ struct HostFn { enum HostFnReturn { Unit, U32, + U64, ReturnCode, } @@ -134,8 +136,7 @@ impl HostFnReturn { fn map_output(&self) -> TokenStream2 { match self { Self::Unit => quote! { |_| None }, - Self::U32 => quote! { |ret_val| Some(ret_val) }, - Self::ReturnCode => quote! { |ret_code| Some(ret_code.into()) }, + _ => quote! { |ret_val| Some(ret_val.into()) }, } } @@ -143,6 +144,7 @@ impl HostFnReturn { match self { Self::Unit => syn::ReturnType::Default, Self::U32 => parse_quote! { -> u32 }, + Self::U64 => parse_quote! { -> u64 }, Self::ReturnCode => parse_quote! { -> ReturnErrorCode }, } } @@ -243,7 +245,8 @@ impl HostFn { let msg = r#"Should return one of the following: - Result<(), TrapReason>, - Result, - - Result"#; + - Result, + - Result"#; let ret_ty = match item.clone().sig.output { syn::ReturnType::Type(_, ty) => Ok(ty.clone()), _ => Err(err(span, &msg)), @@ -305,6 +308,7 @@ impl HostFn { let returns = match ok_ty_str.as_str() { "()" => Ok(HostFnReturn::Unit), "u32" => Ok(HostFnReturn::U32), + "u64" => Ok(HostFnReturn::U64), "ReturnErrorCode" => Ok(HostFnReturn::ReturnCode), _ => Err(err(arg1.span(), &msg)), }?; @@ -339,50 +343,61 @@ where P: Iterator> + Clone, I: Iterator> + Clone, { - const ALLOWED_REGISTERS: u32 = 6; - let mut registers_used = 0; - let mut bindings = vec![]; - let mut idx = 0; - for (name, ty) in param_names.clone().zip(param_types.clone()) { + const ALLOWED_REGISTERS: usize = 6; + + // all of them take one register but we truncate them before passing into the function + // it is important to not allow any type which has illegal bit patterns like 'bool' + if !param_types.clone().all(|ty| { let syn::Type::Path(path) = &**ty else { panic!("Type needs to be path"); }; let Some(ident) = path.path.get_ident() else { panic!("Type needs to be ident"); }; - let size = if ident == "i8" || - ident == "i16" || - ident == "i32" || - ident == "u8" || - ident == "u16" || - ident == "u32" - { - 1 - } else if ident == "i64" || ident == "u64" { - 2 - } else { - panic!("Pass by value only supports primitives"); - }; - registers_used += size; - if registers_used > ALLOWED_REGISTERS { - return quote! { - let (#( #param_names, )*): (#( #param_types, )*) = memory.read_as(__a0__)?; - } - } - let this_reg = quote::format_ident!("__a{}__", idx); - let next_reg = quote::format_ident!("__a{}__", idx + 1); - let binding = if size == 1 { + matches!(ident.to_string().as_ref(), "u8" | "u16" | "u32" | "u64") + }) { + panic!("Only primitive unsigned integers are allowed as arguments to syscalls"); + } + + // too many arguments: pass as pointer to a struct in memory + if param_names.clone().count() > ALLOWED_REGISTERS { + let fields = param_names.clone().zip(param_types.clone()).map(|(name, ty)| { quote! { - let #name = #this_reg as #ty; + #name: #ty, } - } else { - quote! { - let #name = (#this_reg as #ty) | ((#next_reg as #ty) << 32); + }); + return quote! { + #[derive(Default)] + #[repr(C)] + struct Args { + #(#fields)* } - }; - bindings.push(binding); - idx += size; + let Args { #(#param_names,)* } = { + let len = ::core::mem::size_of::(); + let mut args = Args::default(); + let ptr = &mut args as *mut Args as *mut u8; + // Safety + // 1. The struct is initialized at all times. + // 2. We only allow primitive integers (no bools) as arguments so every bit pattern is safe. + // 3. The reference doesn't outlive the args field. + // 4. There is only the single reference to the args field. + // 5. The length of the generated slice is the same as the struct. + let reference = unsafe { + ::core::slice::from_raw_parts_mut(ptr, len) + }; + memory.read_into_buf(__a0__ as _, reference)?; + args + }; + } } + + // otherwise: one argument per register + let bindings = param_names.zip(param_types).enumerate().map(|(idx, (name, ty))| { + let reg = quote::format_ident!("__a{}__", idx); + quote! { + let #name = #reg as #ty; + } + }); quote! { #( #bindings )* } @@ -409,7 +424,7 @@ fn expand_env(def: &EnvDef) -> TokenStream2 { memory: &mut M, __syscall_symbol__: &[u8], __available_api_version__: ApiVersion, - ) -> Result, TrapReason> + ) -> Result, TrapReason> { #impls } diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 7734c8c57209..920318b26f71 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -218,6 +218,8 @@ async fn deploy_and_call() -> anyhow::Result<()> { Ok(()) } +/// TODO: enable ( https://github.com/paritytech/contract-issues/issues/12 ) +#[ignore] #[tokio::test] async fn revert_call() -> anyhow::Result<()> { let _lock = SHARED_RESOURCES.write(); @@ -240,6 +242,8 @@ async fn revert_call() -> anyhow::Result<()> { Ok(()) } +/// TODO: enable ( https://github.com/paritytech/contract-issues/issues/12 ) +#[ignore] #[tokio::test] async fn event_logs() -> anyhow::Result<()> { let _lock = SHARED_RESOURCES.write(); @@ -279,6 +283,8 @@ async fn invalid_transaction() -> anyhow::Result<()> { Ok(()) } +/// TODO: enable ( https://github.com/paritytech/contract-issues/issues/12 ) +#[ignore] #[tokio::test] async fn native_evm_ratio_works() -> anyhow::Result<()> { let _lock = SHARED_RESOURCES.write(); diff --git a/substrate/frame/revive/src/chain_extension.rs b/substrate/frame/revive/src/chain_extension.rs index ccea12945054..5b3e886a5628 100644 --- a/substrate/frame/revive/src/chain_extension.rs +++ b/substrate/frame/revive/src/chain_extension.rs @@ -75,7 +75,7 @@ use crate::{ Error, }; use alloc::vec::Vec; -use codec::{Decode, MaxEncodedLen}; +use codec::Decode; use frame_support::weights::Weight; use sp_runtime::DispatchError; @@ -304,16 +304,6 @@ impl<'a, 'b, E: Ext, M: ?Sized + Memory> Environment<'a, 'b, E, M> { Ok(()) } - /// Reads and decodes a type with a size fixed at compile time from contract memory. - /// - /// This function is secure and recommended for all input types of fixed size - /// as long as the cost of reading the memory is included in the overall already charged - /// weight of the chain extension. This should usually be the case when fixed input types - /// are used. - pub fn read_as(&mut self) -> Result { - self.memory.read_as(self.input_ptr) - } - /// Reads and decodes a type with a dynamic size from contract memory. /// /// Make sure to include `len` in your weight calculations. diff --git a/substrate/frame/revive/src/limits.rs b/substrate/frame/revive/src/limits.rs index 64e66382b9ab..5ce96f59c14d 100644 --- a/substrate/frame/revive/src/limits.rs +++ b/substrate/frame/revive/src/limits.rs @@ -129,23 +129,36 @@ pub mod code { Error::::CodeRejected })?; + if !program.is_64_bit() { + log::debug!(target: LOG_TARGET, "32bit programs are not supported."); + Err(Error::::CodeRejected)?; + } + // This scans the whole program but we only do it once on code deployment. // It is safe to do unchecked math in u32 because the size of the program // was already checked above. - use polkavm::program::ISA32_V1_NoSbrk as ISA; + use polkavm::program::ISA64_V1 as ISA; let mut num_instructions: u32 = 0; let mut max_basic_block_size: u32 = 0; let mut basic_block_size: u32 = 0; for inst in program.instructions(ISA) { + use polkavm::program::Instruction; num_instructions += 1; basic_block_size += 1; if inst.kind.opcode().starts_new_basic_block() { max_basic_block_size = max_basic_block_size.max(basic_block_size); basic_block_size = 0; } - if matches!(inst.kind, polkavm::program::Instruction::invalid) { - log::debug!(target: LOG_TARGET, "invalid instruction at offset {}", inst.offset); - return Err(>::InvalidInstruction.into()) + match inst.kind { + Instruction::invalid => { + log::debug!(target: LOG_TARGET, "invalid instruction at offset {}", inst.offset); + return Err(>::InvalidInstruction.into()) + }, + Instruction::sbrk(_, _) => { + log::debug!(target: LOG_TARGET, "sbrk instruction is not allowed. offset {}", inst.offset); + return Err(>::InvalidInstruction.into()) + }, + _ => (), } } diff --git a/substrate/frame/revive/src/wasm/mod.rs b/substrate/frame/revive/src/wasm/mod.rs index f10c4f5fddf8..d87ec7112286 100644 --- a/substrate/frame/revive/src/wasm/mod.rs +++ b/substrate/frame/revive/src/wasm/mod.rs @@ -293,8 +293,15 @@ impl WasmBlob { ) -> Result, ExecError> { let mut config = polkavm::Config::default(); config.set_backend(Some(polkavm::BackendKind::Interpreter)); - let engine = - polkavm::Engine::new(&config).expect("interpreter is available on all plattforms; qed"); + config.set_cache_enabled(false); + #[cfg(feature = "std")] + if std::env::var_os("REVIVE_USE_COMPILER").is_some() { + config.set_backend(Some(polkavm::BackendKind::Compiler)); + } + let engine = polkavm::Engine::new(&config).expect( + "on-chain (no_std) use of interpreter is hard coded. + interpreter is available on all plattforms; qed", + ); let mut module_config = polkavm::ModuleConfig::new(); module_config.set_page_size(limits::PAGE_SIZE); @@ -306,6 +313,15 @@ impl WasmBlob { Error::::CodeRejected })?; + // This is checked at deploy time but we also want to reject pre-existing + // 32bit programs. + // TODO: Remove when we reset the test net. + // https://github.com/paritytech/contract-issues/issues/11 + if !module.is_64_bit() { + log::debug!(target: LOG_TARGET, "32bit programs are not supported."); + Err(Error::::CodeRejected)?; + } + let entry_program_counter = module .exports() .find(|export| export.symbol().as_bytes() == entry_point.identifier().as_bytes()) diff --git a/substrate/frame/revive/src/wasm/runtime.rs b/substrate/frame/revive/src/wasm/runtime.rs index 3e2c83db1ebd..7ea518081e23 100644 --- a/substrate/frame/revive/src/wasm/runtime.rs +++ b/substrate/frame/revive/src/wasm/runtime.rs @@ -27,7 +27,7 @@ use crate::{ Config, Error, LOG_TARGET, SENTINEL, }; use alloc::{boxed::Box, vec, vec::Vec}; -use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; +use codec::{Decode, DecodeLimit, Encode}; use core::{fmt, marker::PhantomData, mem}; use frame_support::{ dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, @@ -126,34 +126,13 @@ pub trait Memory { /// /// # Note /// - /// There must be an extra benchmark for determining the influence of `len` with - /// regard to the overall weight. + /// 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) } - - /// Reads and decodes a type with a size fixed at compile time from contract memory. - /// - /// # Only use on fixed size types - /// - /// Don't use this for types where the encoded size is not fixed but merely bounded. Otherwise - /// this implementation will out of bound access the buffer declared by the guest. Some examples - /// of those bounded but not fixed types: Enums with data, `BoundedVec` or any compact encoded - /// integer. - /// - /// # Note - /// - /// The weight of reading a fixed value is included in the overall weight of any - /// contract callable function. - fn read_as(&self, ptr: u32) -> Result { - let buf = self.read(ptr, D::max_encoded_len() as u32)?; - let decoded = D::decode_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. @@ -164,8 +143,8 @@ pub trait Memory { pub trait PolkaVmInstance: Memory { fn gas(&self) -> polkavm::Gas; fn set_gas(&mut self, gas: polkavm::Gas); - fn read_input_regs(&self) -> (u32, u32, u32, u32, u32, u32); - fn write_output(&mut self, output: u32); + fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64); + fn write_output(&mut self, output: u64); } // Memory implementation used in benchmarking where guest memory is mapped into the host. @@ -214,7 +193,7 @@ impl PolkaVmInstance for polkavm::RawInstance { self.set_gas(gas) } - fn read_input_regs(&self) -> (u32, u32, u32, u32, u32, u32) { + fn read_input_regs(&self) -> (u64, u64, u64, u64, u64, u64) { ( self.reg(polkavm::Reg::A0), self.reg(polkavm::Reg::A1), @@ -225,7 +204,7 @@ impl PolkaVmInstance for polkavm::RawInstance { ) } - fn write_output(&mut self, output: u32) { + fn write_output(&mut self, output: u64) { self.set_reg(polkavm::Reg::A0, output); } } diff --git a/substrate/frame/revive/uapi/Cargo.toml b/substrate/frame/revive/uapi/Cargo.toml index 0c7461a35d69..b55391dd5d6c 100644 --- a/substrate/frame/revive/uapi/Cargo.toml +++ b/substrate/frame/revive/uapi/Cargo.toml @@ -20,11 +20,11 @@ codec = { features = [ "max-encoded-len", ], optional = true, workspace = true } -[target.'cfg(target_arch = "riscv32")'.dependencies] -polkavm-derive = { version = "0.14.0" } +[target.'cfg(target_arch = "riscv64")'.dependencies] +polkavm-derive = { version = "0.17.0" } [package.metadata.docs.rs] -default-target = ["wasm32-unknown-unknown"] +default-target = ["riscv64imac-unknown-none-elf"] [features] default = ["scale"] diff --git a/substrate/frame/revive/uapi/src/host.rs b/substrate/frame/revive/uapi/src/host.rs index 6b3a8b07f040..d3fd4ac8d03e 100644 --- a/substrate/frame/revive/uapi/src/host.rs +++ b/substrate/frame/revive/uapi/src/host.rs @@ -14,8 +14,8 @@ use crate::{CallFlags, Result, ReturnFlags, StorageFlags}; use paste::paste; -#[cfg(target_arch = "riscv32")] -mod riscv32; +#[cfg(target_arch = "riscv64")] +mod riscv64; macro_rules! hash_fn { ( $name:ident, $bytes:literal ) => { diff --git a/substrate/frame/revive/uapi/src/host/riscv32.rs b/substrate/frame/revive/uapi/src/host/riscv64.rs similarity index 93% rename from substrate/frame/revive/uapi/src/host/riscv32.rs rename to substrate/frame/revive/uapi/src/host/riscv64.rs index e8b27057ed18..3cba14db6a04 100644 --- a/substrate/frame/revive/uapi/src/host/riscv32.rs +++ b/substrate/frame/revive/uapi/src/host/riscv64.rs @@ -26,10 +26,10 @@ mod sys { mod abi {} impl abi::FromHost for ReturnCode { - type Regs = (u32,); + type Regs = (u64,); fn from_host((a0,): Self::Regs) -> Self { - ReturnCode(a0) + ReturnCode(a0 as _) } } @@ -207,33 +207,33 @@ impl HostFn for HostFnImpl { let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); let deposit_limit_ptr = ptr_or_sentinel(&deposit_limit); let salt_ptr = ptr_or_sentinel(&salt); - #[repr(packed)] + #[repr(C)] #[allow(dead_code)] struct Args { - code_hash: *const u8, + code_hash: u32, ref_time_limit: u64, proof_size_limit: u64, - deposit_limit: *const u8, - value: *const u8, - input: *const u8, + deposit_limit: u32, + value: u32, + input: u32, input_len: u32, - address: *const u8, - output: *mut u8, - output_len: *mut u32, - salt: *const u8, + address: u32, + output: u32, + output_len: u32, + salt: u32, } let args = Args { - code_hash: code_hash.as_ptr(), + code_hash: code_hash.as_ptr() as _, ref_time_limit, proof_size_limit, - deposit_limit: deposit_limit_ptr, - value: value.as_ptr(), - input: input.as_ptr(), + deposit_limit: deposit_limit_ptr as _, + value: value.as_ptr() as _, + input: input.as_ptr() as _, input_len: input.len() as _, - address, - output: output_ptr, - output_len: &mut output_len as *mut _, - salt: salt_ptr, + address: address as _, + output: output_ptr as _, + output_len: &mut output_len as *mut _ as _, + salt: salt_ptr as _, }; let ret_code = { unsafe { sys::instantiate(&args as *const Args as *const _) } }; @@ -257,31 +257,31 @@ impl HostFn for HostFnImpl { ) -> Result { let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); let deposit_limit_ptr = ptr_or_sentinel(&deposit_limit); - #[repr(packed)] + #[repr(C)] #[allow(dead_code)] struct Args { flags: u32, - callee: *const u8, + callee: u32, ref_time_limit: u64, proof_size_limit: u64, - deposit_limit: *const u8, - value: *const u8, - input: *const u8, + deposit_limit: u32, + value: u32, + input: u32, input_len: u32, - output: *mut u8, - output_len: *mut u32, + output: u32, + output_len: u32, } let args = Args { flags: flags.bits(), - callee: callee.as_ptr(), + callee: callee.as_ptr() as _, ref_time_limit, proof_size_limit, - deposit_limit: deposit_limit_ptr, - value: value.as_ptr(), - input: input.as_ptr(), + deposit_limit: deposit_limit_ptr as _, + value: value.as_ptr() as _, + input: input.as_ptr() as _, input_len: input.len() as _, - output: output_ptr, - output_len: &mut output_len as *mut _, + output: output_ptr as _, + output_len: &mut output_len as *mut _ as _, }; let ret_code = { unsafe { sys::call(&args as *const Args as *const _) } }; @@ -308,29 +308,29 @@ impl HostFn for HostFnImpl { ) -> Result { let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); let deposit_limit_ptr = ptr_or_sentinel(&deposit_limit); - #[repr(packed)] + #[repr(C)] #[allow(dead_code)] struct Args { flags: u32, - address: *const u8, + address: u32, ref_time_limit: u64, proof_size_limit: u64, - deposit_limit: *const u8, - input: *const u8, + deposit_limit: u32, + input: u32, input_len: u32, - output: *mut u8, - output_len: *mut u32, + output: u32, + output_len: u32, } let args = Args { flags: flags.bits(), - address: address.as_ptr(), + address: address.as_ptr() as _, ref_time_limit, proof_size_limit, - deposit_limit: deposit_limit_ptr, - input: input.as_ptr(), + deposit_limit: deposit_limit_ptr as _, + input: input.as_ptr() as _, input_len: input.len() as _, - output: output_ptr, - output_len: &mut output_len as *mut _, + output: output_ptr as _, + output_len: &mut output_len as *mut _ as _, }; let ret_code = { unsafe { sys::delegate_call(&args as *const Args as *const _) } }; diff --git a/substrate/frame/revive/uapi/src/lib.rs b/substrate/frame/revive/uapi/src/lib.rs index e660ce36ef75..91c2543bb719 100644 --- a/substrate/frame/revive/uapi/src/lib.rs +++ b/substrate/frame/revive/uapi/src/lib.rs @@ -65,6 +65,12 @@ impl From for u32 { } } +impl From for u64 { + fn from(error: ReturnErrorCode) -> Self { + u32::from(error).into() + } +} + define_error_codes! { /// The called function trapped and has its state changes reverted. /// In this case no output buffer is returned. From 1e89a311471eba937a9552d7d1f55af1661feb08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bastian=20K=C3=B6cher?= Date: Fri, 29 Nov 2024 14:09:49 +0100 Subject: [PATCH 159/166] Fix runtime api impl detection by construct runtime (#6665) Construct runtime uses autoref-based specialization to fetch the metadata about the implemented runtime apis. This is done to not fail to compile when there are no runtime apis implemented. However, there was an issue with detecting runtime apis when they were implemented in a different file. The problem is solved by moving the trait implemented by `impl_runtime_apis!` to the metadata ir crate. Closes: https://github.com/paritytech/polkadot-sdk/issues/6659 --------- Co-authored-by: GitHub Action --- Cargo.lock | 1 + prdoc/pr_6665.prdoc | 15 ++++++ .../src/construct_runtime/expand/metadata.rs | 2 + .../procedural/src/construct_runtime/mod.rs | 3 +- .../support/test/tests/runtime_metadata.rs | 49 ++++++++++--------- .../api/proc-macro/src/runtime_metadata.rs | 6 +-- substrate/primitives/api/test/Cargo.toml | 3 +- .../api/test/tests/decl_and_impl.rs | 2 + substrate/primitives/metadata-ir/src/lib.rs | 10 ++++ 9 files changed, 62 insertions(+), 29 deletions(-) create mode 100644 prdoc/pr_6665.prdoc diff --git a/Cargo.lock b/Cargo.lock index e1abeea49283..5e4e9c267b08 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25548,6 +25548,7 @@ dependencies = [ "sp-api 26.0.0", "sp-consensus", "sp-core 28.0.0", + "sp-metadata-ir 0.6.0", "sp-runtime 31.0.1", "sp-state-machine 0.35.0", "sp-tracing 16.0.0", diff --git a/prdoc/pr_6665.prdoc b/prdoc/pr_6665.prdoc new file mode 100644 index 000000000000..b5aaf8a3b184 --- /dev/null +++ b/prdoc/pr_6665.prdoc @@ -0,0 +1,15 @@ +title: Fix runtime api impl detection by construct runtime +doc: +- audience: Runtime Dev + description: |- + Construct runtime uses autoref-based specialization to fetch the metadata about the implemented runtime apis. This is done to not fail to compile when there are no runtime apis implemented. However, there was an issue with detecting runtime apis when they were implemented in a different file. The problem is solved by moving the trait implemented by `impl_runtime_apis!` to the metadata ir crate. + + + Closes: https://github.com/paritytech/polkadot-sdk/issues/6659 +crates: +- name: frame-support-procedural + bump: patch +- name: sp-api-proc-macro + bump: patch +- name: sp-metadata-ir + bump: patch diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs index 4590a3a7f490..0b3bd5168865 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs @@ -113,6 +113,8 @@ pub fn expand_runtime_metadata( <#extrinsic as #scrate::traits::SignedTransactionBuilder>::Extension >(); + use #scrate::__private::metadata_ir::InternalImplRuntimeApis; + #scrate::__private::metadata_ir::MetadataIR { pallets: #scrate::__private::vec![ #(#pallets),* ], extrinsic: #scrate::__private::metadata_ir::ExtrinsicMetadataIR { diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 17042c248780..087faf37252d 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -466,7 +466,6 @@ fn construct_runtime_final_expansion( // Therefore, the `Deref` trait will resolve the `runtime_metadata` from `impl_runtime_apis!` // when both macros are called; and will resolve an empty `runtime_metadata` when only the `construct_runtime!` // is called. - #[doc(hidden)] trait InternalConstructRuntime { #[inline(always)] @@ -477,6 +476,8 @@ fn construct_runtime_final_expansion( #[doc(hidden)] impl InternalConstructRuntime for &#name {} + use #scrate::__private::metadata_ir::InternalImplRuntimeApis; + #outer_event #outer_error diff --git a/substrate/frame/support/test/tests/runtime_metadata.rs b/substrate/frame/support/test/tests/runtime_metadata.rs index 7523a415d458..a098643abb91 100644 --- a/substrate/frame/support/test/tests/runtime_metadata.rs +++ b/substrate/frame/support/test/tests/runtime_metadata.rs @@ -80,34 +80,39 @@ sp_api::decl_runtime_apis! { } } -sp_api::impl_runtime_apis! { - impl self::Api for Runtime { - fn test(_data: u64) { - unimplemented!() - } +// Module to emulate having the implementation in a different file. +mod apis { + use super::{Block, BlockT, Runtime}; - fn something_with_block(_: Block) -> Block { - unimplemented!() - } + sp_api::impl_runtime_apis! { + impl crate::Api for Runtime { + fn test(_data: u64) { + unimplemented!() + } - fn function_with_two_args(_: u64, _: Block) { - unimplemented!() - } + fn something_with_block(_: Block) -> Block { + unimplemented!() + } - fn same_name() {} + fn function_with_two_args(_: u64, _: Block) { + unimplemented!() + } - fn wild_card(_: u32) {} - } + fn same_name() {} - impl sp_api::Core for Runtime { - fn version() -> sp_version::RuntimeVersion { - unimplemented!() - } - fn execute_block(_: Block) { - unimplemented!() + fn wild_card(_: u32) {} } - fn initialize_block(_: &::Header) -> sp_runtime::ExtrinsicInclusionMode { - unimplemented!() + + impl sp_api::Core for Runtime { + fn version() -> sp_version::RuntimeVersion { + unimplemented!() + } + fn execute_block(_: Block) { + unimplemented!() + } + fn initialize_block(_: &::Header) -> sp_runtime::ExtrinsicInclusionMode { + unimplemented!() + } } } } diff --git a/substrate/primitives/api/proc-macro/src/runtime_metadata.rs b/substrate/primitives/api/proc-macro/src/runtime_metadata.rs index 6be396339259..1706f8ca6fbb 100644 --- a/substrate/primitives/api/proc-macro/src/runtime_metadata.rs +++ b/substrate/primitives/api/proc-macro/src/runtime_metadata.rs @@ -298,18 +298,14 @@ pub fn generate_impl_runtime_metadata(impls: &[ItemImpl]) -> Result #crate_::vec::Vec<#crate_::metadata_ir::RuntimeApiMetadataIR> { #crate_::vec![ #( #metadata, )* ] } } - #[doc(hidden)] - impl InternalImplRuntimeApis for #runtime_name {} } )) } diff --git a/substrate/primitives/api/test/Cargo.toml b/substrate/primitives/api/test/Cargo.toml index 1d21f23eb804..27f6dafa24bf 100644 --- a/substrate/primitives/api/test/Cargo.toml +++ b/substrate/primitives/api/test/Cargo.toml @@ -21,6 +21,7 @@ sp-version = { workspace = true, default-features = true } sp-tracing = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } sp-consensus = { workspace = true, default-features = true } +sp-metadata-ir = { workspace = true, default-features = true } sc-block-builder = { workspace = true, default-features = true } codec = { workspace = true, default-features = true } sp-state-machine = { workspace = true, default-features = true } @@ -40,5 +41,5 @@ name = "bench" harness = false [features] -"enable-staging-api" = [] +enable-staging-api = [] disable-ui-tests = [] diff --git a/substrate/primitives/api/test/tests/decl_and_impl.rs b/substrate/primitives/api/test/tests/decl_and_impl.rs index 890cf6eccdbc..2e5a078cb382 100644 --- a/substrate/primitives/api/test/tests/decl_and_impl.rs +++ b/substrate/primitives/api/test/tests/decl_and_impl.rs @@ -309,6 +309,8 @@ fn mock_runtime_api_works_with_advanced() { #[test] fn runtime_api_metadata_matches_version_implemented() { + use sp_metadata_ir::InternalImplRuntimeApis; + let rt = Runtime {}; let runtime_metadata = rt.runtime_metadata(); diff --git a/substrate/primitives/metadata-ir/src/lib.rs b/substrate/primitives/metadata-ir/src/lib.rs index bf234432a1a6..dc01f7eaadb3 100644 --- a/substrate/primitives/metadata-ir/src/lib.rs +++ b/substrate/primitives/metadata-ir/src/lib.rs @@ -87,6 +87,16 @@ pub fn into_unstable(metadata: MetadataIR) -> RuntimeMetadataPrefixed { latest.into() } +/// INTERNAL USE ONLY +/// +/// Special trait that is used together with `InternalConstructRuntime` by `construct_runtime!` to +/// fetch the runtime api metadata without exploding when there is no runtime api implementation +/// available. +#[doc(hidden)] +pub trait InternalImplRuntimeApis { + fn runtime_metadata(&self) -> alloc::vec::Vec; +} + #[cfg(test)] mod test { use super::*; From 4e7c968ae97c66812df989117ad251cba3864632 Mon Sep 17 00:00:00 2001 From: Alexandru Vasile <60601340+lexnv@users.noreply.github.com> Date: Fri, 29 Nov 2024 16:49:45 +0200 Subject: [PATCH 160/166] archive: Refactor `archive_storage` method into subscription (#6483) This PR adapts the `archive_storage` implementation from a method to a subscription. This keeps the archive APIs uniform and consistent. Builds on: https://github.com/paritytech/polkadot-sdk/pull/5997 cc @paritytech/subxt-team --------- Signed-off-by: Alexandru Vasile Co-authored-by: James Wilson --- .../client/rpc-spec-v2/src/archive/api.rs | 13 +- .../client/rpc-spec-v2/src/archive/archive.rs | 202 +++---- .../src/archive/archive_storage.rs | 105 +--- .../client/rpc-spec-v2/src/archive/mod.rs | 2 +- .../client/rpc-spec-v2/src/archive/tests.rs | 500 +++++++----------- .../rpc-spec-v2/src/chain_head/event.rs | 3 +- .../client/rpc-spec-v2/src/common/events.rs | 59 ++- .../client/rpc-spec-v2/src/common/storage.rs | 151 ++++-- substrate/client/service/src/builder.rs | 2 - 9 files changed, 458 insertions(+), 579 deletions(-) diff --git a/substrate/client/rpc-spec-v2/src/archive/api.rs b/substrate/client/rpc-spec-v2/src/archive/api.rs index dcfeaecb147b..a205d0502c93 100644 --- a/substrate/client/rpc-spec-v2/src/archive/api.rs +++ b/substrate/client/rpc-spec-v2/src/archive/api.rs @@ -20,8 +20,7 @@ use crate::{ common::events::{ - ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageResult, - PaginatedStorageQuery, + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageEvent, StorageQuery, }, MethodResult, }; @@ -100,13 +99,17 @@ pub trait ArchiveApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "archive_unstable_storage", blocking)] + #[subscription( + name = "archive_unstable_storage" => "archive_unstable_storageEvent", + unsubscribe = "archive_unstable_stopStorage", + item = ArchiveStorageEvent, + )] fn archive_unstable_storage( &self, hash: Hash, - items: Vec>, + items: Vec>, child_trie: Option, - ) -> RpcResult; + ); /// Returns the storage difference between two blocks. /// diff --git a/substrate/client/rpc-spec-v2/src/archive/archive.rs b/substrate/client/rpc-spec-v2/src/archive/archive.rs index 55054d91d85d..62e44a016241 100644 --- a/substrate/client/rpc-spec-v2/src/archive/archive.rs +++ b/substrate/client/rpc-spec-v2/src/archive/archive.rs @@ -20,13 +20,13 @@ use crate::{ archive::{ - archive_storage::{ArchiveStorage, ArchiveStorageDiff}, - error::Error as ArchiveError, - ArchiveApiServer, + archive_storage::ArchiveStorageDiff, error::Error as ArchiveError, ArchiveApiServer, }, - common::events::{ - ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageResult, - PaginatedStorageQuery, + common::{ + events::{ + ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageEvent, StorageQuery, + }, + storage::{QueryResult, StorageSubscriptionClient}, }, hex_string, MethodResult, SubscriptionTaskExecutor, }; @@ -57,42 +57,12 @@ use tokio::sync::mpsc; pub(crate) const LOG_TARGET: &str = "rpc-spec-v2::archive"; -/// The configuration of [`Archive`]. -pub struct ArchiveConfig { - /// The maximum number of items the `archive_storage` can return for a descendant query before - /// pagination is required. - pub max_descendant_responses: usize, - /// The maximum number of queried items allowed for the `archive_storage` at a time. - pub max_queried_items: usize, -} - -/// The maximum number of items the `archive_storage` can return for a descendant query before -/// pagination is required. -/// -/// Note: this is identical to the `chainHead` value. -const MAX_DESCENDANT_RESPONSES: usize = 5; - -/// The maximum number of queried items allowed for the `archive_storage` at a time. -/// -/// Note: A queried item can also be a descendant query which can return up to -/// `MAX_DESCENDANT_RESPONSES`. -const MAX_QUERIED_ITEMS: usize = 8; - /// The buffer capacity for each storage query. /// /// This is small because the underlying JSON-RPC server has /// its down buffer capacity per connection as well. const STORAGE_QUERY_BUF: usize = 16; -impl Default for ArchiveConfig { - fn default() -> Self { - Self { - max_descendant_responses: MAX_DESCENDANT_RESPONSES, - max_queried_items: MAX_QUERIED_ITEMS, - } - } -} - /// An API for archive RPC calls. pub struct Archive, Block: BlockT, Client> { /// Substrate client. @@ -103,11 +73,6 @@ pub struct Archive, Block: BlockT, Client> { executor: SubscriptionTaskExecutor, /// The hexadecimal encoded hash of the genesis block. genesis_hash: String, - /// The maximum number of items the `archive_storage` can return for a descendant query before - /// pagination is required. - storage_max_descendant_responses: usize, - /// The maximum number of queried items allowed for the `archive_storage` at a time. - storage_max_queried_items: usize, /// Phantom member to pin the block type. _phantom: PhantomData, } @@ -119,18 +84,9 @@ impl, Block: BlockT, Client> Archive { backend: Arc, genesis_hash: GenesisHash, executor: SubscriptionTaskExecutor, - config: ArchiveConfig, ) -> Self { let genesis_hash = hex_string(&genesis_hash.as_ref()); - Self { - client, - backend, - executor, - genesis_hash, - storage_max_descendant_responses: config.max_descendant_responses, - storage_max_queried_items: config.max_queried_items, - _phantom: PhantomData, - } + Self { client, backend, executor, genesis_hash, _phantom: PhantomData } } } @@ -260,47 +216,53 @@ where fn archive_unstable_storage( &self, + pending: PendingSubscriptionSink, hash: Block::Hash, - items: Vec>, + items: Vec>, child_trie: Option, - ) -> RpcResult { - let items = items - .into_iter() - .map(|query| { - let key = StorageKey(parse_hex_param(query.key)?); - let pagination_start_key = query - .pagination_start_key - .map(|key| parse_hex_param(key).map(|key| StorageKey(key))) - .transpose()?; - - // Paginated start key is only supported - if pagination_start_key.is_some() && !query.query_type.is_descendant_query() { - return Err(ArchiveError::InvalidParam( - "Pagination start key is only supported for descendants queries" - .to_string(), - )) - } + ) { + let mut storage_client = + StorageSubscriptionClient::::new(self.client.clone()); + + let fut = async move { + let Ok(mut sink) = pending.accept().await.map(Subscription::from) else { return }; - Ok(PaginatedStorageQuery { - key, - query_type: query.query_type, - pagination_start_key, + let items = match items + .into_iter() + .map(|query| { + let key = StorageKey(parse_hex_param(query.key)?); + Ok(StorageQuery { key, query_type: query.query_type }) }) - }) - .collect::, ArchiveError>>()?; + .collect::, ArchiveError>>() + { + Ok(items) => items, + Err(error) => { + let _ = sink.send(&ArchiveStorageEvent::err(error.to_string())); + return + }, + }; - let child_trie = child_trie - .map(|child_trie| parse_hex_param(child_trie)) - .transpose()? - .map(ChildInfo::new_default_from_vec); + let child_trie = child_trie.map(|child_trie| parse_hex_param(child_trie)).transpose(); + let child_trie = match child_trie { + Ok(child_trie) => child_trie.map(ChildInfo::new_default_from_vec), + Err(error) => { + let _ = sink.send(&ArchiveStorageEvent::err(error.to_string())); + return + }, + }; - let storage_client = ArchiveStorage::new( - self.client.clone(), - self.storage_max_descendant_responses, - self.storage_max_queried_items, - ); + let (tx, mut rx) = tokio::sync::mpsc::channel(STORAGE_QUERY_BUF); + let storage_fut = storage_client.generate_events(hash, items, child_trie, tx); - Ok(storage_client.handle_query(hash, items, child_trie)) + // We don't care about the return value of this join: + // - process_events might encounter an error (if the client disconnected) + // - storage_fut might encounter an error while processing a trie queries and + // the error is propagated via the sink. + let _ = futures::future::join(storage_fut, process_storage_events(&mut rx, &mut sink)) + .await; + }; + + self.executor.spawn("substrate-rpc-subscription", Some("rpc"), fut.boxed()); } fn archive_unstable_storage_diff( @@ -337,24 +299,74 @@ where // - process_events might encounter an error (if the client disconnected) // - storage_fut might encounter an error while processing a trie queries and // the error is propagated via the sink. - let _ = futures::future::join(storage_fut, process_events(&mut rx, &mut sink)).await; + let _ = + futures::future::join(storage_fut, process_storage_diff_events(&mut rx, &mut sink)) + .await; }; self.executor.spawn("substrate-rpc-subscription", Some("rpc"), fut.boxed()); } } -/// Sends all the events to the sink. -async fn process_events(rx: &mut mpsc::Receiver, sink: &mut Subscription) { - while let Some(event) = rx.recv().await { - if event.is_done() { - log::debug!(target: LOG_TARGET, "Finished processing partial trie query"); - } else if event.is_err() { - log::debug!(target: LOG_TARGET, "Error encountered while processing partial trie query"); +/// Sends all the events of the storage_diff method to the sink. +async fn process_storage_diff_events( + rx: &mut mpsc::Receiver, + sink: &mut Subscription, +) { + loop { + tokio::select! { + _ = sink.closed() => { + return + }, + + maybe_event = rx.recv() => { + let Some(event) = maybe_event else { + break; + }; + + if event.is_done() { + log::debug!(target: LOG_TARGET, "Finished processing partial trie query"); + } else if event.is_err() { + log::debug!(target: LOG_TARGET, "Error encountered while processing partial trie query"); + } + + if sink.send(&event).await.is_err() { + return + } + } } + } +} + +/// Sends all the events of the storage method to the sink. +async fn process_storage_events(rx: &mut mpsc::Receiver, sink: &mut Subscription) { + loop { + tokio::select! { + _ = sink.closed() => { + break + } + + maybe_storage = rx.recv() => { + let Some(event) = maybe_storage else { + break; + }; + + match event { + Ok(None) => continue, + + Ok(Some(event)) => + if sink.send(&ArchiveStorageEvent::result(event)).await.is_err() { + return + }, - if sink.send(&event).await.is_err() { - return + Err(error) => { + let _ = sink.send(&ArchiveStorageEvent::err(error)).await; + return + } + } + } } } + + let _ = sink.send(&ArchiveStorageEvent::StorageDone).await; } diff --git a/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs b/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs index 5a3920882f00..390db765a48f 100644 --- a/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs +++ b/substrate/client/rpc-spec-v2/src/archive/archive_storage.rs @@ -33,114 +33,13 @@ use crate::{ common::{ events::{ ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageDiffOperationType, - ArchiveStorageDiffResult, ArchiveStorageDiffType, ArchiveStorageResult, - PaginatedStorageQuery, StorageQueryType, StorageResult, + ArchiveStorageDiffResult, ArchiveStorageDiffType, StorageResult, }, - storage::{IterQueryType, QueryIter, Storage}, + storage::Storage, }, }; use tokio::sync::mpsc; -/// Generates the events of the `archive_storage` method. -pub struct ArchiveStorage { - /// Storage client. - client: Storage, - /// The maximum number of responses the API can return for a descendant query at a time. - storage_max_descendant_responses: usize, - /// The maximum number of queried items allowed for the `archive_storage` at a time. - storage_max_queried_items: usize, -} - -impl ArchiveStorage { - /// Constructs a new [`ArchiveStorage`]. - pub fn new( - client: Arc, - storage_max_descendant_responses: usize, - storage_max_queried_items: usize, - ) -> Self { - Self { - client: Storage::new(client), - storage_max_descendant_responses, - storage_max_queried_items, - } - } -} - -impl ArchiveStorage -where - Block: BlockT + 'static, - BE: Backend + 'static, - Client: StorageProvider + 'static, -{ - /// Generate the response of the `archive_storage` method. - pub fn handle_query( - &self, - hash: Block::Hash, - mut items: Vec>, - child_key: Option, - ) -> ArchiveStorageResult { - let discarded_items = items.len().saturating_sub(self.storage_max_queried_items); - items.truncate(self.storage_max_queried_items); - - let mut storage_results = Vec::with_capacity(items.len()); - for item in items { - match item.query_type { - StorageQueryType::Value => { - match self.client.query_value(hash, &item.key, child_key.as_ref()) { - Ok(Some(value)) => storage_results.push(value), - Ok(None) => continue, - Err(error) => return ArchiveStorageResult::err(error), - } - }, - StorageQueryType::Hash => - match self.client.query_hash(hash, &item.key, child_key.as_ref()) { - Ok(Some(value)) => storage_results.push(value), - Ok(None) => continue, - Err(error) => return ArchiveStorageResult::err(error), - }, - StorageQueryType::ClosestDescendantMerkleValue => - match self.client.query_merkle_value(hash, &item.key, child_key.as_ref()) { - Ok(Some(value)) => storage_results.push(value), - Ok(None) => continue, - Err(error) => return ArchiveStorageResult::err(error), - }, - StorageQueryType::DescendantsValues => { - match self.client.query_iter_pagination( - QueryIter { - query_key: item.key, - ty: IterQueryType::Value, - pagination_start_key: item.pagination_start_key, - }, - hash, - child_key.as_ref(), - self.storage_max_descendant_responses, - ) { - Ok((results, _)) => storage_results.extend(results), - Err(error) => return ArchiveStorageResult::err(error), - } - }, - StorageQueryType::DescendantsHashes => { - match self.client.query_iter_pagination( - QueryIter { - query_key: item.key, - ty: IterQueryType::Hash, - pagination_start_key: item.pagination_start_key, - }, - hash, - child_key.as_ref(), - self.storage_max_descendant_responses, - ) { - Ok((results, _)) => storage_results.extend(results), - Err(error) => return ArchiveStorageResult::err(error), - } - }, - }; - } - - ArchiveStorageResult::ok(storage_results, discarded_items) - } -} - /// Parse hex-encoded string parameter as raw bytes. /// /// If the parsing fails, returns an error propagated to the RPC method. diff --git a/substrate/client/rpc-spec-v2/src/archive/mod.rs b/substrate/client/rpc-spec-v2/src/archive/mod.rs index 5f020c203eab..14fa104c113a 100644 --- a/substrate/client/rpc-spec-v2/src/archive/mod.rs +++ b/substrate/client/rpc-spec-v2/src/archive/mod.rs @@ -32,4 +32,4 @@ pub mod archive; pub mod error; pub use api::ArchiveApiServer; -pub use archive::{Archive, ArchiveConfig}; +pub use archive::Archive; diff --git a/substrate/client/rpc-spec-v2/src/archive/tests.rs b/substrate/client/rpc-spec-v2/src/archive/tests.rs index 994c5d28bd61..cddaafde6659 100644 --- a/substrate/client/rpc-spec-v2/src/archive/tests.rs +++ b/substrate/client/rpc-spec-v2/src/archive/tests.rs @@ -19,16 +19,13 @@ use crate::{ common::events::{ ArchiveStorageDiffEvent, ArchiveStorageDiffItem, ArchiveStorageDiffOperationType, - ArchiveStorageDiffResult, ArchiveStorageDiffType, ArchiveStorageMethodOk, - ArchiveStorageResult, PaginatedStorageQuery, StorageQueryType, StorageResultType, + ArchiveStorageDiffResult, ArchiveStorageDiffType, ArchiveStorageEvent, StorageQuery, + StorageQueryType, StorageResult, StorageResultType, }, hex_string, MethodResult, }; -use super::{ - archive::{Archive, ArchiveConfig}, - *, -}; +use super::{archive::Archive, *}; use assert_matches::assert_matches; use codec::{Decode, Encode}; @@ -55,8 +52,6 @@ use substrate_test_runtime_client::{ const CHAIN_GENESIS: [u8; 32] = [0; 32]; const INVALID_HASH: [u8; 32] = [1; 32]; -const MAX_PAGINATION_LIMIT: usize = 5; -const MAX_QUERIED_LIMIT: usize = 5; const KEY: &[u8] = b":mock"; const VALUE: &[u8] = b"hello world"; const CHILD_STORAGE_KEY: &[u8] = b"child"; @@ -65,10 +60,7 @@ const CHILD_VALUE: &[u8] = b"child value"; type Header = substrate_test_runtime_client::runtime::Header; type Block = substrate_test_runtime_client::runtime::Block; -fn setup_api( - max_descendant_responses: usize, - max_queried_items: usize, -) -> (Arc>, RpcModule>>) { +fn setup_api() -> (Arc>, RpcModule>>) { let child_info = ChildInfo::new_default(CHILD_STORAGE_KEY); let builder = TestClientBuilder::new().add_extra_child_storage( &child_info, @@ -83,7 +75,6 @@ fn setup_api( backend, CHAIN_GENESIS, Arc::new(TokioTestExecutor::default()), - ArchiveConfig { max_descendant_responses, max_queried_items }, ) .into_rpc(); @@ -101,7 +92,7 @@ async fn get_next_event(sub: &mut RpcSubscriptio #[tokio::test] async fn archive_genesis() { - let (_client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (_client, api) = setup_api(); let genesis: String = api.call("archive_unstable_genesisHash", EmptyParams::new()).await.unwrap(); @@ -110,7 +101,7 @@ async fn archive_genesis() { #[tokio::test] async fn archive_body() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Invalid block hash. let invalid_hash = hex_string(&INVALID_HASH); @@ -144,7 +135,7 @@ async fn archive_body() { #[tokio::test] async fn archive_header() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Invalid block hash. let invalid_hash = hex_string(&INVALID_HASH); @@ -178,7 +169,7 @@ async fn archive_header() { #[tokio::test] async fn archive_finalized_height() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); let client_height: u32 = client.info().finalized_number.saturated_into(); @@ -190,7 +181,7 @@ async fn archive_finalized_height() { #[tokio::test] async fn archive_hash_by_height() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Genesis height. let hashes: Vec = api.call("archive_unstable_hashByHeight", [0]).await.unwrap(); @@ -296,7 +287,7 @@ async fn archive_hash_by_height() { #[tokio::test] async fn archive_call() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); let invalid_hash = hex_string(&INVALID_HASH); // Invalid parameter (non-hex). @@ -355,7 +346,7 @@ async fn archive_call() { #[tokio::test] async fn archive_storage_hashes_values() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); let block = BlockBuilderBuilder::new(&*client) .on_parent_block(client.chain_info().genesis_hash) @@ -369,42 +360,23 @@ async fn archive_storage_hashes_values() { let block_hash = format!("{:?}", block.header.hash()); let key = hex_string(&KEY); - let items: Vec> = vec![ - PaginatedStorageQuery { - key: key.clone(), - query_type: StorageQueryType::DescendantsHashes, - pagination_start_key: None, - }, - PaginatedStorageQuery { - key: key.clone(), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: None, - }, - PaginatedStorageQuery { - key: key.clone(), - query_type: StorageQueryType::Hash, - pagination_start_key: None, - }, - PaginatedStorageQuery { - key: key.clone(), - query_type: StorageQueryType::Value, - pagination_start_key: None, - }, + let items: Vec> = vec![ + StorageQuery { key: key.clone(), query_type: StorageQueryType::DescendantsHashes }, + StorageQuery { key: key.clone(), query_type: StorageQueryType::DescendantsValues }, + StorageQuery { key: key.clone(), query_type: StorageQueryType::Hash }, + StorageQuery { key: key.clone(), query_type: StorageQueryType::Value }, ]; - let result: ArchiveStorageResult = api - .call("archive_unstable_storage", rpc_params![&block_hash, items.clone()]) + let mut sub = api + .subscribe_unbounded("archive_unstable_storage", rpc_params![&block_hash, items.clone()]) .await .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - // Key has not been imported yet. - assert_eq!(result.len(), 0); - assert_eq!(discarded_items, 0); - }, - _ => panic!("Unexpected result"), - }; + // Key has not been imported yet. + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::StorageDone, + ); // Import a block with the given key value pair. let mut builder = BlockBuilderBuilder::new(&*client) @@ -420,32 +392,103 @@ async fn archive_storage_hashes_values() { let expected_hash = format!("{:?}", Blake2Hasher::hash(&VALUE)); let expected_value = hex_string(&VALUE); - let result: ArchiveStorageResult = api - .call("archive_unstable_storage", rpc_params![&block_hash, items]) + let mut sub = api + .subscribe_unbounded("archive_unstable_storage", rpc_params![&block_hash, items]) .await .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 4); - assert_eq!(discarded_items, 0); - - assert_eq!(result[0].key, key); - assert_eq!(result[0].result, StorageResultType::Hash(expected_hash.clone())); - assert_eq!(result[1].key, key); - assert_eq!(result[1].result, StorageResultType::Value(expected_value.clone())); - assert_eq!(result[2].key, key); - assert_eq!(result[2].result, StorageResultType::Hash(expected_hash)); - assert_eq!(result[3].key, key); - assert_eq!(result[3].result, StorageResultType::Value(expected_value)); - }, - _ => panic!("Unexpected result"), - }; + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Hash(expected_hash.clone()), + child_trie_key: None, + }), + ); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Value(expected_value.clone()), + child_trie_key: None, + }), + ); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Hash(expected_hash), + child_trie_key: None, + }), + ); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Value(expected_value), + child_trie_key: None, + }), + ); + + assert_matches!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::StorageDone + ); +} + +#[tokio::test] +async fn archive_storage_hashes_values_child_trie() { + let (client, api) = setup_api(); + + // Get child storage values set in `setup_api`. + let child_info = hex_string(&CHILD_STORAGE_KEY); + let key = hex_string(&KEY); + let genesis_hash = format!("{:?}", client.genesis_hash()); + let expected_hash = format!("{:?}", Blake2Hasher::hash(&CHILD_VALUE)); + let expected_value = hex_string(&CHILD_VALUE); + + let items: Vec> = vec![ + StorageQuery { key: key.clone(), query_type: StorageQueryType::DescendantsHashes }, + StorageQuery { key: key.clone(), query_type: StorageQueryType::DescendantsValues }, + ]; + let mut sub = api + .subscribe_unbounded( + "archive_unstable_storage", + rpc_params![&genesis_hash, items, &child_info], + ) + .await + .unwrap(); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Hash(expected_hash.clone()), + child_trie_key: Some(child_info.clone()), + }) + ); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: key.clone(), + result: StorageResultType::Value(expected_value.clone()), + child_trie_key: Some(child_info.clone()), + }) + ); + + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::StorageDone, + ); } #[tokio::test] async fn archive_storage_closest_merkle_value() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); /// The core of this test. /// @@ -457,55 +500,47 @@ async fn archive_storage_closest_merkle_value() { api: &RpcModule>>, block_hash: String, ) -> HashMap { - let result: ArchiveStorageResult = api - .call( + let mut sub = api + .subscribe_unbounded( "archive_unstable_storage", rpc_params![ &block_hash, vec![ - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAAA"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAAB"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, // Key with descendant. - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":A"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AA"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, // Keys below this comment do not produce a result. // Key that exceed the keyspace of the trie. - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAAAX"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAABX"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, // Key that are not part of the trie. - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAX"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, - PaginatedStorageQuery { + StorageQuery { key: hex_string(b":AAAX"), query_type: StorageQueryType::ClosestDescendantMerkleValue, - pagination_start_key: None, }, ] ], @@ -513,19 +548,21 @@ async fn archive_storage_closest_merkle_value() { .await .unwrap(); - let merkle_values: HashMap<_, _> = match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, .. }) => result - .into_iter() - .map(|res| { - let value = match res.result { + let mut merkle_values = HashMap::new(); + loop { + let event = get_next_event::(&mut sub).await; + match event { + ArchiveStorageEvent::Storage(result) => { + let str_result = match result.result { StorageResultType::ClosestDescendantMerkleValue(value) => value, - _ => panic!("Unexpected StorageResultType"), + _ => panic!("Unexpected result type"), }; - (res.key, value) - }) - .collect(), - _ => panic!("Unexpected result"), - }; + merkle_values.insert(result.key, str_result); + }, + ArchiveStorageEvent::StorageError(err) => panic!("Unexpected error {err:?}"), + ArchiveStorageEvent::StorageDone => break, + } + } // Response for AAAA, AAAB, A and AA. assert_eq!(merkle_values.len(), 4); @@ -604,9 +641,9 @@ async fn archive_storage_closest_merkle_value() { } #[tokio::test] -async fn archive_storage_paginate_iterations() { +async fn archive_storage_iterations() { // 1 iteration allowed before pagination kicks in. - let (client, api) = setup_api(1, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Import a new block with storage changes. let mut builder = BlockBuilderBuilder::new(&*client) @@ -625,237 +662,94 @@ async fn archive_storage_paginate_iterations() { // Calling with an invalid hash. let invalid_hash = hex_string(&INVALID_HASH); - let result: ArchiveStorageResult = api - .call( + let mut sub = api + .subscribe_unbounded( "archive_unstable_storage", rpc_params![ &invalid_hash, - vec![PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: None, - }] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Err(_) => (), - _ => panic!("Unexpected result"), - }; - - // Valid call with storage at the key. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: None, - }] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 0); - - assert_eq!(result[0].key, hex_string(b":m")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"a"))); - }, - _ => panic!("Unexpected result"), - }; - - // Continue with pagination. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: Some(hex_string(b":m")), - }] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 0); - - assert_eq!(result[0].key, hex_string(b":mo")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"ab"))); - }, - _ => panic!("Unexpected result"), - }; - - // Continue with pagination. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![PaginatedStorageQuery { + vec![StorageQuery { key: hex_string(b":m"), query_type: StorageQueryType::DescendantsValues, - pagination_start_key: Some(hex_string(b":mo")), }] ], ) .await .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 0); - - assert_eq!(result[0].key, hex_string(b":moD")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"abcmoD"))); - }, - _ => panic!("Unexpected result"), - }; - // Continue with pagination. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: Some(hex_string(b":moD")), - }] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 0); - - assert_eq!(result[0].key, hex_string(b":moc")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"abc"))); - }, - _ => panic!("Unexpected result"), - }; + assert_matches!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::StorageError(_) + ); - // Continue with pagination. - let result: ArchiveStorageResult = api - .call( + // Valid call with storage at the key. + let mut sub = api + .subscribe_unbounded( "archive_unstable_storage", rpc_params![ &block_hash, - vec![PaginatedStorageQuery { + vec![StorageQuery { key: hex_string(b":m"), query_type: StorageQueryType::DescendantsValues, - pagination_start_key: Some(hex_string(b":moc")), }] ], ) .await .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 0); - assert_eq!(result[0].key, hex_string(b":mock")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"abcd"))); - }, - _ => panic!("Unexpected result"), - }; + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: hex_string(b":m"), + result: StorageResultType::Value(hex_string(b"a")), + child_trie_key: None, + }) + ); - // Continue with pagination until no keys are returned. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::DescendantsValues, - pagination_start_key: Some(hex_string(b":mock")), - }] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 0); - assert_eq!(discarded_items, 0); - }, - _ => panic!("Unexpected result"), - }; -} + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: hex_string(b":mo"), + result: StorageResultType::Value(hex_string(b"ab")), + child_trie_key: None, + }) + ); -#[tokio::test] -async fn archive_storage_discarded_items() { - // One query at a time - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, 1); + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: hex_string(b":moD"), + result: StorageResultType::Value(hex_string(b"abcmoD")), + child_trie_key: None, + }) + ); - // Import a new block with storage changes. - let mut builder = BlockBuilderBuilder::new(&*client) - .on_parent_block(client.chain_info().genesis_hash) - .with_parent_block_number(0) - .build() - .unwrap(); - builder.push_storage_change(b":m".to_vec(), Some(b"a".to_vec())).unwrap(); - let block = builder.build().unwrap().block; - let block_hash = format!("{:?}", block.header.hash()); - client.import(BlockOrigin::Own, block.clone()).await.unwrap(); + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: hex_string(b":moc"), + result: StorageResultType::Value(hex_string(b"abc")), + child_trie_key: None, + }) + ); - // Valid call with storage at the key. - let result: ArchiveStorageResult = api - .call( - "archive_unstable_storage", - rpc_params![ - &block_hash, - vec![ - PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::Value, - pagination_start_key: None, - }, - PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::Hash, - pagination_start_key: None, - }, - PaginatedStorageQuery { - key: hex_string(b":m"), - query_type: StorageQueryType::Hash, - pagination_start_key: None, - } - ] - ], - ) - .await - .unwrap(); - match result { - ArchiveStorageResult::Ok(ArchiveStorageMethodOk { result, discarded_items }) => { - assert_eq!(result.len(), 1); - assert_eq!(discarded_items, 2); + assert_eq!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::Storage(StorageResult { + key: hex_string(b":mock"), + result: StorageResultType::Value(hex_string(b"abcd")), + child_trie_key: None, + }) + ); - assert_eq!(result[0].key, hex_string(b":m")); - assert_eq!(result[0].result, StorageResultType::Value(hex_string(b"a"))); - }, - _ => panic!("Unexpected result"), - }; + assert_matches!( + get_next_event::(&mut sub).await, + ArchiveStorageEvent::StorageDone + ); } #[tokio::test] async fn archive_storage_diff_main_trie() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); let mut builder = BlockBuilderBuilder::new(&*client) .on_parent_block(client.chain_info().genesis_hash) @@ -965,7 +859,7 @@ async fn archive_storage_diff_main_trie() { #[tokio::test] async fn archive_storage_diff_no_changes() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Build 2 identical blocks. let mut builder = BlockBuilderBuilder::new(&*client) @@ -1012,7 +906,7 @@ async fn archive_storage_diff_no_changes() { #[tokio::test] async fn archive_storage_diff_deleted_changes() { - let (client, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (client, api) = setup_api(); // Blocks are imported as forks. let mut builder = BlockBuilderBuilder::new(&*client) @@ -1079,7 +973,7 @@ async fn archive_storage_diff_deleted_changes() { #[tokio::test] async fn archive_storage_diff_invalid_params() { let invalid_hash = hex_string(&INVALID_HASH); - let (_, api) = setup_api(MAX_PAGINATION_LIMIT, MAX_QUERIED_LIMIT); + let (_, api) = setup_api(); // Invalid shape for parameters. let items: Vec> = Vec::new(); diff --git a/substrate/client/rpc-spec-v2/src/chain_head/event.rs b/substrate/client/rpc-spec-v2/src/chain_head/event.rs index bd9863060910..de74145a3f08 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/event.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/event.rs @@ -235,7 +235,7 @@ pub struct OperationCallDone { pub output: String, } -/// The response of the `chainHead_call` method. +/// The response of the `chainHead_storage` method. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct OperationStorageItems { @@ -536,6 +536,7 @@ mod tests { items: vec![StorageResult { key: "0x1".into(), result: StorageResultType::Value("0x123".to_string()), + child_trie_key: None, }], }); diff --git a/substrate/client/rpc-spec-v2/src/common/events.rs b/substrate/client/rpc-spec-v2/src/common/events.rs index 198a60bf4cac..44f722c0c61b 100644 --- a/substrate/client/rpc-spec-v2/src/common/events.rs +++ b/substrate/client/rpc-spec-v2/src/common/events.rs @@ -78,6 +78,10 @@ pub struct StorageResult { /// The result of the query. #[serde(flatten)] pub result: StorageResultType, + /// The child trie key if provided. + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(default)] + pub child_trie_key: Option, } /// The type of the storage query. @@ -105,23 +109,41 @@ pub struct StorageResultErr { /// The result of a storage call. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(untagged)] -pub enum ArchiveStorageResult { +#[serde(rename_all = "camelCase")] +#[serde(tag = "event")] +pub enum ArchiveStorageEvent { /// Query generated a result. - Ok(ArchiveStorageMethodOk), + Storage(StorageResult), /// Query encountered an error. - Err(ArchiveStorageMethodErr), + StorageError(ArchiveStorageMethodErr), + /// Operation storage is done. + StorageDone, } -impl ArchiveStorageResult { - /// Create a new `ArchiveStorageResult::Ok` result. - pub fn ok(result: Vec, discarded_items: usize) -> Self { - Self::Ok(ArchiveStorageMethodOk { result, discarded_items }) +impl ArchiveStorageEvent { + /// Create a new `ArchiveStorageEvent::StorageErr` event. + pub fn err(error: String) -> Self { + Self::StorageError(ArchiveStorageMethodErr { error }) } - /// Create a new `ArchiveStorageResult::Err` result. - pub fn err(error: String) -> Self { - Self::Err(ArchiveStorageMethodErr { error }) + /// Create a new `ArchiveStorageEvent::StorageResult` event. + pub fn result(result: StorageResult) -> Self { + Self::Storage(result) + } + + /// Checks if the event is a `StorageDone` event. + pub fn is_done(&self) -> bool { + matches!(self, Self::StorageDone) + } + + /// Checks if the event is a `StorageErr` event. + pub fn is_err(&self) -> bool { + matches!(self, Self::StorageError(_)) + } + + /// Checks if the event is a `StorageResult` event. + pub fn is_result(&self) -> bool { + matches!(self, Self::Storage(_)) } } @@ -354,8 +376,11 @@ mod tests { #[test] fn storage_result() { // Item with Value. - let item = - StorageResult { key: "0x1".into(), result: StorageResultType::Value("res".into()) }; + let item = StorageResult { + key: "0x1".into(), + result: StorageResultType::Value("res".into()), + child_trie_key: None, + }; // Encode let ser = serde_json::to_string(&item).unwrap(); let exp = r#"{"key":"0x1","value":"res"}"#; @@ -365,8 +390,11 @@ mod tests { assert_eq!(dec, item); // Item with Hash. - let item = - StorageResult { key: "0x1".into(), result: StorageResultType::Hash("res".into()) }; + let item = StorageResult { + key: "0x1".into(), + result: StorageResultType::Hash("res".into()), + child_trie_key: None, + }; // Encode let ser = serde_json::to_string(&item).unwrap(); let exp = r#"{"key":"0x1","hash":"res"}"#; @@ -379,6 +407,7 @@ mod tests { let item = StorageResult { key: "0x1".into(), result: StorageResultType::ClosestDescendantMerkleValue("res".into()), + child_trie_key: None, }; // Encode let ser = serde_json::to_string(&item).unwrap(); diff --git a/substrate/client/rpc-spec-v2/src/common/storage.rs b/substrate/client/rpc-spec-v2/src/common/storage.rs index 673e20b2bc78..a1e34d51530e 100644 --- a/substrate/client/rpc-spec-v2/src/common/storage.rs +++ b/substrate/client/rpc-spec-v2/src/common/storage.rs @@ -24,7 +24,7 @@ use sc_client_api::{Backend, ChildInfo, StorageKey, StorageProvider}; use sp_runtime::traits::Block as BlockT; use tokio::sync::mpsc; -use super::events::{StorageResult, StorageResultType}; +use super::events::{StorageQuery, StorageQueryType, StorageResult, StorageResultType}; use crate::hex_string; /// Call into the storage of blocks. @@ -70,9 +70,6 @@ pub enum IterQueryType { /// The result of making a query call. pub type QueryResult = Result, String>; -/// The result of iterating over keys. -pub type QueryIterResult = Result<(Vec, Option), String>; - impl Storage where Block: BlockT + 'static, @@ -97,6 +94,7 @@ where QueryResult::Ok(opt.map(|storage_data| StorageResult { key: hex_string(&key.0), result: StorageResultType::Value(hex_string(&storage_data.0)), + child_trie_key: child_key.map(|c| hex_string(&c.storage_key())), })) }) .unwrap_or_else(|error| QueryResult::Err(error.to_string())) @@ -120,6 +118,7 @@ where QueryResult::Ok(opt.map(|storage_data| StorageResult { key: hex_string(&key.0), result: StorageResultType::Hash(hex_string(&storage_data.as_ref())), + child_trie_key: child_key.map(|c| hex_string(&c.storage_key())), })) }) .unwrap_or_else(|error| QueryResult::Err(error.to_string())) @@ -149,6 +148,7 @@ where StorageResult { key: hex_string(&key.0), result: StorageResultType::ClosestDescendantMerkleValue(result), + child_trie_key: child_key.map(|c| hex_string(&c.storage_key())), } })) }) @@ -199,56 +199,6 @@ where } } - /// Iterate over at most the provided number of keys. - /// - /// Returns the storage result with a potential next key to resume iteration. - pub fn query_iter_pagination( - &self, - query: QueryIter, - hash: Block::Hash, - child_key: Option<&ChildInfo>, - count: usize, - ) -> QueryIterResult { - let QueryIter { ty, query_key, pagination_start_key } = query; - - let mut keys_iter = if let Some(child_key) = child_key { - self.client.child_storage_keys( - hash, - child_key.to_owned(), - Some(&query_key), - pagination_start_key.as_ref(), - ) - } else { - self.client.storage_keys(hash, Some(&query_key), pagination_start_key.as_ref()) - } - .map_err(|err| err.to_string())?; - - let mut ret = Vec::with_capacity(count); - let mut next_pagination_key = None; - for _ in 0..count { - let Some(key) = keys_iter.next() else { break }; - - next_pagination_key = Some(key.clone()); - - let result = match ty { - IterQueryType::Value => self.query_value(hash, &key, child_key), - IterQueryType::Hash => self.query_hash(hash, &key, child_key), - }?; - - if let Some(value) = result { - ret.push(value); - } - } - - // Save the next key if any to continue the iteration. - let maybe_next_query = keys_iter.next().map(|_| QueryIter { - ty, - query_key, - pagination_start_key: next_pagination_key, - }); - Ok((ret, maybe_next_query)) - } - /// Raw iterator over the keys. pub fn raw_keys_iter( &self, @@ -264,3 +214,96 @@ where keys_iter.map_err(|err| err.to_string()) } } + +/// Generates storage events for `chainHead_storage` and `archive_storage` subscriptions. +pub struct StorageSubscriptionClient { + /// Storage client. + client: Storage, + _phandom: PhantomData<(BE, Block)>, +} + +impl Clone for StorageSubscriptionClient { + fn clone(&self) -> Self { + Self { client: self.client.clone(), _phandom: PhantomData } + } +} + +impl StorageSubscriptionClient { + /// Constructs a new [`StorageSubscriptionClient`]. + pub fn new(client: Arc) -> Self { + Self { client: Storage::new(client), _phandom: PhantomData } + } +} + +impl StorageSubscriptionClient +where + Block: BlockT + 'static, + BE: Backend + 'static, + Client: StorageProvider + Send + Sync + 'static, +{ + /// Generate storage events to the provided sender. + pub async fn generate_events( + &mut self, + hash: Block::Hash, + items: Vec>, + child_key: Option, + tx: mpsc::Sender, + ) -> Result<(), tokio::task::JoinError> { + let this = self.clone(); + + tokio::task::spawn_blocking(move || { + for item in items { + match item.query_type { + StorageQueryType::Value => { + let rp = this.client.query_value(hash, &item.key, child_key.as_ref()); + if tx.blocking_send(rp).is_err() { + break; + } + }, + StorageQueryType::Hash => { + let rp = this.client.query_hash(hash, &item.key, child_key.as_ref()); + if tx.blocking_send(rp).is_err() { + break; + } + }, + StorageQueryType::ClosestDescendantMerkleValue => { + let rp = + this.client.query_merkle_value(hash, &item.key, child_key.as_ref()); + if tx.blocking_send(rp).is_err() { + break; + } + }, + StorageQueryType::DescendantsValues => { + let query = QueryIter { + query_key: item.key, + ty: IterQueryType::Value, + pagination_start_key: None, + }; + this.client.query_iter_pagination_with_producer( + query, + hash, + child_key.as_ref(), + &tx, + ) + }, + StorageQueryType::DescendantsHashes => { + let query = QueryIter { + query_key: item.key, + ty: IterQueryType::Hash, + pagination_start_key: None, + }; + this.client.query_iter_pagination_with_producer( + query, + hash, + child_key.as_ref(), + &tx, + ) + }, + } + } + }) + .await?; + + Ok(()) + } +} diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 027a444012af..a47a05c0a190 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -756,8 +756,6 @@ where backend.clone(), genesis_hash, task_executor.clone(), - // Defaults to sensible limits for the `Archive`. - sc_rpc_spec_v2::archive::ArchiveConfig::default(), ) .into_rpc(); rpc_api.merge(archive_v2).map_err(|e| Error::Application(e.into()))?; From 1d519a1054d2edb8fc0b868eba6318fb3d448b33 Mon Sep 17 00:00:00 2001 From: Pavlo Khrystenko <45178695+pkhry@users.noreply.github.com> Date: Fri, 29 Nov 2024 16:24:58 +0100 Subject: [PATCH 161/166] Update scale-info to 2.11.6 (#6681) # Description Updates scale-info to from 2.11.5 2.11.6, so that generated code is annotated with `allow(deprecated)` Pre-requisite for https://github.com/paritytech/polkadot-sdk/pull/6312 --- Cargo.lock | 8 +- Cargo.toml | 2 +- prdoc/pr_6681.prdoc | 406 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 411 insertions(+), 5 deletions(-) create mode 100644 prdoc/pr_6681.prdoc diff --git a/Cargo.lock b/Cargo.lock index 5e4e9c267b08..1fe2d766f16a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23715,9 +23715,9 @@ dependencies = [ [[package]] name = "scale-info" -version = "2.11.5" +version = "2.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa7ffc1c0ef49b0452c6e2986abf2b07743320641ffd5fc63d552458e3b779b" +checksum = "346a3b32eba2640d17a9cb5927056b08f3de90f65b72fe09402c2ad07d684d0b" dependencies = [ "bitvec", "cfg-if", @@ -23729,9 +23729,9 @@ dependencies = [ [[package]] name = "scale-info-derive" -version = "2.11.5" +version = "2.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46385cc24172cf615450267463f937c10072516359b3ff1cb24228a4a08bf951" +checksum = "c6630024bf739e2179b91fb424b28898baf819414262c5d376677dbff1fe7ebf" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.86", diff --git a/Cargo.toml b/Cargo.toml index 964964908a9b..ecc385504181 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1197,7 +1197,7 @@ sc-tracing-proc-macro = { path = "substrate/client/tracing/proc-macro", default- sc-transaction-pool = { path = "substrate/client/transaction-pool", default-features = false } sc-transaction-pool-api = { path = "substrate/client/transaction-pool/api", default-features = false } sc-utils = { path = "substrate/client/utils", default-features = false } -scale-info = { version = "2.11.1", default-features = false } +scale-info = { version = "2.11.6", default-features = false } schemars = { version = "0.8.13", default-features = false } schnellru = { version = "0.2.3" } schnorrkel = { version = "0.11.4", default-features = false } diff --git a/prdoc/pr_6681.prdoc b/prdoc/pr_6681.prdoc new file mode 100644 index 000000000000..93a967d4a66c --- /dev/null +++ b/prdoc/pr_6681.prdoc @@ -0,0 +1,406 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: update scale-info to 2.11.6 + +doc: + - audience: Runtime Dev + description: | + Updates scale-info to 2.11.1 from 2.11.5. + Updated version of scale-info annotates generated code with `allow(deprecated)` + +crates: + - name: bridge-runtime-common + bump: none + - name: bp-header-chain + bump: none + - name: bp-runtime + bump: none + - name: frame-support + bump: none + - name: sp-core + bump: none + - name: sp-trie + bump: none + - name: sp-runtime + bump: none + - name: sp-application-crypto + bump: none + - name: sp-arithmetic + bump: none + - name: sp-weights + bump: none + - name: sp-api + bump: none + - name: sp-metadata-ir + bump: none + - name: sp-version + bump: none + - name: sp-inherents + bump: none + - name: frame-executive + bump: none + - name: frame-system + bump: none + - name: pallet-balances + bump: none + - name: frame-benchmarking + bump: none + - name: pallet-migrations + bump: none + - name: cumulus-pallet-parachain-system + bump: none + - name: cumulus-primitives-core + bump: none + - name: polkadot-core-primitives + bump: none + - name: polkadot-parachain-primitives + bump: none + - name: polkadot-primitives + bump: none + - name: sp-authority-discovery + bump: none + - name: sp-consensus-slots + bump: none + - name: sp-staking + bump: none + - name: staging-xcm + bump: none + - name: cumulus-primitives-parachain-inherent + bump: none + - name: pallet-message-queue + bump: none + - name: polkadot-runtime-common + bump: none + - name: frame-election-provider-support + bump: none + - name: sp-npos-elections + bump: none + - name: sp-consensus-grandpa + bump: none + - name: polkadot-primitives + bump: none + - name: sp-authority-discovery + bump: none + - name: sp-consensus-grandpa + bump: none + - name: sp-genesis-builder + bump: none + - name: sp-consensus-babe + bump: none + - name: sp-mixnet + bump: none + - name: sc-rpc-api + bump: none + - name: sp-session + bump: none + - name: sp-statement-store + bump: none + - name: sp-transaction-storage-proof + bump: none + - name: pallet-asset-rate + bump: none + - name: pallet-authorship + bump: none + - name: pallet-babe + bump: none + - name: pallet-session + bump: none + - name: pallet-timestamp + bump: none + - name: pallet-offences + bump: none + - name: pallet-staking + bump: none + - name: pallet-bags-list + bump: none + - name: pallet-broker + bump: none + - name: pallet-election-provider-multi-phase + bump: none + - name: pallet-fast-unstake + bump: none + - name: pallet-identity + bump: none + - name: pallet-transaction-payment + bump: none + - name: pallet-treasury + bump: none + - name: pallet-utility + bump: none + - name: pallet-collective + bump: none + - name: pallet-root-testing + bump: none + - name: pallet-vesting + bump: none + - name: polkadot-runtime-parachains + bump: none + - name: pallet-authority-discovery + bump: none + - name: pallet-mmr + bump: none + - name: sp-mmr-primitives + bump: none + - name: staging-xcm-executor + bump: none + - name: staging-xcm-builder + bump: none + - name: pallet-asset-conversion + bump: none + - name: pallet-assets + bump: none + - name: pallet-salary + bump: none + - name: pallet-ranked-collective + bump: none + - name: pallet-xcm + bump: none + - name: xcm-runtime-apis + bump: none + - name: pallet-grandpa + bump: none + - name: pallet-indices + bump: none + - name: pallet-sudo + bump: none + - name: sp-consensus-beefy + bump: none + - name: cumulus-primitives-storage-weight-reclaim + bump: none + - name: cumulus-pallet-aura-ext + bump: none + - name: pallet-aura + bump: none + - name: sp-consensus-aura + bump: none + - name: pallet-collator-selection + bump: none + - name: pallet-glutton + bump: none + - name: staging-parachain-info + bump: none + - name: westend-runtime + bump: none + - name: frame-metadata-hash-extension + bump: none + - name: frame-system-benchmarking + bump: none + - name: pallet-beefy + bump: none + - name: pallet-beefy-mmr + bump: none + - name: pallet-conviction-voting + bump: none + - name: pallet-scheduler + bump: none + - name: pallet-preimage + bump: none + - name: pallet-delegated-staking + bump: none + - name: pallet-nomination-pools + bump: none + - name: pallet-democracy + bump: none + - name: pallet-elections-phragmen + bump: none + - name: pallet-membership + bump: none + - name: pallet-multisig + bump: none + - name: polkadot-sdk-frame + bump: none + - name: pallet-dev-mode + bump: none + - name: pallet-verify-signature + bump: none + - name: pallet-nomination-pools-benchmarking + bump: none + - name: pallet-offences-benchmarking + bump: none + - name: pallet-im-online + bump: none + - name: pallet-parameters + bump: none + - name: pallet-proxy + bump: none + - name: pallet-recovery + bump: none + - name: pallet-referenda + bump: none + - name: pallet-society + bump: none + - name: pallet-state-trie-migration + bump: none + - name: pallet-whitelist + bump: none + - name: pallet-xcm-benchmarks + bump: none + - name: rococo-runtime + bump: none + - name: pallet-bounties + bump: none + - name: pallet-child-bounties + bump: none + - name: pallet-nis + bump: none + - name: pallet-tips + bump: none + - name: parachains-common + bump: none + - name: pallet-asset-tx-payment + bump: none + - name: cumulus-pallet-xcmp-queue + bump: none + - name: bp-xcm-bridge-hub-router + bump: none + - name: pallet-xcm-bridge-hub-router + bump: none + - name: assets-common + bump: none + - name: bp-messages + bump: none + - name: bp-parachains + bump: none + - name: bp-polkadot-core + bump: none + - name: bp-relayers + bump: none + - name: bp-xcm-bridge-hub + bump: none + - name: bridge-hub-common + bump: none + - name: snowbridge-core + bump: none + - name: snowbridge-beacon-primitives + bump: none + - name: snowbridge-ethereum + bump: none + - name: pallet-bridge-grandpa + bump: none + - name: pallet-bridge-messages + bump: none + - name: pallet-bridge-parachains + bump: none + - name: pallet-bridge-relayers + bump: none + - name: pallet-xcm-bridge-hub + bump: none + - name: cumulus-pallet-dmp-queue + bump: none + - name: cumulus-pallet-solo-to-para + bump: none + - name: cumulus-pallet-xcm + bump: none + - name: cumulus-ping + bump: none + - name: frame-benchmarking-pallet-pov + bump: none + - name: pallet-alliance + bump: none + - name: pallet-asset-conversion-ops + bump: none + - name: pallet-asset-conversion-tx-payment + bump: none + - name: pallet-assets-freezer + bump: none + - name: pallet-atomic-swap + bump: none + - name: pallet-collective-content + bump: none + - name: pallet-contracts + bump: none + - name: pallet-contracts-uapi + bump: none + - name: pallet-insecure-randomness-collective-flip + bump: none + - name: pallet-contracts-mock-network + bump: none + - name: xcm-simulator + bump: none + - name: pallet-core-fellowship + bump: none + - name: pallet-lottery + bump: none + - name: pallet-mixnet + bump: none + - name: pallet-nft-fractionalization + bump: none + - name: pallet-nfts + bump: none + - name: pallet-node-authorization + bump: none + - name: pallet-paged-list + bump: none + - name: pallet-remark + bump: none + - name: pallet-revive + bump: none + - name: pallet-revive-uapi + bump: none + - name: pallet-revive-eth-rpc + bump: none + - name: pallet-skip-feeless-payment + bump: none + - name: pallet-revive-mock-network + bump: none + - name: pallet-root-offences + bump: none + - name: pallet-safe-mode + bump: none + - name: pallet-scored-pool + bump: none + - name: pallet-statement + bump: none + - name: pallet-transaction-storage + bump: none + - name: pallet-tx-pause + bump: none + - name: pallet-uniques + bump: none + - name: snowbridge-outbound-queue-merkle-tree + bump: none + - name: snowbridge-pallet-ethereum-client + bump: none + - name: snowbridge-pallet-inbound-queue + bump: none + - name: snowbridge-router-primitives + bump: none + - name: snowbridge-pallet-outbound-queue + bump: none + - name: snowbridge-pallet-system + bump: none + - name: bp-asset-hub-rococo + bump: none + - name: bp-asset-hub-westend + bump: none + - name: bp-polkadot-bulletin + bump: none + - name: asset-hub-rococo-runtime + bump: none + - name: asset-hub-westend-runtime + bump: none + - name: bridge-hub-rococo-runtime + bump: none + - name: bridge-hub-westend-runtime + bump: none + - name: collectives-westend-runtime + bump: none + - name: coretime-rococo-runtime + bump: none + - name: coretime-westend-runtime + bump: none + - name: people-rococo-runtime + bump: none + - name: people-westend-runtime + bump: none + - name: penpal-runtime + bump: none + - name: contracts-rococo-runtime + bump: none + - name: glutton-westend-runtime + bump: none + - name: rococo-parachain-runtime + bump: none + - name: xcm-simulator-example + bump: none \ No newline at end of file From 5ad8780b653350050c6a854205de20c439aa7b65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20R=2E=20Bald=C3=A9?= Date: Fri, 29 Nov 2024 19:35:06 +0000 Subject: [PATCH 162/166] People chain integration tests (#6377) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # Description Made as a follow-up of https://github.com/polkadot-fellows/runtimes/pull/499 ## Integration N/A ## Review Notes N/A --------- Co-authored-by: Dónal Murray --- Cargo.lock | 1 + .../tests/people/people-westend/Cargo.toml | 1 + .../people-westend/src/tests/governance.rs | 503 ++++++++++++++++++ .../people/people-westend/src/tests/mod.rs | 1 + 4 files changed, 506 insertions(+) create mode 100644 cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/governance.rs diff --git a/Cargo.lock b/Cargo.lock index 1fe2d766f16a..a945d148e051 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16662,6 +16662,7 @@ dependencies = [ "sp-runtime 31.0.1", "staging-xcm 7.0.0", "staging-xcm-executor 7.0.0", + "westend-runtime", "westend-runtime-constants 7.0.0", "westend-system-emulated-network", ] diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml index aa6eebc5458f..53acd038cdf5 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml @@ -21,6 +21,7 @@ sp-runtime = { workspace = true } # Polkadot polkadot-runtime-common = { workspace = true, default-features = true } westend-runtime-constants = { workspace = true, default-features = true } +westend-runtime = { workspace = true } xcm = { workspace = true } xcm-executor = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/governance.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/governance.rs new file mode 100644 index 000000000000..3dadcdd94870 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/governance.rs @@ -0,0 +1,503 @@ +// 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::imports::*; +use frame_support::traits::ProcessMessageError; + +use codec::Encode; +use frame_support::sp_runtime::traits::Dispatchable; +use parachains_common::AccountId; +use people_westend_runtime::people::IdentityInfo; +use westend_runtime::governance::pallet_custom_origins::Origin::GeneralAdmin as GeneralAdminOrigin; +use westend_system_emulated_network::people_westend_emulated_chain::people_westend_runtime; + +use pallet_identity::Data; + +use emulated_integration_tests_common::accounts::{ALICE, BOB}; + +#[test] +fn relay_commands_add_registrar() { + let (origin_kind, origin) = (OriginKind::Superuser, ::RuntimeOrigin::root()); + + let registrar: AccountId = [1; 32].into(); + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let add_registrar_call = + PeopleCall::Identity(pallet_identity::Call::::add_registrar { + account: registrar.into(), + }); + + let xcm_message = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: add_registrar_call.encode().into() } + ]))), + }); + + assert_ok!(xcm_message.dispatch(origin)); + + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + PeopleWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::Identity(pallet_identity::Event::RegistrarAdded { .. }) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) => {}, + ] + ); + }); +} + +#[test] +fn relay_commands_add_registrar_wrong_origin() { + let people_westend_alice = PeopleWestend::account_id_of(ALICE); + + let origins = vec![ + ( + OriginKind::SovereignAccount, + ::RuntimeOrigin::signed(people_westend_alice), + ), + (OriginKind::Xcm, GeneralAdminOrigin.into()), + ]; + + let mut signed_origin = true; + + for (origin_kind, origin) in origins { + let registrar: AccountId = [1; 32].into(); + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let add_registrar_call = + PeopleCall::Identity(pallet_identity::Call::::add_registrar { + account: registrar.into(), + }); + + let xcm_message = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: add_registrar_call.encode().into() } + ]))), + }); + + assert_ok!(xcm_message.dispatch(origin)); + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + PeopleWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + + if signed_origin { + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::MessageQueue(pallet_message_queue::Event::ProcessingFailed { error: ProcessMessageError::Unsupported, .. }) => {}, + ] + ); + } else { + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) => {}, + ] + ); + } + }); + + signed_origin = false; + } +} + +#[test] +fn relay_commands_kill_identity() { + // To kill an identity, first one must be set + PeopleWestend::execute_with(|| { + type PeopleRuntime = ::Runtime; + type PeopleRuntimeEvent = ::RuntimeEvent; + + let people_westend_alice = + ::RuntimeOrigin::signed(PeopleWestend::account_id_of(ALICE)); + + let identity_info = IdentityInfo { + email: Data::Raw(b"test@test.io".to_vec().try_into().unwrap()), + ..Default::default() + }; + let identity: Box<::IdentityInformation> = + Box::new(identity_info); + + assert_ok!(::Identity::set_identity( + people_westend_alice, + identity + )); + + assert_expected_events!( + PeopleWestend, + vec![ + PeopleRuntimeEvent::Identity(pallet_identity::Event::IdentitySet { .. }) => {}, + ] + ); + }); + + let (origin_kind, origin) = (OriginKind::Superuser, ::RuntimeOrigin::root()); + + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type PeopleCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleRuntime = ::Runtime; + + let kill_identity_call = + PeopleCall::Identity(pallet_identity::Call::::kill_identity { + target: people_westend_runtime::MultiAddress::Id(PeopleWestend::account_id_of( + ALICE, + )), + }); + + let xcm_message = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: kill_identity_call.encode().into() } + ]))), + }); + + assert_ok!(xcm_message.dispatch(origin)); + + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + PeopleWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::Identity(pallet_identity::Event::IdentityKilled { .. }) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) => {}, + ] + ); + }); +} + +#[test] +fn relay_commands_kill_identity_wrong_origin() { + let people_westend_alice = PeopleWestend::account_id_of(BOB); + + let origins = vec![ + ( + OriginKind::SovereignAccount, + ::RuntimeOrigin::signed(people_westend_alice), + ), + (OriginKind::Xcm, GeneralAdminOrigin.into()), + ]; + + for (origin_kind, origin) in origins { + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type PeopleCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleRuntime = ::Runtime; + + let kill_identity_call = + PeopleCall::Identity(pallet_identity::Call::::kill_identity { + target: people_westend_runtime::MultiAddress::Id(PeopleWestend::account_id_of( + ALICE, + )), + }); + + let xcm_message = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: kill_identity_call.encode().into() } + ]))), + }); + + assert_ok!(xcm_message.dispatch(origin)); + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + PeopleWestend::execute_with(|| { + assert_expected_events!(PeopleWestend, vec![]); + }); + } +} + +#[test] +fn relay_commands_add_remove_username_authority() { + let people_westend_alice = PeopleWestend::account_id_of(ALICE); + let people_westend_bob = PeopleWestend::account_id_of(BOB); + + let (origin_kind, origin, usr) = + (OriginKind::Superuser, ::RuntimeOrigin::root(), "rootusername"); + + // First, add a username authority. + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let add_username_authority = + PeopleCall::Identity(pallet_identity::Call::::add_username_authority { + authority: people_westend_runtime::MultiAddress::Id(people_westend_alice.clone()), + suffix: b"suffix1".into(), + allocation: 10, + }); + + let add_authority_xcm_msg = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: add_username_authority.encode().into() } + ]))), + }); + + assert_ok!(add_authority_xcm_msg.dispatch(origin.clone())); + + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + // Check events system-parachain-side + PeopleWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::Identity(pallet_identity::Event::AuthorityAdded { .. }) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) => {}, + ] + ); + }); + + // Now, use the previously added username authority to concede a username to an account. + PeopleWestend::execute_with(|| { + type PeopleRuntimeEvent = ::RuntimeEvent; + let full_username = [usr.to_owned(), ".suffix1".to_owned()].concat().into_bytes(); + + assert_ok!(::Identity::set_username_for( + ::RuntimeOrigin::signed(people_westend_alice.clone()), + people_westend_runtime::MultiAddress::Id(people_westend_bob.clone()), + full_username, + None, + true + )); + + assert_expected_events!( + PeopleWestend, + vec![ + PeopleRuntimeEvent::Identity(pallet_identity::Event::UsernameQueued { .. }) => {}, + ] + ); + }); + + // Accept the given username + PeopleWestend::execute_with(|| { + type PeopleRuntimeEvent = ::RuntimeEvent; + let full_username = [usr.to_owned(), ".suffix1".to_owned()].concat().into_bytes(); + + assert_ok!(::Identity::accept_username( + ::RuntimeOrigin::signed(people_westend_bob.clone()), + full_username.try_into().unwrap(), + )); + + assert_expected_events!( + PeopleWestend, + vec![ + PeopleRuntimeEvent::Identity(pallet_identity::Event::UsernameSet { .. }) => {}, + ] + ); + }); + + // Now, remove the username authority with another priviledged XCM call. + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let remove_username_authority = PeopleCall::Identity(pallet_identity::Call::< + PeopleRuntime, + >::remove_username_authority { + authority: people_westend_runtime::MultiAddress::Id(people_westend_alice.clone()), + suffix: b"suffix1".into(), + }); + + let remove_authority_xcm_msg = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: remove_username_authority.encode().into() } + ]))), + }); + + assert_ok!(remove_authority_xcm_msg.dispatch(origin)); + + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + // Final event check. + PeopleWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PeopleWestend, + vec![ + RuntimeEvent::Identity(pallet_identity::Event::AuthorityRemoved { .. }) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true, .. }) => {}, + ] + ); + }); +} + +#[test] +fn relay_commands_add_remove_username_authority_wrong_origin() { + let people_westend_alice = PeopleWestend::account_id_of(ALICE); + + let origins = vec![ + ( + OriginKind::SovereignAccount, + ::RuntimeOrigin::signed(people_westend_alice.clone()), + ), + (OriginKind::Xcm, GeneralAdminOrigin.into()), + ]; + + for (origin_kind, origin) in origins { + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let add_username_authority = PeopleCall::Identity(pallet_identity::Call::< + PeopleRuntime, + >::add_username_authority { + authority: people_westend_runtime::MultiAddress::Id(people_westend_alice.clone()), + suffix: b"suffix1".into(), + allocation: 10, + }); + + let add_authority_xcm_msg = RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { origin_kind, call: add_username_authority.encode().into() } + ]))), + }); + + assert_ok!(add_authority_xcm_msg.dispatch(origin.clone())); + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + // Check events system-parachain-side + PeopleWestend::execute_with(|| { + assert_expected_events!(PeopleWestend, vec![]); + }); + + Westend::execute_with(|| { + type Runtime = ::Runtime; + type RuntimeCall = ::RuntimeCall; + type RuntimeEvent = ::RuntimeEvent; + type PeopleCall = ::RuntimeCall; + type PeopleRuntime = ::Runtime; + + let remove_username_authority = PeopleCall::Identity(pallet_identity::Call::< + PeopleRuntime, + >::remove_username_authority { + authority: people_westend_runtime::MultiAddress::Id(people_westend_alice.clone()), + suffix: b"suffix1".into(), + }); + + let remove_authority_xcm_msg = + RuntimeCall::XcmPallet(pallet_xcm::Call::::send { + dest: bx!(VersionedLocation::from(Location::new(0, [Parachain(1004)]))), + message: bx!(VersionedXcm::from(Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + Transact { + origin_kind: OriginKind::SovereignAccount, + call: remove_username_authority.encode().into(), + } + ]))), + }); + + assert_ok!(remove_authority_xcm_msg.dispatch(origin)); + assert_expected_events!( + Westend, + vec![ + RuntimeEvent::XcmPallet(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + PeopleWestend::execute_with(|| { + assert_expected_events!(PeopleWestend, vec![]); + }); + } +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs index 08749b295dc2..b9ad9e3db467 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs @@ -14,4 +14,5 @@ // limitations under the License. mod claim_assets; +mod governance; mod teleport; From 8eac4e887c827ea0bac8915901c305a05457a8d9 Mon Sep 17 00:00:00 2001 From: Dmitry Markin Date: Fri, 29 Nov 2024 23:28:34 +0200 Subject: [PATCH 163/166] network/libp2p-backend: Suppress warning adding already reserved node as reserved (#6703) Fixes https://github.com/paritytech/polkadot-sdk/issues/6598. --------- Co-authored-by: GitHub Action --- prdoc/pr_6703.prdoc | 7 +++++++ substrate/client/network/src/protocol_controller.rs | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 prdoc/pr_6703.prdoc diff --git a/prdoc/pr_6703.prdoc b/prdoc/pr_6703.prdoc new file mode 100644 index 000000000000..2dd0962a3eea --- /dev/null +++ b/prdoc/pr_6703.prdoc @@ -0,0 +1,7 @@ +title: 'network/libp2p-backend: Suppress warning adding already reserved node as reserved' +doc: +- audience: Node Dev + description: Fixes https://github.com/paritytech/polkadot-sdk/issues/6598. +crates: +- name: sc-network + bump: patch diff --git a/substrate/client/network/src/protocol_controller.rs b/substrate/client/network/src/protocol_controller.rs index af7adb50907f..11f5321294d0 100644 --- a/substrate/client/network/src/protocol_controller.rs +++ b/substrate/client/network/src/protocol_controller.rs @@ -464,7 +464,7 @@ impl ProtocolController { /// maintain connections with such peers. fn on_add_reserved_peer(&mut self, peer_id: PeerId) { if self.reserved_nodes.contains_key(&peer_id) { - warn!( + debug!( target: LOG_TARGET, "Trying to add an already reserved node {peer_id} as reserved on {:?}.", self.set_id, From 5e0bcb0ee9788b7bb16ccfbda4fdc153b24c6386 Mon Sep 17 00:00:00 2001 From: eskimor Date: Sat, 30 Nov 2024 00:31:27 +0100 Subject: [PATCH 164/166] Let's be a bit less strict here. (#6662) This might actually happen in non malicious cases. Co-authored-by: eskimor --- polkadot/node/network/collator-protocol/src/error.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polkadot/node/network/collator-protocol/src/error.rs b/polkadot/node/network/collator-protocol/src/error.rs index ae7f9a8c1fbc..598cdcf43900 100644 --- a/polkadot/node/network/collator-protocol/src/error.rs +++ b/polkadot/node/network/collator-protocol/src/error.rs @@ -122,7 +122,7 @@ impl SecondingError { PersistedValidationDataMismatch | CandidateHashMismatch | RelayParentMismatch | - Duplicate | ParentHeadDataMismatch | + ParentHeadDataMismatch | InvalidCoreIndex(_, _) | InvalidSessionIndex(_, _) | InvalidReceiptVersion(_) From d1fafa85fa1254af143b8e9b0ebf5d2731f8d91a Mon Sep 17 00:00:00 2001 From: PG Herveou Date: Sun, 1 Dec 2024 17:30:09 +0100 Subject: [PATCH 165/166] [pallet-revive] eth-prc fix geth diff (#6608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add a bunch of differential tests to ensure that responses from eth-rpc matches the one from `geth` - These [tests](https://github.com/paritytech/polkadot-sdk/blob/pg/fix-geth-diff/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts) are not run in CI for now but can be run locally with ```bash cd revive/rpc/examples/js bun test ``` * EVM RPC server will not fail gas_estimation if no gas is specified, I updated pallet-revive to add an extra `skip_transfer` boolean check to replicate this behavior in our pallet * `eth_transact` and `bare_eth_transact` api have been updated to use `GenericTransaction` directly as this is what is used by `eth_estimateGas` and `eth_call` ## TODO - [ ] Add tests the new `skip_transfer` flag --------- Co-authored-by: GitHub Action Co-authored-by: Alexander Theißen --- Cargo.lock | 1 + .../assets/asset-hub-westend/src/lib.rs | 30 +- prdoc/pr_6608.prdoc | 14 + substrate/bin/node/runtime/src/lib.rs | 25 +- substrate/frame/revive/Cargo.toml | 1 + .../frame/revive/mock-network/src/tests.rs | 4 +- substrate/frame/revive/rpc/Cargo.toml | 2 +- .../revive/rpc/examples/js/abi/errorTester.ts | 106 ++++++ .../revive/rpc/examples/js/abi/event.json | 34 -- .../frame/revive/rpc/examples/js/abi/event.ts | 34 ++ .../revive/rpc/examples/js/abi/piggyBank.json | 65 ---- .../piggyBank.ts} | 19 +- .../revive/rpc/examples/js/abi/revert.json | 14 - .../frame/revive/rpc/examples/js/bun.lockb | Bin 45391 -> 33662 bytes .../rpc/examples/js/contracts/.solhint.json | 3 + .../rpc/examples/js/contracts/ErrorTester.sol | 51 +++ .../rpc/examples/js/contracts/PiggyBank.sol | 8 +- .../frame/revive/rpc/examples/js/package.json | 41 ++- .../rpc/examples/js/pvm/errorTester.polkavm | Bin 0 -> 12890 bytes .../revive/rpc/examples/js/src/balance.ts | 8 + .../rpc/examples/js/src/build-contracts.ts | 27 +- .../frame/revive/rpc/examples/js/src/event.ts | 40 +- .../rpc/examples/js/src/geth-diff-setup.ts | 162 ++++++++ .../rpc/examples/js/src/geth-diff.test.ts | 245 +++++++++++++ .../frame/revive/rpc/examples/js/src/lib.ts | 126 ++++--- .../revive/rpc/examples/js/src/piggy-bank.ts | 81 +++- .../revive/rpc/examples/js/src/revert.ts | 10 - .../revive/rpc/examples/js/src/transfer.ts | 15 +- .../js/types/ethers-contracts/Event.ts | 117 ------ .../js/types/ethers-contracts/PiggyBank.ts | 96 ----- .../js/types/ethers-contracts/Revert.ts | 78 ---- .../js/types/ethers-contracts/common.ts | 100 ----- .../factories/Event__factory.ts | 51 --- .../factories/Revert__factory.ts | 31 -- .../types/ethers-contracts/factories/index.ts | 6 - .../js/types/ethers-contracts/index.ts | 10 - .../frame/revive/rpc/revive_chain.metadata | Bin 658056 -> 659977 bytes substrate/frame/revive/rpc/src/client.rs | 125 ++++--- substrate/frame/revive/rpc/src/lib.rs | 44 +-- .../frame/revive/rpc/src/rpc_methods_gen.rs | 1 + .../frame/revive/rpc/src/subxt_client.rs | 12 +- substrate/frame/revive/rpc/src/tests.rs | 3 +- .../frame/revive/src/benchmarking/mod.rs | 2 +- .../frame/revive/src/evm/api/rlp_codec.rs | 18 +- .../frame/revive/src/evm/api/rpc_types.rs | 148 ++++---- .../frame/revive/src/evm/api/rpc_types_gen.rs | 24 +- substrate/frame/revive/src/evm/runtime.rs | 345 ++++++++++-------- substrate/frame/revive/src/exec.rs | 73 +++- substrate/frame/revive/src/lib.rs | 215 +++++++---- substrate/frame/revive/src/primitives.rs | 45 ++- substrate/frame/revive/src/storage/meter.rs | 52 ++- .../frame/revive/src/test_utils/builder.rs | 11 +- substrate/frame/revive/src/tests.rs | 12 +- .../frame/revive/src/tests/test_debug.rs | 5 +- substrate/frame/revive/src/wasm/mod.rs | 11 +- 55 files changed, 1553 insertions(+), 1248 deletions(-) create mode 100644 prdoc/pr_6608.prdoc create mode 100644 substrate/frame/revive/rpc/examples/js/abi/errorTester.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/abi/event.json create mode 100644 substrate/frame/revive/rpc/examples/js/abi/event.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/abi/piggyBank.json rename substrate/frame/revive/rpc/examples/js/{types/ethers-contracts/factories/PiggyBank__factory.ts => abi/piggyBank.ts} (62%) delete mode 100644 substrate/frame/revive/rpc/examples/js/abi/revert.json create mode 100644 substrate/frame/revive/rpc/examples/js/contracts/.solhint.json create mode 100644 substrate/frame/revive/rpc/examples/js/contracts/ErrorTester.sol create mode 100644 substrate/frame/revive/rpc/examples/js/pvm/errorTester.polkavm create mode 100644 substrate/frame/revive/rpc/examples/js/src/balance.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/geth-diff-setup.ts create mode 100644 substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/src/revert.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts delete mode 100644 substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts diff --git a/Cargo.lock b/Cargo.lock index a945d148e051..bc2ebb2a057d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14633,6 +14633,7 @@ dependencies = [ "assert_matches", "bitflags 1.3.2", "derive_more 0.99.17", + "env_logger 0.11.3", "environmental", "ethereum-types 0.15.1", "frame-benchmarking 28.0.0", 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 f20b6b1fece0..98d647d868db 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -124,7 +124,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: alloc::borrow::Cow::Borrowed("westmint"), impl_name: alloc::borrow::Cow::Borrowed("westmint"), authoring_version: 1, - spec_version: 1_016_006, + spec_version: 1_016_008, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, @@ -2081,18 +2081,10 @@ impl_runtime_apis! { let account = ::AddressMapper::to_account_id(&address); System::account_nonce(account) } - fn eth_transact( - from: H160, - dest: Option, - value: U256, - input: Vec, - gas_limit: Option, - storage_deposit_limit: Option, - ) -> pallet_revive::EthContractResult + + fn eth_transact(tx: pallet_revive::evm::GenericTransaction) -> Result, pallet_revive::EthTransactError> { - use pallet_revive::AddressMapper; - let blockweights = ::BlockWeights::get(); - let origin = ::AddressMapper::to_account_id(&from); + let blockweights: BlockWeights = ::BlockWeights::get(); let encoded_size = |pallet_call| { let call = RuntimeCall::Revive(pallet_call); @@ -2101,15 +2093,9 @@ impl_runtime_apis! { }; Revive::bare_eth_transact( - origin, - dest, - value, - input, - gas_limit.unwrap_or(blockweights.max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + tx, + blockweights.max_block, encoded_size, - pallet_revive::DebugInfo::UnsafeDebug, - pallet_revive::CollectEvents::UnsafeCollect, ) } @@ -2127,7 +2113,7 @@ impl_runtime_apis! { dest, value, gas_limit.unwrap_or(blockweights.max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)), input_data, pallet_revive::DebugInfo::UnsafeDebug, pallet_revive::CollectEvents::UnsafeCollect, @@ -2149,7 +2135,7 @@ impl_runtime_apis! { RuntimeOrigin::signed(origin), value, gas_limit.unwrap_or(blockweights.max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)), code, data, salt, diff --git a/prdoc/pr_6608.prdoc b/prdoc/pr_6608.prdoc new file mode 100644 index 000000000000..b9cd7008de47 --- /dev/null +++ b/prdoc/pr_6608.prdoc @@ -0,0 +1,14 @@ +title: '[pallet-revive] eth-prc fix geth diff' +doc: +- audience: Runtime Dev + description: |- + * Add a bunch of differential tests to ensure that responses from eth-rpc matches the one from `geth` + * EVM RPC server will not fail gas_estimation if no gas is specified, I updated pallet-revive to add an extra `skip_transfer` boolean check to replicate this behavior in our pallet + * `eth_transact` and `bare_eth_transact` api have been updated to use `GenericTransaction` directly as this is what is used by `eth_estimateGas` and `eth_call` +crates: +- name: pallet-revive-eth-rpc + bump: minor +- name: pallet-revive + bump: minor +- name: asset-hub-westend-runtime + bump: minor diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index bff263548087..faffcd23fbcf 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -3218,18 +3218,9 @@ impl_runtime_apis! { System::account_nonce(account) } - fn eth_transact( - from: H160, - dest: Option, - value: U256, - input: Vec, - gas_limit: Option, - storage_deposit_limit: Option, - ) -> pallet_revive::EthContractResult + fn eth_transact(tx: pallet_revive::evm::GenericTransaction) -> Result, pallet_revive::EthTransactError> { - use pallet_revive::AddressMapper; let blockweights: BlockWeights = ::BlockWeights::get(); - let origin = ::AddressMapper::to_account_id(&from); let encoded_size = |pallet_call| { let call = RuntimeCall::Revive(pallet_call); @@ -3238,15 +3229,9 @@ impl_runtime_apis! { }; Revive::bare_eth_transact( - origin, - dest, - value, - input, - gas_limit.unwrap_or(blockweights.max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + tx, + blockweights.max_block, encoded_size, - pallet_revive::DebugInfo::UnsafeDebug, - pallet_revive::CollectEvents::UnsafeCollect, ) } @@ -3263,7 +3248,7 @@ impl_runtime_apis! { dest, value, gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)), input_data, pallet_revive::DebugInfo::UnsafeDebug, pallet_revive::CollectEvents::UnsafeCollect, @@ -3284,7 +3269,7 @@ impl_runtime_apis! { RuntimeOrigin::signed(origin), value, gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block), - storage_deposit_limit.unwrap_or(u128::MAX), + pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)), code, data, salt, diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index 677ef0e1367f..098a66df8dee 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -65,6 +65,7 @@ pallet-revive-fixtures = { workspace = true, default-features = true } secp256k1 = { workspace = true, features = ["recovery"] } serde_json = { workspace = true } hex-literal = { workspace = true } +env_logger = { workspace = true } # Polkadot SDK Dependencies pallet-balances = { workspace = true, default-features = true } diff --git a/substrate/frame/revive/mock-network/src/tests.rs b/substrate/frame/revive/mock-network/src/tests.rs index bd05726a1a45..34f797c2b530 100644 --- a/substrate/frame/revive/mock-network/src/tests.rs +++ b/substrate/frame/revive/mock-network/src/tests.rs @@ -24,7 +24,7 @@ use frame_support::traits::{fungibles::Mutate, Currency}; use frame_system::RawOrigin; use pallet_revive::{ test_utils::{self, builder::*}, - Code, + Code, DepositLimit, }; use pallet_revive_fixtures::compile_module; use pallet_revive_uapi::ReturnErrorCode; @@ -52,7 +52,7 @@ fn instantiate_test_contract(name: &str) -> Contract { RawOrigin::Signed(ALICE).into(), Code::Upload(wasm), ) - .storage_deposit_limit(1_000_000_000_000) + .storage_deposit_limit(DepositLimit::Balance(1_000_000_000_000)) .build_and_unwrap_contract() }); diff --git a/substrate/frame/revive/rpc/Cargo.toml b/substrate/frame/revive/rpc/Cargo.toml index 9f89b74c668f..fe9cc82dd4d9 100644 --- a/substrate/frame/revive/rpc/Cargo.toml +++ b/substrate/frame/revive/rpc/Cargo.toml @@ -67,13 +67,13 @@ hex = { workspace = true } hex-literal = { workspace = true, optional = true } scale-info = { workspace = true } secp256k1 = { workspace = true, optional = true, features = ["recovery"] } -env_logger = { workspace = true } ethabi = { version = "18.0.0" } [features] example = ["hex-literal", "rlp", "secp256k1", "subxt-signer"] [dev-dependencies] +env_logger = { workspace = true } static_init = { workspace = true } hex-literal = { workspace = true } pallet-revive-fixtures = { workspace = true } diff --git a/substrate/frame/revive/rpc/examples/js/abi/errorTester.ts b/substrate/frame/revive/rpc/examples/js/abi/errorTester.ts new file mode 100644 index 000000000000..93daf34e02b6 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/abi/errorTester.ts @@ -0,0 +1,106 @@ +export const abi = [ + { + inputs: [ + { + internalType: 'string', + name: 'message', + type: 'string', + }, + ], + name: 'CustomError', + type: 'error', + }, + { + inputs: [ + { + internalType: 'bool', + name: 'newState', + type: 'bool', + }, + ], + name: 'setState', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, + { + inputs: [], + name: 'state', + outputs: [ + { + internalType: 'bool', + name: '', + type: 'bool', + }, + ], + stateMutability: 'view', + type: 'function', + }, + { + inputs: [], + name: 'triggerAssertError', + outputs: [], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [], + name: 'triggerCustomError', + outputs: [], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [], + name: 'triggerDivisionByZero', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + ], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [], + name: 'triggerOutOfBoundsError', + outputs: [ + { + internalType: 'uint256', + name: '', + type: 'uint256', + }, + ], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [], + name: 'triggerRequireError', + outputs: [], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [], + name: 'triggerRevertError', + outputs: [], + stateMutability: 'pure', + type: 'function', + }, + { + inputs: [ + { + internalType: 'uint256', + name: 'value', + type: 'uint256', + }, + ], + name: 'valueMatch', + outputs: [], + stateMutability: 'payable', + type: 'function', + }, +] as const diff --git a/substrate/frame/revive/rpc/examples/js/abi/event.json b/substrate/frame/revive/rpc/examples/js/abi/event.json deleted file mode 100644 index d36089fbc84e..000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/event.json +++ /dev/null @@ -1,34 +0,0 @@ -[ - { - "anonymous": false, - "inputs": [ - { - "indexed": true, - "internalType": "address", - "name": "sender", - "type": "address" - }, - { - "indexed": false, - "internalType": "uint256", - "name": "value", - "type": "uint256" - }, - { - "indexed": false, - "internalType": "string", - "name": "message", - "type": "string" - } - ], - "name": "ExampleEvent", - "type": "event" - }, - { - "inputs": [], - "name": "triggerEvent", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/substrate/frame/revive/rpc/examples/js/abi/event.ts b/substrate/frame/revive/rpc/examples/js/abi/event.ts new file mode 100644 index 000000000000..c389e2daf1da --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/abi/event.ts @@ -0,0 +1,34 @@ +export const abi = [ + { + anonymous: false, + inputs: [ + { + indexed: true, + internalType: 'address', + name: 'sender', + type: 'address', + }, + { + indexed: false, + internalType: 'uint256', + name: 'value', + type: 'uint256', + }, + { + indexed: false, + internalType: 'string', + name: 'message', + type: 'string', + }, + ], + name: 'ExampleEvent', + type: 'event', + }, + { + inputs: [], + name: 'triggerEvent', + outputs: [], + stateMutability: 'nonpayable', + type: 'function', + }, +] as const diff --git a/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json deleted file mode 100644 index 2c2cfd5f7533..000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/piggyBank.json +++ /dev/null @@ -1,65 +0,0 @@ -[ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "deposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "payable", - "type": "function" - }, - { - "inputs": [], - "name": "getDeposit", - "outputs": [ - { - "internalType": "uint256", - "name": "", - "type": "uint256" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [], - "name": "owner", - "outputs": [ - { - "internalType": "address", - "name": "", - "type": "address" - } - ], - "stateMutability": "view", - "type": "function" - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "withdrawAmount", - "type": "uint256" - } - ], - "name": "withdraw", - "outputs": [ - { - "internalType": "uint256", - "name": "remainingBal", - "type": "uint256" - } - ], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts similarity index 62% rename from substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts rename to substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts index 0efea80ed2dc..3d44cd998ad1 100644 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/PiggyBank__factory.ts +++ b/substrate/frame/revive/rpc/examples/js/abi/piggyBank.ts @@ -1,11 +1,4 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ - -import { Contract, Interface, type ContractRunner } from 'ethers' -import type { PiggyBank, PiggyBankInterface } from '../PiggyBank' - -const _abi = [ +export const abi = [ { inputs: [], stateMutability: 'nonpayable', @@ -70,13 +63,3 @@ const _abi = [ type: 'function', }, ] as const - -export class PiggyBank__factory { - static readonly abi = _abi - static createInterface(): PiggyBankInterface { - return new Interface(_abi) as PiggyBankInterface - } - static connect(address: string, runner?: ContractRunner | null): PiggyBank { - return new Contract(address, _abi, runner) as unknown as PiggyBank - } -} diff --git a/substrate/frame/revive/rpc/examples/js/abi/revert.json b/substrate/frame/revive/rpc/examples/js/abi/revert.json deleted file mode 100644 index be2945fcc0a5..000000000000 --- a/substrate/frame/revive/rpc/examples/js/abi/revert.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - { - "inputs": [], - "stateMutability": "nonpayable", - "type": "constructor" - }, - { - "inputs": [], - "name": "doRevert", - "outputs": [], - "stateMutability": "nonpayable", - "type": "function" - } -] diff --git a/substrate/frame/revive/rpc/examples/js/bun.lockb b/substrate/frame/revive/rpc/examples/js/bun.lockb index 700dca51da2ad3f843e890258b59c16fd4df6457..0ff3d54157db21a636e30076634343a24c812dca 100755 GIT binary patch delta 9083 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 delta 15944 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 diff --git a/substrate/frame/revive/rpc/examples/js/contracts/.solhint.json b/substrate/frame/revive/rpc/examples/js/contracts/.solhint.json new file mode 100644 index 000000000000..ce2220e0b756 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/contracts/.solhint.json @@ -0,0 +1,3 @@ +{ + "extends": "solhint:recommended" +} diff --git a/substrate/frame/revive/rpc/examples/js/contracts/ErrorTester.sol b/substrate/frame/revive/rpc/examples/js/contracts/ErrorTester.sol new file mode 100644 index 000000000000..f1fdd219624a --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/contracts/ErrorTester.sol @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +contract ErrorTester { + bool public state; + + // Payable function that can be used to test insufficient funds errors + function valueMatch(uint256 value) public payable { + require(msg.value == value , "msg.value does not match value"); + } + + function setState(bool newState) public { + state = newState; + } + + // Trigger a require statement failure with a custom error message + function triggerRequireError() public pure { + require(false, "This is a require error"); + } + + // Trigger an assert statement failure + function triggerAssertError() public pure { + assert(false); + } + + // Trigger a revert statement with a custom error message + function triggerRevertError() public pure { + revert("This is a revert error"); + } + + // Trigger a division by zero error + function triggerDivisionByZero() public pure returns (uint256) { + uint256 a = 1; + uint256 b = 0; + return a / b; + } + + // Trigger an out-of-bounds array access + function triggerOutOfBoundsError() public pure returns (uint256) { + uint256[] memory arr = new uint256[](1); + return arr[2]; + } + + // Trigger a custom error + error CustomError(string message); + + function triggerCustomError() public pure { + revert CustomError("This is a custom error"); + } +} + diff --git a/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol b/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol index 1906c4658889..0c8a4d26f4dc 100644 --- a/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol +++ b/substrate/frame/revive/rpc/examples/js/contracts/PiggyBank.sol @@ -3,7 +3,7 @@ pragma solidity ^0.8.0; contract PiggyBank { - uint private balance; + uint256 private balance; address public owner; constructor() { @@ -11,16 +11,16 @@ contract PiggyBank { balance = 0; } - function deposit() public payable returns (uint) { + function deposit() public payable returns (uint256) { balance += msg.value; return balance; } - function getDeposit() public view returns (uint) { + function getDeposit() public view returns (uint256) { return balance; } - function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + function withdraw(uint256 withdrawAmount) public returns (uint256 remainingBal) { require(msg.sender == owner); balance -= withdrawAmount; (bool success, ) = payable(msg.sender).call{value: withdrawAmount}(""); diff --git a/substrate/frame/revive/rpc/examples/js/package.json b/substrate/frame/revive/rpc/examples/js/package.json index 3ae1f0fbd799..6d8d00fd4214 100644 --- a/substrate/frame/revive/rpc/examples/js/package.json +++ b/substrate/frame/revive/rpc/examples/js/package.json @@ -1,22 +1,23 @@ { - "name": "demo", - "private": true, - "version": "0.0.0", - "type": "module", - "scripts": { - "dev": "vite", - "build": "tsc && vite build", - "preview": "vite preview", - "generate-types": "typechain --target=ethers-v6 'abi/*.json'" - }, - "dependencies": { - "@typechain/ethers-v6": "^0.5.1", - "ethers": "^6.13.4", - "solc": "^0.8.28", - "typechain": "^8.3.2" - }, - "devDependencies": { - "typescript": "^5.5.3", - "vite": "^5.4.8" - } + "name": "demo", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc && vite build", + "preview": "vite preview" + }, + "dependencies": { + "ethers": "^6.13.4", + "solc": "^0.8.28", + "viem": "^2.21.47", + "@parity/revive": "^0.0.5" + }, + "devDependencies": { + "prettier": "^3.3.3", + "@types/bun": "^1.1.13", + "typescript": "^5.5.3", + "vite": "^5.4.8" + } } diff --git a/substrate/frame/revive/rpc/examples/js/pvm/errorTester.polkavm b/substrate/frame/revive/rpc/examples/js/pvm/errorTester.polkavm new file mode 100644 index 0000000000000000000000000000000000000000..aebe24c4c0f597fb3d0171a9f527bc86d2d77b93 GIT binary patch literal 12890 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 P|DsnIq4bp_3F&_TlmMih literal 0 HcmV?d00001 diff --git a/substrate/frame/revive/rpc/examples/js/src/balance.ts b/substrate/frame/revive/rpc/examples/js/src/balance.ts new file mode 100644 index 000000000000..1261dcab7812 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/balance.ts @@ -0,0 +1,8 @@ +import { walletClient } from './lib.ts' + +const recipient = '0x8D97689C9818892B700e27F316cc3E41e17fBeb9' +try { + console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) +} catch (err) { + console.error(err) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts b/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts index c6b7700d1ccf..b25b5a7f2199 100644 --- a/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts +++ b/substrate/frame/revive/rpc/examples/js/src/build-contracts.ts @@ -1,11 +1,23 @@ import { compile } from '@parity/revive' +import { format } from 'prettier' +import { parseArgs } from 'node:util' import solc from 'solc' import { readFileSync, writeFileSync } from 'fs' import { join } from 'path' type CompileInput = Parameters[0] -type CompileOutput = Awaited> -type Abi = CompileOutput['contracts'][string][string]['abi'] + +const { + values: { filter }, +} = parseArgs({ + args: process.argv.slice(2), + options: { + filter: { + type: 'string', + short: 'f', + }, + }, +}) function evmCompile(sources: CompileInput) { const input = { @@ -27,9 +39,9 @@ console.log('Compiling contracts...') const input = [ { file: 'Event.sol', contract: 'EventExample', keypath: 'event' }, - { file: 'Revert.sol', contract: 'RevertExample', keypath: 'revert' }, { file: 'PiggyBank.sol', contract: 'PiggyBank', keypath: 'piggyBank' }, -] + { file: 'ErrorTester.sol', contract: 'ErrorTester', keypath: 'errorTester' }, +].filter(({ keypath }) => !filter || keypath.includes(filter)) for (const { keypath, contract, file } of input) { const input = { @@ -41,7 +53,12 @@ for (const { keypath, contract, file } of input) { const out = JSON.parse(evmCompile(input)) const entry = out.contracts[file][contract] writeFileSync(join('evm', `${keypath}.bin`), Buffer.from(entry.evm.bytecode.object, 'hex')) - writeFileSync(join('abi', `${keypath}.json`), JSON.stringify(entry.abi, null, 2)) + writeFileSync( + join('abi', `${keypath}.ts`), + await format(`export const abi = ${JSON.stringify(entry.abi, null, 2)} as const`, { + parser: 'typescript', + }) + ) } { diff --git a/substrate/frame/revive/rpc/examples/js/src/event.ts b/substrate/frame/revive/rpc/examples/js/src/event.ts index 94cc2560272e..2e672a9772ff 100644 --- a/substrate/frame/revive/rpc/examples/js/src/event.ts +++ b/substrate/frame/revive/rpc/examples/js/src/event.ts @@ -1,15 +1,29 @@ //! Run with bun run script-event.ts -import { call, getContract, deploy } from './lib.ts' - -try { - const { abi, bytecode } = getContract('event') - const contract = await deploy(bytecode, abi) - const receipt = await call('triggerEvent', await contract.getAddress(), abi) - if (receipt) { - for (const log of receipt.logs) { - console.log('Event log:', JSON.stringify(log, null, 2)) - } - } -} catch (err) { - console.error(err) + +import { abi } from '../abi/event.ts' +import { assert, getByteCode, walletClient } from './lib.ts' + +const deployHash = await walletClient.deployContract({ + abi, + bytecode: getByteCode('event'), +}) +const deployReceipt = await walletClient.waitForTransactionReceipt({ hash: deployHash }) +const contractAddress = deployReceipt.contractAddress +console.log('Contract deployed:', contractAddress) +assert(contractAddress, 'Contract address should be set') + +const { request } = await walletClient.simulateContract({ + account: walletClient.account, + address: contractAddress, + abi, + functionName: 'triggerEvent', +}) + +const hash = await walletClient.writeContract(request) +const receipt = await walletClient.waitForTransactionReceipt({ hash }) +console.log(`Receipt: ${receipt.status}`) +console.log(`Logs receipt: ${receipt.status}`) + +for (const log of receipt.logs) { + console.log('Event log:', log) } diff --git a/substrate/frame/revive/rpc/examples/js/src/geth-diff-setup.ts b/substrate/frame/revive/rpc/examples/js/src/geth-diff-setup.ts new file mode 100644 index 000000000000..92b20473d165 --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/geth-diff-setup.ts @@ -0,0 +1,162 @@ +import { spawn, spawnSync, Subprocess } from 'bun' +import { join, resolve } from 'path' +import { readFileSync } from 'fs' +import { createWalletClient, defineChain, Hex, http, publicActions } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' + +export function getByteCode(name: string, evm: boolean): Hex { + const bytecode = evm ? readFileSync(`evm/${name}.bin`) : readFileSync(`pvm/${name}.polkavm`) + return `0x${Buffer.from(bytecode).toString('hex')}` +} + +export type JsonRpcError = { + code: number + message: string + data: Hex +} + +export function killProcessOnPort(port: number) { + // Check which process is using the specified port + const result = spawnSync(['lsof', '-ti', `:${port}`]) + const output = result.stdout.toString().trim() + + if (output) { + console.log(`Port ${port} is in use. Killing process...`) + const pids = output.split('\n') + + // Kill each process using the port + for (const pid of pids) { + spawnSync(['kill', '-9', pid]) + console.log(`Killed process with PID: ${pid}`) + } + } +} + +export let jsonRpcErrors: JsonRpcError[] = [] +export async function createEnv(name: 'geth' | 'kitchensink') { + const gethPort = process.env.GETH_PORT || '8546' + const kitchensinkPort = process.env.KITCHENSINK_PORT || '8545' + const url = `http://localhost:${name == 'geth' ? gethPort : kitchensinkPort}` + const chain = defineChain({ + id: name == 'geth' ? 1337 : 420420420, + name, + nativeCurrency: { + name: 'Westie', + symbol: 'WST', + decimals: 18, + }, + rpcUrls: { + default: { + http: [url], + }, + }, + testnet: true, + }) + + const transport = http(url, { + onFetchResponse: async (response) => { + const raw = await response.clone().json() + if (raw.error) { + jsonRpcErrors.push(raw.error as JsonRpcError) + } + }, + }) + + const wallet = createWalletClient({ + transport, + chain, + }) + + const [account] = await wallet.getAddresses() + const serverWallet = createWalletClient({ + account, + transport, + chain, + }).extend(publicActions) + + const accountWallet = createWalletClient({ + account: privateKeyToAccount( + '0xa872f6cbd25a0e04a08b1e21098017a9e6194d101d75e13111f71410c59cd57f' + ), + transport, + chain, + }).extend(publicActions) + + return { serverWallet, accountWallet, evm: name == 'geth' } +} + +// wait for http request to return 200 +export function waitForHealth(url: string) { + return new Promise((resolve, reject) => { + const start = Date.now() + const interval = setInterval(() => { + fetch(url) + .then((res) => { + if (res.status === 200) { + clearInterval(interval) + resolve() + } + }) + .catch(() => { + const elapsed = Date.now() - start + if (elapsed > 30_000) { + clearInterval(interval) + reject(new Error('hit timeout')) + } + }) + }, 1000) + }) +} + +export const procs: Subprocess[] = [] +const polkadotSdkPath = resolve(__dirname, '../../../../../../..') +if (!process.env.USE_LIVE_SERVERS) { + procs.push( + // Run geth on port 8546 + // + (() => { + killProcessOnPort(8546) + return spawn( + 'geth --http --http.api web3,eth,debug,personal,net --http.port 8546 --dev --verbosity 0'.split( + ' ' + ), + { stdout: Bun.file('/tmp/geth.out.log'), stderr: Bun.file('/tmp/geth.err.log') } + ) + })(), + //Run the substate node + (() => { + killProcessOnPort(9944) + return spawn( + [ + './target/debug/substrate-node', + '--dev', + '-l=error,evm=debug,sc_rpc_server=info,runtime::revive=debug', + ], + { + stdout: Bun.file('/tmp/kitchensink.out.log'), + stderr: Bun.file('/tmp/kitchensink.err.log'), + cwd: polkadotSdkPath, + } + ) + })(), + // Run eth-rpc on 8545 + await (async () => { + killProcessOnPort(8545) + const proc = spawn( + [ + './target/debug/eth-rpc', + '--dev', + '--node-rpc-url=ws://localhost:9944', + '-l=rpc-metrics=debug,eth-rpc=debug', + ], + { + stdout: Bun.file('/tmp/eth-rpc.out.log'), + stderr: Bun.file('/tmp/eth-rpc.err.log'), + cwd: polkadotSdkPath, + } + ) + await waitForHealth('http://localhost:8545/health').catch() + return proc + })() + ) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts b/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts new file mode 100644 index 000000000000..468e7860bb9a --- /dev/null +++ b/substrate/frame/revive/rpc/examples/js/src/geth-diff.test.ts @@ -0,0 +1,245 @@ +import { jsonRpcErrors, procs, createEnv, getByteCode } from './geth-diff-setup.ts' +import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test' +import { encodeFunctionData, Hex, parseEther } from 'viem' +import { abi } from '../abi/errorTester' + +afterEach(() => { + jsonRpcErrors.length = 0 +}) + +afterAll(async () => { + procs.forEach((proc) => proc.kill()) +}) + +const envs = await Promise.all([createEnv('geth'), createEnv('kitchensink')]) + +for (const env of envs) { + describe(env.serverWallet.chain.name, () => { + let errorTesterAddr: Hex = '0x' + beforeAll(async () => { + const hash = await env.serverWallet.deployContract({ + abi, + bytecode: getByteCode('errorTester', env.evm), + }) + const deployReceipt = await env.serverWallet.waitForTransactionReceipt({ hash }) + if (!deployReceipt.contractAddress) throw new Error('Contract address should be set') + errorTesterAddr = deployReceipt.contractAddress + }) + + test('triggerAssertError', async () => { + expect.assertions(3) + try { + await env.accountWallet.readContract({ + address: errorTesterAddr, + abi, + functionName: 'triggerAssertError', + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.data).toBe( + '0x4e487b710000000000000000000000000000000000000000000000000000000000000001' + ) + expect(lastJsonRpcError?.message).toBe('execution reverted: assert(false)') + } + }) + + test('triggerRevertError', async () => { + expect.assertions(3) + try { + await env.accountWallet.readContract({ + address: errorTesterAddr, + abi, + functionName: 'triggerRevertError', + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.message).toBe('execution reverted: This is a revert error') + expect(lastJsonRpcError?.data).toBe( + '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001654686973206973206120726576657274206572726f7200000000000000000000' + ) + } + }) + + test('triggerDivisionByZero', async () => { + expect.assertions(3) + try { + await env.accountWallet.readContract({ + address: errorTesterAddr, + abi, + functionName: 'triggerDivisionByZero', + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.data).toBe( + '0x4e487b710000000000000000000000000000000000000000000000000000000000000012' + ) + expect(lastJsonRpcError?.message).toBe( + 'execution reverted: division or modulo by zero' + ) + } + }) + + test('triggerOutOfBoundsError', async () => { + expect.assertions(3) + try { + await env.accountWallet.readContract({ + address: errorTesterAddr, + abi, + functionName: 'triggerOutOfBoundsError', + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.data).toBe( + '0x4e487b710000000000000000000000000000000000000000000000000000000000000032' + ) + expect(lastJsonRpcError?.message).toBe( + 'execution reverted: out-of-bounds access of an array or bytesN' + ) + } + }) + + test('triggerCustomError', async () => { + expect.assertions(3) + try { + await env.accountWallet.readContract({ + address: errorTesterAddr, + abi, + functionName: 'triggerCustomError', + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.data).toBe( + '0x8d6ea8be0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001654686973206973206120637573746f6d206572726f7200000000000000000000' + ) + expect(lastJsonRpcError?.message).toBe('execution reverted') + } + }) + + test('eth_call (not enough funds)', async () => { + expect.assertions(3) + try { + await env.accountWallet.simulateContract({ + address: errorTesterAddr, + abi, + functionName: 'valueMatch', + value: parseEther('10'), + args: [parseEther('10')], + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(-32000) + expect(lastJsonRpcError?.message).toInclude('insufficient funds') + expect(lastJsonRpcError?.data).toBeUndefined() + } + }) + + test('eth_call transfer (not enough funds)', async () => { + expect.assertions(3) + try { + await env.accountWallet.sendTransaction({ + to: '0x75E480dB528101a381Ce68544611C169Ad7EB342', + value: parseEther('10'), + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(-32000) + expect(lastJsonRpcError?.message).toInclude('insufficient funds') + expect(lastJsonRpcError?.data).toBeUndefined() + } + }) + + test('eth_estimate (not enough funds)', async () => { + expect.assertions(3) + try { + await env.accountWallet.estimateContractGas({ + address: errorTesterAddr, + abi, + functionName: 'valueMatch', + value: parseEther('10'), + args: [parseEther('10')], + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(-32000) + expect(lastJsonRpcError?.message).toInclude('insufficient funds') + expect(lastJsonRpcError?.data).toBeUndefined() + } + }) + + test('eth_estimate (revert)', async () => { + expect.assertions(3) + try { + await env.serverWallet.estimateContractGas({ + address: errorTesterAddr, + abi, + functionName: 'valueMatch', + value: parseEther('11'), + args: [parseEther('10')], + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(3) + expect(lastJsonRpcError?.message).toBe( + 'execution reverted: msg.value does not match value' + ) + expect(lastJsonRpcError?.data).toBe( + '0x08c379a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001e6d73672e76616c756520646f6573206e6f74206d617463682076616c75650000' + ) + } + }) + + test('eth_get_balance (no account)', async () => { + const balance = await env.serverWallet.getBalance({ + address: '0x0000000000000000000000000000000000000123', + }) + expect(balance).toBe(0n) + }) + + test('eth_estimate (not enough funds to cover gas specified)', async () => { + expect.assertions(4) + try { + let balance = await env.serverWallet.getBalance(env.accountWallet.account) + expect(balance).toBe(0n) + + await env.accountWallet.estimateContractGas({ + address: errorTesterAddr, + abi, + functionName: 'setState', + args: [true], + }) + } catch (err) { + const lastJsonRpcError = jsonRpcErrors.pop() + expect(lastJsonRpcError?.code).toBe(-32000) + expect(lastJsonRpcError?.message).toInclude('insufficient funds') + expect(lastJsonRpcError?.data).toBeUndefined() + } + }) + + test('eth_estimate (no gas specified)', async () => { + let balance = await env.serverWallet.getBalance(env.accountWallet.account) + expect(balance).toBe(0n) + + const data = encodeFunctionData({ + abi, + functionName: 'setState', + args: [true], + }) + + await env.accountWallet.request({ + method: 'eth_estimateGas', + params: [ + { + data, + from: env.accountWallet.account.address, + to: errorTesterAddr, + }, + ], + }) + }) + }) +} diff --git a/substrate/frame/revive/rpc/examples/js/src/lib.ts b/substrate/frame/revive/rpc/examples/js/src/lib.ts index 975d8faf15b3..e1f0e780d95b 100644 --- a/substrate/frame/revive/rpc/examples/js/src/lib.ts +++ b/substrate/frame/revive/rpc/examples/js/src/lib.ts @@ -1,22 +1,11 @@ -import { - Contract, - ContractFactory, - JsonRpcProvider, - TransactionReceipt, - TransactionResponse, - Wallet, -} from 'ethers' import { readFileSync } from 'node:fs' -import type { compile } from '@parity/revive' import { spawn } from 'node:child_process' import { parseArgs } from 'node:util' -import { BaseContract } from 'ethers' - -type CompileOutput = Awaited> -type Abi = CompileOutput['contracts'][string][string]['abi'] +import { createWalletClient, defineChain, Hex, http, parseEther, publicActions } from 'viem' +import { privateKeyToAccount } from 'viem/accounts' const { - values: { geth, westend, ['private-key']: privateKey }, + values: { geth, proxy, westend, endowment, ['private-key']: privateKey }, } = parseArgs({ args: process.argv.slice(2), options: { @@ -24,6 +13,13 @@ const { type: 'string', short: 'k', }, + endowment: { + type: 'string', + short: 'e', + }, + proxy: { + type: 'boolean', + }, geth: { type: 'boolean', }, @@ -42,7 +38,7 @@ if (geth) { '--http.api', 'web3,eth,debug,personal,net', '--http.port', - '8546', + process.env.GETH_PORT ?? '8546', '--dev', '--verbosity', '0', @@ -55,56 +51,78 @@ if (geth) { await new Promise((resolve) => setTimeout(resolve, 500)) } -export const provider = new JsonRpcProvider( - westend +const rpcUrl = proxy + ? 'http://localhost:8080' + : westend ? 'https://westend-asset-hub-eth-rpc.polkadot.io' : geth ? 'http://localhost:8546' : 'http://localhost:8545' -) -export const signer = privateKey ? new Wallet(privateKey, provider) : await provider.getSigner() -console.log(`Signer address: ${await signer.getAddress()}, Nonce: ${await signer.getNonce()}`) +export const chain = defineChain({ + id: geth ? 1337 : 420420420, + name: 'Asset Hub Westend', + network: 'asset-hub', + nativeCurrency: { + name: 'Westie', + symbol: 'WST', + decimals: 18, + }, + rpcUrls: { + default: { + http: [rpcUrl], + }, + }, + testnet: true, +}) + +const wallet = createWalletClient({ + transport: http(), + chain, +}) +const [account] = await wallet.getAddresses() +export const serverWalletClient = createWalletClient({ + account, + transport: http(), + chain, +}) + +export const walletClient = await (async () => { + if (privateKey) { + const account = privateKeyToAccount(`0x${privateKey}`) + console.log(`Wallet address ${account.address}`) + + const wallet = createWalletClient({ + account, + transport: http(), + chain, + }) + + if (endowment) { + await serverWalletClient.sendTransaction({ + to: account.address, + value: parseEther(endowment), + }) + console.log(`Endowed address ${account.address} with: ${endowment}`) + } + + return wallet.extend(publicActions) + } else { + return serverWalletClient.extend(publicActions) + } +})() /** * Get one of the pre-built contracts * @param name - the contract name */ -export function getContract(name: string): { abi: Abi; bytecode: string } { +export function getByteCode(name: string): Hex { const bytecode = geth ? readFileSync(`evm/${name}.bin`) : readFileSync(`pvm/${name}.polkavm`) - const abi = JSON.parse(readFileSync(`abi/${name}.json`, 'utf8')) as Abi - return { abi, bytecode: Buffer.from(bytecode).toString('hex') } + return `0x${Buffer.from(bytecode).toString('hex')}` } -/** - * Deploy a contract - * @returns the contract address - **/ -export async function deploy(bytecode: string, abi: Abi, args: any[] = []): Promise { - console.log('Deploying contract with', args) - const contractFactory = new ContractFactory(abi, bytecode, signer) - - const contract = await contractFactory.deploy(args) - await contract.waitForDeployment() - const address = await contract.getAddress() - console.log(`Contract deployed: ${address}`) - - return contract -} - -/** - * Call a contract - **/ -export async function call( - method: string, - address: string, - abi: Abi, - args: any[] = [], - opts: { value?: bigint } = {} -): Promise { - console.log(`Calling ${method} at ${address} with`, args, opts) - const contract = new Contract(address, abi, signer) - const tx = (await contract[method](...args, opts)) as TransactionResponse - console.log('Call transaction hash:', tx.hash) - return tx.wait() +export function assert(condition: any, message: string): asserts condition { + if (!condition) { + throw new Error(message) + } } diff --git a/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts b/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts index 7a8edbde3662..0040b0c78dc4 100644 --- a/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts +++ b/substrate/frame/revive/rpc/examples/js/src/piggy-bank.ts @@ -1,24 +1,69 @@ -import { provider, call, getContract, deploy } from './lib.ts' -import { parseEther } from 'ethers' -import { PiggyBank } from '../types/ethers-contracts/PiggyBank' +import { assert, getByteCode, walletClient } from './lib.ts' +import { abi } from '../abi/piggyBank.ts' +import { parseEther } from 'viem' -try { - const { abi, bytecode } = getContract('piggyBank') - const contract = (await deploy(bytecode, abi)) as PiggyBank - const address = await contract.getAddress() +const hash = await walletClient.deployContract({ + abi, + bytecode: getByteCode('piggyBank'), +}) +const deployReceipt = await walletClient.waitForTransactionReceipt({ hash }) +const contractAddress = deployReceipt.contractAddress +console.log('Contract deployed:', contractAddress) +assert(contractAddress, 'Contract address should be set') - let receipt = await call('deposit', address, abi, [], { - value: parseEther('10.0'), +// Deposit 10 WST +{ + const result = await walletClient.estimateContractGas({ + account: walletClient.account, + address: contractAddress, + abi, + functionName: 'deposit', + value: parseEther('10'), }) - console.log('Deposit receipt:', receipt?.status) - console.log(`Contract balance: ${await provider.getBalance(address)}`) - console.log('deposit: ', await contract.getDeposit()) + console.log(`Gas estimate: ${result}`) - receipt = await call('withdraw', address, abi, [parseEther('5.0')]) - console.log('Withdraw receipt:', receipt?.status) - console.log(`Contract balance: ${await provider.getBalance(address)}`) - console.log('deposit: ', await contract.getDeposit()) -} catch (err) { - console.error(err) + const { request } = await walletClient.simulateContract({ + account: walletClient.account, + address: contractAddress, + abi, + functionName: 'deposit', + value: parseEther('10'), + }) + + request.nonce = 0 + const hash = await walletClient.writeContract(request) + + const receipt = await walletClient.waitForTransactionReceipt({ hash }) + console.log(`Deposit receipt: ${receipt.status}`) + if (process.env.STOP) { + process.exit(0) + } +} + +// Withdraw 5 WST +{ + const { request } = await walletClient.simulateContract({ + account: walletClient.account, + address: contractAddress, + abi, + functionName: 'withdraw', + args: [parseEther('5')], + }) + + const hash = await walletClient.writeContract(request) + const receipt = await walletClient.waitForTransactionReceipt({ hash }) + console.log(`Withdraw receipt: ${receipt.status}`) + + // Check remaining balance + const balance = await walletClient.readContract({ + address: contractAddress, + abi, + functionName: 'getDeposit', + }) + + console.log(`Get deposit: ${balance}`) + console.log( + `Get contract balance: ${await walletClient.getBalance({ address: contractAddress })}` + ) } diff --git a/substrate/frame/revive/rpc/examples/js/src/revert.ts b/substrate/frame/revive/rpc/examples/js/src/revert.ts deleted file mode 100644 index ea1bf4eceeb9..000000000000 --- a/substrate/frame/revive/rpc/examples/js/src/revert.ts +++ /dev/null @@ -1,10 +0,0 @@ -//! Run with bun run script-revert.ts -import { call, getContract, deploy } from './lib.ts' - -try { - const { abi, bytecode } = getContract('revert') - const contract = await deploy(bytecode, abi) - await call('doRevert', await contract.getAddress(), abi) -} catch (err) { - console.error(err) -} diff --git a/substrate/frame/revive/rpc/examples/js/src/transfer.ts b/substrate/frame/revive/rpc/examples/js/src/transfer.ts index ae2dd50f2af8..aef9a487b0c0 100644 --- a/substrate/frame/revive/rpc/examples/js/src/transfer.ts +++ b/substrate/frame/revive/rpc/examples/js/src/transfer.ts @@ -1,17 +1,18 @@ -import { parseEther } from 'ethers' -import { provider, signer } from './lib.ts' +import { parseEther } from 'viem' +import { walletClient } from './lib.ts' const recipient = '0x75E480dB528101a381Ce68544611C169Ad7EB342' try { - console.log(`Signer balance: ${await provider.getBalance(signer.address)}`) - console.log(`Recipient balance: ${await provider.getBalance(recipient)}`) - await signer.sendTransaction({ + console.log(`Signer balance: ${await walletClient.getBalance(walletClient.account)}`) + console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) + + await walletClient.sendTransaction({ to: recipient, value: parseEther('1.0'), }) console.log(`Sent: ${parseEther('1.0')}`) - console.log(`Signer balance: ${await provider.getBalance(signer.address)}`) - console.log(`Recipient balance: ${await provider.getBalance(recipient)}`) + console.log(`Signer balance: ${await walletClient.getBalance(walletClient.account)}`) + console.log(`Recipient balance: ${await walletClient.getBalance({ address: recipient })}`) } catch (err) { console.error(err) } diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts deleted file mode 100644 index d65f953969f0..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Event.ts +++ /dev/null @@ -1,117 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BigNumberish, - BytesLike, - FunctionFragment, - Result, - Interface, - EventFragment, - AddressLike, - ContractRunner, - ContractMethod, - Listener, -} from 'ethers' -import type { - TypedContractEvent, - TypedDeferredTopicFilter, - TypedEventLog, - TypedLogDescription, - TypedListener, - TypedContractMethod, -} from './common' - -export interface EventInterface extends Interface { - getFunction(nameOrSignature: 'triggerEvent'): FunctionFragment - - getEvent(nameOrSignatureOrTopic: 'ExampleEvent'): EventFragment - - encodeFunctionData(functionFragment: 'triggerEvent', values?: undefined): string - - decodeFunctionResult(functionFragment: 'triggerEvent', data: BytesLike): Result -} - -export namespace ExampleEventEvent { - export type InputTuple = [sender: AddressLike, value: BigNumberish, message: string] - export type OutputTuple = [sender: string, value: bigint, message: string] - export interface OutputObject { - sender: string - value: bigint - message: string - } - export type Event = TypedContractEvent - export type Filter = TypedDeferredTopicFilter - export type Log = TypedEventLog - export type LogDescription = TypedLogDescription -} - -export interface Event extends BaseContract { - connect(runner?: ContractRunner | null): Event - waitForDeployment(): Promise - - interface: EventInterface - - queryFilter( - event: TCEvent, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - queryFilter( - filter: TypedDeferredTopicFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - - on( - event: TCEvent, - listener: TypedListener - ): Promise - on( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - once( - event: TCEvent, - listener: TypedListener - ): Promise - once( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - listeners( - event: TCEvent - ): Promise>> - listeners(eventName?: string): Promise> - removeAllListeners(event?: TCEvent): Promise - - triggerEvent: TypedContractMethod<[], [void], 'nonpayable'> - - getFunction(key: string | FunctionFragment): T - - getFunction(nameOrSignature: 'triggerEvent'): TypedContractMethod<[], [void], 'nonpayable'> - - getEvent( - key: 'ExampleEvent' - ): TypedContractEvent< - ExampleEventEvent.InputTuple, - ExampleEventEvent.OutputTuple, - ExampleEventEvent.OutputObject - > - - filters: { - 'ExampleEvent(address,uint256,string)': TypedContractEvent< - ExampleEventEvent.InputTuple, - ExampleEventEvent.OutputTuple, - ExampleEventEvent.OutputObject - > - ExampleEvent: TypedContractEvent< - ExampleEventEvent.InputTuple, - ExampleEventEvent.OutputTuple, - ExampleEventEvent.OutputObject - > - } -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts deleted file mode 100644 index ca137fcc8b30..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/PiggyBank.ts +++ /dev/null @@ -1,96 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BigNumberish, - BytesLike, - FunctionFragment, - Result, - Interface, - ContractRunner, - ContractMethod, - Listener, -} from 'ethers' -import type { - TypedContractEvent, - TypedDeferredTopicFilter, - TypedEventLog, - TypedListener, - TypedContractMethod, -} from './common' - -export interface PiggyBankInterface extends Interface { - getFunction(nameOrSignature: 'deposit' | 'getDeposit' | 'owner' | 'withdraw'): FunctionFragment - - encodeFunctionData(functionFragment: 'deposit', values?: undefined): string - encodeFunctionData(functionFragment: 'getDeposit', values?: undefined): string - encodeFunctionData(functionFragment: 'owner', values?: undefined): string - encodeFunctionData(functionFragment: 'withdraw', values: [BigNumberish]): string - - decodeFunctionResult(functionFragment: 'deposit', data: BytesLike): Result - decodeFunctionResult(functionFragment: 'getDeposit', data: BytesLike): Result - decodeFunctionResult(functionFragment: 'owner', data: BytesLike): Result - decodeFunctionResult(functionFragment: 'withdraw', data: BytesLike): Result -} - -export interface PiggyBank extends BaseContract { - connect(runner?: ContractRunner | null): PiggyBank - waitForDeployment(): Promise - - interface: PiggyBankInterface - - queryFilter( - event: TCEvent, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - queryFilter( - filter: TypedDeferredTopicFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - - on( - event: TCEvent, - listener: TypedListener - ): Promise - on( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - once( - event: TCEvent, - listener: TypedListener - ): Promise - once( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - listeners( - event: TCEvent - ): Promise>> - listeners(eventName?: string): Promise> - removeAllListeners(event?: TCEvent): Promise - - deposit: TypedContractMethod<[], [bigint], 'payable'> - - getDeposit: TypedContractMethod<[], [bigint], 'view'> - - owner: TypedContractMethod<[], [string], 'view'> - - withdraw: TypedContractMethod<[withdrawAmount: BigNumberish], [bigint], 'nonpayable'> - - getFunction(key: string | FunctionFragment): T - - getFunction(nameOrSignature: 'deposit'): TypedContractMethod<[], [bigint], 'payable'> - getFunction(nameOrSignature: 'getDeposit'): TypedContractMethod<[], [bigint], 'view'> - getFunction(nameOrSignature: 'owner'): TypedContractMethod<[], [string], 'view'> - getFunction( - nameOrSignature: 'withdraw' - ): TypedContractMethod<[withdrawAmount: BigNumberish], [bigint], 'nonpayable'> - - filters: {} -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts deleted file mode 100644 index ad6e23b38a65..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/Revert.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - BaseContract, - BytesLike, - FunctionFragment, - Result, - Interface, - ContractRunner, - ContractMethod, - Listener, -} from 'ethers' -import type { - TypedContractEvent, - TypedDeferredTopicFilter, - TypedEventLog, - TypedListener, - TypedContractMethod, -} from './common' - -export interface RevertInterface extends Interface { - getFunction(nameOrSignature: 'doRevert'): FunctionFragment - - encodeFunctionData(functionFragment: 'doRevert', values?: undefined): string - - decodeFunctionResult(functionFragment: 'doRevert', data: BytesLike): Result -} - -export interface Revert extends BaseContract { - connect(runner?: ContractRunner | null): Revert - waitForDeployment(): Promise - - interface: RevertInterface - - queryFilter( - event: TCEvent, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - queryFilter( - filter: TypedDeferredTopicFilter, - fromBlockOrBlockhash?: string | number | undefined, - toBlock?: string | number | undefined - ): Promise>> - - on( - event: TCEvent, - listener: TypedListener - ): Promise - on( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - once( - event: TCEvent, - listener: TypedListener - ): Promise - once( - filter: TypedDeferredTopicFilter, - listener: TypedListener - ): Promise - - listeners( - event: TCEvent - ): Promise>> - listeners(eventName?: string): Promise> - removeAllListeners(event?: TCEvent): Promise - - doRevert: TypedContractMethod<[], [void], 'nonpayable'> - - getFunction(key: string | FunctionFragment): T - - getFunction(nameOrSignature: 'doRevert'): TypedContractMethod<[], [void], 'nonpayable'> - - filters: {} -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts deleted file mode 100644 index 247b9468ece2..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/common.ts +++ /dev/null @@ -1,100 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -import type { - FunctionFragment, - Typed, - EventFragment, - ContractTransaction, - ContractTransactionResponse, - DeferredTopicFilter, - EventLog, - TransactionRequest, - LogDescription, -} from 'ethers' - -export interface TypedDeferredTopicFilter<_TCEvent extends TypedContractEvent> - extends DeferredTopicFilter {} - -export interface TypedContractEvent< - InputTuple extends Array = any, - OutputTuple extends Array = any, - OutputObject = any, -> { - ( - ...args: Partial - ): TypedDeferredTopicFilter> - name: string - fragment: EventFragment - getFragment(...args: Partial): EventFragment -} - -type __TypechainAOutputTuple = T extends TypedContractEvent ? W : never -type __TypechainOutputObject = - T extends TypedContractEvent ? V : never - -export interface TypedEventLog extends Omit { - args: __TypechainAOutputTuple & __TypechainOutputObject -} - -export interface TypedLogDescription - extends Omit { - args: __TypechainAOutputTuple & __TypechainOutputObject -} - -export type TypedListener = ( - ...listenerArg: [...__TypechainAOutputTuple, TypedEventLog, ...undefined[]] -) => void - -export type MinEthersFactory = { - deploy(...a: ARGS[]): Promise -} - -export type GetContractTypeFromFactory = F extends MinEthersFactory ? C : never -export type GetARGsTypeFromFactory = - F extends MinEthersFactory ? Parameters : never - -export type StateMutability = 'nonpayable' | 'payable' | 'view' - -export type BaseOverrides = Omit -export type NonPayableOverrides = Omit -export type PayableOverrides = Omit -export type ViewOverrides = Omit -export type Overrides = S extends 'nonpayable' - ? NonPayableOverrides - : S extends 'payable' - ? PayableOverrides - : ViewOverrides - -export type PostfixOverrides, S extends StateMutability> = - | A - | [...A, Overrides] -export type ContractMethodArgs, S extends StateMutability> = PostfixOverrides< - { [I in keyof A]-?: A[I] | Typed }, - S -> - -export type DefaultReturnType = R extends Array ? R[0] : R - -// export interface ContractMethod = Array, R = any, D extends R | ContractTransactionResponse = R | ContractTransactionResponse> { -export interface TypedContractMethod< - A extends Array = Array, - R = any, - S extends StateMutability = 'payable', -> { - ( - ...args: ContractMethodArgs - ): S extends 'view' ? Promise> : Promise - - name: string - - fragment: FunctionFragment - - getFragment(...args: ContractMethodArgs): FunctionFragment - - populateTransaction(...args: ContractMethodArgs): Promise - staticCall(...args: ContractMethodArgs): Promise> - send(...args: ContractMethodArgs): Promise - estimateGas(...args: ContractMethodArgs): Promise - staticCallResult(...args: ContractMethodArgs): Promise -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts deleted file mode 100644 index 2e16b18a7ed8..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Event__factory.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ - -import { Contract, Interface, type ContractRunner } from 'ethers' -import type { Event, EventInterface } from '../Event' - -const _abi = [ - { - anonymous: false, - inputs: [ - { - indexed: true, - internalType: 'address', - name: 'sender', - type: 'address', - }, - { - indexed: false, - internalType: 'uint256', - name: 'value', - type: 'uint256', - }, - { - indexed: false, - internalType: 'string', - name: 'message', - type: 'string', - }, - ], - name: 'ExampleEvent', - type: 'event', - }, - { - inputs: [], - name: 'triggerEvent', - outputs: [], - stateMutability: 'nonpayable', - type: 'function', - }, -] as const - -export class Event__factory { - static readonly abi = _abi - static createInterface(): EventInterface { - return new Interface(_abi) as EventInterface - } - static connect(address: string, runner?: ContractRunner | null): Event { - return new Contract(address, _abi, runner) as unknown as Event - } -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts deleted file mode 100644 index ece1c6b5426e..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/Revert__factory.ts +++ /dev/null @@ -1,31 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ - -import { Contract, Interface, type ContractRunner } from 'ethers' -import type { Revert, RevertInterface } from '../Revert' - -const _abi = [ - { - inputs: [], - stateMutability: 'nonpayable', - type: 'constructor', - }, - { - inputs: [], - name: 'doRevert', - outputs: [], - stateMutability: 'nonpayable', - type: 'function', - }, -] as const - -export class Revert__factory { - static readonly abi = _abi - static createInterface(): RevertInterface { - return new Interface(_abi) as RevertInterface - } - static connect(address: string, runner?: ContractRunner | null): Revert { - return new Contract(address, _abi, runner) as unknown as Revert - } -} diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts deleted file mode 100644 index 67370dba411c..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/factories/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export { Event__factory } from './Event__factory' -export { PiggyBank__factory } from './PiggyBank__factory' -export { Revert__factory } from './Revert__factory' diff --git a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts b/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts deleted file mode 100644 index 3e324e80dcb1..000000000000 --- a/substrate/frame/revive/rpc/examples/js/types/ethers-contracts/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -/* Autogenerated file. Do not edit manually. */ -/* tslint:disable */ -/* eslint-disable */ -export type { Event } from './Event' -export type { PiggyBank } from './PiggyBank' -export type { Revert } from './Revert' -export * as factories from './factories' -export { Event__factory } from './factories/Event__factory' -export { PiggyBank__factory } from './factories/PiggyBank__factory' -export { Revert__factory } from './factories/Revert__factory' diff --git a/substrate/frame/revive/rpc/revive_chain.metadata b/substrate/frame/revive/rpc/revive_chain.metadata index 3560b3b90407acce7f602ce91ac089843be8dea8..64b1f2014dd06815fcea6a87bc96306eb00eda8b 100644 GIT binary patch delta 13838 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 delta 11763 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 MsTJ4Mlv;)V0}5B>2><{9 diff --git a/substrate/frame/revive/rpc/src/client.rs b/substrate/frame/revive/rpc/src/client.rs index d37f1d760065..901c15e9756b 100644 --- a/substrate/frame/revive/rpc/src/client.rs +++ b/substrate/frame/revive/rpc/src/client.rs @@ -32,7 +32,7 @@ use pallet_revive::{ Block, BlockNumberOrTag, BlockNumberOrTagOrHash, Bytes256, GenericTransaction, Log, ReceiptInfo, SyncingProgress, SyncingStatus, TransactionSigned, H160, H256, U256, }, - EthContractResult, + EthTransactError, EthTransactInfo, }; use sp_core::keccak_256; use sp_weights::Weight; @@ -116,18 +116,42 @@ fn unwrap_call_err(err: &subxt::error::RpcError) -> Option { /// Extract the revert message from a revert("msg") solidity statement. fn extract_revert_message(exec_data: &[u8]) -> Option { - let function_selector = exec_data.get(0..4)?; - - // keccak256("Error(string)") - let expected_selector = [0x08, 0xC3, 0x79, 0xA0]; - if function_selector != expected_selector { - return None; - } + let error_selector = exec_data.get(0..4)?; + + match error_selector { + // assert(false) + [0x4E, 0x48, 0x7B, 0x71] => { + let panic_code: u32 = U256::from_big_endian(exec_data.get(4..36)?).try_into().ok()?; + + // See https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require + let msg = match panic_code { + 0x00 => "generic panic", + 0x01 => "assert(false)", + 0x11 => "arithmetic underflow or overflow", + 0x12 => "division or modulo by zero", + 0x21 => "enum overflow", + 0x22 => "invalid encoded storage byte array accessed", + 0x31 => "out-of-bounds array access; popping on an empty array", + 0x32 => "out-of-bounds access of an array or bytesN", + 0x41 => "out of memory", + 0x51 => "uninitialized function", + code => return Some(format!("execution reverted: unknown panic code: {code:#x}")), + }; - let decoded = ethabi::decode(&[ethabi::ParamType::String], &exec_data[4..]).ok()?; - match decoded.first()? { - ethabi::Token::String(msg) => Some(msg.to_string()), - _ => None, + Some(format!("execution reverted: {msg}")) + }, + // revert(string) + [0x08, 0xC3, 0x79, 0xA0] => { + let decoded = ethabi::decode(&[ethabi::ParamType::String], &exec_data[4..]).ok()?; + if let Some(ethabi::Token::String(msg)) = decoded.first() { + return Some(format!("execution reverted: {msg}")) + } + Some("execution reverted".to_string()) + }, + _ => { + log::debug!(target: LOG_TARGET, "Unknown revert function selector: {error_selector:?}"); + Some("execution reverted".to_string()) + }, } } @@ -146,42 +170,46 @@ pub enum ClientError { /// A [`codec::Error`] wrapper error. #[error(transparent)] CodecError(#[from] codec::Error), - /// The dry run failed. - #[error("Dry run failed: {0}")] - DryRunFailed(String), /// Contract reverted - #[error("Execution reverted: {}", extract_revert_message(.0).unwrap_or_default())] - Reverted(Vec), + #[error("contract reverted")] + Reverted(EthTransactError), /// A decimal conversion failed. - #[error("Conversion failed")] + #[error("conversion failed")] ConversionFailed, /// The block hash was not found. - #[error("Hash not found")] + #[error("hash not found")] BlockNotFound, /// The transaction fee could not be found - #[error("TransactionFeePaid event not found")] + #[error("transactionFeePaid event not found")] TxFeeNotFound, /// The cache is empty. - #[error("Cache is empty")] + #[error("cache is empty")] CacheEmpty, } -// TODO convert error code to https://eips.ethereum.org/EIPS/eip-1474#error-codes +const REVERT_CODE: i32 = 3; impl From for ErrorObjectOwned { fn from(err: ClientError) -> Self { - let msg = err.to_string(); match err { ClientError::SubxtError(subxt::Error::Rpc(err)) | ClientError::RpcError(err) => { if let Some(err) = unwrap_call_err(&err) { return err; } - ErrorObjectOwned::owned::>(CALL_EXECUTION_FAILED_CODE, msg, None) + ErrorObjectOwned::owned::>( + CALL_EXECUTION_FAILED_CODE, + err.to_string(), + None, + ) }, - ClientError::Reverted(data) => { + ClientError::Reverted(EthTransactError::Data(data)) => { + let msg = extract_revert_message(&data).unwrap_or_default(); let data = format!("0x{}", hex::encode(data)); - ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, Some(data)) + ErrorObjectOwned::owned::(REVERT_CODE, msg, Some(data)) }, - _ => ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, None), + ClientError::Reverted(EthTransactError::Message(msg)) => + ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, msg, None), + _ => + ErrorObjectOwned::owned::(CALL_EXECUTION_FAILED_CODE, err.to_string(), None), } } } @@ -634,54 +662,25 @@ impl Client { Ok(result) } - /// Dry run a transaction and returns the [`EthContractResult`] for the transaction. + /// Dry run a transaction and returns the [`EthTransactInfo`] for the transaction. pub async fn dry_run( &self, - tx: &GenericTransaction, + tx: GenericTransaction, block: BlockNumberOrTagOrHash, - ) -> Result>, ClientError> { + ) -> Result, ClientError> { let runtime_api = self.runtime_api(&block).await?; + let payload = subxt_client::apis().revive_api().eth_transact(tx.into()); - // TODO: remove once subxt is updated - let value = subxt::utils::Static(tx.value.unwrap_or_default()); - let from = tx.from.map(|v| v.0.into()); - let to = tx.to.map(|v| v.0.into()); - - let payload = subxt_client::apis().revive_api().eth_transact( - from.unwrap_or_default(), - to, - value, - tx.input.clone().unwrap_or_default().0, - None, - None, - ); - - let EthContractResult { fee, gas_required, storage_deposit, result } = - runtime_api.call(payload).await?.0; + let result = runtime_api.call(payload).await?; match result { Err(err) => { log::debug!(target: LOG_TARGET, "Dry run failed {err:?}"); - Err(ClientError::DryRunFailed(format!("{err:?}"))) + Err(ClientError::Reverted(err.0)) }, - Ok(result) if result.did_revert() => { - log::debug!(target: LOG_TARGET, "Dry run reverted"); - Err(ClientError::Reverted(result.0.data)) - }, - Ok(result) => - Ok(EthContractResult { fee, gas_required, storage_deposit, result: result.0.data }), + Ok(result) => Ok(result.0), } } - /// Dry run a transaction and returns the gas estimate for the transaction. - pub async fn estimate_gas( - &self, - tx: &GenericTransaction, - block: BlockNumberOrTagOrHash, - ) -> Result { - let dry_run = self.dry_run(tx, block).await?; - Ok(U256::from(dry_run.fee / GAS_PRICE as u128) + GAS_PRICE) - } - /// Get the nonce of the given address. pub async fn nonce( &self, diff --git a/substrate/frame/revive/rpc/src/lib.rs b/substrate/frame/revive/rpc/src/lib.rs index 6a324e63a857..ccd8bb043e90 100644 --- a/substrate/frame/revive/rpc/src/lib.rs +++ b/substrate/frame/revive/rpc/src/lib.rs @@ -23,7 +23,7 @@ use jsonrpsee::{ core::{async_trait, RpcResult}, types::{ErrorCode, ErrorObjectOwned}, }; -use pallet_revive::{evm::*, EthContractResult}; +use pallet_revive::evm::*; use sp_core::{keccak_256, H160, H256, U256}; use thiserror::Error; @@ -128,10 +128,22 @@ impl EthRpcServer for EthRpcServerImpl { async fn estimate_gas( &self, transaction: GenericTransaction, - _block: Option, + block: Option, ) -> RpcResult { - let result = self.client.estimate_gas(&transaction, BlockTag::Latest.into()).await?; - Ok(result) + let dry_run = self.client.dry_run(transaction, block.unwrap_or_default().into()).await?; + Ok(dry_run.eth_gas) + } + + async fn call( + &self, + transaction: GenericTransaction, + block: Option, + ) -> RpcResult { + let dry_run = self + .client + .dry_run(transaction, block.unwrap_or_else(|| BlockTag::Latest.into())) + .await?; + Ok(dry_run.data.into()) } async fn send_raw_transaction(&self, transaction: Bytes) -> RpcResult { @@ -150,15 +162,17 @@ impl EthRpcServer for EthRpcServerImpl { let tx = GenericTransaction::from_signed(tx, Some(eth_addr)); // Dry run the transaction to get the weight limit and storage deposit limit - let dry_run = self.client.dry_run(&tx, BlockTag::Latest.into()).await?; + let dry_run = self.client.dry_run(tx, BlockTag::Latest.into()).await?; - let EthContractResult { gas_required, storage_deposit, .. } = dry_run; let call = subxt_client::tx().revive().eth_transact( transaction.0, - gas_required.into(), - storage_deposit, + dry_run.gas_required.into(), + dry_run.storage_deposit, ); - self.client.submit(call).await?; + self.client.submit(call).await.map_err(|err| { + log::debug!(target: LOG_TARGET, "submit call failed: {err:?}"); + err + })?; log::debug!(target: LOG_TARGET, "send_raw_transaction hash: {hash:?}"); Ok(hash) } @@ -234,18 +248,6 @@ impl EthRpcServer for EthRpcServerImpl { Ok(self.accounts.iter().map(|account| account.address()).collect()) } - async fn call( - &self, - transaction: GenericTransaction, - block: Option, - ) -> RpcResult { - let dry_run = self - .client - .dry_run(&transaction, block.unwrap_or_else(|| BlockTag::Latest.into())) - .await?; - Ok(dry_run.result.into()) - } - async fn get_block_by_number( &self, block: BlockNumberOrTag, diff --git a/substrate/frame/revive/rpc/src/rpc_methods_gen.rs b/substrate/frame/revive/rpc/src/rpc_methods_gen.rs index 339080368969..ad34dbfdfb49 100644 --- a/substrate/frame/revive/rpc/src/rpc_methods_gen.rs +++ b/substrate/frame/revive/rpc/src/rpc_methods_gen.rs @@ -14,6 +14,7 @@ // 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. + //! Generated JSON-RPC methods. #![allow(missing_docs)] diff --git a/substrate/frame/revive/rpc/src/subxt_client.rs b/substrate/frame/revive/rpc/src/subxt_client.rs index a232b231bc7c..1e1c395028a4 100644 --- a/substrate/frame/revive/rpc/src/subxt_client.rs +++ b/substrate/frame/revive/rpc/src/subxt_client.rs @@ -27,8 +27,16 @@ use subxt::config::{signed_extensions, Config, PolkadotConfig}; with = "::subxt::utils::Static<::sp_core::U256>" ), substitute_type( - path = "pallet_revive::primitives::EthContractResult", - with = "::subxt::utils::Static<::pallet_revive::EthContractResult>" + path = "pallet_revive::evm::api::rpc_types_gen::GenericTransaction", + with = "::subxt::utils::Static<::pallet_revive::evm::GenericTransaction>" + ), + substitute_type( + path = "pallet_revive::primitives::EthTransactInfo", + with = "::subxt::utils::Static<::pallet_revive::EthTransactInfo>" + ), + substitute_type( + path = "pallet_revive::primitives::EthTransactError", + with = "::subxt::utils::Static<::pallet_revive::EthTransactError>" ), substitute_type( path = "pallet_revive::primitives::ExecReturnValue", diff --git a/substrate/frame/revive/rpc/src/tests.rs b/substrate/frame/revive/rpc/src/tests.rs index 920318b26f71..7f2d4e683c31 100644 --- a/substrate/frame/revive/rpc/src/tests.rs +++ b/substrate/frame/revive/rpc/src/tests.rs @@ -238,7 +238,8 @@ async fn revert_call() -> anyhow::Result<()> { .unwrap_err(); let call_err = unwrap_call_err!(err.source().unwrap()); - assert_eq!(call_err.message(), "Execution reverted: revert message"); + assert_eq!(call_err.message(), "execution reverted: revert message"); + assert_eq!(call_err.code(), 3); Ok(()) } diff --git a/substrate/frame/revive/src/benchmarking/mod.rs b/substrate/frame/revive/src/benchmarking/mod.rs index 9c4d817a07de..b73815bfb9ea 100644 --- a/substrate/frame/revive/src/benchmarking/mod.rs +++ b/substrate/frame/revive/src/benchmarking/mod.rs @@ -103,7 +103,7 @@ where origin, 0u32.into(), Weight::MAX, - default_deposit_limit::(), + DepositLimit::Balance(default_deposit_limit::()), Code::Upload(module.code), data, salt, diff --git a/substrate/frame/revive/src/evm/api/rlp_codec.rs b/substrate/frame/revive/src/evm/api/rlp_codec.rs index 3442ed73acca..9b61cd042ec5 100644 --- a/substrate/frame/revive/src/evm/api/rlp_codec.rs +++ b/substrate/frame/revive/src/evm/api/rlp_codec.rs @@ -88,14 +88,14 @@ impl TransactionSigned { } } -impl TransactionLegacyUnsigned { - /// Get the rlp encoded bytes of a signed transaction with a dummy 65 bytes signature. +impl TransactionUnsigned { + /// Get a signed transaction payload with a dummy 65 bytes signature. pub fn dummy_signed_payload(&self) -> Vec { - let mut s = rlp::RlpStream::new(); - s.append(self); const DUMMY_SIGNATURE: [u8; 65] = [0u8; 65]; - s.append_raw(&DUMMY_SIGNATURE.as_ref(), 1); - s.out().to_vec() + self.unsigned_payload() + .into_iter() + .chain(DUMMY_SIGNATURE.iter().copied()) + .collect::>() } } @@ -567,7 +567,7 @@ mod test { #[test] fn dummy_signed_payload_works() { - let tx = TransactionLegacyUnsigned { + let tx: TransactionUnsigned = TransactionLegacyUnsigned { chain_id: Some(596.into()), gas: U256::from(21000), nonce: U256::from(1), @@ -576,10 +576,10 @@ mod test { value: U256::from(123123), input: Bytes(vec![]), r#type: TypeLegacy, - }; + } + .into(); let dummy_signed_payload = tx.dummy_signed_payload(); - let tx: TransactionUnsigned = tx.into(); let payload = Account::default().sign_transaction(tx).signed_payload(); assert_eq!(dummy_signed_payload.len(), payload.len()); } diff --git a/substrate/frame/revive/src/evm/api/rpc_types.rs b/substrate/frame/revive/src/evm/api/rpc_types.rs index 1cf8d984b68b..ed046cb4da44 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types.rs @@ -19,6 +19,27 @@ use super::*; use alloc::vec::Vec; use sp_core::{H160, U256}; +impl From for BlockNumberOrTagOrHash { + fn from(b: BlockNumberOrTag) -> Self { + match b { + BlockNumberOrTag::U256(n) => BlockNumberOrTagOrHash::U256(n), + BlockNumberOrTag::BlockTag(t) => BlockNumberOrTagOrHash::BlockTag(t), + } + } +} + +impl From for TransactionUnsigned { + fn from(tx: TransactionSigned) -> Self { + use TransactionSigned::*; + match tx { + Transaction4844Signed(tx) => tx.transaction_4844_unsigned.into(), + Transaction1559Signed(tx) => tx.transaction_1559_unsigned.into(), + Transaction2930Signed(tx) => tx.transaction_2930_unsigned.into(), + TransactionLegacySigned(tx) => tx.transaction_legacy_unsigned.into(), + } + } +} + impl TransactionInfo { /// Create a new [`TransactionInfo`] from a receipt and a signed transaction. pub fn new(receipt: ReceiptInfo, transaction_signed: TransactionSigned) -> Self { @@ -143,76 +164,69 @@ fn logs_bloom_works() { impl GenericTransaction { /// Create a new [`GenericTransaction`] from a signed transaction. pub fn from_signed(tx: TransactionSigned, from: Option) -> Self { - use TransactionSigned::*; + Self::from_unsigned(tx.into(), from) + } + + /// Create a new [`GenericTransaction`] from a unsigned transaction. + pub fn from_unsigned(tx: TransactionUnsigned, from: Option) -> Self { + use TransactionUnsigned::*; match tx { - TransactionLegacySigned(tx) => { - let tx = tx.transaction_legacy_unsigned; - GenericTransaction { - from, - r#type: Some(tx.r#type.as_byte()), - chain_id: tx.chain_id, - input: Some(tx.input), - nonce: Some(tx.nonce), - value: Some(tx.value), - to: tx.to, - gas: Some(tx.gas), - gas_price: Some(tx.gas_price), - ..Default::default() - } + TransactionLegacyUnsigned(tx) => GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: tx.chain_id, + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + ..Default::default() }, - Transaction4844Signed(tx) => { - let tx = tx.transaction_4844_unsigned; - GenericTransaction { - from, - r#type: Some(tx.r#type.as_byte()), - chain_id: Some(tx.chain_id), - input: Some(tx.input), - nonce: Some(tx.nonce), - value: Some(tx.value), - to: Some(tx.to), - gas: Some(tx.gas), - gas_price: Some(tx.max_fee_per_blob_gas), - access_list: Some(tx.access_list), - blob_versioned_hashes: Some(tx.blob_versioned_hashes), - max_fee_per_blob_gas: Some(tx.max_fee_per_blob_gas), - max_fee_per_gas: Some(tx.max_fee_per_gas), - max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), - ..Default::default() - } + Transaction4844Unsigned(tx) => GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: Some(tx.to), + gas: Some(tx.gas), + gas_price: Some(tx.max_fee_per_blob_gas), + access_list: Some(tx.access_list), + blob_versioned_hashes: tx.blob_versioned_hashes, + max_fee_per_blob_gas: Some(tx.max_fee_per_blob_gas), + max_fee_per_gas: Some(tx.max_fee_per_gas), + max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), + ..Default::default() }, - Transaction1559Signed(tx) => { - let tx = tx.transaction_1559_unsigned; - GenericTransaction { - from, - r#type: Some(tx.r#type.as_byte()), - chain_id: Some(tx.chain_id), - input: Some(tx.input), - nonce: Some(tx.nonce), - value: Some(tx.value), - to: tx.to, - gas: Some(tx.gas), - gas_price: Some(tx.gas_price), - access_list: Some(tx.access_list), - max_fee_per_gas: Some(tx.max_fee_per_gas), - max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), - ..Default::default() - } + Transaction1559Unsigned(tx) => GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + access_list: Some(tx.access_list), + max_fee_per_gas: Some(tx.max_fee_per_gas), + max_priority_fee_per_gas: Some(tx.max_priority_fee_per_gas), + ..Default::default() }, - Transaction2930Signed(tx) => { - let tx = tx.transaction_2930_unsigned; - GenericTransaction { - from, - r#type: Some(tx.r#type.as_byte()), - chain_id: Some(tx.chain_id), - input: Some(tx.input), - nonce: Some(tx.nonce), - value: Some(tx.value), - to: tx.to, - gas: Some(tx.gas), - gas_price: Some(tx.gas_price), - access_list: Some(tx.access_list), - ..Default::default() - } + Transaction2930Unsigned(tx) => GenericTransaction { + from, + r#type: Some(tx.r#type.as_byte()), + chain_id: Some(tx.chain_id), + input: Some(tx.input), + nonce: Some(tx.nonce), + value: Some(tx.value), + to: tx.to, + gas: Some(tx.gas), + gas_price: Some(tx.gas_price), + access_list: Some(tx.access_list), + ..Default::default() }, } } @@ -269,7 +283,7 @@ impl GenericTransaction { max_fee_per_blob_gas: self.max_fee_per_blob_gas.unwrap_or_default(), max_priority_fee_per_gas: self.max_priority_fee_per_gas.unwrap_or_default(), access_list: self.access_list.unwrap_or_default(), - blob_versioned_hashes: self.blob_versioned_hashes.unwrap_or_default(), + blob_versioned_hashes: self.blob_versioned_hashes, } .into()), _ => Err(()), diff --git a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs index 5037ec05d881..1d65fdefdde6 100644 --- a/substrate/frame/revive/src/evm/api/rpc_types_gen.rs +++ b/substrate/frame/revive/src/evm/api/rpc_types_gen.rs @@ -94,8 +94,8 @@ pub struct Block { /// Uncles pub uncles: Vec, /// Withdrawals - #[serde(skip_serializing_if = "Option::is_none")] - pub withdrawals: Option>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub withdrawals: Vec, /// Withdrawals root #[serde(rename = "withdrawalsRoot", skip_serializing_if = "Option::is_none")] pub withdrawals_root: Option, @@ -114,7 +114,7 @@ pub enum BlockNumberOrTag { } impl Default for BlockNumberOrTag { fn default() -> Self { - BlockNumberOrTag::U256(Default::default()) + BlockNumberOrTag::BlockTag(Default::default()) } } @@ -133,7 +133,7 @@ pub enum BlockNumberOrTagOrHash { } impl Default for BlockNumberOrTagOrHash { fn default() -> Self { - BlockNumberOrTagOrHash::U256(Default::default()) + BlockNumberOrTagOrHash::BlockTag(Default::default()) } } @@ -148,12 +148,12 @@ pub struct GenericTransaction { pub access_list: Option, /// blobVersionedHashes /// List of versioned blob hashes associated with the transaction's EIP-4844 data blobs. - #[serde(rename = "blobVersionedHashes", skip_serializing_if = "Option::is_none")] - pub blob_versioned_hashes: Option>, + #[serde(rename = "blobVersionedHashes", default, skip_serializing_if = "Vec::is_empty")] + pub blob_versioned_hashes: Vec, /// blobs /// Raw blob data. - #[serde(skip_serializing_if = "Option::is_none")] - pub blobs: Option>, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub blobs: Vec, /// chainId /// Chain ID that this transaction is valid on. #[serde(rename = "chainId", skip_serializing_if = "Option::is_none")] @@ -319,7 +319,7 @@ pub enum TransactionUnsigned { } impl Default for TransactionUnsigned { fn default() -> Self { - TransactionUnsigned::Transaction4844Unsigned(Default::default()) + TransactionUnsigned::TransactionLegacyUnsigned(Default::default()) } } @@ -341,13 +341,13 @@ pub type AccessList = Vec; )] pub enum BlockTag { #[serde(rename = "earliest")] - #[default] Earliest, #[serde(rename = "finalized")] Finalized, #[serde(rename = "safe")] Safe, #[serde(rename = "latest")] + #[default] Latest, #[serde(rename = "pending")] Pending, @@ -392,7 +392,7 @@ pub struct Log { #[serde(skip_serializing_if = "Option::is_none")] pub removed: Option, /// topics - #[serde(skip_serializing_if = "Vec::is_empty")] + #[serde(default, skip_serializing_if = "Vec::is_empty")] pub topics: Vec, /// transaction hash #[serde(rename = "transactionHash")] @@ -574,7 +574,7 @@ pub enum TransactionSigned { } impl Default for TransactionSigned { fn default() -> Self { - TransactionSigned::Transaction4844Signed(Default::default()) + TransactionSigned::TransactionLegacySigned(Default::default()) } } diff --git a/substrate/frame/revive/src/evm/runtime.rs b/substrate/frame/revive/src/evm/runtime.rs index b5dc9a36065b..24b75de83569 100644 --- a/substrate/frame/revive/src/evm/runtime.rs +++ b/substrate/frame/revive/src/evm/runtime.rs @@ -455,236 +455,265 @@ mod test { /// A builder for creating an unchecked extrinsic, and test that the check function works. #[derive(Clone)] struct UncheckedExtrinsicBuilder { - tx: TransactionLegacyUnsigned, + tx: GenericTransaction, gas_limit: Weight, storage_deposit_limit: BalanceOf, + before_validate: Option>, } impl UncheckedExtrinsicBuilder { /// Create a new builder with default values. fn new() -> Self { Self { - tx: TransactionLegacyUnsigned { + tx: GenericTransaction { + from: Some(Account::default().address()), chain_id: Some(::ChainId::get().into()), - gas_price: U256::from(GAS_PRICE), + gas_price: Some(U256::from(GAS_PRICE)), ..Default::default() }, gas_limit: Weight::zero(), storage_deposit_limit: 0, + before_validate: None, } } fn estimate_gas(&mut self) { - let dry_run = crate::Pallet::::bare_eth_transact( - Account::default().substrate_account(), - self.tx.to, - self.tx.value.try_into().unwrap(), - self.tx.input.clone().0, - Weight::MAX, - u64::MAX, - |call| { + let dry_run = + crate::Pallet::::bare_eth_transact(self.tx.clone(), Weight::MAX, |call| { let call = RuntimeCall::Contracts(call); let uxt: Ex = sp_runtime::generic::UncheckedExtrinsic::new_bare(call).into(); uxt.encoded_size() as u32 + }); + + match dry_run { + Ok(dry_run) => { + log::debug!(target: LOG_TARGET, "Estimated gas: {:?}", dry_run.eth_gas); + self.tx.gas = Some(dry_run.eth_gas); + }, + Err(err) => { + log::debug!(target: LOG_TARGET, "Failed to estimate gas: {:?}", err); }, - crate::DebugInfo::Skip, - crate::CollectEvents::Skip, - ); - self.tx.gas = ((dry_run.fee + GAS_PRICE as u64) / (GAS_PRICE as u64)).into(); + } } /// Create a new builder with a call to the given address. fn call_with(dest: H160) -> Self { let mut builder = Self::new(); builder.tx.to = Some(dest); - builder.estimate_gas(); + ExtBuilder::default().build().execute_with(|| builder.estimate_gas()); builder } /// Create a new builder with an instantiate call. fn instantiate_with(code: Vec, data: Vec) -> Self { let mut builder = Self::new(); - builder.tx.input = Bytes(code.into_iter().chain(data.into_iter()).collect()); - builder.estimate_gas(); + builder.tx.input = Some(Bytes(code.into_iter().chain(data.into_iter()).collect())); + ExtBuilder::default().build().execute_with(|| builder.estimate_gas()); builder } /// Update the transaction with the given function. - fn update(mut self, f: impl FnOnce(&mut TransactionLegacyUnsigned) -> ()) -> Self { + fn update(mut self, f: impl FnOnce(&mut GenericTransaction) -> ()) -> Self { f(&mut self.tx); self } + /// Set before_validate function. + fn before_validate(mut self, f: impl Fn() + Send + Sync + 'static) -> Self { + self.before_validate = Some(std::sync::Arc::new(f)); + self + } /// Call `check` on the unchecked extrinsic, and `pre_dispatch` on the signed extension. fn check(&self) -> Result<(RuntimeCall, SignedExtra), TransactionValidityError> { - let UncheckedExtrinsicBuilder { tx, gas_limit, storage_deposit_limit } = self.clone(); - - // Fund the account. - let account = Account::default(); - let _ = ::Currency::set_balance( - &account.substrate_account(), - 100_000_000_000_000, - ); - - let payload = account.sign_transaction(tx.into()).signed_payload(); - let call = RuntimeCall::Contracts(crate::Call::eth_transact { - payload, - gas_limit, - storage_deposit_limit, - }); - - let encoded_len = call.encoded_size(); - let uxt: Ex = generic::UncheckedExtrinsic::new_bare(call).into(); - let result: CheckedExtrinsic<_, _, _> = uxt.check(&TestContext {})?; - let (account_id, extra): (AccountId32, SignedExtra) = match result.format { - ExtrinsicFormat::Signed(signer, extra) => (signer, extra), - _ => unreachable!(), - }; - - extra.clone().validate_and_prepare( - RuntimeOrigin::signed(account_id), - &result.function, - &result.function.get_dispatch_info(), - encoded_len, - 0, - )?; + ExtBuilder::default().build().execute_with(|| { + let UncheckedExtrinsicBuilder { + tx, + gas_limit, + storage_deposit_limit, + before_validate, + } = self.clone(); + + // Fund the account. + let account = Account::default(); + let _ = ::Currency::set_balance( + &account.substrate_account(), + 100_000_000_000_000, + ); + + let payload = + account.sign_transaction(tx.try_into_unsigned().unwrap()).signed_payload(); + let call = RuntimeCall::Contracts(crate::Call::eth_transact { + payload, + gas_limit, + storage_deposit_limit, + }); + + let encoded_len = call.encoded_size(); + let uxt: Ex = generic::UncheckedExtrinsic::new_bare(call).into(); + let result: CheckedExtrinsic<_, _, _> = uxt.check(&TestContext {})?; + let (account_id, extra): (AccountId32, SignedExtra) = match result.format { + ExtrinsicFormat::Signed(signer, extra) => (signer, extra), + _ => unreachable!(), + }; - Ok((result.function, extra)) + before_validate.map(|f| f()); + extra.clone().validate_and_prepare( + RuntimeOrigin::signed(account_id), + &result.function, + &result.function.get_dispatch_info(), + encoded_len, + 0, + )?; + + Ok((result.function, extra)) + }) } } #[test] fn check_eth_transact_call_works() { - ExtBuilder::default().build().execute_with(|| { - let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])); - assert_eq!( - builder.check().unwrap().0, - crate::Call::call:: { - dest: builder.tx.to.unwrap(), - value: builder.tx.value.as_u64(), - gas_limit: builder.gas_limit, - storage_deposit_limit: builder.storage_deposit_limit, - data: builder.tx.input.0 - } - .into() - ); - }); + let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])); + assert_eq!( + builder.check().unwrap().0, + crate::Call::call:: { + dest: builder.tx.to.unwrap(), + value: builder.tx.value.unwrap_or_default().as_u64(), + gas_limit: builder.gas_limit, + storage_deposit_limit: builder.storage_deposit_limit, + data: builder.tx.input.unwrap_or_default().0 + } + .into() + ); } #[test] fn check_eth_transact_instantiate_works() { - ExtBuilder::default().build().execute_with(|| { - let (code, _) = compile_module("dummy").unwrap(); - let data = vec![]; - let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()); - - assert_eq!( - builder.check().unwrap().0, - crate::Call::instantiate_with_code:: { - value: builder.tx.value.as_u64(), - gas_limit: builder.gas_limit, - storage_deposit_limit: builder.storage_deposit_limit, - code, - data, - salt: None - } - .into() - ); - }); + let (code, _) = compile_module("dummy").unwrap(); + let data = vec![]; + let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()); + + assert_eq!( + builder.check().unwrap().0, + crate::Call::instantiate_with_code:: { + value: builder.tx.value.unwrap_or_default().as_u64(), + gas_limit: builder.gas_limit, + storage_deposit_limit: builder.storage_deposit_limit, + code, + data, + salt: None + } + .into() + ); } #[test] fn check_eth_transact_nonce_works() { - ExtBuilder::default().build().execute_with(|| { - let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])) - .update(|tx| tx.nonce = 1u32.into()); - - assert_eq!( - builder.check(), - Err(TransactionValidityError::Invalid(InvalidTransaction::Future)) - ); - - >::inc_account_nonce(Account::default().substrate_account()); - - let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])); - assert_eq!( - builder.check(), - Err(TransactionValidityError::Invalid(InvalidTransaction::Stale)) - ); - }); + let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])) + .update(|tx| tx.nonce = Some(1u32.into())); + + assert_eq!( + builder.check(), + Err(TransactionValidityError::Invalid(InvalidTransaction::Future)) + ); + + let builder = + UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).before_validate(|| { + >::inc_account_nonce(Account::default().substrate_account()); + }); + + assert_eq!( + builder.check(), + Err(TransactionValidityError::Invalid(InvalidTransaction::Stale)) + ); } #[test] fn check_eth_transact_chain_id_works() { - ExtBuilder::default().build().execute_with(|| { - let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])) - .update(|tx| tx.chain_id = Some(42.into())); - - assert_eq!( - builder.check(), - Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) - ); - }); + let builder = UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])) + .update(|tx| tx.chain_id = Some(42.into())); + + assert_eq!( + builder.check(), + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + ); } #[test] fn check_instantiate_data() { - ExtBuilder::default().build().execute_with(|| { - let code = b"invalid code".to_vec(); - let data = vec![1]; - let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()); - - // Fail because the tx input fail to get the blob length - assert_eq!( - builder.clone().update(|tx| tx.input = Bytes(vec![1, 2, 3])).check(), - Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) - ); - }); + let code = b"invalid code".to_vec(); + let data = vec![1]; + let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()); + + // Fail because the tx input fail to get the blob length + assert_eq!( + builder.clone().update(|tx| tx.input = Some(Bytes(vec![1, 2, 3]))).check(), + Err(TransactionValidityError::Invalid(InvalidTransaction::Call)) + ); } #[test] fn check_transaction_fees() { - ExtBuilder::default().build().execute_with(|| { - let scenarios: [(_, Box, _); 5] = [ - ("Eth fees too low", Box::new(|tx| tx.gas_price /= 2), InvalidTransaction::Payment), - ("Gas fees too high", Box::new(|tx| tx.gas *= 2), InvalidTransaction::Call), - ("Gas fees too low", Box::new(|tx| tx.gas *= 2), InvalidTransaction::Call), - ( - "Diff > 10%", - Box::new(|tx| tx.gas = tx.gas * 111 / 100), - InvalidTransaction::Call, - ), - ( - "Diff < 10%", - Box::new(|tx| { - tx.gas_price *= 2; - tx.gas = tx.gas * 89 / 100 - }), - InvalidTransaction::Call, - ), - ]; - - for (msg, update_tx, err) in scenarios { - let builder = - UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).update(update_tx); - - assert_eq!(builder.check(), Err(TransactionValidityError::Invalid(err)), "{}", msg); - } - }); + let scenarios: [(_, Box, _); 5] = [ + ( + "Eth fees too low", + Box::new(|tx| { + tx.gas_price = Some(tx.gas_price.unwrap() / 2); + }), + InvalidTransaction::Payment, + ), + ( + "Gas fees too high", + Box::new(|tx| { + tx.gas = Some(tx.gas.unwrap() * 2); + }), + InvalidTransaction::Call, + ), + ( + "Gas fees too low", + Box::new(|tx| { + tx.gas = Some(tx.gas.unwrap() * 2); + }), + InvalidTransaction::Call, + ), + ( + "Diff > 10%", + Box::new(|tx| { + tx.gas = Some(tx.gas.unwrap() * 111 / 100); + }), + InvalidTransaction::Call, + ), + ( + "Diff < 10%", + Box::new(|tx| { + tx.gas_price = Some(tx.gas_price.unwrap() * 2); + tx.gas = Some(tx.gas.unwrap() * 89 / 100); + }), + InvalidTransaction::Call, + ), + ]; + + for (msg, update_tx, err) in scenarios { + let builder = + UncheckedExtrinsicBuilder::call_with(H160::from([1u8; 20])).update(update_tx); + + assert_eq!(builder.check(), Err(TransactionValidityError::Invalid(err)), "{}", msg); + } } #[test] fn check_transaction_tip() { - ExtBuilder::default().build().execute_with(|| { - let (code, _) = compile_module("dummy").unwrap(); - let data = vec![]; - let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()) - .update(|tx| tx.gas_price = tx.gas_price * 103 / 100); - - let tx = &builder.tx; - let expected_tip = tx.gas_price * tx.gas - U256::from(GAS_PRICE) * tx.gas; - let (_, extra) = builder.check().unwrap(); - assert_eq!(U256::from(extra.1.tip()), expected_tip); - }); + let (code, _) = compile_module("dummy").unwrap(); + let data = vec![]; + let builder = UncheckedExtrinsicBuilder::instantiate_with(code.clone(), data.clone()) + .update(|tx| { + tx.gas_price = Some(tx.gas_price.unwrap() * 103 / 100); + log::debug!(target: LOG_TARGET, "Gas price: {:?}", tx.gas_price); + }); + + let tx = &builder.tx; + let expected_tip = + tx.gas_price.unwrap() * tx.gas.unwrap() - U256::from(GAS_PRICE) * tx.gas.unwrap(); + let (_, extra) = builder.check().unwrap(); + assert_eq!(U256::from(extra.1.tip()), expected_tip); } } diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 49c08166483e..b23d7e4e60ef 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -562,6 +562,9 @@ pub struct Stack<'a, T: Config, E> { debug_message: Option<&'a mut DebugBuffer>, /// Transient storage used to store data, which is kept for the duration of a transaction. transient_storage: TransientStorage, + /// Whether or not actual transfer of funds should be performed. + /// This is set to `true` exclusively when we simulate a call through eth_transact. + skip_transfer: bool, /// No executable is held by the struct but influences its behaviour. _phantom: PhantomData, } @@ -777,6 +780,7 @@ where storage_meter: &'a mut storage::meter::Meter, value: U256, input_data: Vec, + skip_transfer: bool, debug_message: Option<&'a mut DebugBuffer>, ) -> ExecResult { let dest = T::AddressMapper::to_account_id(&dest); @@ -786,6 +790,7 @@ where gas_meter, storage_meter, value, + skip_transfer, debug_message, )? { stack.run(executable, input_data).map(|_| stack.first_frame.last_frame_output) @@ -812,6 +817,7 @@ where value: U256, input_data: Vec, salt: Option<&[u8; 32]>, + skip_transfer: bool, debug_message: Option<&'a mut DebugBuffer>, ) -> Result<(H160, ExecReturnValue), ExecError> { let (mut stack, executable) = Self::new( @@ -825,6 +831,7 @@ where gas_meter, storage_meter, value, + skip_transfer, debug_message, )? .expect(FRAME_ALWAYS_EXISTS_ON_INSTANTIATE); @@ -853,6 +860,7 @@ where gas_meter, storage_meter, value.into(), + false, debug_message, ) .unwrap() @@ -869,6 +877,7 @@ where gas_meter: &'a mut GasMeter, storage_meter: &'a mut storage::meter::Meter, value: U256, + skip_transfer: bool, debug_message: Option<&'a mut DebugBuffer>, ) -> Result, ExecError> { origin.ensure_mapped()?; @@ -896,6 +905,7 @@ where frames: Default::default(), debug_message, transient_storage: TransientStorage::new(limits::TRANSIENT_STORAGE_BYTES), + skip_transfer, _phantom: Default::default(), }; @@ -1073,6 +1083,7 @@ where &frame.account_id, frame.contract_info.get(&frame.account_id), executable.code_info(), + self.skip_transfer, )?; // Needs to be incremented before calling into the code so that it is visible // in case of recursion. @@ -2101,6 +2112,7 @@ mod tests { &mut storage_meter, value.into(), vec![], + false, None, ), Ok(_) @@ -2193,6 +2205,7 @@ mod tests { &mut storage_meter, value.into(), vec![], + false, None, ) .unwrap(); @@ -2233,6 +2246,7 @@ mod tests { &mut storage_meter, value.into(), vec![], + false, None, )); @@ -2269,6 +2283,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ), ExecError { @@ -2286,6 +2301,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -2314,6 +2330,7 @@ mod tests { &mut storage_meter, 55u64.into(), vec![], + false, None, ) .unwrap(); @@ -2363,6 +2380,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); @@ -2392,6 +2410,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); @@ -2421,6 +2440,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![1, 2, 3, 4], + false, None, ); assert_matches!(result, Ok(_)); @@ -2457,6 +2477,7 @@ mod tests { min_balance.into(), vec![1, 2, 3, 4], Some(&[0; 32]), + false, None, ); assert_matches!(result, Ok(_)); @@ -2511,6 +2532,7 @@ mod tests { &mut storage_meter, value.into(), vec![], + false, None, ); @@ -2575,6 +2597,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); @@ -2640,6 +2663,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); @@ -2672,6 +2696,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); assert_matches!(result, Ok(_)); @@ -2709,6 +2734,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -2735,6 +2761,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -2779,6 +2806,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -2805,6 +2833,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -2831,6 +2860,7 @@ mod tests { &mut storage_meter, 1u64.into(), vec![0], + false, None, ); assert_matches!(result, Err(_)); @@ -2875,6 +2905,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -2920,6 +2951,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); @@ -2946,6 +2978,7 @@ mod tests { U256::zero(), // <- zero value vec![], Some(&[0; 32]), + false, None, ), Err(_) @@ -2981,6 +3014,7 @@ mod tests { min_balance.into(), vec![], Some(&[0 ;32]), + false, None, ), Ok((address, ref output)) if output.data == vec![80, 65, 83, 83] => address @@ -3032,10 +3066,10 @@ mod tests { executable, &mut gas_meter, &mut storage_meter, - min_balance.into(), vec![], Some(&[0; 32]), + false, None, ), Ok((address, ref output)) if output.data == vec![70, 65, 73, 76] => address @@ -3100,6 +3134,7 @@ mod tests { &mut storage_meter, (min_balance * 10).into(), vec![], + false, None, ), Ok(_) @@ -3180,6 +3215,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ), Ok(_) @@ -3223,6 +3259,7 @@ mod tests { 100u64.into(), vec![], Some(&[0; 32]), + false, None, ), Err(Error::::TerminatedInConstructor.into()) @@ -3287,6 +3324,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -3349,6 +3387,7 @@ mod tests { 10u64.into(), vec![], Some(&[0; 32]), + false, None, ); assert_matches!(result, Ok(_)); @@ -3395,6 +3434,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap(); @@ -3426,6 +3466,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, Some(&mut debug_buffer), ) .unwrap(); @@ -3459,6 +3500,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, Some(&mut debug_buffer), ); assert!(result.is_err()); @@ -3492,6 +3534,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, Some(&mut debug_buf_after), ) .unwrap(); @@ -3525,6 +3568,7 @@ mod tests { &mut storage_meter, U256::zero(), CHARLIE_ADDR.as_bytes().to_vec(), + false, None, )); @@ -3537,6 +3581,7 @@ mod tests { &mut storage_meter, U256::zero(), BOB_ADDR.as_bytes().to_vec(), + false, None, ) .map_err(|e| e.error), @@ -3587,6 +3632,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ) .map_err(|e| e.error), @@ -3621,6 +3667,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap(); @@ -3705,6 +3752,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap(); @@ -3831,6 +3879,7 @@ mod tests { (min_balance * 100).into(), vec![], Some(&[0; 32]), + false, None, ) .ok(); @@ -3844,6 +3893,7 @@ mod tests { (min_balance * 100).into(), vec![], Some(&[0; 32]), + false, None, )); assert_eq!(System::account_nonce(&ALICE), 1); @@ -3856,6 +3906,7 @@ mod tests { (min_balance * 200).into(), vec![], Some(&[0; 32]), + false, None, )); assert_eq!(System::account_nonce(&ALICE), 2); @@ -3868,6 +3919,7 @@ mod tests { (min_balance * 200).into(), vec![], Some(&[0; 32]), + false, None, )); assert_eq!(System::account_nonce(&ALICE), 3); @@ -3936,6 +3988,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4047,6 +4100,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4086,6 +4140,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4125,6 +4180,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4178,6 +4234,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4234,6 +4291,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4309,6 +4367,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4379,6 +4438,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -4417,6 +4477,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, )); }); @@ -4479,6 +4540,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -4512,6 +4574,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); assert_matches!(result, Ok(_)); @@ -4595,6 +4658,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap() @@ -4663,6 +4727,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ); assert_matches!(result, Ok(_)); @@ -4734,6 +4799,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ); assert_matches!(result, Ok(_)); @@ -4785,6 +4851,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap() @@ -4854,6 +4921,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap() @@ -4900,6 +4968,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap() @@ -4944,6 +5013,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![], + false, None, ) .unwrap() @@ -4999,6 +5069,7 @@ mod tests { &mut storage_meter, U256::zero(), vec![0], + false, None, ), Ok(_) diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index b55854e2eec5..1dee1da03bc4 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -41,13 +41,13 @@ pub mod test_utils; pub mod weights; use crate::{ - evm::{runtime::GAS_PRICE, TransactionLegacyUnsigned}, + evm::{runtime::GAS_PRICE, GenericTransaction}, exec::{AccountIdOf, ExecError, Executable, Ext, Key, Origin, Stack as ExecStack}, gas::GasMeter, storage::{meter::Meter as StorageMeter, ContractInfo, DeletionQueueManager}, wasm::{CodeInfo, RuntimeCosts, WasmBlob}, }; -use alloc::boxed::Box; +use alloc::{boxed::Box, format, vec}; use codec::{Codec, Decode, Encode}; use environmental::*; use frame_support::{ @@ -74,7 +74,7 @@ use pallet_transaction_payment::OnChargeTransaction; use scale_info::TypeInfo; use sp_core::{H160, H256, U256}; use sp_runtime::{ - traits::{BadOrigin, Convert, Dispatchable, Saturating, Zero}, + traits::{BadOrigin, Bounded, Convert, Dispatchable, Saturating, Zero}, DispatchError, }; @@ -823,7 +823,7 @@ pub mod pallet { dest, value, gas_limit, - storage_deposit_limit, + DepositLimit::Balance(storage_deposit_limit), data, DebugInfo::Skip, CollectEvents::Skip, @@ -859,7 +859,7 @@ pub mod pallet { origin, value, gas_limit, - storage_deposit_limit, + DepositLimit::Balance(storage_deposit_limit), Code::Existing(code_hash), data, salt, @@ -925,7 +925,7 @@ pub mod pallet { origin, value, gas_limit, - storage_deposit_limit, + DepositLimit::Balance(storage_deposit_limit), Code::Upload(code), data, salt, @@ -1083,7 +1083,7 @@ fn dispatch_result( impl Pallet where - BalanceOf: Into + TryFrom, + BalanceOf: Into + TryFrom + Bounded, MomentOf: Into, T::Hash: frame_support::traits::IsType, { @@ -1098,7 +1098,7 @@ where dest: H160, value: BalanceOf, gas_limit: Weight, - storage_deposit_limit: BalanceOf, + storage_deposit_limit: DepositLimit>, data: Vec, debug: DebugInfo, collect_events: CollectEvents, @@ -1112,7 +1112,10 @@ where }; let try_call = || { let origin = Origin::from_runtime_origin(origin)?; - let mut storage_meter = StorageMeter::new(&origin, storage_deposit_limit, value)?; + let mut storage_meter = match storage_deposit_limit { + DepositLimit::Balance(limit) => StorageMeter::new(&origin, limit, value)?, + DepositLimit::Unchecked => StorageMeter::new_unchecked(BalanceOf::::max_value()), + }; let result = ExecStack::>::run_call( origin.clone(), dest, @@ -1120,9 +1123,14 @@ where &mut storage_meter, Self::convert_native_to_evm(value), data, + storage_deposit_limit.is_unchecked(), debug_message.as_mut(), )?; - storage_deposit = storage_meter.try_into_deposit(&origin)?; + storage_deposit = storage_meter + .try_into_deposit(&origin, storage_deposit_limit.is_unchecked()) + .inspect_err(|err| { + log::error!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}"); + })?; Ok(result) }; let result = Self::run_guarded(try_call); @@ -1151,7 +1159,7 @@ where origin: OriginFor, value: BalanceOf, gas_limit: Weight, - mut storage_deposit_limit: BalanceOf, + storage_deposit_limit: DepositLimit>, code: Code, data: Vec, salt: Option<[u8; 32]>, @@ -1162,13 +1170,24 @@ where let mut storage_deposit = Default::default(); let mut debug_message = if debug == DebugInfo::UnsafeDebug { Some(DebugBuffer::default()) } else { None }; + + let unchecked_deposit_limit = storage_deposit_limit.is_unchecked(); + let mut storage_deposit_limit = match storage_deposit_limit { + DepositLimit::Balance(limit) => limit, + DepositLimit::Unchecked => BalanceOf::::max_value(), + }; + let try_instantiate = || { let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?; let (executable, upload_deposit) = match code { Code::Upload(code) => { let upload_account = T::UploadOrigin::ensure_origin(origin)?; - let (executable, upload_deposit) = - Self::try_upload_code(upload_account, code, storage_deposit_limit)?; + let (executable, upload_deposit) = Self::try_upload_code( + upload_account, + code, + storage_deposit_limit, + unchecked_deposit_limit, + )?; storage_deposit_limit.saturating_reduce(upload_deposit); (executable, upload_deposit) }, @@ -1176,8 +1195,12 @@ where (WasmBlob::from_storage(code_hash, &mut gas_meter)?, Default::default()), }; let instantiate_origin = Origin::from_account_id(instantiate_account.clone()); - let mut storage_meter = - StorageMeter::new(&instantiate_origin, storage_deposit_limit, value)?; + let mut storage_meter = if unchecked_deposit_limit { + StorageMeter::new_unchecked(storage_deposit_limit) + } else { + StorageMeter::new(&instantiate_origin, storage_deposit_limit, value)? + }; + let result = ExecStack::>::run_instantiate( instantiate_account, executable, @@ -1186,10 +1209,11 @@ where Self::convert_native_to_evm(value), data, salt.as_ref(), + unchecked_deposit_limit, debug_message.as_mut(), ); storage_deposit = storage_meter - .try_into_deposit(&instantiate_origin)? + .try_into_deposit(&instantiate_origin, unchecked_deposit_limit)? .saturating_add(&StorageDeposit::Charge(upload_deposit)); result }; @@ -1215,28 +1239,15 @@ where /// /// # Parameters /// - /// - `origin`: The origin of the call. - /// - `dest`: The destination address of the call. - /// - `value`: The EVM value to transfer. - /// - `input`: The input data. + /// - `tx`: The Ethereum transaction to simulate. /// - `gas_limit`: The gas limit enforced during contract execution. - /// - `storage_deposit_limit`: The maximum balance that can be charged to the caller for storage - /// usage. /// - `utx_encoded_size`: A function that takes a call and returns the encoded size of the /// unchecked extrinsic. - /// - `debug`: Debugging configuration. - /// - `collect_events`: Event collection configuration. pub fn bare_eth_transact( - origin: T::AccountId, - dest: Option, - value: U256, - input: Vec, + mut tx: GenericTransaction, gas_limit: Weight, - storage_deposit_limit: BalanceOf, utx_encoded_size: impl Fn(Call) -> u32, - debug: DebugInfo, - collect_events: CollectEvents, - ) -> EthContractResult> + ) -> Result>, EthTransactError> where T: pallet_transaction_payment::Config, ::RuntimeCall: @@ -1247,26 +1258,58 @@ where T::Nonce: Into, T::Hash: frame_support::traits::IsType, { - log::debug!(target: LOG_TARGET, "bare_eth_transact: dest: {dest:?} value: {value:?} - gas_limit: {gas_limit:?} storage_deposit_limit: {storage_deposit_limit:?}"); + log::debug!(target: LOG_TARGET, "bare_eth_transact: tx: {tx:?} gas_limit: {gas_limit:?}"); + + let from = tx.from.unwrap_or_default(); + let origin = T::AddressMapper::to_account_id(&from); - // Get the nonce to encode in the tx. - let nonce: T::Nonce = >::account_nonce(&origin); + let storage_deposit_limit = if tx.gas.is_some() { + DepositLimit::Balance(BalanceOf::::max_value()) + } else { + DepositLimit::Unchecked + }; + + // TODO remove once we have revisited how we encode the gas limit. + if tx.nonce.is_none() { + tx.nonce = Some(>::account_nonce(&origin).into()); + } + if tx.gas_price.is_none() { + tx.gas_price = Some(GAS_PRICE.into()); + } + if tx.chain_id.is_none() { + tx.chain_id = Some(T::ChainId::get().into()); + } // Convert the value to the native balance type. - let native_value = match Self::convert_evm_to_native(value) { + let evm_value = tx.value.unwrap_or_default(); + let native_value = match Self::convert_evm_to_native(evm_value) { Ok(v) => v, - Err(err) => - return EthContractResult { - gas_required: Default::default(), - storage_deposit: Default::default(), - fee: Default::default(), - result: Err(err.into()), - }, + Err(_) => return Err(EthTransactError::Message("Failed to convert value".into())), + }; + + let input = tx.input.clone().unwrap_or_default().0; + let debug = DebugInfo::Skip; + let collect_events = CollectEvents::Skip; + + let extract_error = |err| { + if err == Error::::TransferFailed.into() || + err == Error::::StorageDepositNotEnoughFunds.into() || + err == Error::::StorageDepositLimitExhausted.into() + { + let balance = Self::evm_balance(&from); + return Err(EthTransactError::Message( + format!("insufficient funds for gas * price + value: address {from:?} have {balance} (supplied gas {})", + tx.gas.unwrap_or_default())) + ); + } + + return Err(EthTransactError::Message(format!( + "Failed to instantiate contract: {err:?}" + ))); }; // Dry run the call - let (mut result, dispatch_info) = match dest { + let (mut result, dispatch_info) = match tx.to { // A contract call. Some(dest) => { // Dry run the call. @@ -1281,11 +1324,24 @@ where collect_events, ); - let result = EthContractResult { + let data = match result.result { + Ok(return_value) => { + if return_value.did_revert() { + return Err(EthTransactError::Data(return_value.data)); + } + return_value.data + }, + Err(err) => { + log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}"); + return extract_error(err) + }, + }; + + let result = EthTransactInfo { gas_required: result.gas_required, storage_deposit: result.storage_deposit.charge_or_zero(), - result: result.result, - fee: Default::default(), + data, + eth_gas: Default::default(), }; // Get the dispatch info of the call. let dispatch_call: ::RuntimeCall = crate::Call::::call { @@ -1326,11 +1382,24 @@ where collect_events, ); - let result = EthContractResult { + let returned_data = match result.result { + Ok(return_value) => { + if return_value.result.did_revert() { + return Err(EthTransactError::Data(return_value.result.data)); + } + return_value.result.data + }, + Err(err) => { + log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}"); + return extract_error(err) + }, + }; + + let result = EthTransactInfo { gas_required: result.gas_required, storage_deposit: result.storage_deposit.charge_or_zero(), - result: result.result.map(|v| v.result), - fee: Default::default(), + data: returned_data, + eth_gas: Default::default(), }; // Get the dispatch info of the call. @@ -1348,23 +1417,18 @@ where }, }; - let mut tx = TransactionLegacyUnsigned { - value, - input: input.into(), - nonce: nonce.into(), - chain_id: Some(T::ChainId::get().into()), - gas_price: GAS_PRICE.into(), - to: dest, - ..Default::default() - }; - // The transaction fees depend on the extrinsic's length, which in turn is influenced by // the encoded length of the gas limit specified in the transaction (tx.gas). // We iteratively compute the fee by adjusting tx.gas until the fee stabilizes. // with a maximum of 3 iterations to avoid an infinite loop. for _ in 0..3 { + let Ok(unsigned_tx) = tx.clone().try_into_unsigned() else { + log::debug!(target: LOG_TARGET, "Failed to convert to unsigned"); + return Err(EthTransactError::Message("Invalid transaction".into())); + }; + let eth_dispatch_call = crate::Call::::eth_transact { - payload: tx.dummy_signed_payload(), + payload: unsigned_tx.dummy_signed_payload(), gas_limit: result.gas_required, storage_deposit_limit: result.storage_deposit, }; @@ -1375,17 +1439,18 @@ where 0u32.into(), ) .into(); + let eth_gas: U256 = (fee / GAS_PRICE.into()).into(); - if fee == result.fee { - log::trace!(target: LOG_TARGET, "bare_eth_call: encoded_len: {encoded_len:?} fee: {fee:?}"); + if eth_gas == result.eth_gas { + log::trace!(target: LOG_TARGET, "bare_eth_call: encoded_len: {encoded_len:?} eth_gas: {eth_gas:?}"); break; } - result.fee = fee; - tx.gas = (fee / GAS_PRICE.into()).into(); - log::debug!(target: LOG_TARGET, "Adjusting Eth gas to: {:?}", tx.gas); + result.eth_gas = eth_gas; + tx.gas = Some(eth_gas.into()); + log::debug!(target: LOG_TARGET, "Adjusting Eth gas to: {eth_gas:?}"); } - result + Ok(result) } /// Get the balance with EVM decimals of the given `address`. @@ -1403,7 +1468,7 @@ where storage_deposit_limit: BalanceOf, ) -> CodeUploadResult> { let origin = T::UploadOrigin::ensure_origin(origin)?; - let (module, deposit) = Self::try_upload_code(origin, code, storage_deposit_limit)?; + let (module, deposit) = Self::try_upload_code(origin, code, storage_deposit_limit, false)?; Ok(CodeUploadReturnValue { code_hash: *module.code_hash(), deposit }) } @@ -1421,9 +1486,10 @@ where origin: T::AccountId, code: Vec, storage_deposit_limit: BalanceOf, + skip_transfer: bool, ) -> Result<(WasmBlob, BalanceOf), DispatchError> { let mut module = WasmBlob::from_code(code, origin)?; - let deposit = module.store_code()?; + let deposit = module.store_code(skip_transfer)?; ensure!(storage_deposit_limit >= deposit, >::StorageDepositLimitExhausted); Ok((module, deposit)) } @@ -1527,14 +1593,7 @@ sp_api::decl_runtime_apis! { /// Perform an Ethereum call. /// /// See [`crate::Pallet::bare_eth_transact`] - fn eth_transact( - origin: H160, - dest: Option, - value: U256, - input: Vec, - gas_limit: Option, - storage_deposit_limit: Option, - ) -> EthContractResult; + fn eth_transact(tx: GenericTransaction) -> Result, EthTransactError>; /// Upload new code without instantiating a contract from it. /// diff --git a/substrate/frame/revive/src/primitives.rs b/substrate/frame/revive/src/primitives.rs index 024b1f3448e1..a7127f812b4b 100644 --- a/substrate/frame/revive/src/primitives.rs +++ b/substrate/frame/revive/src/primitives.rs @@ -17,8 +17,8 @@ //! A crate that hosts a common definitions that are relevant for the pallet-revive. -use crate::H160; -use alloc::vec::Vec; +use crate::{H160, U256}; +use alloc::{string::String, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::weights::Weight; use pallet_revive_uapi::ReturnFlags; @@ -28,6 +28,30 @@ use sp_runtime::{ DispatchError, RuntimeDebug, }; +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub enum DepositLimit { + /// Allows bypassing all balance transfer checks. + Unchecked, + + /// Specifies a maximum allowable balance for a deposit. + Balance(Balance), +} + +impl DepositLimit { + pub fn is_unchecked(&self) -> bool { + match self { + Self::Unchecked => true, + _ => false, + } + } +} + +impl From for DepositLimit { + fn from(value: T) -> Self { + Self::Balance(value) + } +} + /// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and /// `ContractsApi::instantiate`. /// @@ -84,15 +108,22 @@ pub struct ContractResult { /// The result of the execution of a `eth_transact` call. #[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] -pub struct EthContractResult> { - /// The fee charged for the execution. - pub fee: Balance, +pub struct EthTransactInfo { /// The amount of gas that was necessary to execute the transaction. pub gas_required: Weight, /// Storage deposit charged. pub storage_deposit: Balance, - /// The execution result. - pub result: R, + /// The weight and deposit equivalent in EVM Gas. + pub eth_gas: U256, + /// The execution return value. + pub data: Vec, +} + +/// Error type of a `eth_transact` call. +#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] +pub enum EthTransactError { + Data(Vec), + Message(String), } /// Result type of a `bare_code_upload` call. diff --git a/substrate/frame/revive/src/storage/meter.rs b/substrate/frame/revive/src/storage/meter.rs index 712010bc8257..6eddf048be98 100644 --- a/substrate/frame/revive/src/storage/meter.rs +++ b/substrate/frame/revive/src/storage/meter.rs @@ -373,24 +373,36 @@ where } } + /// Create new storage meter without checking the limit. + pub fn new_unchecked(limit: BalanceOf) -> Self { + return Self { limit, ..Default::default() } + } + /// The total amount of deposit that should change hands as result of the execution /// that this meter was passed into. This will also perform all the charges accumulated /// in the whole contract stack. /// /// This drops the root meter in order to make sure it is only called when the whole /// execution did finish. - pub fn try_into_deposit(self, origin: &Origin) -> Result, DispatchError> { - // Only refund or charge deposit if the origin is not root. - let origin = match origin { - Origin::Root => return Ok(Deposit::Charge(Zero::zero())), - Origin::Signed(o) => o, - }; - for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Refund(_))) { - E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; - } - for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Charge(_))) { - E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; + pub fn try_into_deposit( + self, + origin: &Origin, + skip_transfer: bool, + ) -> Result, DispatchError> { + if !skip_transfer { + // Only refund or charge deposit if the origin is not root. + let origin = match origin { + Origin::Root => return Ok(Deposit::Charge(Zero::zero())), + Origin::Signed(o) => o, + }; + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Refund(_))) { + E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; + } + for charge in self.charges.iter().filter(|c| matches!(c.amount, Deposit::Charge(_))) { + E::charge(origin, &charge.contract, &charge.amount, &charge.state)?; + } } + Ok(self.total_deposit) } } @@ -425,13 +437,18 @@ impl> RawMeter { contract: &T::AccountId, contract_info: &mut ContractInfo, code_info: &CodeInfo, + skip_transfer: bool, ) -> Result<(), DispatchError> { debug_assert!(matches!(self.contract_state(), ContractState::Alive)); // We need to make sure that the contract's account exists. let ed = Pallet::::min_balance(); self.total_deposit = Deposit::Charge(ed); - T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; + if skip_transfer { + T::Currency::set_balance(contract, ed); + } else { + T::Currency::transfer(origin, contract, ed, Preservation::Preserve)?; + } // A consumer is added at account creation and removed it on termination, otherwise the // runtime could remove the account. As long as a contract exists its account must exist. @@ -479,6 +496,7 @@ impl> RawMeter { } if let Deposit::Charge(amount) = total_deposit { if amount > self.limit { + log::debug!( target: LOG_TARGET, "Storage deposit limit exhausted: {:?} > {:?}", amount, self.limit); return Err(>::StorageDepositLimitExhausted.into()) } } @@ -811,7 +829,10 @@ mod tests { nested0.enforce_limit(Some(&mut nested0_info)).unwrap(); meter.absorb(nested0, &BOB, Some(&mut nested0_info)); - assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit); + assert_eq!( + meter.try_into_deposit(&test_case.origin, false).unwrap(), + test_case.deposit + ); assert_eq!(nested0_info.extra_deposit(), 112); assert_eq!(nested1_info.extra_deposit(), 110); @@ -882,7 +903,10 @@ mod tests { nested0.absorb(nested1, &CHARLIE, None); meter.absorb(nested0, &BOB, None); - assert_eq!(meter.try_into_deposit(&test_case.origin).unwrap(), test_case.deposit); + assert_eq!( + meter.try_into_deposit(&test_case.origin, false).unwrap(), + test_case.deposit + ); assert_eq!(TestExtTestValue::get(), test_case.expected) } } diff --git a/substrate/frame/revive/src/test_utils/builder.rs b/substrate/frame/revive/src/test_utils/builder.rs index e64f58894432..8ba5e7384070 100644 --- a/substrate/frame/revive/src/test_utils/builder.rs +++ b/substrate/frame/revive/src/test_utils/builder.rs @@ -18,7 +18,8 @@ use super::{deposit_limit, GAS_LIMIT}; use crate::{ address::AddressMapper, AccountIdOf, BalanceOf, Code, CollectEvents, Config, ContractResult, - DebugInfo, EventRecordOf, ExecReturnValue, InstantiateReturnValue, OriginFor, Pallet, Weight, + DebugInfo, DepositLimit, EventRecordOf, ExecReturnValue, InstantiateReturnValue, OriginFor, + Pallet, Weight, }; use frame_support::pallet_prelude::DispatchResultWithPostInfo; use paste::paste; @@ -133,7 +134,7 @@ builder!( origin: OriginFor, value: BalanceOf, gas_limit: Weight, - storage_deposit_limit: BalanceOf, + storage_deposit_limit: DepositLimit>, code: Code, data: Vec, salt: Option<[u8; 32]>, @@ -159,7 +160,7 @@ builder!( origin, value: 0u32.into(), gas_limit: GAS_LIMIT, - storage_deposit_limit: deposit_limit::(), + storage_deposit_limit: DepositLimit::Balance(deposit_limit::()), code, data: vec![], salt: Some([0; 32]), @@ -198,7 +199,7 @@ builder!( dest: H160, value: BalanceOf, gas_limit: Weight, - storage_deposit_limit: BalanceOf, + storage_deposit_limit: DepositLimit>, data: Vec, debug: DebugInfo, collect_events: CollectEvents, @@ -216,7 +217,7 @@ builder!( dest, value: 0u32.into(), gas_limit: GAS_LIMIT, - storage_deposit_limit: deposit_limit::(), + storage_deposit_limit: DepositLimit::Balance(deposit_limit::()), data: vec![], debug: DebugInfo::UnsafeDebug, collect_events: CollectEvents::Skip, diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index 34afe8aabfe6..1df300f031a7 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -1249,7 +1249,7 @@ fn transfer_expendable_cannot_kill_account() { test_utils::contract_info_storage_deposit(&addr) ); - // Some ot the total balance is held, so it can't be transferred. + // Some or the total balance is held, so it can't be transferred. assert_err!( <::Currency as Mutate>::transfer( &account, @@ -2290,7 +2290,7 @@ fn gas_estimation_for_subcalls() { // 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()) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) .data(input.clone()) .build(); assert_ok!(&result.result); @@ -2298,7 +2298,7 @@ fn gas_estimation_for_subcalls() { // 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()) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) .data(input.clone()) .build(); assert_err!(result.result, error); @@ -2306,7 +2306,7 @@ fn gas_estimation_for_subcalls() { // 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()) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) .data(input.clone()) .build(); assert_err!(result.result, error); @@ -3592,7 +3592,7 @@ fn deposit_limit_in_nested_instantiate() { // Set enough deposit limit for the child instantiate. This should succeed. let result = builder::bare_call(addr_caller) .origin(RuntimeOrigin::signed(BOB)) - .storage_deposit_limit(callee_info_len + 2 + ED + 4 + 2) + .storage_deposit_limit((callee_info_len + 2 + ED + 4 + 2).into()) .data((1u32, &code_hash_callee, U256::from(callee_info_len + 2 + ED + 3 + 2)).encode()) .build(); @@ -3879,7 +3879,7 @@ fn locking_delegate_dependency_works() { // Locking a dependency with a storage limit too low should fail. assert_err!( builder::bare_call(addr_caller) - .storage_deposit_limit(dependency_deposit - 1) + .storage_deposit_limit((dependency_deposit - 1).into()) .data((1u32, hash2addr(&callee_hashes[0]), callee_hashes[0]).encode()) .build() .result, diff --git a/substrate/frame/revive/src/tests/test_debug.rs b/substrate/frame/revive/src/tests/test_debug.rs index 7c4fbba71f65..c9e19e52ace1 100644 --- a/substrate/frame/revive/src/tests/test_debug.rs +++ b/substrate/frame/revive/src/tests/test_debug.rs @@ -21,6 +21,7 @@ use crate::{ debug::{CallInterceptor, CallSpan, ExecResult, ExportedFunction, Tracing}, primitives::ExecReturnValue, test_utils::*, + DepositLimit, }; use frame_support::traits::Currency; use pretty_assertions::assert_eq; @@ -114,7 +115,7 @@ fn debugging_works() { RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, - deposit_limit::(), + DepositLimit::Balance(deposit_limit::()), Code::Upload(wasm), vec![], Some([0u8; 32]), @@ -198,7 +199,7 @@ fn call_interception_works() { RuntimeOrigin::signed(ALICE), 0, GAS_LIMIT, - deposit_limit::(), + deposit_limit::().into(), Code::Upload(wasm), vec![], // some salt to ensure that the address of this contract is unique among all tests diff --git a/substrate/frame/revive/src/wasm/mod.rs b/substrate/frame/revive/src/wasm/mod.rs index d87ec7112286..54fb02c866e1 100644 --- a/substrate/frame/revive/src/wasm/mod.rs +++ b/substrate/frame/revive/src/wasm/mod.rs @@ -183,7 +183,7 @@ where } /// Puts the module blob into storage, and returns the deposit collected for the storage. - pub fn store_code(&mut self) -> Result, Error> { + pub fn store_code(&mut self, skip_transfer: bool) -> Result, Error> { let code_hash = *self.code_hash(); >::mutate(code_hash, |stored_code_info| { match stored_code_info { @@ -195,15 +195,16 @@ where // the `owner` is always the origin of the current transaction. None => { let deposit = self.code_info.deposit; - T::Currency::hold( + + if !skip_transfer { + T::Currency::hold( &HoldReason::CodeUploadDepositReserve.into(), &self.code_info.owner, deposit, - ) - .map_err(|err| { - log::debug!(target: LOG_TARGET, "failed to store code for owner: {:?}: {err:?}", self.code_info.owner); + ) .map_err(|err| { log::debug!(target: LOG_TARGET, "failed to store code for owner: {:?}: {err:?}", self.code_info.owner); >::StorageDepositNotEnoughFunds })?; + } self.code_info.refcount = 0; >::insert(code_hash, &self.code); From c0921339f9d486981b3681760ee83ba9237f2eaa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 2 Dec 2024 07:20:56 +0000 Subject: [PATCH 166/166] Bump the ci_dependencies group across 1 directory with 3 updates (#6516) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the ci_dependencies group with 3 updates in the / directory: [lycheeverse/lychee-action](https://github.com/lycheeverse/lychee-action), [actions/attest-build-provenance](https://github.com/actions/attest-build-provenance) and [codecov/codecov-action](https://github.com/codecov/codecov-action). Updates `lycheeverse/lychee-action` from 2.0.2 to 2.1.0
Commits

Updates `actions/attest-build-provenance` from 1.4.3 to 1.4.4
Release notes

Sourced from actions/attest-build-provenance's releases.

v1.4.4

What's Changed

Full Changelog: https://github.com/actions/attest-build-provenance/compare/v1.4.3...v1.4.4

Commits
  • ef24412 bump predicate from 1.1.3 to 1.1.4 (#310)
  • 36fa7d0 bump @​actions/attest from 1.4.2 to 1.5.0 (#309)
  • 390c0bb Bump @​types/node from 22.8.1 to 22.8.7 in the npm-development group (#305)
  • 21da615 Bump the npm-development group with 3 updates (#299)
  • 0704961 Bump actions/publish-immutable-action in the actions-minor group (#298)
  • d01b070 Bump the npm-development group with 3 updates (#278)
  • b1d65e4 Add workflow file for publishing releases to immutable action package (#277)
  • 3a27694 Bump @​actions/core from 1.10.1 to 1.11.1 (#275)
  • dff1ae6 prevent e2e workflows on forks (#272)
  • e5892d0 Bump the npm-development group with 3 updates (#263)
  • Additional commits viewable in compare view

Updates `codecov/codecov-action` from 4 to 5
Release notes

Sourced from codecov/codecov-action's releases.

v5.0.0

v5 Release

v5 of the Codecov GitHub Action will use the Codecov Wrapper to encapsulate the CLI. This will help ensure that the Action gets updates quicker.

Migration Guide

The v5 release also coincides with the opt-out feature for tokens for public repositories. In the Global Upload Token section of the settings page of an organization in codecov.io, you can set the ability for Codecov to receive a coverage reports from any source. This will allow contributors or other members of a repository to upload without needing access to the Codecov token. For more details see how to upload without a token.

[!WARNING]
The following arguments have been changed

  • file (this has been deprecated in favor of files)
  • plugin (this has been deprecated in favor of plugins)

The following arguments have been added:

  • binary
  • gcov_args
  • gcov_executable
  • gcov_ignore
  • gcov_include
  • report_type
  • skip_validation
  • swift_project

You can see their usage in the action.yml file.

What's Changed

... (truncated)

Changelog

Sourced from codecov/codecov-action's changelog.

4.0.0-beta.2

Fixes

  • #1085 not adding -n if empty to do-upload command

4.0.0-beta.1

v4 represents a move from the universal uploader to the Codecov CLI. Although this will unlock new features for our users, the CLI is not yet at feature parity with the universal uploader.

Breaking Changes

  • No current support for aarch64 and alpine architectures.
  • Tokenless uploading is unsuported
  • Various arguments to the Action have been removed

3.1.4

Fixes

  • #967 Fix typo in README.md
  • #971 fix: add back in working dir
  • #969 fix: CLI option names for uploader

Dependencies

  • #970 build(deps-dev): bump @​types/node from 18.15.12 to 18.16.3
  • #979 build(deps-dev): bump @​types/node from 20.1.0 to 20.1.2
  • #981 build(deps-dev): bump @​types/node from 20.1.2 to 20.1.4

3.1.3

Fixes

  • #960 fix: allow for aarch64 build

Dependencies

  • #957 build(deps-dev): bump jest-junit from 15.0.0 to 16.0.0
  • #958 build(deps): bump openpgp from 5.7.0 to 5.8.0
  • #959 build(deps-dev): bump @​types/node from 18.15.10 to 18.15.12

3.1.2

Fixes

  • #718 Update README.md
  • #851 Remove unsupported path_to_write_report argument
  • #898 codeql-analysis.yml
  • #901 Update README to contain correct information - inputs and negate feature
  • #955 fix: add in all the extra arguments for uploader

Dependencies

  • #819 build(deps): bump openpgp from 5.4.0 to 5.5.0
  • #835 build(deps): bump node-fetch from 3.2.4 to 3.2.10
  • #840 build(deps): bump ossf/scorecard-action from 1.1.1 to 2.0.4
  • #841 build(deps): bump @​actions/core from 1.9.1 to 1.10.0
  • #843 build(deps): bump @​actions/github from 5.0.3 to 5.1.1
  • #869 build(deps): bump node-fetch from 3.2.10 to 3.3.0
  • #872 build(deps-dev): bump jest-junit from 13.2.0 to 15.0.0
  • #879 build(deps): bump decode-uri-component from 0.2.0 to 0.2.2

... (truncated)

Commits

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. [//]: # (dependabot-automerge-start) [//]: # (dependabot-automerge-end) ---
Dependabot commands and options
You can trigger Dependabot actions by commenting on this PR: - `@dependabot rebase` will rebase this PR - `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it - `@dependabot merge` will merge this PR after your CI passes on it - `@dependabot squash and merge` will squash and merge this PR after your CI passes on it - `@dependabot cancel merge` will cancel a previously requested merge and block automerging - `@dependabot reopen` will reopen this PR if it is closed - `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually - `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency - `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) - `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) - `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) - `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency - `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/check-links.yml | 2 +- .github/workflows/release-reusable-rc-buid.yml | 6 +++--- .github/workflows/tests-linux-stable-coverage.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml index dd9d3eaf824f..cea6b9a8636a 100644 --- a/.github/workflows/check-links.yml +++ b/.github/workflows/check-links.yml @@ -33,7 +33,7 @@ jobs: - uses: actions/checkout@6d193bf28034eafb982f37bd894289fe649468fc # v4.1.0 (22. Sep 2023) - name: Lychee link checker - uses: lycheeverse/lychee-action@7cd0af4c74a61395d455af97419279d86aafaede # for v1.9.1 (10. Jan 2024) + uses: lycheeverse/lychee-action@f81112d0d2814ded911bd23e3beaa9dda9093915 # for v1.9.1 (10. Jan 2024) with: args: >- --config .config/lychee.toml diff --git a/.github/workflows/release-reusable-rc-buid.yml b/.github/workflows/release-reusable-rc-buid.yml index 7e31a4744b59..f5240878cba2 100644 --- a/.github/workflows/release-reusable-rc-buid.yml +++ b/.github/workflows/release-reusable-rc-buid.yml @@ -104,7 +104,7 @@ jobs: ./.github/scripts/release/build-linux-release.sh ${{ matrix.binaries }} ${{ inputs.package }} - name: Generate artifact attestation - uses: actions/attest-build-provenance@1c608d11d69870c2092266b3f9a6f3abbf17002c # v1.4.3 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1.4.4 with: subject-path: /artifacts/${{ matrix.binaries }}/${{ matrix.binaries }} @@ -220,7 +220,7 @@ jobs: ./.github/scripts/release/build-macos-release.sh ${{ matrix.binaries }} ${{ inputs.package }} - name: Generate artifact attestation - uses: actions/attest-build-provenance@1c608d11d69870c2092266b3f9a6f3abbf17002c # v1.4.3 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1.4.4 with: subject-path: ${{ env.ARTIFACTS_PATH }}/${{ matrix.binaries }} @@ -278,7 +278,7 @@ jobs: . "${GITHUB_WORKSPACE}"/.github/scripts/release/build-deb.sh ${{ inputs.package }} ${VERSION} - name: Generate artifact attestation - uses: actions/attest-build-provenance@1c608d11d69870c2092266b3f9a6f3abbf17002c # v1.4.3 + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1.4.4 with: subject-path: target/production/*.deb diff --git a/.github/workflows/tests-linux-stable-coverage.yml b/.github/workflows/tests-linux-stable-coverage.yml index c5af6bcae77f..61e01cda4428 100644 --- a/.github/workflows/tests-linux-stable-coverage.yml +++ b/.github/workflows/tests-linux-stable-coverage.yml @@ -102,7 +102,7 @@ jobs: merge-multiple: true - run: ls -al reports/ - name: Upload to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@v5 with: token: ${{ secrets.CODECOV_TOKEN }} verbose: true
Release notes

Sourced from lycheeverse/lychee-action's releases.

Version 2.1.0

What's Changed

New Contributors

Full Changelog: https://github.com/lycheeverse/lychee-action/compare/v2...v2.1.0