Skip to content

Commit

Permalink
pallet_balances: Add try_state for checking Holds and Freezes (#…
Browse files Browse the repository at this point in the history
…4490)

Co-authored-by: command-bot <>
  • Loading branch information
bkchr committed May 17, 2024
1 parent 2c48b9d commit ca0fb0d
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
25 changes: 24 additions & 1 deletion substrate/frame/balances/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,8 +542,8 @@ pub mod pallet {

#[pallet::hooks]
impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
#[cfg(not(feature = "insecure_zero_ed"))]
fn integrity_test() {
#[cfg(not(feature = "insecure_zero_ed"))]
assert!(
!<T as Config<I>>::ExistentialDeposit::get().is_zero(),
"The existential deposit must be greater than zero!"
Expand All @@ -555,6 +555,29 @@ pub mod pallet {
T::MaxFreezes::get(), <T::RuntimeFreezeReason as VariantCount>::VARIANT_COUNT,
);
}

#[cfg(feature = "try-runtime")]
fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
Holds::<T, I>::iter_keys().try_for_each(|k| {
if Holds::<T, I>::decode_len(k).unwrap_or(0) >
T::RuntimeHoldReason::VARIANT_COUNT as usize
{
Err("Found `Hold` with too many elements")
} else {
Ok(())
}
})?;

Freezes::<T, I>::iter_keys().try_for_each(|k| {
if Freezes::<T, I>::decode_len(k).unwrap_or(0) > T::MaxFreezes::get() as usize {
Err("Found `Freeze` with too many elements")
} else {
Ok(())
}
})?;

Ok(())
}
}

#[pallet::call(weight(<T as Config<I>>::WeightInfo))]
Expand Down
32 changes: 32 additions & 0 deletions substrate/frame/balances/src/tests/general_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,35 @@ fn regression_historic_acc_does_not_evaporate_reserve() {
});
});
}

#[cfg(feature = "try-runtime")]
#[test]
fn try_state_works() {
use crate::{Config, Freezes, Holds};
use frame_support::{
storage,
traits::{Get, Hooks, VariantCount},
};

ExtBuilder::default().build_and_execute_with(|| {
storage::unhashed::put(
&Holds::<Test>::hashed_key_for(1),
&vec![0u8; <Test as Config>::RuntimeHoldReason::VARIANT_COUNT as usize + 1],
);

assert!(format!("{:?}", Balances::try_state(0).unwrap_err())
.contains("Found `Hold` with too many elements"));
});

ExtBuilder::default().build_and_execute_with(|| {
let max_freezes: u32 = <Test as Config>::MaxFreezes::get();

storage::unhashed::put(
&Freezes::<Test>::hashed_key_for(1),
&vec![0u8; max_freezes as usize + 1],
);

assert!(format!("{:?}", Balances::try_state(0).unwrap_err())
.contains("Found `Freeze` with too many elements"));
});
}

0 comments on commit ca0fb0d

Please sign in to comment.