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

Try State Hook for Recovery #5290

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions prdoc/pr_5290.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
title: Try State Hook for Recovery.

doc:
- audience: Runtime User
description: |
Invariant for storage items in the recovery pallet. Enforces the following Invariant:
1.`Friends` should not exceed the `MaxFriends` capacity.
crates:
- name: pallet-recovery
bump: minor
2 changes: 1 addition & 1 deletion substrate/frame/recovery/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,5 +378,5 @@ benchmarks! {
account_lookup
)

impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test);
impl_benchmark_test_suite!(Pallet, crate::mock::ExtBuilder::default().build(), crate::mock::Test);
}
46 changes: 40 additions & 6 deletions substrate/frame/recovery/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,12 @@ use alloc::{boxed::Box, vec::Vec};
use codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_runtime::{
traits::{CheckedAdd, CheckedMul, Dispatchable, SaturatedConversion, StaticLookup},
traits::{CheckedAdd, CheckedMul, Dispatchable, Get, SaturatedConversion, StaticLookup},
RuntimeDebug,
};

use frame_support::{
dispatch::{GetDispatchInfo, PostDispatchInfo},
traits::{BalanceStatus, Currency, ReservableCurrency},
BoundedVec,
};
use frame_support::{dispatch::{GetDispatchInfo, PostDispatchInfo}, traits::{BalanceStatus, Currency, ReservableCurrency}, BoundedVec, ensure};
use frame_support::dispatch::DispatchResult;

pub use pallet::*;
pub use weights::WeightInfo;
Expand Down Expand Up @@ -705,6 +702,43 @@ pub mod pallet {
Ok(())
}
}

#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
Self::do_try_state()
}
}
}


#[cfg(any(feature = "try-runtime", test))]
impl<T: Config> Pallet<T> {
/// Ensure the correctness of the state of this pallet.
///
/// This should be valid before or after each state transition of this pallet.
pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
Self::try_state_friends()?;

Ok(())
}

/// # Invariants
///
/// `Friends` should not exceed the `MaxFriends` capacity.
fn try_state_friends() -> Result<(), sp_runtime::TryRuntimeError> {
Recoverable::<T>::iter().try_for_each(|(_, recovery_config)| -> DispatchResult {
ensure!(
recovery_config.friends.len() as u32 <= T::MaxFriends::get(),
Copy link
Member

Choose a reason for hiding this comment

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

friends is a bounded vec, which are guaranteed on a type level to never exceed their allowed length:

type FriendsOf<T> = BoundedVec<<T as frame_system::Config>::AccountId, <T as Config>::MaxFriends>;

So i dont see how this is useful.

Copy link
Author

Choose a reason for hiding this comment

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

@ggwpez Any suggestion?

"Friends number exceeds what the pallet config allows."
);

Ok(())
})?;

Ok(())
}
}

impl<T: Config> Pallet<T> {
Expand Down
31 changes: 24 additions & 7 deletions substrate/frame/recovery/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,16 +76,33 @@ impl Config for Test {
pub type BalancesCall = pallet_balances::Call<Test>;
pub type RecoveryCall = super::Call<Test>;

pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)],
pub struct ExtBuilder {}

impl Default for ExtBuilder {
fn default() -> Self {
Self {}
}
.assimilate_storage(&mut t)
.unwrap();
t.into()
}

impl ExtBuilder {
pub fn build(self) -> sp_io::TestExternalities {
let ext: sp_io::TestExternalities = RuntimeGenesisConfig {
system: frame_system::GenesisConfig::default(),
balances: pallet_balances::GenesisConfig { balances: vec![(1, 100), (2, 100), (3, 100), (4, 100), (5, 100)], },
}
.build_storage()
.unwrap()
.into();
ext
}

pub fn build_and_execute(self, test: impl FnOnce() -> ()) {
self.build().execute_with(|| {
test();
Recovery::do_try_state().expect("All invariants must hold after a test");
})
}
}
/// Run until a particular block.
pub fn run_to_block(n: u64) {
while System::block_number() < n {
Expand Down
30 changes: 15 additions & 15 deletions substrate/frame/recovery/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@
use super::*;
use frame_support::{assert_noop, assert_ok, traits::Currency};
use mock::{
new_test_ext, run_to_block, Balances, BalancesCall, MaxFriends, Recovery, RecoveryCall,
ExtBuilder, run_to_block, Balances, BalancesCall, MaxFriends, Recovery, RecoveryCall,
RuntimeCall, RuntimeOrigin, Test,
};
use sp_runtime::{bounded_vec, traits::BadOrigin};

#[test]
fn basic_setup_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Nothing in storage to start
assert_eq!(Recovery::proxy(&2), None);
assert_eq!(Recovery::active_recovery(&1, &2), None);
Expand All @@ -39,7 +39,7 @@ fn basic_setup_works() {

#[test]
fn set_recovered_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Not accessible by a normal user
assert_noop!(Recovery::set_recovered(RuntimeOrigin::signed(1), 5, 1), BadOrigin);
// Root can set a recovered account though
Expand All @@ -58,7 +58,7 @@ fn set_recovered_works() {

#[test]
fn recovery_life_cycle_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
let friends = vec![2, 3, 4];
let threshold = 3;
let delay_period = 10;
Expand Down Expand Up @@ -116,7 +116,7 @@ fn recovery_life_cycle_works() {

#[test]
fn malicious_recovery_fails() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
let friends = vec![2, 3, 4];
let threshold = 3;
let delay_period = 10;
Expand Down Expand Up @@ -176,7 +176,7 @@ fn malicious_recovery_fails() {

#[test]
fn create_recovery_handles_basic_errors() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// No friends
assert_noop!(
Recovery::create_recovery(RuntimeOrigin::signed(5), vec![], 1, 0),
Expand Down Expand Up @@ -223,7 +223,7 @@ fn create_recovery_handles_basic_errors() {

#[test]
fn create_recovery_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
let friends = vec![2, 3, 4];
let threshold = 3;
let delay_period = 10;
Expand All @@ -250,7 +250,7 @@ fn create_recovery_works() {

#[test]
fn initiate_recovery_handles_basic_errors() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// No recovery process set up for the account
assert_noop!(
Recovery::initiate_recovery(RuntimeOrigin::signed(1), 5),
Expand Down Expand Up @@ -279,7 +279,7 @@ fn initiate_recovery_handles_basic_errors() {

#[test]
fn initiate_recovery_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Create a recovery process for the test
let friends = vec![2, 3, 4];
let threshold = 3;
Expand All @@ -305,7 +305,7 @@ fn initiate_recovery_works() {

#[test]
fn vouch_recovery_handles_basic_errors() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Cannot vouch for non-recoverable account
assert_noop!(
Recovery::vouch_recovery(RuntimeOrigin::signed(2), 5, 1),
Expand Down Expand Up @@ -344,7 +344,7 @@ fn vouch_recovery_handles_basic_errors() {

#[test]
fn vouch_recovery_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Create and initiate a recovery process for the test
let friends = vec![2, 3, 4];
let threshold = 3;
Expand All @@ -370,7 +370,7 @@ fn vouch_recovery_works() {

#[test]
fn claim_recovery_handles_basic_errors() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Cannot claim a non-recoverable account
assert_noop!(
Recovery::claim_recovery(RuntimeOrigin::signed(1), 5),
Expand Down Expand Up @@ -411,7 +411,7 @@ fn claim_recovery_handles_basic_errors() {

#[test]
fn claim_recovery_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Create, initiate, and vouch recovery process for the test
let friends = vec![2, 3, 4];
let threshold = 3;
Expand Down Expand Up @@ -450,7 +450,7 @@ fn claim_recovery_works() {

#[test]
fn close_recovery_handles_basic_errors() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Cannot close a non-active recovery
assert_noop!(
Recovery::close_recovery(RuntimeOrigin::signed(5), 1),
Expand All @@ -461,7 +461,7 @@ fn close_recovery_handles_basic_errors() {

#[test]
fn remove_recovery_works() {
new_test_ext().execute_with(|| {
ExtBuilder::default().build_and_execute(|| {
// Cannot remove an unrecoverable account
assert_noop!(
Recovery::remove_recovery(RuntimeOrigin::signed(5)),
Expand Down