Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

DigestItem trait #636

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
45 changes: 41 additions & 4 deletions demo/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ extern crate demo_primitives;
use rstd::prelude::*;
use demo_primitives::{AccountId, AccountIndex, Balance, BlockNumber, Hash, Index, SessionKey, Signature};
use runtime_primitives::generic;
use runtime_primitives::traits::{Convert, HasPublicAux, BlakeTwo256};
use runtime_primitives::traits::{Convert, HasPublicAux, BlakeTwo256, Identity, DigestItem, AuthoritiesChangeDigest};
use version::RuntimeVersion;

#[cfg(any(feature = "std", test))]
Expand Down Expand Up @@ -94,9 +94,9 @@ impl system::Trait for Concrete {
type BlockNumber = BlockNumber;
type Hash = Hash;
type Hashing = BlakeTwo256;
type Digest = generic::Digest<Vec<u8>>;
type Digest = generic::Digest<ConcreteLog>;
type AccountId = AccountId;
type Header = generic::Header<BlockNumber, BlakeTwo256, Vec<u8>>;
type Header = generic::Header<BlockNumber, BlakeTwo256, ConcreteLog>;
type Event = Event;
}

Expand All @@ -118,6 +118,7 @@ impl consensus::Trait for Concrete {
const NOTE_OFFLINE_POSITION: u32 = 1;
type SessionKey = SessionKey;
type OnOfflineValidator = Staking;
type ConvertSessionKeyToAuthorityId = Identity;
}

/// Consensus module for this concrete runtime.
Expand Down Expand Up @@ -170,6 +171,42 @@ pub type Council = council::Module<Concrete>;
/// Council voting module for this concrete runtime.
pub type CouncilVoting = council::voting::Module<Concrete>;

/// Concrete log type.
Copy link
Member

Choose a reason for hiding this comment

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

could do with more information. consider what it is in relation to other types and why it exists as a type at all.

#[derive(Clone, PartialEq, Eq, Encode, Decode)]
#[cfg_attr(feature = "std", derive(Debug, Serialize, Deserialize))]
pub enum ConcreteLog {
/// Authority changes log.
Copy link
Member

Choose a reason for hiding this comment

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

more information. describe specifically under what circumstances this item is used as opposed to any other.

AuthorityChanges(Vec<SessionKey>),
}

impl Default for ConcreteLog {
fn default() -> Self {
unreachable!("shouldn't be called ever")
}
}

impl DigestItem for ConcreteLog {
type AuthoritiesChange = Vec<SessionKey>;

fn as_authorities_change(&self) -> Option<&Self::AuthoritiesChange> {
match self {
ConcreteLog::AuthorityChanges(ref authorities_change) => Some(authorities_change),
}
}
}

impl AuthoritiesChangeDigest<ConcreteLog> for Vec<SessionKey> {
type AuthorityId = SessionKey;

fn new(authorities: Vec<SessionKey>) -> Option<ConcreteLog> {
Some(ConcreteLog::AuthorityChanges(authorities))
}

fn authorities(&self) -> &[SessionKey] {
&self[..]
}
}

impl_outer_event! {
pub enum Event for Concrete {
balances, session, staking
Expand Down Expand Up @@ -206,7 +243,7 @@ impl_outer_dispatch! {
/// The address format for describing accounts.
pub type Address = balances::Address<Concrete>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256, Vec<u8>>;
pub type Header = generic::Header<BlockNumber, BlakeTwo256, ConcreteLog>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// BlockId type as expected by this runtime.
Expand Down
4 changes: 0 additions & 4 deletions demo/runtime/wasm/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
35 changes: 32 additions & 3 deletions substrate/runtime/consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ extern crate substrate_runtime_system as system;
extern crate substrate_primitives;

use rstd::prelude::*;
use runtime_support::{storage, Parameter};
use runtime_support::{storage, StorageValue, Parameter};
use runtime_support::dispatch::Result;
use runtime_support::storage::unhashed::StorageVec;
use primitives::traits::{MaybeSerializeDebug, MaybeEmpty};
use primitives::traits::{MaybeSerializeDebug, MaybeEmpty, Convert,
Executable, DigestItem, AuthoritiesChangeDigest};
use primitives::bft::MisbehaviorReport;

#[cfg(any(feature = "std", test))]
Expand Down Expand Up @@ -77,6 +78,9 @@ pub trait Trait: system::Trait {

type SessionKey: Parameter + Default + MaybeSerializeDebug;
type OnOfflineValidator: OnOfflineValidator;
type ConvertSessionKeyToAuthorityId: Convert<Self::SessionKey,
<<system::DigestItemFor<Self> as DigestItem>::AuthoritiesChange as
AuthoritiesChangeDigest<system::DigestItemFor<Self>>>::AuthorityId>;
}

decl_module! {
Expand All @@ -96,6 +100,14 @@ decl_module! {
}
}

decl_storage! {
trait Store for Module<T: Trait> as Consensus {
// Authorities set actual at the block execution start. IsSome only if
Copy link
Member

Choose a reason for hiding this comment

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

IsSome or !empty()? (with default you don't get access to whether it's Some or None)

// the set has been changed.
SavedAuthorities get(saved_authorities): default Vec<T::SessionKey>;
Copy link
Member

Choose a reason for hiding this comment

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

Consider rename to OriginalAuthorities

Copy link
Member

Choose a reason for hiding this comment

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

Also consider removing default, to ensure it's Some in the case that the set changed and None otherwise.

}
}

impl<T: Trait> Module<T> {
/// Get the current set of authorities. These are the session keys.
pub fn authorities() -> Vec<T::SessionKey> {
Expand Down Expand Up @@ -149,7 +161,15 @@ impl<T: Trait> Module<T> {
///
/// Called by `next_session` only.
pub fn set_authorities(authorities: &[T::SessionKey]) {
AuthorityStorageVec::<T::SessionKey>::set_items(authorities);
let previous_authorities = AuthorityStorageVec::<T::SessionKey>::items();
if previous_authorities != authorities {
let saved_authorities = Self::saved_authorities();
if saved_authorities.is_empty() {
Copy link
Member

Choose a reason for hiding this comment

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

this would then become original_authorities.is_none()

<SavedAuthorities<T>>::put(previous_authorities);
}

AuthorityStorageVec::<T::SessionKey>::set_items(authorities);
}
}

/// Set a single authority by index.
Expand All @@ -158,6 +178,15 @@ impl<T: Trait> Module<T> {
}
}

/// Finalization hook for the consensus module.
impl<T: Trait> Executable for Module<T> {
fn execute() {
let _saved_authorities = <SavedAuthorities<T>>::take();

// TODO: call deposit_log for saved_authorities
}
}

#[cfg(any(feature = "std", test))]
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
Expand Down
1 change: 1 addition & 0 deletions substrate/runtime/contract/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub struct Test;
impl HasPublicAux for Test {
type PublicAux = u64;
}

impl system::Trait for Test {
type PublicAux = <Self as HasPublicAux>::PublicAux;
type Index = u64;
Expand Down
3 changes: 2 additions & 1 deletion substrate/runtime/executive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::{H256, KeccakHasher};
use primitives::BuildStorage;
use primitives::traits::{HasPublicAux, Identity, Header as HeaderT, BlakeTwo256, AuxLookup};
use primitives::traits::{HasPublicAux, Empty, Identity, Header as HeaderT, BlakeTwo256, AuxLookup};
use primitives::testing::{Digest, Header, Block};

struct NullLookup;
Expand Down Expand Up @@ -259,6 +259,7 @@ mod tests {
const NOTE_OFFLINE_POSITION: u32 = 1;
type SessionKey = u64;
type OnOfflineValidator = staking::Module<Test>;
type ConvertSessionKeyToAuthorityId = Empty;
}
impl balances::Trait for Test {
type Balance = u64;
Expand Down
2 changes: 1 addition & 1 deletion substrate/runtime/primitives/src/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ pub struct Digest<Item> {
}

impl<Item> traits::Digest for Digest<Item> where
Item: Member + Default + Codec
Item: traits::DigestItem + Default + Codec
{
type Item = Item;
fn push(&mut self, item: Self::Item) {
Expand Down
4 changes: 4 additions & 0 deletions substrate/runtime/primitives/src/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ impl traits::Digest for Digest {
}
}

impl traits::DigestItem for u64 {
type AuthoritiesChange = traits::StubDigestItem;
}

#[derive(PartialEq, Eq, Clone, Serialize, Deserialize, Debug, Encode, Decode)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
Expand Down
50 changes: 43 additions & 7 deletions substrate/runtime/primitives/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,13 +322,6 @@ impl<T> MaybeDisplay for T {}
pub trait Member: Send + Sync + Sized + MaybeSerializeDebug + Eq + PartialEq + Clone + 'static {}
impl<T: Send + Sync + Sized + MaybeSerializeDebug + Eq + PartialEq + Clone + 'static> Member for T {}

/// Something that acts like a `Digest` - it can have `Log`s `push`ed onto it and these `Log`s are
/// each `Codec`.
pub trait Digest {
type Item: Member;
fn push(&mut self, item: Self::Item);
}

/// Something which fulfills the abstract idea of a Substrate header. It has types for a `Number`,
/// a `Hash` and a `Digest`. It provides access to an `extrinsics_root`, `state_root` and
/// `parent_hash`, as well as a `digest` and a block `number`.
Expand Down Expand Up @@ -434,3 +427,46 @@ pub trait Applyable: Sized + Send + Sync {
fn sender(&self) -> &Self::AccountId;
fn apply(self) -> Result<(), &'static str>;
}

/// Something that acts like a `Digest` - it can have `Log`s `push`ed onto it and these `Log`s are
/// each `Codec`.
pub trait Digest {
type Item: DigestItem;

fn push(&mut self, item: Self::Item);
}

/// Single digest item.
pub trait DigestItem: Member {
Copy link
Member

Choose a reason for hiding this comment

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

Consider copying the Event infrastructure for this - it should be able to be used almost wholesale.

/// Type of authorities change log entry.
type AuthoritiesChange: AuthoritiesChangeDigest<Self>; // TODO: = StubDigestItem when associated type defaults are stabilized

/// Returns Some if the entry is the 'authorities change' log entry.
fn as_authorities_change(&self) -> Option<&Self::AuthoritiesChange> {
None
}
}

/// Authorities change digest item.
pub trait AuthoritiesChangeDigest<I: DigestItem> {
/// Type of authority Id.
type AuthorityId: Member;

/// Make new authorities change log entry.
fn new(authorities: Vec<Self::AuthorityId>) -> Option<I>;

/// Get new authorities set.
fn authorities(&self) -> &[Self::AuthorityId];
}

/// Empty digest item that is never created and used.
///
/// Should be used as a stub for items that are not supported by runtimes.
pub struct StubDigestItem;

impl<I: DigestItem> AuthoritiesChangeDigest<I> for StubDigestItem {
type AuthorityId = ();

fn new(_authorities: Vec<Self::AuthorityId>) -> Option<I> { None }
fn authorities(&self) -> &[Self::AuthorityId] { unreachable!("StubDigestItem is never created") }
}
3 changes: 2 additions & 1 deletion substrate/runtime/session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::{H256, KeccakHasher};
use primitives::BuildStorage;
use primitives::traits::{HasPublicAux, Identity, BlakeTwo256};
use primitives::traits::{HasPublicAux, Empty, Identity, BlakeTwo256};
use primitives::testing::{Digest, Header};

#[derive(Clone, Eq, PartialEq)]
Expand All @@ -305,6 +305,7 @@ mod tests {
const NOTE_OFFLINE_POSITION: u32 = 1;
type SessionKey = u64;
type OnOfflineValidator = ();
type ConvertSessionKeyToAuthorityId = Empty;
Copy link
Member

Choose a reason for hiding this comment

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

Use () now.

}
impl system::Trait for Test {
type PublicAux = <Self as HasPublicAux>::PublicAux;
Expand Down
3 changes: 2 additions & 1 deletion substrate/runtime/staking/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
#![cfg(test)]

use primitives::BuildStorage;
use primitives::traits::{HasPublicAux, Identity};
use primitives::traits::{HasPublicAux, Empty, Identity};
use primitives::testing::{Digest, Header};
use substrate_primitives::{H256, KeccakHasher};
use runtime_io;
Expand All @@ -35,6 +35,7 @@ impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1;
type SessionKey = u64;
type OnOfflineValidator = ();
type ConvertSessionKeyToAuthorityId = Empty;
}
impl system::Trait for Test {
type PublicAux = <Self as HasPublicAux>::PublicAux;
Expand Down
3 changes: 3 additions & 0 deletions substrate/runtime/system/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ pub trait Trait: Eq + Clone {
type Event: Parameter + Member;
}

/// Type of digest item from the Trait.
pub type DigestItemFor<T> = <<T as Trait>::Digest as traits::Digest>::Item;

decl_module! {
pub struct Module<T: Trait>;
}
Expand Down
3 changes: 2 additions & 1 deletion substrate/runtime/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ mod tests {
use runtime_io::with_externalities;
use substrate_primitives::H256;
use runtime_primitives::BuildStorage;
use runtime_primitives::traits::{HasPublicAux, BlakeTwo256};
use runtime_primitives::traits::{HasPublicAux, BlakeTwo256, Empty};
use runtime_primitives::testing::{Digest, Header};

#[derive(Clone, Eq, PartialEq)]
Expand All @@ -166,6 +166,7 @@ mod tests {
const NOTE_OFFLINE_POSITION: u32 = 1;
type SessionKey = u64;
type OnOfflineValidator = ();
type ConvertSessionKeyToAuthorityId = Empty;
}
impl Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
Expand Down
Binary file not shown.
Binary file not shown.