im-online: use generic crypto (#3500)

* im-online: support using ed25519 and sr25519 crypto

* app-crypto: add trait bounds to RuntimePublic::Signature

* im-online: add missing type annotations

* authority-discovery: depend on im-online module and use its crypto

* node: set i'm online crypto to sr25519

* node: bump spec_version

* rpc: don't generate i'm online pubkey in insert_key method

* im-online: fix docs

* im-online: move app crypto packages

* aura: move app crypto packages
This commit is contained in:
André Silva
2019-08-28 13:46:52 +01:00
committed by Bastian Köcher
parent b5c6cc3996
commit 574f68fd7e
9 changed files with 157 additions and 103 deletions
+1
View File
@@ -3826,6 +3826,7 @@ dependencies = [
"serde 1.0.97 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.97 (registry+https://github.com/rust-lang/crates.io-index)",
"sr-io 2.0.0", "sr-io 2.0.0",
"sr-primitives 2.0.0", "sr-primitives 2.0.0",
"sr-staking-primitives 2.0.0",
"sr-std 2.0.0", "sr-std 2.0.0",
"srml-im-online 0.1.0", "srml-im-online 0.1.0",
"srml-session 2.0.0", "srml-session 2.0.0",
@@ -17,6 +17,7 @@
use primitives::crypto::{KeyTypeId, CryptoType, IsWrappedBy, Public}; use primitives::crypto::{KeyTypeId, CryptoType, IsWrappedBy, Public};
#[cfg(feature = "std")] #[cfg(feature = "std")]
use primitives::crypto::Pair; use primitives::crypto::Pair;
use codec::Codec;
/// An application-specific key. /// An application-specific key.
pub trait AppKey: 'static + Send + Sync + Sized + CryptoType + Clone { pub trait AppKey: 'static + Send + Sync + Sized + CryptoType + Clone {
@@ -72,7 +73,7 @@ pub trait AppSignature: AppKey + Eq + PartialEq + MaybeDebugHash {
/// A runtime interface for a public key. /// A runtime interface for a public key.
pub trait RuntimePublic: Sized { pub trait RuntimePublic: Sized {
/// The signature that will be generated when signing with the corresponding private key. /// The signature that will be generated when signing with the corresponding private key.
type Signature; type Signature: Codec + MaybeDebugHash + Eq + PartialEq + Clone;
/// Returns all public keys for the given key type in the keystore. /// Returns all public keys for the given key type in the keystore.
fn all(key_type: KeyTypeId) -> crate::Vec<Self>; fn all(key_type: KeyTypeId) -> crate::Vec<Self>;
@@ -97,7 +98,7 @@ pub trait RuntimePublic: Sized {
/// A runtime interface for an application's public key. /// A runtime interface for an application's public key.
pub trait RuntimeAppPublic: Sized { pub trait RuntimeAppPublic: Sized {
/// The signature that will be generated when signing with the corresponding private key. /// The signature that will be generated when signing with the corresponding private key.
type Signature; type Signature: Codec + MaybeDebugHash + Eq + PartialEq + Clone;
/// Returns all public keys for this application in the keystore. /// Returns all public keys for this application in the keystore.
fn all() -> crate::Vec<Self>; fn all() -> crate::Vec<Self>;
@@ -23,38 +23,38 @@ use substrate_client::decl_runtime_apis;
use rstd::vec::Vec; use rstd::vec::Vec;
use sr_primitives::ConsensusEngineId; use sr_primitives::ConsensusEngineId;
mod app_sr25519 {
use app_crypto::{app_crypto, key_types::AURA, sr25519};
app_crypto!(sr25519, AURA);
}
pub mod sr25519 { pub mod sr25519 {
mod app_sr25519 {
use app_crypto::{app_crypto, key_types::AURA, sr25519};
app_crypto!(sr25519, AURA);
}
/// An Aura authority keypair using S/R 25519 as its crypto. /// An Aura authority keypair using S/R 25519 as its crypto.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub type AuthorityPair = super::app_sr25519::Pair; pub type AuthorityPair = app_sr25519::Pair;
/// An Aura authority signature using S/R 25519 as its crypto. /// An Aura authority signature using S/R 25519 as its crypto.
pub type AuthoritySignature = super::app_sr25519::Signature; pub type AuthoritySignature = app_sr25519::Signature;
/// An Aura authority identifier using S/R 25519 as its crypto. /// An Aura authority identifier using S/R 25519 as its crypto.
pub type AuthorityId = super::app_sr25519::Public; pub type AuthorityId = app_sr25519::Public;
}
mod app_ed25519 {
use app_crypto::{app_crypto, key_types::AURA, ed25519};
app_crypto!(ed25519, AURA);
} }
pub mod ed25519 { pub mod ed25519 {
mod app_ed25519 {
use app_crypto::{app_crypto, key_types::AURA, ed25519};
app_crypto!(ed25519, AURA);
}
/// An Aura authority keypair using Ed25519 as its crypto. /// An Aura authority keypair using Ed25519 as its crypto.
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub type AuthorityPair = super::app_ed25519::Pair; pub type AuthorityPair = app_ed25519::Pair;
/// An Aura authority signature using Ed25519 as its crypto. /// An Aura authority signature using Ed25519 as its crypto.
pub type AuthoritySignature = super::app_ed25519::Signature; pub type AuthoritySignature = app_ed25519::Signature;
/// An Aura authority identifier using Ed25519 as its crypto. /// An Aura authority identifier using Ed25519 as its crypto.
pub type AuthorityId = super::app_ed25519::Public; pub type AuthorityId = app_ed25519::Public;
} }
/// The `ConsensusEngineId` of AuRa. /// The `ConsensusEngineId` of AuRa.
+1 -1
View File
@@ -162,7 +162,7 @@ impl<B, E, P, RA> AuthorApi<ExHash<P>, BlockHash<P>> for Author<B, E, P, RA> whe
Some(public) => public.0, Some(public) => public.0,
None => { None => {
let maybe_public = match key_type { let maybe_public = match key_type {
key_types::BABE | key_types::IM_ONLINE | key_types::SR25519 => key_types::BABE | key_types::SR25519 =>
sr25519::Pair::from_string(&suri, maybe_password) sr25519::Pair::from_string(&suri, maybe_password)
.map(|pair| pair.public().to_raw_vec()), .map(|pair| pair.public().to_raw_vec()),
key_types::GRANDPA | key_types::ED25519 => key_types::GRANDPA | key_types::ED25519 =>
+1 -1
View File
@@ -30,7 +30,7 @@ use hex_literal::hex;
use substrate_telemetry::TelemetryEndpoints; use substrate_telemetry::TelemetryEndpoints;
use grandpa_primitives::{AuthorityId as GrandpaId}; use grandpa_primitives::{AuthorityId as GrandpaId};
use babe_primitives::{AuthorityId as BabeId}; use babe_primitives::{AuthorityId as BabeId};
use im_online::AuthorityId as ImOnlineId; use im_online::sr25519::{AuthorityId as ImOnlineId};
use sr_primitives::Perbill; use sr_primitives::Perbill;
const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/"; const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
+10 -9
View File
@@ -47,7 +47,7 @@ use elections::VoteIndex;
use version::NativeVersion; use version::NativeVersion;
use primitives::OpaqueMetadata; use primitives::OpaqueMetadata;
use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight}; use grandpa::{AuthorityId as GrandpaId, AuthorityWeight as GrandpaWeight};
use im_online::{AuthorityId as ImOnlineId}; use im_online::sr25519::{AuthorityId as ImOnlineId};
#[cfg(any(feature = "std", test))] #[cfg(any(feature = "std", test))]
pub use sr_primitives::BuildStorage; pub use sr_primitives::BuildStorage;
@@ -79,7 +79,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// and set impl_version to equal spec_version. If only runtime // and set impl_version to equal spec_version. If only runtime
// implementation changes and behavior does not, then leave spec_version as // implementation changes and behavior does not, then leave spec_version as
// is and increment impl_version. // is and increment impl_version.
spec_version: 153, spec_version: 154,
impl_version: 154, impl_version: 154,
apis: RUNTIME_API_VERSIONS, apis: RUNTIME_API_VERSIONS,
}; };
@@ -393,6 +393,7 @@ impl sudo::Trait for Runtime {
} }
impl im_online::Trait for Runtime { impl im_online::Trait for Runtime {
type AuthorityId = ImOnlineId;
type Call = Call; type Call = Call;
type Event = Event; type Event = Event;
type UncheckedExtrinsic = UncheckedExtrinsic; type UncheckedExtrinsic = UncheckedExtrinsic;
@@ -447,8 +448,8 @@ construct_runtime!(
Treasury: treasury::{Module, Call, Storage, Event<T>}, Treasury: treasury::{Module, Call, Storage, Event<T>},
Contracts: contracts, Contracts: contracts,
Sudo: sudo, Sudo: sudo,
ImOnline: im_online::{Module, Call, Storage, Event, ValidateUnsigned, Config}, ImOnline: im_online::{Module, Call, Storage, Event<T>, ValidateUnsigned, Config<T>},
AuthorityDiscovery: authority_discovery::{Module, Call, Config}, AuthorityDiscovery: authority_discovery::{Module, Call, Config<T>},
Offences: offences::{Module, Call, Storage, Event}, Offences: offences::{Module, Call, Storage, Event},
} }
); );
@@ -578,19 +579,19 @@ impl_runtime_apis! {
} }
} }
impl authority_discovery_primitives::AuthorityDiscoveryApi<Block, im_online::AuthorityId> for Runtime { impl authority_discovery_primitives::AuthorityDiscoveryApi<Block, ImOnlineId> for Runtime {
fn authority_id() -> Option<im_online::AuthorityId> { fn authority_id() -> Option<ImOnlineId> {
AuthorityDiscovery::authority_id() AuthorityDiscovery::authority_id()
} }
fn authorities() -> Vec<im_online::AuthorityId> { fn authorities() -> Vec<ImOnlineId> {
AuthorityDiscovery::authorities() AuthorityDiscovery::authorities()
} }
fn sign(payload: Vec<u8>, authority_id: im_online::AuthorityId) -> Option<Vec<u8>> { fn sign(payload: Vec<u8>, authority_id: ImOnlineId) -> Option<Vec<u8>> {
AuthorityDiscovery::sign(payload, authority_id) AuthorityDiscovery::sign(payload, authority_id)
} }
fn verify(payload: Vec<u8>, signature: Vec<u8>, public_key: im_online::AuthorityId) -> bool { fn verify(payload: Vec<u8>, signature: Vec<u8>, public_key: ImOnlineId) -> bool {
AuthorityDiscovery::verify(payload, signature, public_key) AuthorityDiscovery::verify(payload, signature, public_key)
} }
} }
@@ -17,6 +17,9 @@ srml-support = { path = "../support", default-features = false }
sr-io = { package = "sr-io", path = "../../core/sr-io", default-features = false } sr-io = { package = "sr-io", path = "../../core/sr-io", default-features = false }
system = { package = "srml-system", path = "../system", default-features = false } system = { package = "srml-system", path = "../system", default-features = false }
[dev-dependencies]
sr-staking-primitives = { path = "../../core/sr-staking-primitives", default-features = false }
[features] [features]
default = ["std"] default = ["std"]
std = [ std = [
+63 -36
View File
@@ -33,18 +33,20 @@ use codec::{Decode, Encode};
use rstd::prelude::*; use rstd::prelude::*;
use srml_support::{decl_module, decl_storage, StorageValue}; use srml_support::{decl_module, decl_storage, StorageValue};
pub trait Trait: system::Trait + session::Trait {} pub trait Trait: system::Trait + session::Trait + im_online::Trait {}
type AuthorityIdFor<T> = <T as im_online::Trait>::AuthorityId;
decl_storage! { decl_storage! {
trait Store for Module<T: Trait> as AuthorityDiscovery { trait Store for Module<T: Trait> as AuthorityDiscovery {
/// The current set of keys that may issue a heartbeat. /// The current set of keys that may issue a heartbeat.
Keys get(keys): Vec<im_online::AuthorityId>; Keys get(keys): Vec<AuthorityIdFor<T>>;
} }
add_extra_genesis { add_extra_genesis {
config(keys): Vec<im_online::AuthorityId>; config(keys): Vec<AuthorityIdFor<T>>;
build(| build(|
storage: &mut (sr_primitives::StorageOverlay, sr_primitives::ChildrenStorageOverlay), storage: &mut (sr_primitives::StorageOverlay, sr_primitives::ChildrenStorageOverlay),
config: &GenesisConfig config: &GenesisConfig<T>,
| { | {
sr_io::with_storage( sr_io::with_storage(
storage, storage,
@@ -64,10 +66,10 @@ impl<T: Trait> Module<T> {
/// set, otherwise this function returns None. The restriction might be /// set, otherwise this function returns None. The restriction might be
/// softened in the future in case a consumer needs to learn own authority /// softened in the future in case a consumer needs to learn own authority
/// identifier. /// identifier.
pub fn authority_id() -> Option<im_online::AuthorityId> { pub fn authority_id() -> Option<AuthorityIdFor<T>> {
let authorities = Keys::get(); let authorities = Keys::<T>::get();
let local_keys = im_online::AuthorityId::all(); let local_keys = <AuthorityIdFor<T>>::all();
authorities.into_iter().find_map(|authority| { authorities.into_iter().find_map(|authority| {
if local_keys.contains(&authority) { if local_keys.contains(&authority) {
@@ -79,12 +81,12 @@ impl<T: Trait> Module<T> {
} }
/// Retrieve authority identifiers of the current authority set. /// Retrieve authority identifiers of the current authority set.
pub fn authorities() -> Vec<im_online::AuthorityId> { pub fn authorities() -> Vec<AuthorityIdFor<T>> {
Keys::get() Keys::<T>::get()
} }
/// Sign the given payload with the private key corresponding to the given authority id. /// Sign the given payload with the private key corresponding to the given authority id.
pub fn sign(payload: Vec<u8>, authority_id: im_online::AuthorityId) -> Option<Vec<u8>> { pub fn sign(payload: Vec<u8>, authority_id: AuthorityIdFor<T>) -> Option<Vec<u8>> {
authority_id.sign(&payload).map(|s| s.encode()) authority_id.sign(&payload).map(|s| s.encode())
} }
@@ -93,27 +95,27 @@ impl<T: Trait> Module<T> {
pub fn verify( pub fn verify(
payload: Vec<u8>, payload: Vec<u8>,
signature: Vec<u8>, signature: Vec<u8>,
authority_id: im_online::AuthorityId, authority_id: AuthorityIdFor<T>,
) -> bool { ) -> bool {
im_online::AuthoritySignature::decode(&mut &signature[..]) <AuthorityIdFor<T> as RuntimeAppPublic>::Signature::decode(&mut &signature[..])
.map(|s| authority_id.verify(&payload, &s)) .map(|s| authority_id.verify(&payload, &s))
.unwrap_or(false) .unwrap_or(false)
} }
fn initialize_keys(keys: &[im_online::AuthorityId]) { fn initialize_keys(keys: &[AuthorityIdFor<T>]) {
if !keys.is_empty() { if !keys.is_empty() {
assert!(Keys::get().is_empty(), "Keys are already initialized!"); assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::put_ref(keys); Keys::<T>::put_ref(keys);
} }
} }
} }
impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> { impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> {
type Key = im_online::AuthorityId; type Key = AuthorityIdFor<T>;
fn on_genesis_session<'a, I: 'a>(validators: I) fn on_genesis_session<'a, I: 'a>(validators: I)
where where
I: Iterator<Item = (&'a T::AccountId, im_online::AuthorityId)>, I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{ {
let keys = validators.map(|x| x.1).collect::<Vec<_>>(); let keys = validators.map(|x| x.1).collect::<Vec<_>>();
Self::initialize_keys(&keys); Self::initialize_keys(&keys);
@@ -121,10 +123,10 @@ impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> {
fn on_new_session<'a, I: 'a>(_changed: bool, _validators: I, next_validators: I) fn on_new_session<'a, I: 'a>(_changed: bool, _validators: I, next_validators: I)
where where
I: Iterator<Item = (&'a T::AccountId, im_online::AuthorityId)>, I: Iterator<Item = (&'a T::AccountId, Self::Key)>,
{ {
// Remember who the authorities are for the new session. // Remember who the authorities are for the new session.
Keys::put(next_validators.map(|x| x.1).collect::<Vec<_>>()); Keys::<T>::put(next_validators.map(|x| x.1).collect::<Vec<_>>());
} }
fn on_disabled(_i: usize) { fn on_disabled(_i: usize) {
@@ -139,9 +141,11 @@ mod tests {
use primitives::testing::KeyStore; use primitives::testing::KeyStore;
use primitives::{crypto::key_types, sr25519, traits::BareCryptoStore, H256}; use primitives::{crypto::key_types, sr25519, traits::BareCryptoStore, H256};
use sr_io::{with_externalities, TestExternalities}; use sr_io::{with_externalities, TestExternalities};
use sr_primitives::generic::UncheckedExtrinsic;
use sr_primitives::testing::{Header, UintAuthorityId}; use sr_primitives::testing::{Header, UintAuthorityId};
use sr_primitives::traits::{ConvertInto, IdentityLookup, OpaqueKeys}; use sr_primitives::traits::{ConvertInto, IdentityLookup, OpaqueKeys};
use sr_primitives::Perbill; use sr_primitives::Perbill;
use sr_staking_primitives::CurrentElectedSet;
use srml_support::{impl_outer_origin, parameter_types}; use srml_support::{impl_outer_origin, parameter_types};
type AuthorityDiscovery = Module<Test>; type AuthorityDiscovery = Module<Test>;
@@ -151,12 +155,21 @@ mod tests {
pub struct Test; pub struct Test;
impl Trait for Test {} impl Trait for Test {}
type AuthorityId = im_online::sr25519::AuthorityId;
pub struct DummyCurrentElectedSet<T>(std::marker::PhantomData<T>);
impl<T> CurrentElectedSet<T> for DummyCurrentElectedSet<T> {
fn current_elected_set() -> Vec<T> {
vec![]
}
}
pub struct TestOnSessionEnding; pub struct TestOnSessionEnding;
impl session::OnSessionEnding<im_online::AuthorityId> for TestOnSessionEnding { impl session::OnSessionEnding<AuthorityId> for TestOnSessionEnding {
fn on_session_ending( fn on_session_ending(
_: SessionIndex, _: SessionIndex,
_: SessionIndex, _: SessionIndex,
) -> Option<Vec<im_online::AuthorityId>> { ) -> Option<Vec<AuthorityId>> {
None None
} }
} }
@@ -167,11 +180,25 @@ mod tests {
type ShouldEndSession = session::PeriodicSessions<Period, Offset>; type ShouldEndSession = session::PeriodicSessions<Period, Offset>;
type SessionHandler = TestSessionHandler; type SessionHandler = TestSessionHandler;
type Event = (); type Event = ();
type ValidatorId = im_online::AuthorityId; type ValidatorId = AuthorityId;
type ValidatorIdOf = ConvertInto; type ValidatorIdOf = ConvertInto;
type SelectInitialValidators = (); type SelectInitialValidators = ();
} }
impl session::historical::Trait for Test {
type FullIdentification = ();
type FullIdentificationOf = ();
}
impl im_online::Trait for Test {
type AuthorityId = AuthorityId;
type Call = im_online::Call<Test>;
type Event = ();
type UncheckedExtrinsic = UncheckedExtrinsic<(), im_online::Call<Test>, (), ()>;
type ReportUnresponsiveness = ();
type CurrentElectedSet = DummyCurrentElectedSet<AuthorityId>;
}
pub type BlockNumber = u64; pub type BlockNumber = u64;
parameter_types! { parameter_types! {
@@ -191,7 +218,7 @@ mod tests {
type Call = (); type Call = ();
type Hash = H256; type Hash = H256;
type Hashing = ::sr_primitives::traits::BlakeTwo256; type Hashing = ::sr_primitives::traits::BlakeTwo256;
type AccountId = im_online::AuthorityId; type AccountId = AuthorityId;
type Lookup = IdentityLookup<Self::AccountId>; type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header; type Header = Header;
type WeightMultiplierUpdate = (); type WeightMultiplierUpdate = ();
@@ -208,17 +235,17 @@ mod tests {
} }
pub struct TestSessionHandler; pub struct TestSessionHandler;
impl session::SessionHandler<im_online::AuthorityId> for TestSessionHandler { impl session::SessionHandler<AuthorityId> for TestSessionHandler {
fn on_new_session<Ks: OpaqueKeys>( fn on_new_session<Ks: OpaqueKeys>(
_changed: bool, _changed: bool,
_validators: &[(im_online::AuthorityId, Ks)], _validators: &[(AuthorityId, Ks)],
_queued_validators: &[(im_online::AuthorityId, Ks)], _queued_validators: &[(AuthorityId, Ks)],
) { ) {
} }
fn on_disabled(_validator_index: usize) {} fn on_disabled(_validator_index: usize) {}
fn on_genesis_session<Ks: OpaqueKeys>(_validators: &[(im_online::AuthorityId, Ks)]) {} fn on_genesis_session<Ks: OpaqueKeys>(_validators: &[(AuthorityId, Ks)]) {}
} }
#[test] #[test]
@@ -236,17 +263,17 @@ mod tests {
.sr25519_public_keys(key_types::IM_ONLINE) .sr25519_public_keys(key_types::IM_ONLINE)
.pop() .pop()
.unwrap(); .unwrap();
let authority_id = im_online::AuthorityId::from(public_key); let authority_id = AuthorityId::from(public_key);
// Build genesis. // Build genesis.
let mut t = system::GenesisConfig::default() let mut t = system::GenesisConfig::default()
.build_storage::<Test>() .build_storage::<Test>()
.unwrap(); .unwrap();
GenesisConfig { GenesisConfig::<Test> {
keys: vec![authority_id.clone()], keys: vec![authority_id.clone()],
} }
.assimilate_storage::<Test>(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
// Create externalities. // Create externalities.
@@ -279,11 +306,11 @@ mod tests {
let keys = vec![(); 5] let keys = vec![(); 5]
.iter() .iter()
.map(|_x| sr25519::Pair::generate_with_phrase(None).0.public()) .map(|_x| sr25519::Pair::generate_with_phrase(None).0.public())
.map(im_online::AuthorityId::from) .map(AuthorityId::from)
.collect(); .collect();
GenesisConfig { keys: keys } GenesisConfig::<Test> { keys: keys }
.assimilate_storage::<Test>(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
// Create externalities. // Create externalities.
@@ -310,17 +337,17 @@ mod tests {
.sr25519_public_keys(key_types::IM_ONLINE) .sr25519_public_keys(key_types::IM_ONLINE)
.pop() .pop()
.unwrap(); .unwrap();
let authority_id = im_online::AuthorityId::from(public_key); let authority_id = AuthorityId::from(public_key);
// Build genesis. // Build genesis.
let mut t = system::GenesisConfig::default() let mut t = system::GenesisConfig::default()
.build_storage::<Test>() .build_storage::<Test>()
.unwrap(); .unwrap();
GenesisConfig { GenesisConfig::<Test> {
keys: vec![authority_id.clone()], keys: vec![authority_id.clone()],
} }
.assimilate_storage::<Test>(&mut t) .assimilate_storage(&mut t)
.unwrap(); .unwrap();
// Create externalities. // Create externalities.
+59 -38
View File
@@ -67,7 +67,7 @@
// Ensure we're `no_std` when compiling for Wasm. // Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
use app_crypto::RuntimeAppPublic; use app_crypto::{AppPublic, RuntimeAppPublic};
use codec::{Encode, Decode}; use codec::{Encode, Decode};
use primitives::offchain::{OpaqueNetworkState, StorageKind}; use primitives::offchain::{OpaqueNetworkState, StorageKind};
use rstd::prelude::*; use rstd::prelude::*;
@@ -75,7 +75,7 @@ use session::historical::IdentificationTuple;
use sr_io::Printable; use sr_io::Printable;
use sr_primitives::{ use sr_primitives::{
Perbill, ApplyError, Perbill, ApplyError,
traits::{Extrinsic as ExtrinsicT, Convert}, traits::{Convert, Extrinsic as ExtrinsicT, Member},
transaction_validity::{TransactionValidity, TransactionLongevity, ValidTransaction}, transaction_validity::{TransactionValidity, TransactionLongevity, ValidTransaction},
}; };
use sr_staking_primitives::{ use sr_staking_primitives::{
@@ -83,28 +83,44 @@ use sr_staking_primitives::{
offence::{ReportOffence, Offence, Kind}, offence::{ReportOffence, Offence, Kind},
}; };
use srml_support::{ use srml_support::{
StorageValue, decl_module, decl_event, decl_storage, StorageDoubleMap, print, ensure decl_module, decl_event, decl_storage, print, ensure,
Parameter, StorageValue, StorageDoubleMap,
}; };
use system::ensure_none; use system::ensure_none;
mod app { pub mod sr25519 {
pub use app_crypto::sr25519 as crypto; mod app_sr25519 {
use app_crypto::{app_crypto, key_types::IM_ONLINE, sr25519}; use app_crypto::{app_crypto, key_types::IM_ONLINE, sr25519};
app_crypto!(sr25519, IM_ONLINE);
}
app_crypto!(sr25519, IM_ONLINE); /// An i'm online keypair using sr25519 as its crypto.
#[cfg(feature = "std")]
pub type AuthorityPair = app_sr25519::Pair;
/// An i'm online signature using sr25519 as its crypto.
pub type AuthoritySignature = app_sr25519::Signature;
/// An i'm online identifier using sr25519 as its crypto.
pub type AuthorityId = app_sr25519::Public;
} }
/// A Babe authority keypair. Necessarily equivalent to the schnorrkel public key used in pub mod ed25519 {
/// the main Babe module. If that ever changes, then this must, too. mod app_ed25519 {
#[cfg(feature = "std")] use app_crypto::{app_crypto, key_types::IM_ONLINE, ed25519};
pub type AuthorityPair = app::Pair; app_crypto!(ed25519, IM_ONLINE);
}
/// A Babe authority signature. /// An i'm online keypair using ed25519 as its crypto.
pub type AuthoritySignature = app::Signature; #[cfg(feature = "std")]
pub type AuthorityPair = app_ed25519::Pair;
/// A Babe authority identifier. Necessarily equivalent to the schnorrkel public key used in /// An i'm online signature using ed25519 as its crypto.
/// the main Babe module. If that ever changes, then this must, too. pub type AuthoritySignature = app_ed25519::Signature;
pub type AuthorityId = app::Public;
/// An i'm online identifier using ed25519 as its crypto.
pub type AuthorityId = app_ed25519::Public;
}
// The local storage database key under which the worker progress status // The local storage database key under which the worker progress status
// is tracked. // is tracked.
@@ -158,10 +174,13 @@ pub struct Heartbeat<BlockNumber>
} }
pub trait Trait: system::Trait + session::historical::Trait { pub trait Trait: system::Trait + session::historical::Trait {
/// The overarching event type. /// The identifier type for an authority.
type Event: From<Event> + Into<<Self as system::Trait>::Event>; type AuthorityId: Member + Parameter + AppPublic + RuntimeAppPublic + Default;
/// The function call. /// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
/// A dispatchable call type.
type Call: From<Call<Self>>; type Call: From<Call<Self>>;
/// A extrinsic right from the external world. This is unchecked and so /// A extrinsic right from the external world. This is unchecked and so
@@ -181,7 +200,9 @@ pub trait Trait: system::Trait + session::historical::Trait {
} }
decl_event!( decl_event!(
pub enum Event { pub enum Event<T> where
<T as Trait>::AuthorityId,
{
/// A new heartbeat was received from `AuthorityId` /// A new heartbeat was received from `AuthorityId`
HeartbeatReceived(AuthorityId), HeartbeatReceived(AuthorityId),
} }
@@ -193,7 +214,7 @@ decl_storage! {
GossipAt get(gossip_at): T::BlockNumber; GossipAt get(gossip_at): T::BlockNumber;
/// The current set of keys that may issue a heartbeat. /// The current set of keys that may issue a heartbeat.
Keys get(keys): Vec<AuthorityId>; Keys get(keys): Vec<T::AuthorityId>;
/// For each session index we keep a mapping of `AuthorityId` /// For each session index we keep a mapping of `AuthorityId`
/// to `offchain::OpaqueNetworkState`. /// to `offchain::OpaqueNetworkState`.
@@ -201,10 +222,10 @@ decl_storage! {
blake2_256(AuthIndex) => Vec<u8>; blake2_256(AuthIndex) => Vec<u8>;
} }
add_extra_genesis { add_extra_genesis {
config(keys): Vec<AuthorityId>; config(keys): Vec<T::AuthorityId>;
build(| build(|
storage: &mut (sr_primitives::StorageOverlay, sr_primitives::ChildrenStorageOverlay), storage: &mut (sr_primitives::StorageOverlay, sr_primitives::ChildrenStorageOverlay),
config: &GenesisConfig config: &GenesisConfig<T>
| { | {
sr_io::with_storage( sr_io::with_storage(
storage, storage,
@@ -217,12 +238,12 @@ decl_storage! {
decl_module! { decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin { pub struct Module<T: Trait> for enum Call where origin: T::Origin {
fn deposit_event() = default; fn deposit_event<T>() = default;
fn heartbeat( fn heartbeat(
origin, origin,
heartbeat: Heartbeat<T::BlockNumber>, heartbeat: Heartbeat<T::BlockNumber>,
signature: AuthoritySignature signature: <T::AuthorityId as RuntimeAppPublic>::Signature
) { ) {
ensure_none(origin)?; ensure_none(origin)?;
@@ -232,7 +253,7 @@ decl_module! {
&current_session, &current_session,
&heartbeat.authority_index &heartbeat.authority_index
); );
let keys = Keys::get(); let keys = Keys::<T>::get();
let public = keys.get(heartbeat.authority_index as usize); let public = keys.get(heartbeat.authority_index as usize);
if let (true, Some(public)) = (!exists, public) { if let (true, Some(public)) = (!exists, public) {
let signature_valid = heartbeat.using_encoded(|encoded_heartbeat| { let signature_valid = heartbeat.using_encoded(|encoded_heartbeat| {
@@ -240,7 +261,7 @@ decl_module! {
}); });
ensure!(signature_valid, "Invalid heartbeat signature."); ensure!(signature_valid, "Invalid heartbeat signature.");
Self::deposit_event(Event::HeartbeatReceived(public.clone())); Self::deposit_event(Event::<T>::HeartbeatReceived(public.clone()));
let network_state = heartbeat.network_state.encode(); let network_state = heartbeat.network_state.encode();
<ReceivedHeartbeats>::insert( <ReceivedHeartbeats>::insert(
@@ -297,8 +318,8 @@ impl<T: Trait> Module<T> {
fn do_gossip_at(block_number: T::BlockNumber) -> Result<(), OffchainErr> { fn do_gossip_at(block_number: T::BlockNumber) -> Result<(), OffchainErr> {
// we run only when a local authority key is configured // we run only when a local authority key is configured
let authorities = Keys::get(); let authorities = Keys::<T>::get();
let mut local_keys = app::Public::all(); let mut local_keys = T::AuthorityId::all();
local_keys.sort(); local_keys.sort();
for (authority_index, key) in authorities.into_iter() for (authority_index, key) in authorities.into_iter()
@@ -389,27 +410,27 @@ impl<T: Trait> Module<T> {
} }
} }
fn initialize_keys(keys: &[AuthorityId]) { fn initialize_keys(keys: &[T::AuthorityId]) {
if !keys.is_empty() { if !keys.is_empty() {
assert!(Keys::get().is_empty(), "Keys are already initialized!"); assert!(Keys::<T>::get().is_empty(), "Keys are already initialized!");
Keys::put_ref(keys); Keys::<T>::put_ref(keys);
} }
} }
} }
impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> { impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> {
type Key = AuthorityId; type Key = T::AuthorityId;
fn on_genesis_session<'a, I: 'a>(validators: I) fn on_genesis_session<'a, I: 'a>(validators: I)
where I: Iterator<Item=(&'a T::AccountId, AuthorityId)> where I: Iterator<Item=(&'a T::AccountId, T::AuthorityId)>
{ {
let keys = validators.map(|x| x.1).collect::<Vec<_>>(); let keys = validators.map(|x| x.1).collect::<Vec<_>>();
Self::initialize_keys(&keys); Self::initialize_keys(&keys);
} }
fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, _queued_validators: I) fn on_new_session<'a, I: 'a>(_changed: bool, validators: I, _queued_validators: I)
where I: Iterator<Item=(&'a T::AccountId, AuthorityId)> where I: Iterator<Item=(&'a T::AccountId, T::AuthorityId)>
{ {
// Reset heartbeats // Reset heartbeats
<ReceivedHeartbeats>::remove_prefix(&<session::Module<T>>::current_index()); <ReceivedHeartbeats>::remove_prefix(&<session::Module<T>>::current_index());
@@ -418,7 +439,7 @@ impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> {
<GossipAt<T>>::put(<system::Module<T>>::block_number()); <GossipAt<T>>::put(<system::Module<T>>::block_number());
// Remember who the authorities are for the new session. // Remember who the authorities are for the new session.
Keys::put(validators.map(|x| x.1).collect::<Vec<_>>()); Keys::<T>::put(validators.map(|x| x.1).collect::<Vec<_>>());
} }
fn on_before_session_ending() { fn on_before_session_ending() {
@@ -426,7 +447,7 @@ impl<T: Trait> session::OneSessionHandler<T::AccountId> for Module<T> {
let current_session = <session::Module<T>>::current_index(); let current_session = <session::Module<T>>::current_index();
let keys = Keys::get(); let keys = Keys::<T>::get();
let current_elected = T::CurrentElectedSet::current_elected_set(); let current_elected = T::CurrentElectedSet::current_elected_set();
// The invariant is that these two are of the same length. // The invariant is that these two are of the same length.
@@ -481,7 +502,7 @@ impl<T: Trait> srml_support::unsigned::ValidateUnsigned for Module<T> {
} }
// verify that the incoming (unverified) pubkey is actually an authority id // verify that the incoming (unverified) pubkey is actually an authority id
let keys = Keys::get(); let keys = Keys::<T>::get();
let authority_id = match keys.get(heartbeat.authority_index as usize) { let authority_id = match keys.get(heartbeat.authority_index as usize) {
Some(id) => id, Some(id) => id,
None => return TransactionValidity::Invalid(ApplyError::BadSignature as i8), None => return TransactionValidity::Invalid(ApplyError::BadSignature as i8),