Skip to content

Commit

Permalink
Make use of assimilate_storage for GenesisConfig (paritytech#1982)
Browse files Browse the repository at this point in the history
* Make use of `assimilate_storage` for `GenesisConfig`

Fixes incorrect initialization of the staking gensis storage.

* Add some documentation
  • Loading branch information
bkchr authored and MTDK1 committed Apr 12, 2019
1 parent b81ff1f commit 60b690a
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 50 deletions.
3 changes: 3 additions & 0 deletions core/service/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ impl<'a, G: RuntimeGenesis> BuildStorage for &'a ChainSpec<G> {
Genesis::Raw(map) => Ok((map.into_iter().map(|(k, v)| (k.0, v.0)).collect(), Default::default())),
}
}
fn assimilate_storage(self, _: &mut StorageOverlay, _: &mut ChildrenStorageOverlay) -> Result<(), String> {
Err("`assimilate_storage` not implemented for `ChainSpec`.".into())
}
}

#[derive(Serialize, Deserialize)]
Expand Down
23 changes: 1 addition & 22 deletions core/sr-primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,14 +106,7 @@ pub trait BuildStorage: Sized {
Ok((storage, child_storage))
}
/// Assimilate the storage for this module into pre-existing overlays.
fn assimilate_storage(self, storage: &mut StorageOverlay, child_storage: &mut ChildrenStorageOverlay) -> Result<(), String> {
let (s, cs) = self.build_storage()?;
storage.extend(s);
for (other_child_key, other_child_map) in cs {
child_storage.entry(other_child_key).or_default().extend(other_child_map);
}
Ok(())
}
fn assimilate_storage(self, storage: &mut StorageOverlay, child_storage: &mut ChildrenStorageOverlay) -> Result<(), String>;
}

#[cfg(feature = "std")]
Expand Down Expand Up @@ -429,20 +422,6 @@ macro_rules! impl_outer_config {
)*
Ok(())
}
fn build_storage(self) -> ::std::result::Result<($crate::StorageOverlay, $crate::ChildrenStorageOverlay), String> {
let mut top = $crate::StorageOverlay::new();
let mut children = $crate::ChildrenStorageOverlay::new();
$(
if let Some(extra) = self.$snake {
let (other_top, other_children) = extra.build_storage()?;
top.extend(other_top);
for (other_child_key, other_child_map) in other_children {
children.entry(other_child_key).or_default().extend(other_child_map);
}
}
)*
Ok((top, children))
}
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions node/cli/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ fn development_config_genesis() -> GenesisConfig {
get_authority_keys_from_seed("Alice"),
],
get_account_id_from_seed("Alice").into(),
None,
Some(vec![get_authority_keys_from_seed("Alice").0]),
)
}

Expand All @@ -336,7 +336,10 @@ fn local_testnet_genesis() -> GenesisConfig {
get_authority_keys_from_seed("Bob"),
],
get_account_id_from_seed("Alice").into(),
None,
Some(vec![
get_authority_keys_from_seed("Alice").0,
get_authority_keys_from_seed("Bob").0,
]),
)
}

Expand Down
20 changes: 10 additions & 10 deletions node/executor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ mod tests {
use node_primitives::{Hash, BlockNumber, AccountId};
use runtime_primitives::traits::{Header as HeaderT, Digest as DigestT, Hash as HashT};
use runtime_primitives::{generic, generic::Era, ApplyOutcome, ApplyError, ApplyResult, Perbill};
use {balances, indices, staking, session, system, consensus, timestamp, treasury, contract};
use {balances, indices, session, system, consensus, timestamp, treasury, contract};
use contract::ContractAddressFor;
use system::{EventRecord, Phase};
use node_runtime::{Header, Block, UncheckedExtrinsic, CheckedExtrinsic, Call, Runtime, Balances,
Expand Down Expand Up @@ -277,8 +277,8 @@ mod tests {
(alice(), 111),
(bob(), 100),
(charlie(), 100_000_000),
(dave(), 100),
(eve(), 100),
(dave(), 111),
(eve(), 101),
(ferdie(), 100),
],
existential_deposit: 0,
Expand All @@ -298,7 +298,7 @@ mod tests {
staking: Some(StakingConfig {
sessions_per_era: 2,
current_era: 0,
stakers: vec![(dave(), alice(), 111), (eve(), bob(), 100), (ferdie(), charlie(), 100)],
stakers: vec![(dave(), alice(), 111), (eve(), bob(), 101), (ferdie(), charlie(), 100)],
validator_count: 3,
minimum_validator_count: 0,
bonding_duration: 0,
Expand Down Expand Up @@ -449,9 +449,9 @@ mod tests {

let mut digest = generic::Digest::<Log>::default();
digest.push(Log::from(::grandpa::RawLog::AuthoritiesChangeSignal(0, vec![
(Keyring::Charlie.to_raw_public().into(), 1),
(Keyring::Alice.to_raw_public().into(), 1),
(Keyring::Bob.to_raw_public().into(), 1),
(Keyring::Charlie.to_raw_public().into(), 1),
])));
assert_eq!(Header::decode(&mut &block2.0[..]).unwrap().digest, digest);

Expand Down Expand Up @@ -531,7 +531,7 @@ mod tests {
}
]);
});

executor().call::<_, NeverNativeValue, fn() -> _>(
&mut t,
"Core_execute_block",
Expand All @@ -543,7 +543,7 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// bob sends 5, alice sends 15 | bob += 10, alice -= 10
// 111 - 69 - 1 - 10 - 1 = 30
assert_eq!(Balances::total_balance(&alice()), 111 - 69 - 1 - 10 - 1);
assert_eq!(Balances::total_balance(&alice()), 111 - 69 - 1 - 10 - 1);
// 100 + 69 + 10 - 1 = 178
assert_eq!(Balances::total_balance(&bob()), 100 + 69 + 10 - 1);
assert_eq!(System::events(), vec![
Expand Down Expand Up @@ -592,9 +592,9 @@ mod tests {
EventRecord {
phase: Phase::Finalization,
event: Event::grandpa(::grandpa::RawEvent::NewAuthorities(vec![
(Keyring::Charlie.to_raw_public().into(), 1),
(Keyring::Alice.to_raw_public().into(), 1),
(Keyring::Bob.to_raw_public().into(), 1),
(Keyring::Charlie.to_raw_public().into(), 1),
])),
},
EventRecord {
Expand Down Expand Up @@ -641,7 +641,7 @@ mod tests {
runtime_io::with_externalities(&mut t, || {
// bob sends 5, alice sends 15 | bob += 10, alice -= 10
// 111 - 69 - 1 - 10 - 1 = 30
assert_eq!(Balances::total_balance(&alice()), 111 - 69 - 1 - 10 - 1);
assert_eq!(Balances::total_balance(&alice()), 111 - 69 - 1 - 10 - 1);
// 100 + 69 + 10 - 1 = 178
assert_eq!(Balances::total_balance(&bob()), 100 + 69 + 10 - 1);
});
Expand Down Expand Up @@ -896,7 +896,7 @@ mod tests {
#[test]
fn full_wasm_block_import_works_with_changes_trie() {
let block1 = changes_trie_block();

let mut t = new_test_ext(COMPACT_CODE, true);
WasmExecutor::new().call(&mut t, 8, COMPACT_CODE, "Core_execute_block", &block1.0).unwrap();

Expand Down
1 change: 1 addition & 0 deletions srml/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ decl_storage! {
build(|storage: &mut primitives::StorageOverlay, _: &mut primitives::ChildrenStorageOverlay, config: &GenesisConfig<T>| {
with_storage(storage, || {
for &(ref stash, ref controller, balance) in &config.stakers {
assert!(T::Currency::free_balance(&stash) >= balance);
let _ = <Module<T>>::bond(T::Origin::from(Some(stash.clone()).into()), T::Lookup::unlookup(controller.clone()), balance, RewardDestination::Staked);
let _ = <Module<T>>::validate(T::Origin::from(Some(controller.clone()).into()), Default::default());
}
Expand Down
11 changes: 10 additions & 1 deletion srml/staking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,16 @@ impl ExtBuilder {
let _ = balances::GenesisConfig::<Test>{
balances: if self.monied {
if self.reward > 0 {
vec![(1, 10 * balance_factor), (2, 20 * balance_factor), (3, 300 * balance_factor), (4, 400 * balance_factor), (10, balance_factor), (11, balance_factor * 1000), (20, balance_factor), (21, balance_factor * 2000)]
vec![
(1, 10 * balance_factor),
(2, 20 * balance_factor),
(3, 300 * balance_factor),
(4, 400 * balance_factor),
(10, balance_factor),
(11, balance_factor * 1000),
(20, balance_factor),
(21, balance_factor * 2000)
]
} else {
vec![(1, 10 * balance_factor), (2, 20 * balance_factor), (3, 300 * balance_factor), (4, 400 * balance_factor)]
}
Expand Down
15 changes: 0 additions & 15 deletions srml/support/procedural/src/storage/transformation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,21 +389,6 @@ fn decl_store_extra_genesis(

#[cfg(feature = "std")]
impl#fparam #scrate::runtime_primitives::BuildStorage for GenesisConfig#sparam {

fn build_storage(self) -> ::std::result::Result<(#scrate::runtime_primitives::StorageOverlay, #scrate::runtime_primitives::ChildrenStorageOverlay), String> {
let mut r: #scrate::runtime_primitives::StorageOverlay = Default::default();
let mut c: #scrate::runtime_primitives::ChildrenStorageOverlay = Default::default();

{
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
let storage = (RefCell::new(&mut r), PhantomData::<Self>::default());
#builders
}

#scall(&mut r, &mut c, &self);

Ok((r, c))
}
fn assimilate_storage(self, r: &mut #scrate::runtime_primitives::StorageOverlay, c: &mut #scrate::runtime_primitives::ChildrenStorageOverlay) -> ::std::result::Result<(), String> {
use #scrate::rstd::{cell::RefCell, marker::PhantomData};
let storage = (RefCell::new(r), PhantomData::<Self>::default());
Expand Down
5 changes: 5 additions & 0 deletions srml/support/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@
/// - `Inherent $( (CALL) )*` - If the module provides/can check inherents. The optional parameter
/// is for modules that use a `Call` from a different module as
/// inherent.
///
/// # Note
///
/// The population of the genesis storage depends on the order of modules. So, if one of your
/// modules depends on another module. The dependent module need to come before the module depending on it.
#[macro_export]
macro_rules! construct_runtime {

Expand Down

0 comments on commit 60b690a

Please sign in to comment.