From 0f4ce7d23332b515ce89382ad9b7c192838ab11f Mon Sep 17 00:00:00 2001 From: georgepisaltu Date: Mon, 2 Nov 2026 16:13:32 +0200 Subject: [PATCH 1/2] Allow for changes in sss allowances Signed-off-by: georgepisaltu --- pallets/resources/src/benchmarking.rs | 97 ++- pallets/resources/src/lib.rs | 52 +- pallets/resources/src/migration.rs | 284 +++++++ pallets/resources/src/mock.rs | 20 +- pallets/resources/src/tests.rs | 704 +++++++++++++++++- pallets/resources/src/types.rs | 5 + pallets/resources/src/weights.rs | 50 ++ .../src/integration_tests/parameters.rs | 6 +- runtimes/next-people-paseo/src/lib.rs | 2 + runtimes/next-people-paseo/src/parameters.rs | 24 +- .../src/weights/indiv_pallet_resources.rs | 26 + support/src/lib.rs | 1 + support/src/parameters.rs | 39 +- support/src/statement_allowance.rs | 58 ++ 14 files changed, 1300 insertions(+), 68 deletions(-) create mode 100644 pallets/resources/src/migration.rs create mode 100644 support/src/statement_allowance.rs diff --git a/pallets/resources/src/benchmarking.rs b/pallets/resources/src/benchmarking.rs index 68982a81..83b8d608 100644 --- a/pallets/resources/src/benchmarking.rs +++ b/pallets/resources/src/benchmarking.rs @@ -19,15 +19,20 @@ #![allow(unused)] use super::*; -use crate::Pallet as Resources; +use crate::{ + migration::{self, v1::RecordGrantedAllowances}, + Pallet as Resources, +}; use codec::{Decode, Encode}; use core::time::Duration; use frame_benchmarking::v2::{benchmarks, *}; use frame_support::{ assert_ok, dispatch::{DispatchInfo, PostDispatchInfo}, + migrations::SteppedMigration, pallet_prelude::Authorize, - traits::{EnsureOrigin, IsSubType}, + traits::{EnsureOrigin, IsSubType, StorageVersion}, + weights::WeightMeter, BoundedVec, }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; @@ -764,6 +769,7 @@ mod benches { account_id: old_target.clone(), seq: old_seq, since: initial_since, + allowance: T::AccountsApiAllowance::get().into(), }, ); StmtStoreAllowanceByAccount::::insert(&old_target, (period_key, old_seq, alias), ()); @@ -844,7 +850,12 @@ mod benches { StatementStoreAllowances::::insert( past_period_key, alias, - crate::types::StmtStoreAllowanceEntry { account_id: acc.clone(), seq: 0, since: 0 }, + crate::types::StmtStoreAllowanceEntry { + account_id: acc.clone(), + seq: 0, + since: 0, + allowance: T::AccountsApiAllowance::get().into(), + }, ); StmtStoreAllowanceByAccount::::insert(&acc, (past_period_key, 0u32, alias), ()); @@ -916,6 +927,7 @@ mod benches { account_id: existing_target, seq: 1, since: initial_since, + allowance: T::AccountsApiAllowance::get().into(), }, ); // Advance past the replacement cooldown so validation succeeds. @@ -1118,5 +1130,84 @@ mod benches { Ok(()) } + #[benchmark] + fn migrate_stmt_store_allowance_step() { + let account: T::AccountId = whitelisted_caller(); + for i in 0..2u8 { + migration::v1::v0::StatementStoreAllowances::::insert( + indiv_support::utils::BigEndianU32::from(i as u32), + [30u8 + i; 32], + migration::v1::v0::StmtStoreAllowanceEntry { + account_id: account.clone(), + seq: 0, + since: 0, + }, + ); + } + StorageVersion::new(0).put::>(); + let mut keys = migration::v1::v0::StatementStoreAllowances::::iter_keys(); + let first = keys.next().expect("two entries are seeded"); + let second = keys.next().expect("two entries are seeded"); + let mut meter = + WeightMeter::with_limit(::WeightInfo::migrate_stmt_store_allowance_step()); + let start = Some(migration::v1::Cursor::StmtStore(Some(first))); + let cursor; + + #[block] + { + cursor = RecordGrantedAllowances::::step(start, &mut meter).unwrap(); + } + + assert_eq!(cursor, Some(migration::v1::Cursor::StmtStore(Some(second)))); + assert_eq!( + StatementStoreAllowances::::get(second.0, second.1), + Some(crate::types::StmtStoreAllowanceEntry { + account_id: account, + seq: 0, + since: 0, + allowance: T::AccountsApiAllowance::get().into(), + }) + ); + } + + #[benchmark] + fn migrate_notification_registration_step() { + let account: T::AccountId = whitelisted_caller(); + let reference = crate::types::NotificationReference { period: 1, seq: 0 }; + for i in 0..2u8 { + migration::v1::v0::NotificationRegistrationByAlias::::insert( + [32u8 + i; 32], + migration::v1::v0::NotificationRegistration { + account_id: account.clone(), + reference, + }, + ); + } + StorageVersion::new(0).put::>(); + let mut keys = migration::v1::v0::NotificationRegistrationByAlias::::iter_keys(); + let first = keys.next().expect("two registrations are seeded"); + let second = keys.next().expect("two registrations are seeded"); + let mut meter = WeightMeter::with_limit( + ::WeightInfo::migrate_notification_registration_step(), + ); + let start = Some(migration::v1::Cursor::Notification(Some(first))); + let cursor; + + #[block] + { + cursor = RecordGrantedAllowances::::step(start, &mut meter).unwrap(); + } + + assert_eq!(cursor, Some(migration::v1::Cursor::Notification(Some(second)))); + assert_eq!( + NotificationRegistrationByAlias::::get(second), + Some(crate::types::NotificationRegistration { + account_id: account, + reference, + allowance: T::NotificationAllowance::get().into(), + }) + ); + } + impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::Test); } diff --git a/pallets/resources/src/lib.rs b/pallets/resources/src/lib.rs index ef1731e5..1a4ffe87 100644 --- a/pallets/resources/src/lib.rs +++ b/pallets/resources/src/lib.rs @@ -41,6 +41,7 @@ use alloc::vec::Vec; #[cfg(feature = "runtime-benchmarks")] pub mod benchmarking; pub mod extension; +pub mod migration; pub mod types; pub mod weights; @@ -54,6 +55,7 @@ pub use weights::WeightInfo; use frame_support::{ dispatch::DispatchResultWithPostInfo, + migrations::MultiStepMigrator, traits::{DefensiveOption, EnsureOriginWithArg, IsSubType, OriginTrait, UnixTime}, }; use frame_system::offchain::{CreateAuthorizedTransaction, SubmitTransaction}; @@ -90,7 +92,10 @@ pub mod pallet { /// The prefix of the message a lite consumer account signs in [`Call::register_person`]. pub const REGISTER_PERSON_MSG_PREFIX: &[u8] = b"pop:resources:register_person"; + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + #[pallet::pallet] + #[pallet::storage_version(STORAGE_VERSION)] pub struct Pallet(_); #[pallet::config] @@ -152,8 +157,7 @@ pub mod pallet { /// The Statement Store allowance for the accounts API. /// - /// Changing this value requires a migration that updates the existing state. - #[pallet::constant] + /// This parameter can be changed at any time. type AccountsApiAllowance: Get; /// Maximum number of statement store slots a person can claim within one period. @@ -190,8 +194,7 @@ pub mod pallet { /// The Statement Store allowance for notification statement registration. /// - /// Changing this value requires a migration that updates the existing state. - #[pallet::constant] + /// This parameter can be changed at any time. type NotificationAllowance: Get; /// Highest valid notification slot identifier for a person within one period. @@ -526,6 +529,11 @@ pub mod pallet { if !(block_number % T::OffchainWorkerInterval::get()).is_zero() { return; } + // Blocks hold only inherents while a multi-block migration runs. Entries that the + // migration has not reached yet do not decode. + if ::MultiBlockMigrator::ongoing() { + return; + } for registration in NotificationRegistrationByAlias::::iter_values() { if !Self::should_clear_notification_registration(®istration) { @@ -904,10 +912,15 @@ pub mod pallet { Self::validate_notification_registration(alias, &account_id)?; - increase_allowance_by(account_id.clone().into(), T::NotificationAllowance::get()); + let allowance = T::NotificationAllowance::get(); + increase_allowance_by(account_id.clone().into(), allowance.clone()); NotificationRegistrationByAlias::::insert( alias, - types::NotificationRegistration { account_id: account_id.clone(), reference }, + types::NotificationRegistration { + account_id: account_id.clone(), + reference, + allowance: allowance.into(), + }, ); NotificationAliasByAccount::::insert(&account_id, alias); @@ -943,9 +956,15 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { ensure_authorized(origin)?; let alias = Self::notification_alias_for_account(&account)?; - NotificationRegistrationByAlias::::remove(alias); + let Some(registration) = NotificationRegistrationByAlias::::take(alias) else { + log::error!( + target: LOG_TARGET, + "notification storage corruption: missing registration for alias {alias:?} mapped from account {account:?}", + ); + return Err(Error::::InvalidNotificationSequence.into()); + }; NotificationAliasByAccount::::remove(&account); - decrease_allowance_by(account.clone().into(), T::NotificationAllowance::get()); + decrease_allowance_by(account.clone().into(), registration.allowance.into()); Self::deposit_event(Event::NotificationStmtUsageRemoved { account }); Ok(Pays::No.into()) @@ -986,7 +1005,7 @@ pub mod pallet { // Revoke the old allowance and clear the reverse lookup. decrease_allowance_by( existing.account_id.clone().into(), - T::AccountsApiAllowance::get(), + existing.allowance.into(), ); StmtStoreAllowanceByAccount::::remove( &existing.account_id, @@ -995,11 +1014,17 @@ pub mod pallet { } // Grant the statement store allowance to the target account. - increase_allowance_by(target_account.clone().into(), T::AccountsApiAllowance::get()); + let allowance = T::AccountsApiAllowance::get(); + increase_allowance_by(target_account.clone().into(), allowance.clone()); StatementStoreAllowances::::insert( period_key, alias, - StmtStoreAllowanceEntry { account_id: target_account.clone(), seq, since: now }, + StmtStoreAllowanceEntry { + account_id: target_account.clone(), + seq, + since: now, + allowance: allowance.into(), + }, ); StmtStoreAllowanceByAccount::::insert(&target_account, (period_key, seq, alias), ()); Self::deposit_event(Event::StmtStoreAllowanceSet { @@ -1036,10 +1061,7 @@ pub mod pallet { for (alias, entry) in StatementStoreAllowances::::drain_prefix(period_key).take(limit as usize) { - decrease_allowance_by( - entry.account_id.clone().into(), - T::AccountsApiAllowance::get(), - ); + decrease_allowance_by(entry.account_id.clone().into(), entry.allowance.into()); StmtStoreAllowanceByAccount::::remove( entry.account_id, (period_key, entry.seq, alias), diff --git a/pallets/resources/src/migration.rs b/pallets/resources/src/migration.rs new file mode 100644 index 00000000..ef232ff8 --- /dev/null +++ b/pallets/resources/src/migration.rs @@ -0,0 +1,284 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Individuality. +// 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. + +//! Storage migrations for the resources pallet. +//! +//! `try-runtime on-runtime-upgrade` reports a storage version mismatch and undecodable entries +//! for the upgrade that carries a multi-block migration. Both are expected: the pallet checks run +//! after the single-block migrations and before the multi-block migrations. + +use crate::{ + types::{NotificationReference, NotificationRegistration, StmtStoreAllowanceEntry}, + weights::WeightInfo, + Config, NotificationRegistrationByAlias, Pallet, StatementStoreAllowances, +}; +use frame_support::{ + migrations::{MigrationId, SteppedMigration, SteppedMigrationError}, + pallet_prelude::*, + storage_alias, + weights::WeightMeter, +}; +use indiv_support::{traits::Alias, utils::BigEndianU32}; + +#[cfg(feature = "try-runtime")] +use codec::DecodeAll; + +const LOG_TARGET: &str = "runtime::indiv-pallet-resources::migration"; + +pub mod v1 { + use super::*; + + /// The storage as version 0 sees it. + pub mod v0 { + use super::*; + + /// A statement store allowance entry without its granted allowance. + #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen)] + pub struct StmtStoreAllowanceEntry { + pub account_id: AccountId, + pub seq: u32, + pub since: u64, + } + + /// A notification registration without its granted allowance. + #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen)] + pub struct NotificationRegistration { + pub account_id: AccountId, + pub reference: NotificationReference, + } + + #[storage_alias] + pub type StatementStoreAllowances = StorageDoubleMap< + Pallet, + Identity, + BigEndianU32, + Blake2_128Concat, + Alias, + StmtStoreAllowanceEntry<::AccountId>, + >; + + #[storage_alias] + pub type NotificationRegistrationByAlias = StorageMap< + Pallet, + Blake2_128Concat, + Alias, + NotificationRegistration<::AccountId>, + >; + } + + /// The progress of [`RecordGrantedAllowances`]. + #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug, TypeInfo, MaxEncodedLen)] + pub enum Cursor { + /// The last migrated statement store key. + StmtStore(Option<(BigEndianU32, Alias)>), + /// The last migrated notification alias. + Notification(Option), + } + + impl Cursor { + /// The weight of one step at this cursor. + fn step_weight(&self) -> Weight { + match self { + Cursor::StmtStore(_) => T::WeightInfo::migrate_stmt_store_allowance_step(), + Cursor::Notification(_) => T::WeightInfo::migrate_notification_registration_step(), + } + } + } + + /// Records the granted allowance in every statement store allowance entry and notification + /// registration over several blocks. + /// + /// An entry gets the current `AccountsApiAllowance` and a registration gets the current + /// `NotificationAllowance`. This is correct only if the values have not changed since the + /// entry was written. + pub struct RecordGrantedAllowances(PhantomData); + + impl SteppedMigration for RecordGrantedAllowances { + type Cursor = Cursor; + type Identifier = MigrationId<22>; + + fn id() -> Self::Identifier { + MigrationId { pallet_id: *b"indiv-pallet-resources", version_from: 0, version_to: 1 } + } + + fn step( + cursor: Option, + meter: &mut WeightMeter, + ) -> Result, SteppedMigrationError> { + if Pallet::::on_chain_storage_version() != 0 { + return Ok(None); + } + let mut cursor = cursor.unwrap_or(Cursor::StmtStore(None)); + let required = cursor.step_weight::(); + if meter.remaining().any_lt(required) { + return Err(SteppedMigrationError::InsufficientWeight { required }); + } + loop { + if meter.try_consume(cursor.step_weight::()).is_err() { + return Ok(Some(cursor)); + } + cursor = match cursor { + Cursor::StmtStore(last) => match Self::migrate_stmt_store_entry(last) { + Some(key) => Cursor::StmtStore(Some(key)), + None => { + log::info!( + target: LOG_TARGET, + "recorded the allowance of all statement store entries" + ); + Cursor::Notification(None) + }, + }, + Cursor::Notification(last) => match Self::migrate_notification(last) { + Some(alias) => Cursor::Notification(Some(alias)), + None => { + log::info!( + target: LOG_TARGET, + "recorded the allowance of all notification registrations" + ); + StorageVersion::new(1).put::>(); + return Ok(None); + }, + }, + }; + } + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + if Pallet::::on_chain_storage_version() != 0 { + return Ok(None::>.encode()); + } + let state = PreUpgradeState:: { + entries: v0::StatementStoreAllowances::::iter().collect(), + registrations: v0::NotificationRegistrationByAlias::::iter().collect(), + }; + Ok(Some(state).encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: alloc::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { + let state = Option::>::decode_all(&mut &state[..]) + .map_err(|_| "the pre-upgrade state must decode")?; + let Some(state) = state else { + log::info!(target: LOG_TARGET, "the storage version was not 0; nothing to check"); + return Ok(()); + }; + + ensure!( + StatementStoreAllowances::::iter_keys().count() == state.entries.len(), + "the migration must keep every statement store allowance entry" + ); + for (period, alias, entry) in state.entries { + let migrated = StatementStoreAllowances::::get(period, alias) + .ok_or("a statement store allowance entry must decode with its allowance")?; + ensure!( + migrated == + StmtStoreAllowanceEntry { + account_id: entry.account_id, + seq: entry.seq, + since: entry.since, + allowance: T::AccountsApiAllowance::get().into(), + }, + "a statement store allowance entry must keep its fields and record the \ + accounts API allowance" + ); + } + + ensure!( + NotificationRegistrationByAlias::::iter_keys().count() == + state.registrations.len(), + "the migration must keep every notification registration" + ); + for (alias, registration) in state.registrations { + let migrated = NotificationRegistrationByAlias::::get(alias) + .ok_or("a notification registration must decode with its allowance")?; + ensure!( + migrated == + NotificationRegistration { + account_id: registration.account_id, + reference: registration.reference, + allowance: T::NotificationAllowance::get().into(), + }, + "a notification registration must keep its fields and record the \ + notification allowance" + ); + } + + ensure!( + Pallet::::on_chain_storage_version() == 1, + "the storage version must be 1 after the migration" + ); + Ok(()) + } + } + + /// The version 0 state that [`RecordGrantedAllowances::pre_upgrade`] hands to + /// [`RecordGrantedAllowances::post_upgrade`]. Absent when the migration has nothing to do. + #[cfg(feature = "try-runtime")] + #[derive(Encode, Decode)] + struct PreUpgradeState { + entries: alloc::vec::Vec<(BigEndianU32, Alias, v0::StmtStoreAllowanceEntry)>, + registrations: alloc::vec::Vec<(Alias, v0::NotificationRegistration)>, + } + + impl RecordGrantedAllowances { + /// Migrates the statement store entry after `last`, or returns `None` when no entry is + /// left. + fn migrate_stmt_store_entry( + last: Option<(BigEndianU32, Alias)>, + ) -> Option<(BigEndianU32, Alias)> { + let mut iter = match last { + Some((period, alias)) => v0::StatementStoreAllowances::::iter_from( + v0::StatementStoreAllowances::::hashed_key_for(period, alias), + ), + None => v0::StatementStoreAllowances::::iter(), + }; + let (period, alias, entry) = iter.next()?; + StatementStoreAllowances::::insert( + period, + alias, + StmtStoreAllowanceEntry { + account_id: entry.account_id, + seq: entry.seq, + since: entry.since, + allowance: T::AccountsApiAllowance::get().into(), + }, + ); + Some((period, alias)) + } + + /// Migrates the notification registration after `last`, or returns `None` when no + /// registration is left. + fn migrate_notification(last: Option) -> Option { + let mut iter = match last { + Some(alias) => v0::NotificationRegistrationByAlias::::iter_from( + v0::NotificationRegistrationByAlias::::hashed_key_for(alias), + ), + None => v0::NotificationRegistrationByAlias::::iter(), + }; + let (alias, registration) = iter.next()?; + NotificationRegistrationByAlias::::insert( + alias, + NotificationRegistration { + account_id: registration.account_id, + reference: registration.reference, + allowance: T::NotificationAllowance::get().into(), + }, + ); + Some(alias) + } + } +} diff --git a/pallets/resources/src/mock.rs b/pallets/resources/src/mock.rs index 1184474f..16e01ac1 100644 --- a/pallets/resources/src/mock.rs +++ b/pallets/resources/src/mock.rs @@ -259,9 +259,25 @@ frame_support::construct_runtime!( } ); +parameter_types! { + pub storage MigrationOngoing: bool = false; +} + +/// A multi-block migrator that only reports what [`MigrationOngoing`] says. +pub struct MockMigrator; +impl frame_support::migrations::MultiStepMigrator for MockMigrator { + fn ongoing() -> bool { + MigrationOngoing::get() + } + fn step() -> frame_support::weights::Weight { + frame_support::weights::Weight::zero() + } +} + #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; + type MultiBlockMigrator = MockMigrator; type BlockWeights = (); type BlockLength = (); type DbWeight = (); @@ -479,11 +495,11 @@ parameter_types! { max_size: 16 * 1024, // 16 KiB max_count: 50, }; - pub AccountsApiAllowance: sp_statement_store::StatementAllowance = sp_statement_store::StatementAllowance { + pub storage AccountsApiAllowance: sp_statement_store::StatementAllowance = sp_statement_store::StatementAllowance { max_size: 1024, max_count: 2, }; - pub NotificationAllowance: sp_statement_store::StatementAllowance = sp_statement_store::StatementAllowance { + pub storage NotificationAllowance: sp_statement_store::StatementAllowance = sp_statement_store::StatementAllowance { max_size: 512, max_count: 1, }; diff --git a/pallets/resources/src/tests.rs b/pallets/resources/src/tests.rs index c488068e..d8d78c1a 100644 --- a/pallets/resources/src/tests.rs +++ b/pallets/resources/src/tests.rs @@ -25,7 +25,7 @@ use crate::{ use codec::Encode; use frame_support::{ assert_noop, assert_ok, - dispatch::GetDispatchInfo, + dispatch::{GetDispatchInfo, Pays}, traits::{Authorize, Hooks}, }; use frame_system::RawOrigin as SystemOrigin; @@ -39,7 +39,7 @@ use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionSource}, AccountId32, }; -use sp_statement_store::{get_allowance, StatementAllowance}; +use sp_statement_store::{get_allowance, increase_allowance_by, StatementAllowance}; // --- Test Helpers --- @@ -2714,6 +2714,97 @@ mod notification { ); }); } + + #[test] + fn cleanup_revokes_the_recorded_allowance_after_an_allowance_change() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let period = Resources::notification_period_from_timestamp(TestClock::now().as_secs()); + let reference = NotificationReference { period, seq: 0 }; + let account = id_to_account(330); + let base = StatementAllowance { max_size: 10_000, max_count: 100 }; + increase_allowance_by(&account, base.clone()); + let granted = ::NotificationAllowance::get(); + + assert_ok!(Resources::set_notification_statement_account_for_sequence( + notification_origin(33), + reference, + account.clone(), + )); + assert_eq!(get_allowance(&account), base.clone().saturating_add(granted.clone())); + let registration = NotificationRegistrationByAlias::::get(id_to_alias(33)) + .expect("registration should exist"); + assert_eq!(StatementAllowance::from(registration.allowance), granted); + + let raised = + granted.saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + NotificationAllowance::set(&raised); + + set_time_sec(Resources::notification_expiration_time(period).saturating_add(1)); + assert_ok!(Resources::clear_expired_notification_sequence( + SystemOrigin::Authorized.into(), + account.clone(), + reference.seq, + )); + + assert_eq!(get_allowance(&account), base); + }); + } + + #[test] + fn cleanup_rejects_an_account_whose_registration_is_missing() { + new_test_ext().execute_with(|| { + let account = id_to_account(340); + NotificationAliasByAccount::::insert(&account, id_to_alias(34)); + + let refused = Resources::clear_expired_notification_sequence( + SystemOrigin::Authorized.into(), + account.clone(), + 0, + ) + .expect_err("the cleanup is refused"); + + assert_eq!(refused.error, Error::::InvalidNotificationSequence.into()); + assert_eq!(refused.post_info.pays_fee, Pays::Yes); + assert_eq!(NotificationAliasByAccount::::get(&account), Some(id_to_alias(34))); + }); + } + + #[test] + fn cleanup_keeps_the_other_grants_of_the_account() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let now = TestClock::now().as_secs(); + let account = id_to_account(350); + let slot_period = Resources::stmt_store_period_from_timestamp(now); + let slot_grant = ::AccountsApiAllowance::get(); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(35), + slot_period, + 0, + account.clone(), + )); + let period = Resources::notification_period_from_timestamp(now); + let reference = NotificationReference { period, seq: 0 }; + assert_ok!(Resources::set_notification_statement_account_for_sequence( + notification_origin(35), + reference, + account.clone(), + )); + let raised = ::NotificationAllowance::get() + .saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + NotificationAllowance::set(&raised); + + set_time_sec(Resources::notification_expiration_time(period).saturating_add(1)); + assert_ok!(Resources::clear_expired_notification_sequence( + SystemOrigin::Authorized.into(), + account.clone(), + reference.seq, + )); + + assert_eq!(get_allowance(&account), slot_grant); + }); + } } mod long_term_storage { @@ -3734,6 +3825,7 @@ mod stmt_store_allowance { account_id: target.clone(), seq: 0, since: TestClock::now().as_secs(), + allowance: accounts_allowance.clone().into(), }), ); assert_eq!(get_allowance(&target), accounts_allowance); @@ -3754,6 +3846,222 @@ mod stmt_store_allowance { }); } + #[test] + fn offchain_worker_waits_for_an_ongoing_migration() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let now = TestClock::now().as_secs(); + let period = Resources::stmt_store_period_from_timestamp(now); + let target = id_to_account(730); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(73), + period, + 0, + target.clone(), + )); + let notification_period = Resources::notification_period_from_timestamp(now); + let reference = NotificationReference { period: notification_period, seq: 0 }; + assert_ok!(Resources::set_notification_statement_account_for_sequence( + notification_origin(73), + reference, + target.clone(), + )); + let grace_secs: u64 = + <::StmtStoreGraceWindow as Get>::get() as u64; + let slot_expiry = (period as u64 + 1) * SECONDS_PER_DAY + grace_secs; + let notification_expiry = Resources::notification_expiration_time(notification_period); + set_time_sec(slot_expiry.max(notification_expiry) + 1); + + // Both entries are now clearable. + MigrationOngoing::set(&true); + advance_to_block(2); + assert!(StatementStoreAllowances::::contains_key( + BigEndianU32::from(period), + id_to_alias(73) + )); + assert!(NotificationRegistrationByAlias::::contains_key(id_to_alias(73))); + + MigrationOngoing::set(&false); + advance_to_block(3); + assert!(!StatementStoreAllowances::::contains_key( + BigEndianU32::from(period), + id_to_alias(73) + )); + assert!(!NotificationRegistrationByAlias::::contains_key(id_to_alias(73))); + }); + } + + #[test] + fn cleanup_revokes_the_recorded_allowance_after_an_allowance_change() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let period = Resources::stmt_store_period_from_timestamp(TestClock::now().as_secs()); + let target = id_to_account(710); + let base = StatementAllowance { max_size: 10_000, max_count: 100 }; + increase_allowance_by(&target, base.clone()); + let granted = ::AccountsApiAllowance::get(); + + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(71), + period, + 0, + target.clone(), + )); + assert_eq!(get_allowance(&target), base.clone().saturating_add(granted.clone())); + let entry = + StatementStoreAllowances::::get(BigEndianU32::from(period), id_to_alias(71)) + .expect("allowance entry should exist"); + assert_eq!(StatementAllowance::from(entry.allowance), granted); + + let raised = + granted.saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + AccountsApiAllowance::set(&raised); + + let grace_secs: u64 = + <::StmtStoreGraceWindow as Get>::get() as u64; + set_time_sec((period as u64 + 1) * SECONDS_PER_DAY + grace_secs + 1); + assert_ok!(Resources::clear_expired_stmt_store_allowances( + SystemOrigin::Authorized.into(), + period, + id_to_alias(71), + )); + + assert_eq!(get_allowance(&target), base); + }); + } + + #[test] + fn replacement_revokes_the_recorded_allowance_after_an_allowance_change() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let period = Resources::stmt_store_period_from_timestamp(TestClock::now().as_secs()); + let old_target = id_to_account(720); + let new_target = id_to_account(721); + let base = StatementAllowance { max_size: 10_000, max_count: 100 }; + increase_allowance_by(&old_target, base.clone()); + let granted = ::AccountsApiAllowance::get(); + + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(72), + period, + 0, + old_target.clone(), + )); + assert_eq!(get_allowance(&old_target), base.clone().saturating_add(granted.clone())); + + let raised = + granted.saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + AccountsApiAllowance::set(&raised); + + let cooldown: u64 = + <::StmtStoreReplacementCooldown as Get>::get() as u64; + advance_time_sec(cooldown + 1); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(72), + period, + 1, + new_target.clone(), + )); + + assert_eq!(get_allowance(&old_target), base); + assert_eq!(get_allowance(&new_target), raised); + let entry = + StatementStoreAllowances::::get(BigEndianU32::from(period), id_to_alias(72)) + .expect("allowance entry should exist"); + assert_eq!(entry.account_id, new_target); + assert_eq!(StatementAllowance::from(entry.allowance), raised); + }); + } + + #[test] + fn cleanup_revokes_each_entry_at_its_recorded_allowance() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let period = Resources::stmt_store_period_from_timestamp(TestClock::now().as_secs()); + let target = id_to_account(740); + let base = StatementAllowance { max_size: 10_000, max_count: 100 }; + increase_allowance_by(&target, base.clone()); + let granted = ::AccountsApiAllowance::get(); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(74), + period, + 0, + target.clone(), + )); + + let raised = granted + .clone() + .saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + AccountsApiAllowance::set(&raised); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(75), + period, + 1, + target.clone(), + )); + assert_eq!( + get_allowance(&target), + base.clone().saturating_add(granted).saturating_add(raised) + ); + + let grace_secs: u64 = + <::StmtStoreGraceWindow as Get>::get() as u64; + set_time_sec((period as u64 + 1) * SECONDS_PER_DAY + grace_secs + 1); + assert_ok!(Resources::clear_expired_stmt_store_allowances( + SystemOrigin::Authorized.into(), + period, + id_to_alias(74), + )); + + assert_eq!( + StatementStoreAllowances::::iter_prefix(BigEndianU32::from(period)).count(), + 0 + ); + assert_eq!(get_allowance(&target), base); + }); + } + + #[test] + fn replacement_with_the_same_target_records_the_current_allowance() { + new_test_ext().execute_with(|| { + set_time_sec(SECONDS_PER_DAY + 100); + let period = Resources::stmt_store_period_from_timestamp(TestClock::now().as_secs()); + let target = id_to_account(760); + let base = StatementAllowance { max_size: 10_000, max_count: 100 }; + increase_allowance_by(&target, base.clone()); + let granted = ::AccountsApiAllowance::get(); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(76), + period, + 0, + target.clone(), + )); + + let raised = + granted.saturating_add(StatementAllowance { max_size: 4096, max_count: 3 }); + AccountsApiAllowance::set(&raised); + let cooldown: u64 = + <::StmtStoreReplacementCooldown as Get>::get() as u64; + advance_time_sec(cooldown + 1); + assert_ok!(Resources::set_statement_store_account( + stmt_store_slot_origin(76), + period, + 1, + target.clone(), + )); + + assert_eq!(get_allowance(&target), base.saturating_add(raised.clone())); + let entry = + StatementStoreAllowances::::get(BigEndianU32::from(period), id_to_alias(76)) + .expect("allowance entry should exist"); + assert_eq!(StatementAllowance::from(entry.allowance), raised); + assert_eq!( + StmtStoreAllowanceByAccount::::iter_prefix(&target).collect::>(), + vec![((BigEndianU32::from(period), 1, id_to_alias(76)), ())] + ); + }); + } + #[test] fn statement_store_context_uses_allocated_people_raw_suffix() { new_test_ext().execute_with(|| { @@ -4488,3 +4796,395 @@ fn signing_context_constant_is_the_context_the_pallet_verifies() { [&expected[..], b"msg"].concat() ); } + +mod migration { + use super::*; + use crate::migration::v1::{v0, Cursor, RecordGrantedAllowances}; + use frame_support::{ + migrations::{SteppedMigration, SteppedMigrationError}, + traits::{GetStorageVersion, StorageVersion}, + weights::{Weight, WeightMeter}, + }; + use indiv_support::utils::BigEndianU32; + + /// The version 0 statement store entries as `(period, alias id)`. Two share a period, so the + /// migration must resume inside a period as well as across periods. + const V0_ENTRIES: [(u32, u64); 3] = [(1, 1), (1, 3), (2, 2)]; + + fn set_up_v0() { + seed_v0_entries(); + seed_v0_registrations(); + StorageVersion::new(0).put::(); + assert_eq!(migrated_entries(), 0); + assert_eq!(migrated_registrations(), 0); + } + + fn seed_v0_entries() { + for (period, i) in V0_ENTRIES { + v0::StatementStoreAllowances::::insert( + BigEndianU32::from(period), + id_to_alias(i), + v0::StmtStoreAllowanceEntry { + account_id: id_to_account(100 + i), + seq: i as u32, + since: 10 * i, + }, + ); + } + } + + fn seed_v0_registrations() { + for i in 1..=2u64 { + v0::NotificationRegistrationByAlias::::insert( + id_to_alias(10 + i), + v0::NotificationRegistration { + account_id: id_to_account(200 + i), + reference: NotificationReference { period: i as u32, seq: i as u8 }, + }, + ); + } + } + + /// The statement store entries that decode in the current layout. + fn migrated_entries() -> usize { + StatementStoreAllowances::::iter().count() + } + + /// The notification registrations that decode in the current layout. + fn migrated_registrations() -> usize { + NotificationRegistrationByAlias::::iter().count() + } + + fn stmt_step_weight() -> Weight { + <() as WeightInfo>::migrate_stmt_store_allowance_step() + } + + fn notification_step_weight() -> Weight { + <() as WeightInfo>::migrate_notification_registration_step() + } + + #[test] + fn migration_records_the_current_allowances() { + new_test_ext().execute_with(|| { + set_up_v0(); + let mut meter = WeightMeter::new(); + + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + + assert_eq!(Resources::on_chain_storage_version(), 1); + for (period, i) in V0_ENTRIES { + assert_eq!( + StatementStoreAllowances::::get( + BigEndianU32::from(period), + id_to_alias(i) + ), + Some(crate::types::StmtStoreAllowanceEntry { + account_id: id_to_account(100 + i), + seq: i as u32, + since: 10 * i, + allowance: ::AccountsApiAllowance::get().into(), + }) + ); + } + for i in 1..=2u64 { + assert_eq!( + NotificationRegistrationByAlias::::get(id_to_alias(10 + i)), + Some(crate::types::NotificationRegistration { + account_id: id_to_account(200 + i), + reference: NotificationReference { period: i as u32, seq: i as u8 }, + allowance: ::NotificationAllowance::get().into(), + }) + ); + } + }); + } + + #[test] + fn migration_step_weight_covers_one_entry_or_registration() { + new_test_ext().execute_with(|| { + set_up_v0(); + + // The two entries of period 1 come in hash order, so only their period is known. + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + let cursor = RecordGrantedAllowances::::step(None, &mut meter).unwrap(); + assert!(matches!( + cursor, + Some(Cursor::StmtStore(Some((period, _)))) if period == BigEndianU32::from(1u32) + )); + assert_eq!(migrated_entries(), 1); + + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + let cursor = RecordGrantedAllowances::::step(cursor, &mut meter).unwrap(); + assert!(matches!( + cursor, + Some(Cursor::StmtStore(Some((period, _)))) if period == BigEndianU32::from(1u32) + )); + assert_eq!(migrated_entries(), 2); + + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + let cursor = RecordGrantedAllowances::::step(cursor, &mut meter).unwrap(); + assert_eq!( + cursor, + Some(Cursor::StmtStore(Some((BigEndianU32::from(2u32), id_to_alias(2))))) + ); + assert_eq!(migrated_entries(), 3); + + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + let cursor = RecordGrantedAllowances::::step(cursor, &mut meter).unwrap(); + assert_eq!(cursor, Some(Cursor::Notification(None))); + assert_eq!(migrated_registrations(), 0); + + let mut meter = WeightMeter::with_limit(notification_step_weight()); + let cursor = RecordGrantedAllowances::::step(cursor, &mut meter).unwrap(); + assert!(matches!(cursor, Some(Cursor::Notification(Some(_))))); + assert_eq!(migrated_registrations(), 1); + + let mut meter = WeightMeter::with_limit(notification_step_weight()); + let cursor = RecordGrantedAllowances::::step(cursor, &mut meter).unwrap(); + assert!(matches!(cursor, Some(Cursor::Notification(Some(_))))); + assert_eq!(migrated_registrations(), 2); + assert_eq!(Resources::on_chain_storage_version(), 0); + + let mut meter = WeightMeter::with_limit(notification_step_weight()); + assert_eq!(RecordGrantedAllowances::::step(cursor, &mut meter), Ok(None)); + assert_eq!(Resources::on_chain_storage_version(), 1); + }); + } + + #[test] + fn migration_step_requires_the_weight_of_one_entry_or_registration() { + new_test_ext().execute_with(|| { + set_up_v0(); + + let required = stmt_step_weight(); + let mut meter = + WeightMeter::with_limit(required.saturating_sub(Weight::from_parts(1, 0))); + assert_eq!( + RecordGrantedAllowances::::step(None, &mut meter), + Err(SteppedMigrationError::InsufficientWeight { required }) + ); + + let required = notification_step_weight(); + let mut meter = + WeightMeter::with_limit(required.saturating_sub(Weight::from_parts(1, 0))); + assert_eq!( + RecordGrantedAllowances::::step(Some(Cursor::Notification(None)), &mut meter), + Err(SteppedMigrationError::InsufficientWeight { required }) + ); + assert_eq!(migrated_entries(), 0); + assert_eq!(migrated_registrations(), 0); + }); + } + + #[test] + fn migration_completes_on_empty_maps() { + new_test_ext().execute_with(|| { + StorageVersion::new(0).put::(); + + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + let cursor = RecordGrantedAllowances::::step(None, &mut meter).unwrap(); + assert_eq!(cursor, Some(Cursor::Notification(None))); + assert_eq!(Resources::on_chain_storage_version(), 0); + + let mut meter = WeightMeter::with_limit(notification_step_weight()); + assert_eq!(RecordGrantedAllowances::::step(cursor, &mut meter), Ok(None)); + assert_eq!(Resources::on_chain_storage_version(), 1); + }); + } + + #[test] + fn migration_records_registrations_without_entries() { + new_test_ext().execute_with(|| { + seed_v0_registrations(); + StorageVersion::new(0).put::(); + let mut meter = WeightMeter::new(); + + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + + assert_eq!(migrated_registrations(), 2); + assert_eq!(Resources::on_chain_storage_version(), 1); + }); + } + + #[test] + fn migration_records_entries_without_registrations() { + new_test_ext().execute_with(|| { + seed_v0_entries(); + StorageVersion::new(0).put::(); + let mut meter = WeightMeter::new(); + + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + + assert_eq!(migrated_entries(), V0_ENTRIES.len()); + assert_eq!(Resources::on_chain_storage_version(), 1); + }); + } + + #[test] + fn migration_skips_a_chain_past_version_0() { + new_test_ext().execute_with(|| { + set_up_v0(); + StorageVersion::new(1).put::(); + let mut meter = WeightMeter::with_limit(stmt_step_weight()); + + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + + assert_eq!(meter.consumed(), Weight::zero()); + assert_eq!(migrated_entries(), 0); + assert_eq!(migrated_registrations(), 0); + }); + } + + /// Sets up version 0 state, takes the pre-upgrade state and runs the migration to completion. + #[cfg(feature = "try-runtime")] + fn migrate_with_pre_upgrade_state() -> Vec { + set_up_v0(); + let state = RecordGrantedAllowances::::pre_upgrade().unwrap(); + let mut meter = WeightMeter::new(); + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + state + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_accept_a_complete_migration() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + + assert_ok!(RecordGrantedAllowances::::post_upgrade(state)); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_lost_entry() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + StatementStoreAllowances::::remove(BigEndianU32::from(1u32), id_to_alias(1)); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("the migration must keep every statement store allowance entry".into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_lost_registration() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + NotificationRegistrationByAlias::::remove(id_to_alias(11)); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("the migration must keep every notification registration".into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_an_entry_without_an_allowance() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + v0::StatementStoreAllowances::::insert( + BigEndianU32::from(1u32), + id_to_alias(1), + v0::StmtStoreAllowanceEntry { account_id: id_to_account(101), seq: 1, since: 10 }, + ); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("a statement store allowance entry must decode with its allowance".into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_registration_without_an_allowance() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + v0::NotificationRegistrationByAlias::::insert( + id_to_alias(11), + v0::NotificationRegistration { + account_id: id_to_account(201), + reference: NotificationReference { period: 1, seq: 1 }, + }, + ); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("a notification registration must decode with its allowance".into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_changed_accounts_api_allowance() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + let raised = ::AccountsApiAllowance::get() + .saturating_add(StatementAllowance { max_size: 1, max_count: 1 }); + AccountsApiAllowance::set(&raised); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("a statement store allowance entry must keep its fields and record the \ + accounts API allowance" + .into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_changed_notification_allowance() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + let raised = ::NotificationAllowance::get() + .saturating_add(StatementAllowance { max_size: 1, max_count: 1 }); + NotificationAllowance::set(&raised); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("a notification registration must keep its fields and record the \ + notification allowance" + .into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_reject_a_wrong_storage_version() { + new_test_ext().execute_with(|| { + let state = migrate_with_pre_upgrade_state(); + StorageVersion::new(0).put::(); + + assert_eq!( + RecordGrantedAllowances::::post_upgrade(state), + Err("the storage version must be 1 after the migration".into()) + ); + }); + } + + #[test] + #[cfg(feature = "try-runtime")] + fn try_runtime_checks_skip_a_migrated_chain() { + new_test_ext().execute_with(|| { + set_up_v0(); + StorageVersion::new(1).put::(); + + let state = RecordGrantedAllowances::::pre_upgrade().unwrap(); + let mut meter = WeightMeter::new(); + assert_eq!(RecordGrantedAllowances::::step(None, &mut meter), Ok(None)); + assert_ok!(RecordGrantedAllowances::::post_upgrade(state)); + + assert_eq!(migrated_entries(), 0); + assert_eq!(migrated_registrations(), 0); + }); + } +} diff --git a/pallets/resources/src/types.rs b/pallets/resources/src/types.rs index 75035275..4e3830d0 100644 --- a/pallets/resources/src/types.rs +++ b/pallets/resources/src/types.rs @@ -20,6 +20,7 @@ use super::*; use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use frame_support::{CloneNoBound, DebugNoBound, EqNoBound, PartialEqNoBound}; +use indiv_support::statement_allowance::BoundedStatementAllowance; use scale_info::TypeInfo; pub type SignatureOf = @@ -56,6 +57,8 @@ pub struct NotificationRegistration { pub account_id: Account, /// Notification slot used in the registration context. pub reference: NotificationReference, + /// The allowance granted to `account_id`. + pub allowance: BoundedStatementAllowance, } /// Value stored per anonymous statement store allowance entry. @@ -79,6 +82,8 @@ pub struct StmtStoreAllowanceEntry { /// Timestamp (seconds since Unix epoch) when this entry was last set. /// Used to enforce a cooldown before the same alias can replace it within the same period. pub since: u64, + /// The allowance granted to `account_id`. + pub allowance: BoundedStatementAllowance, } /// The information related to a particular consumer. diff --git a/pallets/resources/src/weights.rs b/pallets/resources/src/weights.rs index 5ebf730e..7a19ba40 100644 --- a/pallets/resources/src/weights.rs +++ b/pallets/resources/src/weights.rs @@ -77,6 +77,8 @@ pub trait WeightInfo { fn claim_long_term_storage_tx_ext() -> Weight; fn clear_expired_long_term_storage_aliases(n: u32, ) -> Weight; fn authorize_clear_expired_long_term_storage_aliases() -> Weight; + fn migrate_stmt_store_allowance_step() -> Weight; + fn migrate_notification_registration_step() -> Weight; } /// Weights for `indiv_pallet_resources` using the Substrate node and recommended hardware. @@ -553,6 +555,30 @@ impl WeightInfo for SubstrateWeight { Weight::from_parts(8_507_000, 3517) .saturating_add(T::DbWeight::get().reads(2_u64)) } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::StatementStoreAllowances` (r:1 w:1) + /// Proof: `Resources::StatementStoreAllowances` (`max_values`: None, `max_size`: Some(132), added: 2607, mode: `MaxEncodedLen`) + fn migrate_stmt_store_allowance_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `200` + // Estimated: `3597` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 3597) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::NotificationRegistrationByAlias` (r:1 w:1) + /// Proof: `Resources::NotificationRegistrationByAlias` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn migrate_notification_registration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `160` + // Estimated: `3558` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 3558) + .saturating_add(T::DbWeight::get().reads(2_u64)) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } } // For backwards compatibility and tests. @@ -1028,4 +1054,28 @@ impl WeightInfo for () { Weight::from_parts(8_507_000, 3517) .saturating_add(RocksDbWeight::get().reads(2_u64)) } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::StatementStoreAllowances` (r:1 w:1) + /// Proof: `Resources::StatementStoreAllowances` (`max_values`: None, `max_size`: Some(132), added: 2607, mode: `MaxEncodedLen`) + fn migrate_stmt_store_allowance_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `200` + // Estimated: `3597` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 3597) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::NotificationRegistrationByAlias` (r:1 w:1) + /// Proof: `Resources::NotificationRegistrationByAlias` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn migrate_notification_registration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `160` + // Estimated: `3558` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 3558) + .saturating_add(RocksDbWeight::get().reads(2_u64)) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } } diff --git a/runtimes/next-people-paseo/src/integration_tests/parameters.rs b/runtimes/next-people-paseo/src/integration_tests/parameters.rs index 21798318..7b768e9f 100644 --- a/runtimes/next-people-paseo/src/integration_tests/parameters.rs +++ b/runtimes/next-people-paseo/src/integration_tests/parameters.rs @@ -24,7 +24,9 @@ use crate::{ }; use frame_support::{assert_noop, assert_ok, traits::Get, PalletId}; use indiv_pallet_resources::WeightInfo as ResourcesWeightInfo; -use indiv_support::{parameters::StatementAllowanceParameter, weight_budget::OcwWeightBudget}; +use indiv_support::{ + statement_allowance::BoundedStatementAllowance, weight_budget::OcwWeightBudget, +}; use sp_keyring::Sr25519Keyring; use sp_runtime::{traits::AccountIdConversion, DispatchError}; use sp_statement_store::StatementAllowance; @@ -116,7 +118,7 @@ fn root_parameter_updates_change_what_the_resources_pallet_reads() { set_statement_parameter( statement_storage::PersonStatementLimit, - StatementAllowanceParameter { max_size: 42, max_count: 3 }, + BoundedStatementAllowance { max_size: 42, max_count: 3 }, ); assert_eq!( ::PersonStatementLimit::get(), diff --git a/runtimes/next-people-paseo/src/lib.rs b/runtimes/next-people-paseo/src/lib.rs index 956e2b16..ad1679df 100644 --- a/runtimes/next-people-paseo/src/lib.rs +++ b/runtimes/next-people-paseo/src/lib.rs @@ -807,6 +807,8 @@ impl pallet_migrations::Config for Runtime { ForeignAssetsReservesMigration, // Single use! - remove once the upgrade carrying it is live. indiv_pallet_people_lite::migration::v1::LazyMigrationV0ToV1, + // Single use! - remove once the upgrade carrying it is live. + indiv_pallet_resources::migration::v1::RecordGrantedAllowances, ); // Benchmarks need mocked migrations to guarantee that they succeed. #[cfg(feature = "runtime-benchmarks")] diff --git a/runtimes/next-people-paseo/src/parameters.rs b/runtimes/next-people-paseo/src/parameters.rs index eede9b3c..2cd2f0e5 100644 --- a/runtimes/next-people-paseo/src/parameters.rs +++ b/runtimes/next-people-paseo/src/parameters.rs @@ -11,9 +11,11 @@ use frame_support::{ PalletId, }; use indiv_pallet_resources::types::LongTermStorageAllocation; -use indiv_support::parameters::{ - AtLeast, AtLeastOne, AtMost, BenchmarkMax, SaturatingSubOne, StatementAllowanceGetter, - StatementAllowanceParameter, +use indiv_support::{ + parameters::{ + AtLeast, AtLeastOne, AtMost, BenchmarkMax, SaturatingSubOne, StatementAllowanceGetter, + }, + statement_allowance::BoundedStatementAllowance, }; use sp_runtime::traits::AccountIdConversion; @@ -38,17 +40,17 @@ pub mod dynamic_params { #[codec(index = 0)] pub mod statement_storage { #[codec(index = 0)] - pub static AccountsApiAllowance: StatementAllowanceParameter = - StatementAllowanceParameter { max_size: 500 * 1024, max_count: 2 }; + pub static AccountsApiAllowance: BoundedStatementAllowance = + BoundedStatementAllowance { max_size: 500 * 1024, max_count: 2 }; #[codec(index = 6)] - pub static NotificationAllowance: StatementAllowanceParameter = - StatementAllowanceParameter { max_size: 10 * 1024, max_count: 1 }; + pub static NotificationAllowance: BoundedStatementAllowance = + BoundedStatementAllowance { max_size: 10 * 1024, max_count: 1 }; #[codec(index = 10)] - pub static LitePersonStatementLimit: StatementAllowanceParameter = - StatementAllowanceParameter { max_size: 500 * 1024, max_count: 50 }; + pub static LitePersonStatementLimit: BoundedStatementAllowance = + BoundedStatementAllowance { max_size: 500 * 1024, max_count: 50 }; #[codec(index = 11)] - pub static PersonStatementLimit: StatementAllowanceParameter = - StatementAllowanceParameter { max_size: 1024 * 1024, max_count: 200 }; + pub static PersonStatementLimit: BoundedStatementAllowance = + BoundedStatementAllowance { max_size: 1024 * 1024, max_count: 200 }; #[codec(index = 1)] pub static StmtStoreSlotsPerPeriod: u32 = 20; #[codec(index = 2)] diff --git a/runtimes/next-people-paseo/src/weights/indiv_pallet_resources.rs b/runtimes/next-people-paseo/src/weights/indiv_pallet_resources.rs index 7bf8a1a7..75f4c782 100644 --- a/runtimes/next-people-paseo/src/weights/indiv_pallet_resources.rs +++ b/runtimes/next-people-paseo/src/weights/indiv_pallet_resources.rs @@ -561,4 +561,30 @@ impl indiv_pallet_resources::WeightInfo for WeightInfo< .saturating_add(Weight::from_parts(0, 3517)) .saturating_add(T::DbWeight::get().reads(2)) } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::StatementStoreAllowances` (r:1 w:1) + /// Proof: `Resources::StatementStoreAllowances` (`max_values`: None, `max_size`: Some(132), added: 2607, mode: `MaxEncodedLen`) + fn migrate_stmt_store_allowance_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `200` + // Estimated: `3597` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 0) + .saturating_add(Weight::from_parts(0, 3597)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Resources::PalletVersion` (r:1 w:0) + /// Storage: `Resources::NotificationRegistrationByAlias` (r:1 w:1) + /// Proof: `Resources::NotificationRegistrationByAlias` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `MaxEncodedLen`) + fn migrate_notification_registration_step() -> Weight { + // Proof Size summary in bytes: + // Measured: `160` + // Estimated: `3558` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(20_000_000, 0) + .saturating_add(Weight::from_parts(0, 3558)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } } diff --git a/support/src/lib.rs b/support/src/lib.rs index 48d05d7d..3f35db68 100644 --- a/support/src/lib.rs +++ b/support/src/lib.rs @@ -30,6 +30,7 @@ pub mod members_notifier_subscriber; pub mod offchain; pub mod parameters; pub mod pgas; +pub mod statement_allowance; pub mod traits; pub mod tx_priority; pub mod weight_budget; diff --git a/support/src/parameters.rs b/support/src/parameters.rs index 0e0aed25..a5b01bfe 100644 --- a/support/src/parameters.rs +++ b/support/src/parameters.rs @@ -4,41 +4,14 @@ //! Reusable adapters for runtime-configured parameters. -use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; +use crate::statement_allowance::BoundedStatementAllowance; use core::marker::PhantomData; use frame_support::traits::Get; -use scale_info::TypeInfo; use sp_statement_store::StatementAllowance; -/// A [`StatementAllowance`] representation with a fixed maximum encoded length. -#[derive( - Clone, - Default, - PartialEq, - Eq, - Debug, - Encode, - Decode, - DecodeWithMemTracking, - MaxEncodedLen, - TypeInfo, -)] -pub struct StatementAllowanceParameter { - /// Maximum total statement size in bytes. - pub max_size: u32, - /// Maximum number of statements. - pub max_count: u32, -} - -impl From for StatementAllowance { - fn from(value: StatementAllowanceParameter) -> Self { - Self { max_size: value.max_size, max_count: value.max_count } - } -} - -/// Adapts a [`StatementAllowanceParameter`] getter to the SDK allowance type. +/// Adapts a [`BoundedStatementAllowance`] getter to the SDK allowance type. pub struct StatementAllowanceGetter(PhantomData); -impl> Get +impl> Get for StatementAllowanceGetter { fn get() -> StatementAllowance { @@ -126,9 +99,9 @@ mod tests { } struct Allowance; - impl Get for Allowance { - fn get() -> StatementAllowanceParameter { - StatementAllowanceParameter { max_size: 42, max_count: 3 } + impl Get for Allowance { + fn get() -> BoundedStatementAllowance { + BoundedStatementAllowance { max_size: 42, max_count: 3 } } } diff --git a/support/src/statement_allowance.rs b/support/src/statement_allowance.rs new file mode 100644 index 00000000..3e310891 --- /dev/null +++ b/support/src/statement_allowance.rs @@ -0,0 +1,58 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Individuality. +// 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. + +//! A statement allowance with a fixed maximum encoded length. +//! +//! [`StatementAllowance`] does not implement `MaxEncodedLen`, so it can't be stored. + +use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; +use scale_info::TypeInfo; +use sp_statement_store::StatementAllowance; + +/// A [`StatementAllowance`] with a fixed maximum encoded length. +/// +/// TODO(): Remove once the upstream +/// struct has `MaxEncodedLen`. +#[derive( + Clone, + Default, + PartialEq, + Eq, + Debug, + Encode, + Decode, + DecodeWithMemTracking, + MaxEncodedLen, + TypeInfo, +)] +pub struct BoundedStatementAllowance { + /// Maximum total statement size in bytes. + pub max_size: u32, + /// Maximum number of statements. + pub max_count: u32, +} + +impl From for BoundedStatementAllowance { + fn from(value: StatementAllowance) -> Self { + Self { max_size: value.max_size, max_count: value.max_count } + } +} + +impl From for StatementAllowance { + fn from(value: BoundedStatementAllowance) -> Self { + Self { max_size: value.max_size, max_count: value.max_count } + } +} From cd3e90fe4c59dcb62bd0a8834da70dee55e15e2e Mon Sep 17 00:00:00 2001 From: georgepisaltu Date: Thu, 5 Nov 2026 11:31:27 +0200 Subject: [PATCH 2/2] Adjust SSS allowance numbers Signed-off-by: georgepisaltu --- runtimes/next-people-paseo/src/parameters.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/runtimes/next-people-paseo/src/parameters.rs b/runtimes/next-people-paseo/src/parameters.rs index 2cd2f0e5..4a311261 100644 --- a/runtimes/next-people-paseo/src/parameters.rs +++ b/runtimes/next-people-paseo/src/parameters.rs @@ -41,20 +41,20 @@ pub mod dynamic_params { pub mod statement_storage { #[codec(index = 0)] pub static AccountsApiAllowance: BoundedStatementAllowance = - BoundedStatementAllowance { max_size: 500 * 1024, max_count: 2 }; + BoundedStatementAllowance { max_size: 50 * 1024, max_count: 2 }; #[codec(index = 6)] pub static NotificationAllowance: BoundedStatementAllowance = - BoundedStatementAllowance { max_size: 10 * 1024, max_count: 1 }; + BoundedStatementAllowance { max_size: 5 * 1024 / 2, max_count: 1 }; #[codec(index = 10)] pub static LitePersonStatementLimit: BoundedStatementAllowance = - BoundedStatementAllowance { max_size: 500 * 1024, max_count: 50 }; + BoundedStatementAllowance { max_size: 100 * 1024, max_count: 50 }; #[codec(index = 11)] pub static PersonStatementLimit: BoundedStatementAllowance = BoundedStatementAllowance { max_size: 1024 * 1024, max_count: 200 }; #[codec(index = 1)] - pub static StmtStoreSlotsPerPeriod: u32 = 20; + pub static StmtStoreSlotsPerPeriod: u32 = 70; #[codec(index = 2)] - pub static LiteStmtStoreSlotsPerPeriod: u32 = 10; + pub static LiteStmtStoreSlotsPerPeriod: u32 = 50; #[codec(index = 3)] pub static StmtStoreCleanupLimit: u32 = 50; #[codec(index = 4)] @@ -62,9 +62,9 @@ pub mod dynamic_params { #[codec(index = 5)] pub static StmtStoreGraceWindow: u32 = 2 * 24 * 60 * 60; #[codec(index = 7)] - pub static NotificationSlotsPerPeriod: u8 = 16; + pub static NotificationSlotsPerPeriod: u8 = 70; #[codec(index = 8)] - pub static LiteNotificationSlotsPerPeriod: u8 = 8; + pub static LiteNotificationSlotsPerPeriod: u8 = 50; #[codec(index = 9)] pub static NotificationPeriodDuration: u32 = SECONDS_PER_DAY; }