referrerpolicy=no-referrer-when-downgrade

kitchensink_runtime/
genesis_config_presets.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Genesis Presets for the Kitchensink Runtime
19
20use polkadot_sdk::*;
21
22use crate::{
23	constants::currency::*, frame_support::build_struct_json_patch, AccountId, AssetsConfig,
24	BabeConfig, Balance, BalancesConfig, ElectionsConfig, NominationPoolsConfig, ReviveConfig,
25	RuntimeGenesisConfig, SessionConfig, SessionKeys, SocietyConfig, StakerStatus, StakingConfig,
26	SudoConfig, TechnicalCommitteeConfig, BABE_GENESIS_EPOCH_CONFIG,
27};
28use alloc::{vec, vec::Vec};
29use pallet_im_online::sr25519::AuthorityId as ImOnlineId;
30use pallet_revive::is_eth_derived;
31use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId;
32use sp_consensus_babe::AuthorityId as BabeId;
33use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId;
34use sp_consensus_grandpa::AuthorityId as GrandpaId;
35use sp_core::{crypto::get_public_from_string_or_panic, sr25519};
36use sp_genesis_builder::PresetId;
37use sp_keyring::Sr25519Keyring;
38use sp_mixnet::types::AuthorityId as MixnetId;
39use sp_runtime::Perbill;
40
41pub const ENDOWMENT: Balance = 10_000_000 * DOLLARS;
42pub const STASH: Balance = ENDOWMENT / 1000;
43
44/// The staker type as supplied ot the Staking config.
45pub type Staker = (AccountId, AccountId, Balance, StakerStatus<AccountId>);
46
47/// Helper function to create RuntimeGenesisConfig json patch for testing.
48pub fn kitchensink_genesis(
49	initial_authorities: Vec<(AccountId, AccountId, SessionKeys)>,
50	root_key: AccountId,
51	endowed_accounts: Vec<AccountId>,
52	stakers: Vec<Staker>,
53) -> serde_json::Value {
54	let validator_count = initial_authorities.len() as u32;
55	let minimum_validator_count = validator_count;
56
57	let collective = collective(&endowed_accounts);
58
59	build_struct_json_patch!(RuntimeGenesisConfig {
60		balances: BalancesConfig {
61			balances: endowed_accounts.iter().cloned().map(|x| (x, ENDOWMENT)).collect(),
62			..Default::default()
63		},
64		session: SessionConfig {
65			keys: initial_authorities
66				.iter()
67				.map(|x| { (x.0.clone(), x.1.clone(), x.2.clone()) })
68				.collect(),
69		},
70		staking: StakingConfig {
71			validator_count,
72			minimum_validator_count,
73			invulnerables: initial_authorities
74				.iter()
75				.map(|x| x.0.clone())
76				.collect::<Vec<_>>()
77				.try_into()
78				.expect("Too many invulnerable validators: upper limit is MaxInvulnerables from pallet staking config"),
79			slash_reward_fraction: Perbill::from_percent(10),
80			stakers,
81		},
82		elections: ElectionsConfig {
83			members: collective.iter().cloned().map(|member| (member, STASH)).collect(),
84		},
85		technical_committee: TechnicalCommitteeConfig { members: collective },
86		sudo: SudoConfig { key: Some(root_key) },
87		babe: BabeConfig { epoch_config: BABE_GENESIS_EPOCH_CONFIG },
88		society: SocietyConfig { pot: 0 },
89		assets: AssetsConfig {
90			// This asset is used by the NIS pallet as counterpart currency.
91			assets: vec![(9, Sr25519Keyring::Alice.to_account_id(), true, 1)],
92			..Default::default()
93		},
94		nomination_pools: NominationPoolsConfig {
95			min_create_bond: 10 * DOLLARS,
96			min_join_bond: 1 * DOLLARS,
97		},
98		revive: ReviveConfig { mapped_accounts: endowed_accounts.iter().filter(|x| ! is_eth_derived(x)).cloned().collect() },
99	})
100}
101
102/// Provides the JSON representation of predefined genesis config for given `id`.
103pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
104	// Note: Can't use `Sr25519Keyring::Alice.to_seed()` because the seed comes with `//`.
105	let (alice_stash, alice, alice_session_keys) = authority_keys_from_seed("Alice");
106	let (bob_stash, _bob, bob_session_keys) = authority_keys_from_seed("Bob");
107
108	let endowed = well_known_including_eth_accounts();
109
110	let patch = match id.as_ref() {
111		sp_genesis_builder::DEV_RUNTIME_PRESET => kitchensink_genesis(
112			// Use stash as controller account, otherwise grandpa can't load the authority set at
113			// genesis.
114			vec![(alice_stash.clone(), alice_stash.clone(), alice_session_keys)],
115			alice.clone(),
116			endowed,
117			vec![validator(alice_stash.clone())],
118		),
119		sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET => kitchensink_genesis(
120			vec![
121				// Use stash as controller account, otherwise grandpa can't load the authority set
122				// at genesis.
123				(alice_stash.clone(), alice_stash.clone(), alice_session_keys),
124				(bob_stash.clone(), bob_stash.clone(), bob_session_keys),
125			],
126			alice,
127			endowed,
128			vec![validator(alice_stash), validator(bob_stash)],
129		),
130		_ => return None,
131	};
132
133	Some(
134		serde_json::to_string(&patch)
135			.expect("serialization to json is expected to work. qed.")
136			.into_bytes(),
137	)
138}
139
140/// List of supported presets.
141pub fn preset_names() -> Vec<PresetId> {
142	vec![
143		PresetId::from(sp_genesis_builder::DEV_RUNTIME_PRESET),
144		PresetId::from(sp_genesis_builder::LOCAL_TESTNET_RUNTIME_PRESET),
145	]
146}
147
148/// Sets up the `account` to be a staker of validator variant as supplied to the
149/// staking config.
150pub fn validator(account: AccountId) -> Staker {
151	// validator, controller, stash, staker status
152	(account.clone(), account, STASH, StakerStatus::Validator)
153}
154
155/// Extract some accounts from endowed to be put into the collective.
156fn collective(endowed: &[AccountId]) -> Vec<AccountId> {
157	const MAX_COLLECTIVE_SIZE: usize = 50;
158	let endowed_accounts_count = endowed.len();
159	endowed
160		.iter()
161		.take((endowed_accounts_count.div_ceil(2)).min(MAX_COLLECTIVE_SIZE))
162		.cloned()
163		.collect()
164}
165
166/// The Keyring's wellknown accounts + Alith and Baltathar.
167///
168/// Some integration tests require these ETH accounts.
169pub fn well_known_including_eth_accounts() -> Vec<AccountId> {
170	Sr25519Keyring::well_known()
171		.map(|k| k.to_account_id())
172		.chain([
173			// subxt_signer::eth::dev::alith()
174			array_bytes::hex_n_into_unchecked(
175				"f24ff3a9cf04c71dbc94d0b566f7a27b94566caceeeeeeeeeeeeeeeeeeeeeeee",
176			),
177			// subxt_signer::eth::dev::baltathar()
178			array_bytes::hex_n_into_unchecked(
179				"3cd0a705a2dc65e5b1e1205896baa2be8a07c6e0eeeeeeeeeeeeeeeeeeeeeeee",
180			),
181		])
182		.collect::<Vec<_>>()
183}
184
185/// Helper function to generate stash, controller and session key from seed.
186///
187/// Note: `//` is prepended internally.
188pub fn authority_keys_from_seed(seed: &str) -> (AccountId, AccountId, SessionKeys) {
189	(
190		get_public_from_string_or_panic::<sr25519::Public>(&alloc::format!("{seed}//stash")).into(),
191		get_public_from_string_or_panic::<sr25519::Public>(seed).into(),
192		session_keys_from_seed(seed),
193	)
194}
195
196pub fn session_keys(
197	grandpa: GrandpaId,
198	babe: BabeId,
199	im_online: ImOnlineId,
200	authority_discovery: AuthorityDiscoveryId,
201	mixnet: MixnetId,
202	beefy: BeefyId,
203) -> SessionKeys {
204	SessionKeys { grandpa, babe, im_online, authority_discovery, mixnet, beefy }
205}
206
207/// We have this method as there is no straight forward way to convert the
208/// account keyring into these ids.
209///
210/// Note: `//` is prepended internally.
211pub fn session_keys_from_seed(seed: &str) -> SessionKeys {
212	session_keys(
213		get_public_from_string_or_panic::<GrandpaId>(seed),
214		get_public_from_string_or_panic::<BabeId>(seed),
215		get_public_from_string_or_panic::<ImOnlineId>(seed),
216		get_public_from_string_or_panic::<AuthorityDiscoveryId>(seed),
217		get_public_from_string_or_panic::<MixnetId>(seed),
218		get_public_from_string_or_panic::<BeefyId>(seed),
219	)
220}