Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: tx-pause and safe-mode pallets integration #1388

Merged
merged 15 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
613 changes: 327 additions & 286 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ sp-arithmetic = { git = "https://github.com/paritytech/polkadot-sdk", branch = "
sp-staking = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
sp-externalities = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
sp-genesis-builder = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
sp-weights = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }

# (native)
sp-blockchain = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407" }
Expand Down Expand Up @@ -184,6 +185,8 @@ pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", bra
pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-democracy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-tx-pause = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-safe-mode = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }

# EVM & Ethereum
# (wasm)
Expand Down
9 changes: 9 additions & 0 deletions bin/collator/src/local/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,20 @@ use astar_primitives::*;
const GRANDPA_JUSTIFICATION_PERIOD: u32 = 512;

/// Parachain host functions
#[cfg(not(feature = "runtime-benchmarks"))]
pub type HostFunctions = (
cumulus_client_service::ParachainHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);

/// Host functions required for kitchensink runtime and Substrate node.
#[cfg(feature = "runtime-benchmarks")]
pub type HostFunctions = (
frame_benchmarking::benchmarking::HostFunctions,
cumulus_client_service::ParachainHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);

type ParachainExecutor = WasmExecutor<HostFunctions>;

type FullClient = sc_service::TFullClient<Block, RuntimeApi, ParachainExecutor>;
Expand Down
9 changes: 9 additions & 0 deletions bin/collator/src/parachain/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,20 @@ use crate::{
};

/// Parachain host functions
#[cfg(not(feature = "runtime-benchmarks"))]
pub type HostFunctions = (
cumulus_client_service::ParachainHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);

/// Host functions required for kitchensink runtime and Substrate node.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't need this. The benchmark host functions is injected by benchmarking-cli itself

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am getting this error if I remove benchmarking host functions:

Finished release [optimized] target(s) in 3m 14s
     Running `target/release/astar-collator benchmark overhead --dev --header=./.github/license-check/headers/HEADER-GNUv3`
Error: Service(Client(VersionInvalid("Other error happened while constructing the runtime: runtime requires function imports which are not present on the host: 'env:ext_benchmarking_proof_size_version_1', 'env:ext_benchmarking_add_to_whitelist_version_1', 'env:ext_benchmarking_current_time_version_1', 'env:ext_benchmarking_commit_db_version_1', 'env:ext_benchmarking_read_write_count_version_1', 'env:ext_benchmarking_wipe_db_version_1', 'env:ext_benchmarking_get_read_and_written_keys_version_1', 'env:ext_benchmarking_reset_read_write_count_version_1', 'env:ext_benchmarking_set_whitelist_version_1'")))
2024-12-02 13:52:50 Cannot create a runtime error=Other("runtime requires function imports which are not present on the host: 'env:ext_benchmarking_proof_size_version_1', 'env:ext_benchmarking_add_to_whitelist_version_1', 'env:ext_benchmarking_current_time_version_1', 'env:ext_benchmarking_commit_db_version_1', 'env:ext_benchmarking_read_write_count_version_1', 'env:ext_benchmarking_wipe_db_version_1', 'env:ext_benchmarking_get_read_and_written_keys_version_1', 'env:ext_benchmarking_reset_read_write_count_version_1', 'env:ext_benchmarking_set_whitelist_version_1'")

PS: I will fix the comment (copied)

Copy link
Contributor

@ermalkaleci ermalkaleci Dec 2, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like overhead doesn't include it, wonder why

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can make an issue or PR for it, probably it's small effort.

#[cfg(feature = "runtime-benchmarks")]
pub type HostFunctions = (
frame_benchmarking::benchmarking::HostFunctions,
cumulus_client_service::ParachainHostFunctions,
moonbeam_primitives_ext::moonbeam_ext::HostFunctions,
);

/// Parachain executor
pub type ParachainExecutor = WasmExecutor<HostFunctions>;

Expand Down
27 changes: 23 additions & 4 deletions pallets/dapp-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use frame_support::{
pallet_prelude::*,
traits::{
fungible::{Inspect as FunInspect, MutateFreeze as FunMutateFreeze},
StorageVersion,
SafeModeNotify, StorageVersion,
},
weights::Weight,
};
Expand Down Expand Up @@ -682,9 +682,7 @@ pub mod pallet {
#[pallet::weight(T::WeightInfo::maintenance_mode())]
pub fn maintenance_mode(origin: OriginFor<T>, enabled: bool) -> DispatchResult {
T::ManagerOrigin::ensure_origin(origin)?;
ActiveProtocolState::<T>::mutate(|state| state.maintenance = enabled);

Self::deposit_event(Event::<T>::MaintenanceMode { enabled });
Self::set_maintenance_mode(enabled);
Ok(())
}

Expand Down Expand Up @@ -2210,6 +2208,14 @@ pub mod pallet {
Ok(())
}

/// Internal function to transition the dApp staking protocol maintenance mode.
/// Ensure this method is **not exposed publicly** and is only used for legitimate maintenance mode transitions invoked by privileged or trusted logic,
/// such as `T::ManagerOrigin` or a safe-mode enter/exit notification.
fn set_maintenance_mode(enabled: bool) {
ActiveProtocolState::<T>::mutate(|state| state.maintenance = enabled);
Self::deposit_event(Event::<T>::MaintenanceMode { enabled });
}

/// Ensure the correctness of the state of this pallet.
#[cfg(any(feature = "try-runtime", test))]
pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
Expand Down Expand Up @@ -2470,4 +2476,17 @@ pub mod pallet {
Ok(())
}
}

/// Implementation of the `SafeModeNotify` trait for the `DappStaking` pallet.
/// This integration ensures that the dApp staking protocol transitions to and from
/// maintenance mode when the runtime enters or exits safe mode.
impl<T: Config> SafeModeNotify for Pallet<T> {
fn entered() {
Self::set_maintenance_mode(true);
}

fn exited() {
Self::set_maintenance_mode(false);
}
}
}
24 changes: 23 additions & 1 deletion pallets/dapp-staking/src/test/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use frame_support::{
error::BadOrigin,
traits::{
fungible::Unbalanced as FunUnbalanced, Currency, Get, OnFinalize, OnInitialize,
ReservableCurrency,
ReservableCurrency, SafeModeNotify,
},
BoundedVec,
};
Expand Down Expand Up @@ -185,6 +185,28 @@ fn maintenance_mode_call_filtering_works() {
})
}

#[test]
fn maintenance_safe_mode_entered_exited_works() {
ExtBuilder::default().build_and_execute(|| {
// Check that maintenance mode is disabled by default
assert!(!ActiveProtocolState::<Test>::get().maintenance);

// Call entered and check post-state and event
DappStaking::entered();
assert!(ActiveProtocolState::<Test>::get().maintenance);
System::assert_last_event(RuntimeEvent::DappStaking(Event::MaintenanceMode {
enabled: true,
}));

// Call exited and check post-state and event
DappStaking::exited();
assert!(!ActiveProtocolState::<Test>::get().maintenance);
System::assert_last_event(RuntimeEvent::DappStaking(Event::MaintenanceMode {
enabled: false,
}));
})
}

#[test]
fn on_initialize_is_noop_if_no_era_change() {
ExtBuilder::default().build_and_execute(|| {
Expand Down
8 changes: 8 additions & 0 deletions runtime/local/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,13 @@ pallet-insecure-randomness-collective-flip = { workspace = true }
pallet-membership = { workspace = true }
pallet-preimage = { workspace = true }
pallet-proxy = { workspace = true }
pallet-safe-mode = { workspace = true, default-features = false }
ipapandinas marked this conversation as resolved.
Show resolved Hide resolved
pallet-scheduler = { workspace = true }
pallet-sudo = { workspace = true }
pallet-timestamp = { workspace = true }
pallet-transaction-payment = { workspace = true }
pallet-treasury = { workspace = true }
pallet-tx-pause = { workspace = true, default-features = false }
pallet-utility = { workspace = true }
pallet-vesting = { workspace = true }
sp-api = { workspace = true }
Expand Down Expand Up @@ -160,6 +162,8 @@ std = [
"pallet-utility/std",
"pallet-vesting/std",
"pallet-proxy/std",
"pallet-safe-mode/std",
"pallet-tx-pause/std",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-aura/std",
Expand Down Expand Up @@ -222,9 +226,11 @@ runtime-benchmarks = [
"pallet-evm-precompile-dapp-staking/runtime-benchmarks",
"pallet-grandpa/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-safe-mode/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-static-price-provider/runtime-benchmarks",
"pallet-sudo/runtime-benchmarks",
"pallet-tx-pause/runtime-benchmarks",
"pallet-utility/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
]
Expand All @@ -248,11 +254,13 @@ try-runtime = [
"pallet-sudo/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-tx-pause/try-runtime",
"pallet-utility/try-runtime",
"pallet-vesting/try-runtime",
"pallet-unified-accounts/try-runtime",
"pallet-ethereum/try-runtime",
"pallet-assets/try-runtime",
"pallet-safe-mode/try-runtime",
"pallet-scheduler/try-runtime",
"pallet-proxy/try-runtime",
"pallet-preimage/try-runtime",
Expand Down
2 changes: 2 additions & 0 deletions runtime/local/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ pub fn default_config() -> serde_json::Value {
democracy: Default::default(),
treasury: Default::default(),
community_treasury: Default::default(),
safe_mode: Default::default(),
tx_pause: Default::default(),
};

serde_json::to_value(&config).expect("Could not build genesis config.")
Expand Down
68 changes: 59 additions & 9 deletions runtime/local/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ use frame_support::{
traits::{
fungible::{Balanced, Credit, HoldConsideration},
tokens::{PayFromAccount, UnityAssetBalanceConversion},
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, EqualPrivilegeOnly, FindAuthor, Get,
InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, WithdrawReasons,
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly,
FindAuthor, Get, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize,
WithdrawReasons,
},
weights::{
constants::{ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
Expand All @@ -41,7 +42,7 @@ use frame_support::{
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned,
EnsureRoot, EnsureSigned, EnsureWithSuccess,
};
use pallet_ethereum::PostLogContent;
use pallet_evm::{FeeCalculator, GasWeightMapping, Runner};
Expand Down Expand Up @@ -72,10 +73,10 @@ use astar_primitives::{
governance::{
CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst,
EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee,
EnsureRootOrTwoThirdsCommunityCouncil, EnsureRootOrTwoThirdsMainCouncil,
EnsureRootOrTwoThirdsTechnicalCommittee, MainCouncilCollectiveInst,
MainCouncilMembershipInst, MainTreasuryInst, TechnicalCommitteeCollectiveInst,
TechnicalCommitteeMembershipInst,
EnsureRootOrHalfTechnicalCommittee, EnsureRootOrTwoThirdsCommunityCouncil,
EnsureRootOrTwoThirdsMainCouncil, EnsureRootOrTwoThirdsTechnicalCommittee,
MainCouncilCollectiveInst, MainCouncilMembershipInst, MainTreasuryInst,
TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst,
},
Address, AssetId, Balance, BlockNumber, Hash, Header, Nonce,
};
Expand Down Expand Up @@ -207,10 +208,9 @@ parameter_types! {
}

// Configure FRAME pallets to include in runtime.

impl frame_system::Config for Runtime {
/// The basic call filter to use in dispatchable.
type BaseCallFilter = frame_support::traits::Everything;
type BaseCallFilter = InsideBoth<SafeMode, TxPause>;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The maximum length of a block (in bytes).
Expand Down Expand Up @@ -1127,6 +1127,52 @@ impl pallet_collective_proxy::Config for Runtime {
type WeightInfo = pallet_collective_proxy::weights::SubstrateWeight<Runtime>;
}

/// Calls that can bypass the safe-mode pallet.
pub struct SafeModeWhitelistedCalls;
impl Contains<RuntimeCall> for SafeModeWhitelistedCalls {
fn contains(call: &RuntimeCall) -> bool {
match call {
// System and Timestamp are required for block production
RuntimeCall::System(_)
| RuntimeCall::Timestamp(_)
| RuntimeCall::Sudo(_)
| RuntimeCall::TxPause(_) => true,
_ => false,
}
}
}

impl pallet_safe_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RuntimeHoldReason = RuntimeHoldReason;
type WhitelistedCalls = SafeModeWhitelistedCalls;
type EnterDuration = ConstU32<{ 5 * MINUTES }>;
type EnterDepositAmount = ();
type ExtendDuration = ConstU32<{ 2 * MINUTES }>;
type ExtendDepositAmount = ();
// The 'Success' values below represent the number of blocks that the origin may induce safe mode
type ForceEnterOrigin =
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 5 * MINUTES }>>;
type ForceExtendOrigin =
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 2 * MINUTES }>>;
type ForceExitOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ForceDepositOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ReleaseDelay = ();
type Notify = DappStaking;
type WeightInfo = pallet_safe_mode::weights::SubstrateWeight<Runtime>;
}

impl pallet_tx_pause::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type UnpauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type WhitelistedCalls = ();
type MaxNameLen = ConstU32<256>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}

construct_runtime!(
pub struct Runtime {
System: frame_system = 10,
Expand Down Expand Up @@ -1171,6 +1217,8 @@ construct_runtime!(
Treasury: pallet_treasury::<Instance1> = 107,
CommunityTreasury: pallet_treasury::<Instance2> = 108,
CollectiveProxy: pallet_collective_proxy = 109,
SafeMode: pallet_safe_mode = 110,
TxPause: pallet_tx_pause = 111,
}
);

Expand Down Expand Up @@ -1290,6 +1338,8 @@ mod benches {
[pallet_dapp_staking, DappStaking]
[pallet_inflation, Inflation]
[pallet_dynamic_evm_base_fee, DynamicEvmBaseFee]
[pallet_tx_pause, TxPause]
[pallet_safe_mode, SafeMode]
);
}

Expand Down
Loading
Loading