Skip to content

Commit

Permalink
Merge pull request #61 from mangata-finance/feature/fmt
Browse files Browse the repository at this point in the history
cargo fmt
  • Loading branch information
gleb-urvanov authored Jun 2, 2021
2 parents 85066f2 + 540e7ab commit 4e4bbfa
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 101 deletions.
6 changes: 2 additions & 4 deletions client/basic-authorship/src/basic_authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ where
self.client
.new_block_at(&self.parent_id, inherent_digests, record_proof)?;


// proceed with transactions
let block_timer = time::Instant::now();
let mut skipped = 0;
Expand Down Expand Up @@ -282,8 +281,8 @@ where

self.transaction_pool.remove_invalid(&unqueue_invalid);

let (seed,inherents) = block_builder.create_inherents(inherent_data)?;
for inherent in inherents {
let (seed, inherents) = block_builder.create_inherents(inherent_data)?;
for inherent in inherents {
match block_builder.push(inherent) {
Err(ApplyExtrinsicFailed(Validity(e))) if e.exhausted_resources() => {
warn!("⚠️ Dropping non-mandatory inherent from overweight block.")
Expand All @@ -304,7 +303,6 @@ where
}
}


let (block, storage_changes, proof) = block_builder.build(seed)?.into_inner();

self.metrics.report(|metrics| {
Expand Down
35 changes: 18 additions & 17 deletions client/block-builder/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ use sp_runtime::{
},
};

use sp_inherents::ProvideInherentData;
use pallet_random_seed::RandomSeedInherentDataProvider;
use sp_core::H256;
use sp_inherents::ProvideInherentData;

pub use sp_block_builder::BlockBuilder as BlockBuilderApi;

Expand Down Expand Up @@ -199,22 +199,20 @@ where
// })
}


/// Consume the builder to build a valid `Block` containing all pushed extrinsics.
///
/// Returns the build `Block`, the changes to the storage and an optional `StorageProof`
/// supplied by `self.api`, combined as [`BuiltBlock`].
/// The storage proof will be `Some(_)` when proof recording was enabled.
pub fn build(
mut self,
seed: H256
seed: H256,
) -> Result<BuiltBlock<Block, backend::StateBackendFor<B, Block>>, ApiErrorFor<A, Block>> {
let extrinsics = self.extrinsics.clone();
let parent_hash = self.parent_hash;

let block_id = &self.block_id;


match self
.backend
.blockchain()
Expand Down Expand Up @@ -304,22 +302,25 @@ where
pub fn create_inherents(
&mut self,
mut inherent_data: sp_inherents::InherentData,
) ->
Result<(H256,Vec<Block::Extrinsic>), ApiErrorFor<A, Block>> {
) -> Result<(H256, Vec<Block::Extrinsic>), ApiErrorFor<A, Block>> {
let block_id = self.block_id.clone();
// Result<(H256,Vec<Block::Extrinsic>), ApiErrorFor<A, Block>> {
let seed = BlakeTwo256::hash(&self.extrinsics.encode());
RandomSeedInherentDataProvider(seed).provide_inherent_data(&mut inherent_data).unwrap();

self.api.execute_in_transaction(move |api| {
// `create_inherents` should not change any state, to ensure this we always rollback
// the transaction.
TransactionOutcome::Rollback(api.inherent_extrinsics_with_context(
&block_id,
ExecutionContext::BlockConstruction,
inherent_data,
))
}).map(|inherents| (seed,inherents))
RandomSeedInherentDataProvider(seed)
.provide_inherent_data(&mut inherent_data)
.unwrap();

self.api
.execute_in_transaction(move |api| {
// `create_inherents` should not change any state, to ensure this we always rollback
// the transaction.
TransactionOutcome::Rollback(api.inherent_extrinsics_with_context(
&block_id,
ExecutionContext::BlockConstruction,
inherent_data,
))
})
.map(|inherents| (seed, inherents))
}
}

Expand Down
50 changes: 25 additions & 25 deletions client/shuffler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,45 +8,46 @@ use sp_runtime::traits::{BlakeTwo256, Block as BlockT};
use sp_runtime::AccountId32;
use sp_std::collections::btree_map::BTreeMap;
use sp_std::collections::vec_deque::VecDeque;
use sp_std::vec::Vec;
use sp_std::convert::TryInto;
use sp_std::vec::Vec;

pub struct Xoshiro256PlusPlus {
s: [u64; 4],
}

fn rotl(x:u64, k:u64) -> u64{
fn rotl(x: u64, k: u64) -> u64 {
((x) << (k)) | ((x) >> (64 - (k)))
}

impl Xoshiro256PlusPlus {
#[inline]
fn from_seed(seed: [u8; 32]) -> Xoshiro256PlusPlus {
Xoshiro256PlusPlus { s: [
u64::from_le_bytes(seed[0..8].try_into().unwrap()),
u64::from_le_bytes(seed[8..16].try_into().unwrap()),
u64::from_le_bytes(seed[16..24].try_into().unwrap()),
u64::from_le_bytes(seed[24..32].try_into().unwrap())
] }
Xoshiro256PlusPlus {
s: [
u64::from_le_bytes(seed[0..8].try_into().unwrap()),
u64::from_le_bytes(seed[8..16].try_into().unwrap()),
u64::from_le_bytes(seed[16..24].try_into().unwrap()),
u64::from_le_bytes(seed[24..32].try_into().unwrap()),
],
}
}

fn next_u32(& mut self) -> u32 {
let t: u64 = self.s[1] << 17;
fn next_u32(&mut self) -> u32 {
let t: u64 = self.s[1] << 17;

self.s[2] ^= self.s[0];
self.s[3] ^= self.s[1];
self.s[1] ^= self.s[2];
self.s[0] ^= self.s[3];
self.s[2] ^= self.s[0];
self.s[3] ^= self.s[1];
self.s[1] ^= self.s[2];
self.s[0] ^= self.s[3];

self.s[2] ^= t;
self.s[2] ^= t;

self.s[3] = rotl(self.s[3], 45);
self.s[3] = rotl(self.s[3], 45);

return (self.s[0].wrapping_add(self.s[3])) as u32;
return (self.s[0].wrapping_add(self.s[3])) as u32;
}
}


/// In order to be able to recreate shuffling order anywere lets use
/// explicit algorithms
/// - Xoshiro256StarStar as random number generator
Expand All @@ -60,16 +61,14 @@ impl Xoshiro256PlusPlus {
/// j ← random integer such that 0 ≤ j ≤ i
/// exchange a[j] and a[i]
///
fn fisher_yates<T>(data: &mut Vec<T>, seed: H256)
{
fn fisher_yates<T>(data: &mut Vec<T>, seed: H256) {
let mut s = Xoshiro256PlusPlus::from_seed(seed.into());
for i in (1..(data.len())).rev() {
let j = s.next_u32() % (i as u32);
data.swap(i, j as usize);
}
}


/// shuffles extrinsics assuring that extrinsics signed by single account will be still evaluated
/// in proper order
pub fn shuffle<'a, Block, Api>(
Expand Down Expand Up @@ -101,20 +100,21 @@ where
log::debug!(target: "block_shuffler", "who:{:48} extrinsic:{:?}",who.clone().map(|x| x.to_ss58check()).unwrap_or_else(|| String::from("None")), tx_hash);
(who, tx)
}).collect();

// generate exact number of slots for each account
// [ Alice, Alice, Alice, ... , Bob, Bob, Bob, ... ]
let mut slots: Vec<Option<AccountId32>> = extrinsics.iter().map(|(who,_)| who).cloned().collect();
let mut slots: Vec<Option<AccountId32>> =
extrinsics.iter().map(|(who, _)| who).cloned().collect();

let mut grouped_extrinsics: BTreeMap<Option<AccountId32>, VecDeque<_>> = extrinsics
.into_iter()
.fold(BTreeMap::new(), |mut groups, (who,tx)| {
.fold(BTreeMap::new(), |mut groups, (who, tx)| {
groups.entry(who).or_insert(VecDeque::new()).push_back(tx);
groups
});

// shuffle slots
fisher_yates(& mut slots, seed);
fisher_yates(&mut slots, seed);

// fill slots using extrinsics in order
// [ Alice, Bob, ... , Alice, Bob ]
Expand Down
72 changes: 32 additions & 40 deletions pallets/random-seed/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@

#![cfg_attr(not(feature = "std"), no_std)]

use frame_support::{
decl_module, decl_storage,
weights::DispatchClass,
};
use sp_inherents::{InherentData, InherentIdentifier, ProvideInherent, IsFatalError};
use codec::Decode;
use codec::Encode;
use frame_support::{decl_module, decl_storage, weights::DispatchClass};
use sp_core::H256;
use sp_inherents::{InherentData, InherentIdentifier, IsFatalError, ProvideInherent};
use sp_runtime::RuntimeString;
use sp_std::result;
use sp_core::H256;
use codec::Encode;
use codec::Decode;

#[cfg(feature = "std")]
use sp_inherents::ProvideInherentData;

/// The module configuration trait
pub trait Trait: frame_system::Trait {
}
pub trait Trait: frame_system::Trait {}

decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
Expand Down Expand Up @@ -53,26 +48,25 @@ const RANDOM_SEED_INHERENT_IDENTIFIER: InherentIdentifier = *b"blckseed";
#[derive(Encode, sp_runtime::RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Decode))]
pub enum RandomSeedInherentError {
Other(RuntimeString),
Other(RuntimeString),
}


impl RandomSeedInherentError {
/// Try to create an instance ouf of the given identifier and data.
#[cfg(feature = "std")]
pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option<Self> {
if id == &RANDOM_SEED_INHERENT_IDENTIFIER {
<RandomSeedInherentError as codec::Decode>::decode(&mut &data[..]).ok()
} else {
None
}
}
/// Try to create an instance ouf of the given identifier and data.
#[cfg(feature = "std")]
pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option<Self> {
if id == &RANDOM_SEED_INHERENT_IDENTIFIER {
<RandomSeedInherentError as codec::Decode>::decode(&mut &data[..]).ok()
} else {
None
}
}
}

impl IsFatalError for RandomSeedInherentError {
fn is_fatal_error(&self) -> bool {
fn is_fatal_error(&self) -> bool {
true
}
}
}

fn extract_inherent_data(data: &InherentData) -> Result<RandomSeedInherentType, RuntimeString> {
Expand All @@ -86,37 +80,35 @@ pub struct RandomSeedInherentDataProvider(pub H256);

#[cfg(feature = "std")]
impl ProvideInherentData for RandomSeedInherentDataProvider {
fn inherent_identifier(&self) -> &'static InherentIdentifier {
&RANDOM_SEED_INHERENT_IDENTIFIER
}

fn provide_inherent_data(
&self,
inherent_data: &mut InherentData,
) -> Result<(), sp_inherents::Error> {
fn inherent_identifier(&self) -> &'static InherentIdentifier {
&RANDOM_SEED_INHERENT_IDENTIFIER
}

fn provide_inherent_data(
&self,
inherent_data: &mut InherentData,
) -> Result<(), sp_inherents::Error> {
inherent_data.put_data(RANDOM_SEED_INHERENT_IDENTIFIER, &self.0)
}
}

fn error_to_string(&self, error: &[u8]) -> Option<String> {
RandomSeedInherentError::try_from(&RANDOM_SEED_INHERENT_IDENTIFIER, error).map(|e| format!("{:?}", e))
}
fn error_to_string(&self, error: &[u8]) -> Option<String> {
RandomSeedInherentError::try_from(&RANDOM_SEED_INHERENT_IDENTIFIER, error)
.map(|e| format!("{:?}", e))
}
}


impl<T: Trait> ProvideInherent for Module<T> {
type Call = Call<T>;
type Error = RandomSeedInherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = *b"blckseed";

fn create_inherent(data: &InherentData) -> Option<Self::Call> {
log::debug!(target: "rand-seed", "initializing random seed");
let seed: H256 = extract_inherent_data(data)
.expect("Gets and decodes random seed");
let seed: H256 = extract_inherent_data(data).expect("Gets and decodes random seed");
Some(Call::set(seed))
}

fn check_inherent(_call: &Self::Call, _data: &InherentData) -> result::Result<(), Self::Error> {
Ok(())
}
}

Loading

0 comments on commit 4e4bbfa

Please sign in to comment.