Updates to session hook and test changes

This commit is contained in:
Drew Stone 2018-11-28 20:47:43 +02:00
parent a24173e511
commit 6df8ab4cf9
3 changed files with 113 additions and 169 deletions

View File

@ -1,82 +1,26 @@
[package]
authors = ["Drew Stone <drew@commonwealth.im>"]
name = "edge_bridge"
name = "edge_identity"
version = "0.1.0"
authors = ["Drew Stone <drew@commonwealth.im>"]
[dependencies]
hex-literal = "0.1.1"
[dependencies.parity-codec]
default-features = false
version = "2.1.5"
[dependencies.parity-codec-derive]
default-features = false
version = "2.1.0"
[dependencies.safe-mix]
default-features = false
version = "1.0.0"
[dependencies.serde]
default-features = false
version = "1.0.80"
[dependencies.serde_derive]
optional = true
version = "1.0.80"
[dependencies.sr-io]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.sr-primitives]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.sr-std]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-balances]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-council]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-democracy]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-session]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-support]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-system]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-consensus]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.srml-timestamp]
default-features = false
git = "https://github.com/paritytech/substrate/"
[dependencies.substrate-keyring]
git = "https://github.com/paritytech/substrate/"
optional = true
[dependencies.substrate-primitives]
default-features = false
git = "https://github.com/paritytech/substrate/"
hex-literal = "0.1.0"
serde = { version = "1.0", default-features = false }
serde_derive = { version = "1.0", optional = true }
safe-mix = { version = "1.0", default-features = false}
parity-codec = { version = "2.1", default-features = false }
parity-codec-derive = { version = "2.1", default-features = false }
substrate-keyring = { git = "https://github.com/paritytech/substrate/", optional = true }
substrate-primitives = { git = "https://github.com/paritytech/substrate/", default-features = false }
sr-std = { git = "https://github.com/paritytech/substrate/", default-features = false }
sr-io = { git = "https://github.com/paritytech/substrate/", default-features = false }
sr-primitives = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-support = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-system = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-balances = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-grandpa = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-session = { git = "https://github.com/paritytech/substrate/", default-features = false }
srml-democracy = { git = "https://github.com/paritytech/substrate/", default-features = false }
[features]
default = ["std"]
@ -93,8 +37,7 @@ std = [
"sr-primitives/std",
"srml-system/std",
"srml-balances/std",
"srml-council/std",
"srml-grandpa/std",
"srml-session/std",
"srml-democracy/std",
"srml-timestamp/std",
"srml-consensus/std",
]
]

View File

@ -34,11 +34,11 @@ extern crate sr_io as runtime_io;
extern crate srml_balances as balances;
extern crate srml_system as system;
extern crate srml_democracy as democracy;
extern crate srml_session as session;
extern crate srml_timestamp as timestamp;
extern crate srml_consensus as consensus;
extern crate srml_grandpa as grandpa;
use primitives::AuthorityId;
use grandpa::fg_primitives::ScheduledChange;
use democracy::{Approved, VoteThreshold};
use rstd::prelude::*;
@ -53,21 +53,13 @@ use runtime_primitives::traits::{Zero, Hash, Convert, MaybeSerializeDebug};
pub type DepositIndex = u32;
pub type WithdrawIndex = u32;
struct AuthorityStorageVec<S: codec::Codec + Default>(rstd::marker::PhantomData<S>);
impl<S: codec::Codec + Default> StorageVec for AuthorityStorageVec<S> {
type Item = S;
const PREFIX: &'static [u8] = well_known_keys::AUTHORITY_PREFIX;
}
/// The log type of this crate, projected from module trait type.
pub type Log<T> = grandpa::RawLog<
<T as system::Trait>::BlockNumber,
<T as grandpa::Trait>::SessionKey,
>;
pub trait OnOfflineBridgeAuthority {
fn on_offline_authority(authority_index: usize);
}
impl OnOfflineBridgeAuthority for () {
fn on_offline_authority(_authority_index: usize) {}
}
pub trait Trait: balances::Trait + session::Trait {
pub trait Trait: balances::Trait + grandpa::Trait {
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
}
@ -225,25 +217,26 @@ decl_module! {
}
}
impl<T: Trait> Module<T> {
/// Set the current set of bridge authorities' session keys.
///
/// Called by `next_session` only in srml_session module.
pub fn set_authorities(authorities: &[T::SessionKey]) {
let current_authorities = AuthorityStorageVec::<T::SessionKey>::items();
if current_authorities != authorities {
Self::save_original_authorities(Some(current_authorities));
AuthorityStorageVec::<T::SessionKey>::set_items(authorities);
}
/// Helper for authorities being synchronized with the general session authorities.
///
/// This is not the only way to manage an authority set for GRANDPA, but it is
/// a convenient one. When this is used, no other mechanism for altering authority
/// sets should be.
pub struct SyncedAuthorities<T>(::rstd::marker::PhantomData<T>);
// TODO: remove when https://github.com/rust-lang/rust/issues/26925 is fixed
impl<T> Default for SyncedAuthorities<T> {
fn default() -> Self {
SyncedAuthorities(::rstd::marker::PhantomData)
}
}
impl<X, T> session::OnSessionChange<X> for Module<T> where
impl<X, T> session::OnSessionChange<X> for SyncedAuthorities<T> where
T: Trait,
T: session::Trait,
<T as session::Trait>::ConvertAccountIdToSessionKey: Convert<
<T as system::Trait>::AccountId,
<T as consensus::Trait>::SessionKey,
<T as grandpa::Trait>::SessionKey,
>,
{
fn on_session_change(_: X, _: bool) {
@ -251,7 +244,7 @@ impl<X, T> session::OnSessionChange<X> for Module<T> where
.into_iter()
.map(T::ConvertAccountIdToSessionKey::convert)
.map(|key| (key, 1)) // evenly-weighted.
.collect::<Vec<(<T as consensus::Trait>::SessionKey, u64)>>();
.collect::<Vec<(<T as grandpa::Trait>::SessionKey, u64)>>();
// instant changes
let last_authorities = <Authorities<T>>::get();
@ -266,7 +259,7 @@ decl_event!(
pub enum Event<T> where <T as system::Trait>::Hash,
<T as system::Trait>::AccountId,
<T as balances::Trait>::Balance,
<T as consensus::Trait>::SessionKey {
<T as grandpa::Trait>::SessionKey {
// Deposit event for an account, an eligible blockchain transaction hash, and quantity
Deposit(AccountId, Hash, Balance),
// Withdraw event for an account, and an amount
@ -311,3 +304,50 @@ decl_storage! {
pub WithdrawNonceOf get(withdraw_nonce_of): map T::AccountId => u32;
}
}
/// A logs in this module.
#[cfg_attr(feature = "std", derive(Serialize, Debug))]
#[derive(Encode, Decode, PartialEq, Eq, Clone)]
pub enum RawLog<N, SessionKey> {
/// Authorities set change has been signalled. Contains the new set of authorities
/// and the delay in blocks before applying.
AuthoritiesChangeSignal(N, Vec<(SessionKey, u64)>),
}
impl<N: Clone, SessionKey> RawLog<N, SessionKey> {
/// Try to cast the log entry as a contained signal.
pub fn as_signal(&self) -> Option<(N, &[(SessionKey, u64)])> {
match *self {
RawLog::AuthoritiesChangeSignal(ref n, ref signal) => Some((n.clone(), signal)),
}
}
}
/// Logs which can be scanned by GRANDPA for authorities change events.
pub trait BridgeChangeSignal<N> {
/// Try to cast the log entry as a contained signal.
fn as_signal(&self) -> Option<ScheduledChange<N>>;
}
impl<N, SessionKey> BridgeChangeSignal<N> for RawLog<N, SessionKey>
where N: Clone, SessionKey: Clone + Into<AuthorityId>,
{
fn as_signal(&self) -> Option<ScheduledChange<N>> {
RawLog::as_signal(self).map(|(delay, next_authorities)| ScheduledChange {
delay,
next_authorities: next_authorities.iter()
.cloned()
.map(|(k, w)| (k.into(), w))
.collect(),
})
}
}
impl<T: Trait> Module<T> where AuthorityId: core::convert::From<<T as grandpa::Trait>::SessionKey> {
/// See if the digest contains any scheduled change.
pub fn scrape_digest_change(log: &Log<T>)
-> Option<ScheduledChange<T::BlockNumber>>
{
<Log<T> as BridgeChangeSignal<T::BlockNumber>>::as_signal(log)
}
}

View File

@ -42,14 +42,9 @@ extern crate sr_io as runtime_io;
extern crate srml_system as system;
extern crate srml_balances as balances;
extern crate srml_grandpa as grandpa;
extern crate srml_democracy as democracy;
extern crate srml_council as council;
extern crate srml_session as session;
extern crate srml_consensus as consensus;
extern crate srml_timestamp as timestamp;
use consensus::{Log};
use runtime_primitives::traits::{Identity, BlakeTwo256};
// use council::{voting, motions, seats};
// use rstd::prelude::*;
@ -62,63 +57,43 @@ use bridge::{Module, Trait, RawEvent};
// Tests for Bridge Module
#[cfg(test)]
mod tests {
use consensus::RawLog;
use super::*;
// use system::{EventRecord, Phase};
// use runtime_io::with_externalities;
// use runtime_io::ed25519::Pair;
use super::*;
use primitives::{H256, Blake2Hasher};
// The testing primitives are very useful for avoiding having to work with signatures
// or public keys. `u64` is used as the `AccountId` and no `Signature`s are requried.
use runtime_primitives::{
BuildStorage, traits::{Convert, BlakeTwo256}, testing::{Digest, DigestItem, Header}
};
/// Alias to Ed25519 pubkey that identifies an account on the chain. This will almost
/// certainly continue to be the same as the substrate's `AuthorityId`.
pub type AccountId = H256;
pub type SessionKey = primitives::AuthorityId;
use runtime_primitives::{BuildStorage};
use runtime_primitives::traits::{BlakeTwo256};
use runtime_primitives::testing::{Digest, DigestItem, Header};
use runtime_primitives::generic::DigestItem as GenDigestItem;
/// Session key conversion.
pub struct SessionKeyConversion;
impl Convert<AccountId, SessionKey> for SessionKeyConversion {
fn convert(a: AccountId) -> SessionKey {
a.to_fixed_bytes().into()
impl From<RawLog<u64, u64>> for DigestItem {
fn from(log: RawLog<u64, u64>) -> DigestItem {
GenDigestItem::Other(log.encode())
}
}
impl_outer_origin! {
pub enum Origin for Test {
// motions
}
pub enum Origin for Test {}
}
impl_outer_event! {
pub enum Event for Test {
bridge<T>,
balances<T>,
session<T>,
// democracy<T>,
// council<T>,
// voting<T>,
// motions<T>,
grandpa<T>,
}
}
impl_outer_dispatch! {
pub enum Call for Test where origin: Origin {
balances::Balances,
session::Session,
consensus::Consensus,
// democracy::Democracy,
grandpa::Grandpa,
}
}
// For testing the module, we construct most of a mock runtime. This means
// first constructing a configuration type (`Test`) which `impl`s each of the
// configuration traits of modules we want to use.
#[derive(Clone, Eq, PartialEq, Debug)]
#[derive(Clone, PartialEq, Eq, Debug, Decode, Encode)]
pub struct Test;
impl system::Trait for Test {
type Origin = Origin;
@ -126,8 +101,8 @@ use super::*;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Digest = generic::Digest<Log>;
type AccountId = AccountId;
type Digest = Digest;
type AccountId = u64;
type Header = Header;
type Event = Event;
type Log = DigestItem;
@ -139,33 +114,18 @@ use super::*;
type EnsureAccountLiquid = ();
type Event = Event;
}
impl timestamp::Trait for Test {
const TIMESTAMP_SET_POSITION: u32 = 0;
type Moment = u64;
}
impl session::Trait for Test {
type ConvertAccountIdToSessionKey = SessionKeyConversion;
type OnSessionChange = ();
impl grandpa::Trait for Test {
type Log = DigestItem;
type SessionKey = u64;
type Event = Event;
}
impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = Log;
type SessionKey = SessionKey;
type OnOfflineValidator = ();
}
impl Trait for Test {
type Event = Event;
}
pub type System = system::Module<Test>;
pub type Balances = balances::Module<Test>;
pub type Consensus = consensus::Module<Test>;
pub type Session = session::Module<Test>;
pub type Grandpa = grandpa::Module<Test>;
pub type Bridge = Module<Test>;
// This function basically just builds a genesis storage key/value store according to
@ -174,6 +134,7 @@ use super::*;
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
// // We use default for brevity, but you can configure as desired if needed.
t.extend(bridge::GenesisConfig::<Test>{
authorities: vec![1, 2, 3],
_genesis_phantom_data: Default::default(),
}.build_storage().unwrap().0);
t.into()