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

Balances: Configurable Number of Genesis Accounts with Specified Balances for Benchmarking #6267

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f3bc304
add dev_accounts field
runcomet Oct 28, 2024
cb0d3ba
populate dev_accounts field
runcomet Nov 4, 2024
78fa5fc
use default dev_accounts
runcomet Nov 4, 2024
a4a1eff
BalancesConfig
runcomet Nov 4, 2024
3c968f4
Merge branch 'master' into dev-accounts
runcomet Nov 5, 2024
3163d5f
configure ensure_ti_valid awareness of dev_accounts
runcomet Nov 13, 2024
d8701a8
Merge branch 'master' into dev-accounts
runcomet Nov 13, 2024
25ca49c
nit
runcomet Nov 14, 2024
4cac3a8
Option String
runcomet Nov 21, 2024
b3e4daf
Merge branch 'master' into dev-accounts
runcomet Nov 21, 2024
beb8056
doc fix
runcomet Nov 21, 2024
e647bca
derive_dev_account helper function
runcomet Nov 22, 2024
e8efd68
add prdoc
runcomet Nov 30, 2024
dddac55
Merge branch 'master' into dev-accounts
runcomet Nov 30, 2024
d53d795
adjust genesisconfig addition
runcomet Dec 1, 2024
9128ab9
nit
runcomet Dec 2, 2024
4e8ae42
Merge branch 'master' into dev-accounts
runcomet Dec 11, 2024
be5acd6
remove feature flag
runcomet Dec 27, 2024
fed102f
mutate_account
runcomet Jan 3, 2025
5e8f9e7
update PR doc
runcomet Jan 3, 2025
0474e2c
as_deref, dev_accounts
runcomet Jan 9, 2025
00a7a0f
DEFAULT_ADDRESS_URI
runcomet Jan 9, 2025
88fc87a
fix conficts + Optional dev_accounts + hard derivation
runcomet Jan 10, 2025
c987262
Merge branch 'master' into dev-accounts
runcomet Jan 11, 2025
589af1f
cargo +nightly fmt
runcomet Jan 11, 2025
d13f0d6
add dev_accounts field in missing pallet tests
runcomet Jan 11, 2025
dea6676
CI check to confirm chain-spec issue
runcomet Jan 11, 2025
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
2 changes: 1 addition & 1 deletion bridges/modules/messages/src/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ pub fn inbound_unrewarded_relayers_state(lane: TestLaneIdType) -> UnrewardedRela
/// Return test externalities to use in tests.
pub fn new_test_ext() -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![(ENDOWED_ACCOUNT, 1_000_000)] }
pallet_balances::GenesisConfig::<TestRuntime> { balances: vec![(ENDOWED_ACCOUNT, 1_000_000)], ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
sp_io::TestExternalities::new(t)
Expand Down
2 changes: 1 addition & 1 deletion cumulus/pallets/collator-selection/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
invulnerables,
};
let session = pallet_session::GenesisConfig::<Test> { keys, ..Default::default() };
pallet_balances::GenesisConfig::<Test> { balances }
pallet_balances::GenesisConfig::<Test> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
// collator selection must be initialized before session.
Expand Down
1 change: 1 addition & 0 deletions polkadot/runtime/common/src/assigned_slots/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -773,6 +773,7 @@ mod tests {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions polkadot/runtime/common/src/auctions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -866,6 +866,7 @@ mod tests {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions polkadot/runtime/common/src/crowdloan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1085,6 +1085,7 @@ mod tests {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 1000), (2, 2000), (3, 3000), (4, 4000)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions polkadot/runtime/common/src/paras_registrar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -869,6 +869,7 @@ mod tests {

pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10_000_000), (2, 10_000_000), (3, 10_000_000)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions polkadot/runtime/common/src/slots/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,7 @@ mod tests {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion polkadot/xcm/pallet-xcm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ pub(crate) fn new_test_ext_with_balances_and_xcm_version(
) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();

pallet_balances::GenesisConfig::<Test> { balances }
pallet_balances::GenesisConfig::<Test> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {

pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(0, INITIAL_BALANCE), (1, INITIAL_BALANCE), (2, INITIAL_BALANCE)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion polkadot/xcm/xcm-builder/tests/mock/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ construct_runtime!(
pub fn kusama_like_with_balances(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();

pallet_balances::GenesisConfig::<Runtime> { balances }
pallet_balances::GenesisConfig::<Runtime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand Down
4 changes: 2 additions & 2 deletions polkadot/xcm/xcm-runtime-apis/tests/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ impl pallet_xcm::Config for TestRuntime {
pub fn new_test_ext_with_balances(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap();

pallet_balances::GenesisConfig::<TestRuntime> { balances }
pallet_balances::GenesisConfig::<TestRuntime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand All @@ -380,7 +380,7 @@ pub fn new_test_ext_with_balances_and_assets(
) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<TestRuntime>::default().build_storage().unwrap();

pallet_balances::GenesisConfig::<TestRuntime> { balances }
pallet_balances::GenesisConfig::<TestRuntime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand Down
2 changes: 2 additions & 0 deletions polkadot/xcm/xcm-simulator/example/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ pub fn para_ext(para_id: u32) -> sp_io::TestExternalities {

pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(ALICE, INITIAL_BALANCE), (parent_account_id(), INITIAL_BALANCE)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand All @@ -125,6 +126,7 @@ pub fn relay_ext() -> sp_io::TestExternalities {
(child_account_id(1), INITIAL_BALANCE),
(child_account_id(2), INITIAL_BALANCE),
],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
3 changes: 2 additions & 1 deletion polkadot/xcm/xcm-simulator/fuzzer/src/fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ pub fn para_ext(para_id: u32) -> sp_io::TestExternalities {

pallet_balances::GenesisConfig::<Runtime> {
balances: (0..6).map(|i| ([i; 32].into(), INITIAL_BALANCE)).collect(),
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand All @@ -138,7 +139,7 @@ pub fn relay_ext() -> sp_io::TestExternalities {
balances.append(&mut (1..=3).map(|i| (para_account_id(i), INITIAL_BALANCE)).collect());
balances.append(&mut (0..6).map(|i| ([i; 32].into(), INITIAL_BALANCE)).collect());

pallet_balances::GenesisConfig::<Runtime> { balances }
pallet_balances::GenesisConfig::<Runtime> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand Down
117 changes: 117 additions & 0 deletions prdoc/pr_6267.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0
# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json

title: Allow configurable number of genesis accounts with specified balances for benchmarking.

doc:
- audience: Runtime Dev
description: |
This pull request adds an additional field `dev_accounts` to the `GenesisConfig`
of the balances pallet, feature gated by `runtime-benchmarks`.

Bringing about an abitrary number of derived dev accounts when building the genesis
state. Runtime developers should supply a derivation path that includes an index placeholder
(i.e. "//Sender/{}") to generate multiple accounts from the same root in a consistent
manner.

crates:
- name: pallet-vesting
bump: minor
- name: pallet-utility
bump: minor
- name: pallet-tx-pause
bump: minor
- name: pallet-treasury
bump: minor
- name: pallet-transaction-storage
bump: minor
- name: pallet-transaction-payment
bump: minor
- name: pallet-asset-tx-payment
bump: minor
- name: pallet-asset-conversion-tx-payment
bump: minor
- name: pallet-tips
bump: minor
- name: pallet-state-trie-migration
bump: minor
- name: pallet-staking
bump: minor
- name: pallet-society
bump: minor
- name: pallet-safe-mode
bump: minor
- name: pallet-root-offences
bump: minor
- name: pallet-revive
bump: minor
- name: pallet-revive-mock-network
bump: minor
- name: pallet-referenda
bump: minor
- name: pallet-recovery
bump: minor
- name: pallet-proxy
bump: minor
- name: pallet-preimage
bump: minor
- name: pallet-nis
bump: minor
- name: pallet-multisig
bump: minor
- name: pallet-lottery
bump: minor
- name: pallet-indices
bump: minor
- name: pallet-identity
bump: minor
- name: pallet-grandpa
bump: minor
- name: pallet-fast-unstake
bump: minor
- name: pallet-elections-phragmen
bump: minor
- name: pallet-election-provider-multi-phase
bump: minor
- name: pallet-democracy
bump: minor
- name: pallet-delegated-staking
bump: minor
- name: pallet-conviction-voting
bump: minor
- name: pallet-contracts
bump: minor
- name: pallet-contracts-mock-network
bump: minor
- name: pallet-collective
bump: minor
- name: pallet-child-bounties
bump: minor
- name: pallet-bounties
bump: minor
- name: pallet-balances
bump: minor
- name: pallet-babe
bump: minor
- name: pallet-asset-conversion
bump: minor
- name: pallet-asset-conversion-ops
bump: minor
- name: pallet-alliance
bump: minor
- name: xcm-simulator-fuzzer
bump: minor
- name: xcm-simulator-example
bump: minor
- name: xcm-runtime-apis
bump: minor
- name: staging-xcm-builder
bump: minor
- name: pallet-xcm
bump: minor
- name: polkadot-runtime-common
bump: minor
- name: pallet-collator-selection
bump: minor
- name: pallet-bridge-messages
bump: minor
1 change: 1 addition & 0 deletions substrate/frame/alliance/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
(8, 1000),
(9, 1000),
],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions substrate/frame/asset-conversion/ops/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities {

pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10000), (2, 20000), (3, 30000), (4, 40000)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions substrate/frame/asset-conversion/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities {

pallet_balances::GenesisConfig::<Test> {
balances: vec![(1, 10000), (2, 20000), (3, 30000), (4, 40000)],
..Default::default()
}
.assimilate_storage(&mut t)
.unwrap();
Expand Down
2 changes: 1 addition & 1 deletion substrate/frame/babe/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ pub fn new_test_ext_raw_authorities(authorities: Vec<AuthorityId>) -> sp_io::Tes

let balances: Vec<_> = (0..authorities.len()).map(|i| (i as u64, 10_000_000)).collect();

pallet_balances::GenesisConfig::<Test> { balances }
pallet_balances::GenesisConfig::<Test> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();

Expand Down
2 changes: 1 addition & 1 deletion substrate/frame/balances/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ frame-support = { workspace = true }
frame-system = { workspace = true }
sp-runtime = { workspace = true }
docify = { workspace = true }
sp-core = { workspace = true }

[dev-dependencies]
pallet-transaction-payment = { workspace = true, default-features = true }
frame-support = { features = ["experimental"], workspace = true, default-features = true }
sp-core = { workspace = true, default-features = true }
sp-io = { workspace = true, default-features = true }
paste = { workspace = true, default-features = true }

Expand Down
70 changes: 69 additions & 1 deletion substrate/frame/balances/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,12 @@ use sp_runtime::{
},
ArithmeticError, DispatchError, FixedPointOperand, Perbill, RuntimeDebug, TokenError,
};

#[cfg(feature = "runtime-benchmarks")]
use sp_core::{sr25519::Pair as SrPair, Pair};
#[cfg(feature = "runtime-benchmarks")]
use alloc::{format, string::{String, ToString}};

pub use types::{
AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData,
};
Expand Down Expand Up @@ -505,11 +511,19 @@ pub mod pallet {
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
pub balances: Vec<(T::AccountId, T::Balance)>,

#[cfg(feature = "runtime-benchmarks")]
pub dev_accounts: (u32, T::Balance, Option<String>),
runcomet marked this conversation as resolved.
Show resolved Hide resolved
}

impl<T: Config<I>, I: 'static> Default for GenesisConfig<T, I> {
fn default() -> Self {
Self { balances: Default::default() }
Self {
balances: Default::default(),

#[cfg(feature = "runtime-benchmarks")]
runcomet marked this conversation as resolved.
Show resolved Hide resolved
dev_accounts: (One::one(), <T as Config<I>>::ExistentialDeposit::get(), Some("//Sender/{}".to_string())),
}
}
}

Expand Down Expand Up @@ -540,6 +554,22 @@ pub mod pallet {
"duplicate balances in genesis."
);

// Generate additional dev accounts.
#[cfg(feature = "runtime-benchmarks")]
{
let (num_accounts, balance, ref derivation) = self.dev_accounts;

// Check if `derivation` is `Some` and generate key pair
if let Some(derivation_string) = &derivation {
runcomet marked this conversation as resolved.
Show resolved Hide resolved
Pallet::<T, I>::derive_dev_account(num_accounts, balance, derivation_string);
} else {
// Derivation string is missing, using default..
let default_derivation = "//Sender/{}".to_string();

Pallet::<T, I>::derive_dev_account(num_accounts, balance, &default_derivation);
}
runcomet marked this conversation as resolved.
Show resolved Hide resolved
}

for &(ref who, free) in self.balances.iter() {
frame_system::Pallet::<T>::inc_providers(who);
assert!(T::AccountStore::insert(who, AccountData { free, ..Default::default() })
Expand Down Expand Up @@ -1248,5 +1278,43 @@ pub mod pallet {
});
Ok(actual)
}

/// Generate dev account from derivation string.
#[cfg(feature = "runtime-benchmarks")]
pub fn derive_dev_account(num_accounts: u32, balance: T::Balance, derivation: &String) {
runcomet marked this conversation as resolved.
Show resolved Hide resolved
// Ensure that the number of accounts is not zero
assert!(num_accounts > 0, "num_accounts must be greater than zero");

assert!(
balance >= <T as Config<I>>::ExistentialDeposit::get(),
"the balance of any account should always be at least the existential deposit.",
);

assert!(
derivation.contains("{}"),
"Invalid derivation string"
runcomet marked this conversation as resolved.
Show resolved Hide resolved
);

for index in 0..num_accounts {
// Replace "{}" in the derivation string with the index.
let derivation_string = derivation.replace("{}", &index.to_string());

// Attempt to create the key pair from the derivation string with error handling.
let pair: SrPair = Pair::from_string(&derivation_string, None)
runcomet marked this conversation as resolved.
Show resolved Hide resolved
.expect(&format!("Failed to parse derivation string: {}", derivation_string));

// Convert the public key to AccountId.
let who = T::AccountId::decode(&mut &pair.public().encode()[..])
.expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
.expect(&format!("Failed to parse derivation string: {}", derivation_string));
// Convert the public key to AccountId.
let who = T::AccountId::decode(&mut &pair.public().encode()[..])
.expect(&format!("Failed to decode public key from pair: {:?}", pair.public()));
.unwrap_or_else(|| format!("Failed to parse derivation string: {derivation_string}"));
// Convert the public key to AccountId.
let who = T::AccountId::decode(&mut &pair.public().encode()[..])
.unwrap_or_else(|| format!("Failed to decode public key from pair: {:?}", pair.public()));

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This would expect a default value for the respective operations, .expect() can't be used at genesis?


frame_system::Pallet::<T>::inc_providers(&who);
Copy link
Member

Choose a reason for hiding this comment

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

Why this instead of doing a force_set_balance or something?

The less cases where we manually modify account references, the better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Getting familiar with the codebase.

I prefer your suggestion.

Thanks for the review!

Copy link
Member

Choose a reason for hiding this comment

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

You can look at the tests of the balances pallet, it has plenty of examples on how to force-set the balance of an account 😄

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 used mutate_account_handling_dust

// Insert the account into the store and ensure it succeeds(uri).
assert!(T::AccountStore::insert(
&who,
AccountData { free: balance, ..Default::default() }
)
.is_ok());
}
}
}
}
Loading
Loading