Skip to content

Commit

Permalink
Merge branch 'master' into emit-xcm-event
Browse files Browse the repository at this point in the history
  • Loading branch information
yrong authored Dec 19, 2024
2 parents 4aa1a7f + 243b751 commit c0a33e8
Show file tree
Hide file tree
Showing 14 changed files with 738 additions and 493 deletions.
16 changes: 11 additions & 5 deletions polkadot/runtime/parachains/src/disputes/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,21 @@

use super::*;

use frame_benchmarking::benchmarks;
use frame_benchmarking::v2::*;
use frame_system::RawOrigin;
use sp_runtime::traits::One;

benchmarks! {
force_unfreeze {
#[benchmarks]
mod benchmarks {
use super::*;

#[benchmark]
fn force_unfreeze() {
Frozen::<T>::set(Some(One::one()));
}: _(RawOrigin::Root)
verify {

#[extrinsic_call]
_(RawOrigin::Root);

assert!(Frozen::<T>::get().is_none())
}

Expand Down
6 changes: 3 additions & 3 deletions polkadot/runtime/parachains/src/disputes/slashing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,12 +355,12 @@ impl<T: Config> HandleReports<T> for () {
}

pub trait WeightInfo {
fn report_dispute_lost(validator_count: ValidatorSetCount) -> Weight;
fn report_dispute_lost_unsigned(validator_count: ValidatorSetCount) -> Weight;
}

pub struct TestWeightInfo;
impl WeightInfo for TestWeightInfo {
fn report_dispute_lost(_validator_count: ValidatorSetCount) -> Weight {
fn report_dispute_lost_unsigned(_validator_count: ValidatorSetCount) -> Weight {
Weight::zero()
}
}
Expand Down Expand Up @@ -445,7 +445,7 @@ pub mod pallet {
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(<T as Config>::WeightInfo::report_dispute_lost(
#[pallet::weight(<T as Config>::WeightInfo::report_dispute_lost_unsigned(
key_owner_proof.validator_count()
))]
pub fn report_dispute_lost_unsigned(
Expand Down
38 changes: 19 additions & 19 deletions polkadot/runtime/parachains/src/disputes/slashing/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use super::*;

use crate::{disputes::SlashingHandler, initializer, shared};
use codec::Decode;
use frame_benchmarking::{benchmarks, whitelist_account};
use frame_benchmarking::v2::*;
use frame_support::traits::{OnFinalize, OnInitialize};
use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
use pallet_staking::testing_utils::create_validators;
Expand All @@ -29,6 +29,11 @@ use sp_session::MembershipProof;
// Candidate hash of the disputed candidate.
const CANDIDATE_HASH: CandidateHash = CandidateHash(Hash::zero());

// Simplify getting the value in the benchmark
pub const fn max_validators_for<T: super::Config>() -> u32 {
<<T>::BenchmarkingConfig as BenchmarkingConfiguration>::MAX_VALIDATORS
}

pub trait Config:
pallet_session::Config
+ pallet_session::historical::Config
Expand Down Expand Up @@ -106,6 +111,7 @@ where
(session_index, key_owner_proof, validator_id)
}

/// Submits a single `ForInvalid` dispute.
fn setup_dispute<T>(session_index: SessionIndex, validator_id: ValidatorId) -> DisputeProof
where
T: Config,
Expand All @@ -125,6 +131,7 @@ where
dispute_proof(session_index, validator_id, validator_index)
}

/// Creates a `ForInvalid` dispute proof.
fn dispute_proof(
session_index: SessionIndex,
validator_id: ValidatorId,
Expand All @@ -136,27 +143,20 @@ fn dispute_proof(
DisputeProof { time_slot, kind, validator_index, validator_id }
}

benchmarks! {
where_clause {
where T: Config<KeyOwnerProof = MembershipProof>,
}

// in this setup we have a single `ForInvalid` dispute
// submitted for a past session
report_dispute_lost {
let n in 4..<<T as super::Config>::BenchmarkingConfig as BenchmarkingConfiguration>::MAX_VALIDATORS;
#[benchmarks(where T: Config<KeyOwnerProof = MembershipProof>)]
mod benchmarks {
use super::*;

let origin = RawOrigin::None.into();
#[benchmark]
fn report_dispute_lost_unsigned(n: Linear<4, { max_validators_for::<T>() }>) {
let (session_index, key_owner_proof, validator_id) = setup_validator_set::<T>(n);

// submit a single `ForInvalid` dispute for a past session.
let dispute_proof = setup_dispute::<T>(session_index, validator_id);
}: {
let result = Pallet::<T>::report_dispute_lost_unsigned(
origin,
Box::new(dispute_proof),
key_owner_proof,
);
assert!(result.is_ok());
} verify {

#[extrinsic_call]
_(RawOrigin::None, Box::new(dispute_proof), key_owner_proof);

let unapplied = <UnappliedSlashes<T>>::get(session_index, CANDIDATE_HASH);
assert!(unapplied.is_none());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl<T: frame_system::Config> polkadot_runtime_parachains::disputes::slashing::W
/// Storage: Staking UnappliedSlashes (r:1 w:1)
/// Proof Skipped: Staking UnappliedSlashes (max_values: None, max_size: None, mode: Measured)
/// The range of component `n` is `[4, 300]`.
fn report_dispute_lost(n: u32, ) -> Weight {
fn report_dispute_lost_unsigned(n: u32, ) -> Weight {
// Proof Size summary in bytes:
// Measured: `4531 + n * (189 ±0)`
// Estimated: `7843 + n * (192 ±0)`
Expand Down
13 changes: 13 additions & 0 deletions prdoc/pr_6954.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
title: '[pallet-revive] implement the gas price API'
doc:
- audience: Runtime Dev
description: This PR implements the EVM gas price syscall API method. Currently
this is a compile time constant in revive, but in the EVM it is an opcode. Thus
we should provide an opcode for this in the pallet.
crates:
- name: pallet-revive-fixtures
bump: minor
- name: pallet-revive
bump: minor
- name: pallet-revive-uapi
bump: minor
15 changes: 15 additions & 0 deletions prdoc/pr_6964.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
title: '[pallet-revive] implement the base fee API'
doc:
- audience: Runtime Dev
description: This PR implements the base fee syscall API method. Currently this
is implemented as a compile time constant in the revive compiler, returning 0.
However, since this is an opocde, if we ever need to implement it for compatibility
reasons with [EIP-1559](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1559.md),
it would break already deployed contracts. Thus we provide a syscall method instead.
crates:
- name: pallet-revive-fixtures
bump: minor
- name: pallet-revive
bump: minor
- name: pallet-revive-uapi
bump: minor
36 changes: 36 additions & 0 deletions substrate/frame/revive/fixtures/contracts/base_fee.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// 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.

//! Returns the base fee back to the caller.
#![no_std]
#![no_main]

extern crate common;
use uapi::{HostFn, HostFnImpl as api, ReturnFlags};

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn deploy() {}

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
let mut buf = [0; 32];
api::base_fee(&mut buf);
api::return_value(ReturnFlags::empty(), &buf);
}
34 changes: 34 additions & 0 deletions substrate/frame/revive/fixtures/contracts/gas_price.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// 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.

//! Returns the gas price back to the caller.
#![no_std]
#![no_main]

extern crate common;
use uapi::{HostFn, HostFnImpl as api, ReturnFlags};

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn deploy() {}

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
api::return_value(ReturnFlags::empty(), &api::gas_price().to_le_bytes());
}
24 changes: 24 additions & 0 deletions substrate/frame/revive/src/benchmarking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod call_builder;
mod code;
use self::{call_builder::CallSetup, code::WasmModule};
use crate::{
evm::runtime::GAS_PRICE,
exec::{Key, MomentOf},
limits,
storage::WriteOutcome,
Expand Down Expand Up @@ -820,6 +821,29 @@ mod benchmarks {
assert_eq!(result.unwrap(), T::BlockWeights::get().max_block.ref_time());
}

#[benchmark(pov_mode = Measured)]
fn seal_gas_price() {
build_runtime!(runtime, memory: []);
let result;
#[block]
{
result = runtime.bench_gas_price(memory.as_mut_slice());
}
assert_eq!(result.unwrap(), u64::from(GAS_PRICE));
}

#[benchmark(pov_mode = Measured)]
fn seal_base_fee() {
build_runtime!(runtime, memory: [[1u8;32], ]);
let result;
#[block]
{
result = runtime.bench_base_fee(memory.as_mut_slice(), 0);
}
assert_ok!(result);
assert_eq!(U256::from_little_endian(&memory[..]), U256::zero());
}

#[benchmark(pov_mode = Measured)]
fn seal_block_number() {
build_runtime!(runtime, memory: [[0u8;32], ]);
Expand Down
38 changes: 37 additions & 1 deletion substrate/frame/revive/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use crate::{
ChainExtension, Environment, Ext, RegisteredChainExtension, Result as ExtensionResult,
RetVal, ReturnFlags,
},
evm::GenericTransaction,
evm::{runtime::GAS_PRICE, GenericTransaction},
exec::Key,
limits,
primitives::CodeUploadReturnValue,
Expand Down Expand Up @@ -4364,6 +4364,42 @@ fn create1_with_value_works() {
});
}

#[test]
fn gas_price_api_works() {
let (code, _) = compile_module("gas_price").unwrap();

ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
let _ = <Test as Config>::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();

// Call the contract: It echoes back the value returned by the gas price API.
let received = builder::bare_call(addr).build_and_unwrap_result();
assert_eq!(received.flags, ReturnFlags::empty());
assert_eq!(u64::from_le_bytes(received.data[..].try_into().unwrap()), u64::from(GAS_PRICE));
});
}

#[test]
fn base_fee_api_works() {
let (code, _) = compile_module("base_fee").unwrap();

ExtBuilder::default().existential_deposit(100).build().execute_with(|| {
let _ = <Test as Config>::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();

// Call the contract: It echoes back the value returned by the base fee API.
let received = builder::bare_call(addr).build_and_unwrap_result();
assert_eq!(received.flags, ReturnFlags::empty());
assert_eq!(U256::from_little_endian(received.data[..].try_into().unwrap()), U256::zero());
});
}

#[test]
fn call_data_size_api_works() {
let (code, _) = compile_module("call_data_size").unwrap();
Expand Down
29 changes: 29 additions & 0 deletions substrate/frame/revive/src/wasm/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use crate::{
address::AddressMapper,
evm::runtime::GAS_PRICE,
exec::{ExecError, ExecResult, Ext, Key},
gas::{ChargedAmount, Token},
limits,
Expand Down Expand Up @@ -324,6 +325,10 @@ pub enum RuntimeCosts {
BlockNumber,
/// Weight of calling `seal_block_hash`.
BlockHash,
/// Weight of calling `seal_gas_price`.
GasPrice,
/// Weight of calling `seal_base_fee`.
BaseFee,
/// Weight of calling `seal_now`.
Now,
/// Weight of calling `seal_gas_limit`.
Expand Down Expand Up @@ -477,6 +482,8 @@ impl<T: Config> Token<T> for RuntimeCosts {
MinimumBalance => T::WeightInfo::seal_minimum_balance(),
BlockNumber => T::WeightInfo::seal_block_number(),
BlockHash => T::WeightInfo::seal_block_hash(),
GasPrice => T::WeightInfo::seal_gas_price(),
BaseFee => T::WeightInfo::seal_base_fee(),
Now => T::WeightInfo::seal_now(),
GasLimit => T::WeightInfo::seal_gas_limit(),
WeightToFee => T::WeightInfo::seal_weight_to_fee(),
Expand Down Expand Up @@ -1563,6 +1570,28 @@ pub mod env {
)?)
}

/// Returns the simulated ethereum `GASPRICE` value.
/// See [`pallet_revive_uapi::HostFn::gas_price`].
#[stable]
fn gas_price(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
self.charge_gas(RuntimeCosts::GasPrice)?;
Ok(GAS_PRICE.into())
}

/// Returns the simulated ethereum `BASEFEE` value.
/// See [`pallet_revive_uapi::HostFn::base_fee`].
#[stable]
fn base_fee(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
self.charge_gas(RuntimeCosts::BaseFee)?;
Ok(self.write_fixed_sandbox_output(
memory,
out_ptr,
&U256::zero().to_little_endian(),
false,
already_charged,
)?)
}

/// Load the latest block timestamp into the supplied buffer
/// See [`pallet_revive_uapi::HostFn::now`].
#[stable]
Expand Down
Loading

0 comments on commit c0a33e8

Please sign in to comment.