Make AuthorityId generic (#1296)

* BlockAuthorityId convenience type

* Rename AuthorityId -> Ed25519AuthorityId to make it more precise

* Generalize AuthorityId up to substrate-client

* Fix in client-db

* rename: BlockAuthorityId -> AuthorityIdFor

* typo: should be digest item

* Fix test-runtime authorityId mismatch

One states that AuthorityId is u64 while the other states that it's Ed25519AuthorityId.

* Fix more u64 - Ed25519AuthorityId mismatch

* Fix compile of most of the srml modules

* Continue to pin aura and grandpa with ed25519 and fix compile

* Add MaybeHash trait

* Fix node-runtime compile

* Fix network tests
This commit is contained in:
Wei Tang
2019-01-08 11:14:18 +01:00
committed by Benjamin Kampmann
parent 043831cfb0
commit 71d889b692
46 changed files with 234 additions and 216 deletions
@@ -26,8 +26,8 @@ use client::{self, error, Client as SubstrateClient, CallExecutor};
use client::{block_builder::api::BlockBuilder as BlockBuilderApi, runtime_api::Core}; use client::{block_builder::api::BlockBuilder as BlockBuilderApi, runtime_api::Core};
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use consensus_common::{self, evaluation}; use consensus_common::{self, evaluation};
use primitives::{H256, AuthorityId, ed25519, Blake2Hasher}; use primitives::{H256, Ed25519AuthorityId, ed25519, Blake2Hasher};
use runtime_primitives::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi}; use runtime_primitives::traits::{Block as BlockT, Hash as HashT, Header as HeaderT, ProvideRuntimeApi, AuthorityIdFor};
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::BasicInherentData; use runtime_primitives::BasicInherentData;
use transaction_pool::txpool::{self, Pool as TransactionPool}; use transaction_pool::txpool::{self, Pool as TransactionPool};
@@ -125,8 +125,7 @@ impl<C, A, ConsensusData> consensus_common::Environment<<C as AuthoringApi>::Blo
fn init( fn init(
&self, &self,
parent_header: &<<C as AuthoringApi>::Block as BlockT>::Header, parent_header: &<<C as AuthoringApi>::Block as BlockT>::Header,
_: &[AuthorityId], _: &[AuthorityIdFor<<C as AuthoringApi>::Block>],
_: Arc<ed25519::Pair>,
) -> Result<Self::Proposer, error::Error> { ) -> Result<Self::Proposer, error::Error> {
let parent_hash = parent_header.hash(); let parent_hash = parent_header.hash();
+6 -7
View File
@@ -24,9 +24,8 @@ use kvdb::{KeyValueDB, DBTransaction};
use client::blockchain::Cache as BlockchainCache; use client::blockchain::Cache as BlockchainCache;
use client::error::Result as ClientResult; use client::error::Result as ClientResult;
use codec::{Encode, Decode}; use codec::{Encode, Decode};
use primitives::AuthorityId;
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, As}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, As, AuthorityIdFor};
use utils::{self, COLUMN_META}; use utils::{self, COLUMN_META};
use self::list_cache::ListCache; use self::list_cache::ListCache;
@@ -65,7 +64,7 @@ impl<T> CacheItemT for T where T: Clone + Decode + Encode + PartialEq {}
/// Database-backed blockchain data cache. /// Database-backed blockchain data cache.
pub struct DbCache<Block: BlockT> { pub struct DbCache<Block: BlockT> {
authorities_at: ListCache<Block, Vec<AuthorityId>, self::list_storage::DbStorage>, authorities_at: ListCache<Block, Vec<AuthorityIdFor<Block>>, self::list_storage::DbStorage>,
} }
impl<Block: BlockT> DbCache<Block> { impl<Block: BlockT> DbCache<Block> {
@@ -112,14 +111,14 @@ impl<Block: BlockT> DbCache<Block> {
/// Cache operations that are to be committed after database transaction is committed. /// Cache operations that are to be committed after database transaction is committed.
pub struct DbCacheTransactionOps<Block: BlockT> { pub struct DbCacheTransactionOps<Block: BlockT> {
authorities_at_op: Option<self::list_cache::CommitOperation<Block, Vec<AuthorityId>>>, authorities_at_op: Option<self::list_cache::CommitOperation<Block, Vec<AuthorityIdFor<Block>>>>,
} }
/// Database-backed blockchain data cache transaction valid for single block import. /// Database-backed blockchain data cache transaction valid for single block import.
pub struct DbCacheTransaction<'a, Block: BlockT> { pub struct DbCacheTransaction<'a, Block: BlockT> {
cache: &'a mut DbCache<Block>, cache: &'a mut DbCache<Block>,
tx: &'a mut DBTransaction, tx: &'a mut DBTransaction,
authorities_at_op: Option<self::list_cache::CommitOperation<Block, Vec<AuthorityId>>>, authorities_at_op: Option<self::list_cache::CommitOperation<Block, Vec<AuthorityIdFor<Block>>>>,
} }
impl<'a, Block: BlockT> DbCacheTransaction<'a, Block> { impl<'a, Block: BlockT> DbCacheTransaction<'a, Block> {
@@ -135,7 +134,7 @@ impl<'a, Block: BlockT> DbCacheTransaction<'a, Block> {
mut self, mut self,
parent: ComplexBlockId<Block>, parent: ComplexBlockId<Block>,
block: ComplexBlockId<Block>, block: ComplexBlockId<Block>,
authorities_at: Option<Vec<AuthorityId>>, authorities_at: Option<Vec<AuthorityIdFor<Block>>>,
is_final: bool, is_final: bool,
) -> ClientResult<Self> { ) -> ClientResult<Self> {
assert!(self.authorities_at_op.is_none()); assert!(self.authorities_at_op.is_none());
@@ -179,7 +178,7 @@ impl<'a, Block: BlockT> DbCacheTransaction<'a, Block> {
pub struct DbCacheSync<Block: BlockT>(pub RwLock<DbCache<Block>>); pub struct DbCacheSync<Block: BlockT>(pub RwLock<DbCache<Block>>);
impl<Block: BlockT> BlockchainCache<Block> for DbCacheSync<Block> { impl<Block: BlockT> BlockchainCache<Block> for DbCacheSync<Block> {
fn authorities_at(&self, at: BlockId<Block>) -> Option<Vec<AuthorityId>> { fn authorities_at(&self, at: BlockId<Block>) -> Option<Vec<AuthorityIdFor<Block>>> {
let cache = self.0.read(); let cache = self.0.read();
let storage = cache.authorities_at.storage(); let storage = cache.authorities_at.storage();
let db = storage.db(); let db = storage.db();
+3 -3
View File
@@ -64,10 +64,10 @@ use hash_db::Hasher;
use kvdb::{KeyValueDB, DBTransaction}; use kvdb::{KeyValueDB, DBTransaction};
use trie::MemoryDB; use trie::MemoryDB;
use parking_lot::RwLock; use parking_lot::RwLock;
use primitives::{H256, AuthorityId, Blake2Hasher, ChangesTrieConfiguration, convert_hash}; use primitives::{H256, Blake2Hasher, ChangesTrieConfiguration, convert_hash};
use primitives::storage::well_known_keys; use primitives::storage::well_known_keys;
use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap}; use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, As, NumberFor, Zero, Digest, DigestItem}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, As, NumberFor, Zero, Digest, DigestItem, AuthorityIdFor};
use runtime_primitives::BuildStorage; use runtime_primitives::BuildStorage;
use state_machine::backend::Backend as StateBackend; use state_machine::backend::Backend as StateBackend;
use executor::RuntimeInfo; use executor::RuntimeInfo;
@@ -315,7 +315,7 @@ where Block: BlockT<Hash=H256>,
Ok(()) Ok(())
} }
fn update_authorities(&mut self, _authorities: Vec<AuthorityId>) { fn update_authorities(&mut self, _authorities: Vec<AuthorityIdFor<Block>>) {
// currently authorities are not cached on full nodes // currently authorities are not cached on full nodes
} }
+7 -7
View File
@@ -28,10 +28,10 @@ use client::{cht, LeafSet};
use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult}; use client::error::{ErrorKind as ClientErrorKind, Result as ClientResult};
use client::light::blockchain::Storage as LightBlockchainStorage; use client::light::blockchain::Storage as LightBlockchainStorage;
use codec::{Decode, Encode}; use codec::{Decode, Encode};
use primitives::{AuthorityId, Blake2Hasher}; use primitives::Blake2Hasher;
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, use runtime_primitives::traits::{Block as BlockT, Header as HeaderT,
Zero, One, As, NumberFor, Digest, DigestItem}; Zero, One, As, NumberFor, Digest, DigestItem, AuthorityIdFor};
use cache::{DbCacheSync, DbCache, ComplexBlockId}; use cache::{DbCacheSync, DbCache, ComplexBlockId};
use utils::{meta_keys, Meta, db_err, open_database, use utils::{meta_keys, Meta, db_err, open_database,
read_db, block_id_to_lookup_key, read_meta}; read_db, block_id_to_lookup_key, read_meta};
@@ -306,7 +306,7 @@ impl<Block> LightBlockchainStorage<Block> for LightStorage<Block>
fn import_header( fn import_header(
&self, &self,
header: Block::Header, header: Block::Header,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
leaf_state: NewBlockState, leaf_state: NewBlockState,
aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>, aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
) -> ClientResult<()> { ) -> ClientResult<()> {
@@ -510,7 +510,7 @@ pub(crate) mod tests {
pub fn insert_block<F: Fn() -> Header>( pub fn insert_block<F: Fn() -> Header>(
db: &LightStorage<Block>, db: &LightStorage<Block>,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
header: F, header: F,
) -> Hash { ) -> Hash {
let header = header(); let header = header();
@@ -521,7 +521,7 @@ pub(crate) mod tests {
fn insert_final_block<F: Fn() -> Header>( fn insert_final_block<F: Fn() -> Header>(
db: &LightStorage<Block>, db: &LightStorage<Block>,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
header: F, header: F,
) -> Hash { ) -> Hash {
let header = header(); let header = header();
@@ -532,7 +532,7 @@ pub(crate) mod tests {
fn insert_non_best_block<F: Fn() -> Header>( fn insert_non_best_block<F: Fn() -> Header>(
db: &LightStorage<Block>, db: &LightStorage<Block>,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
header: F, header: F,
) -> Hash { ) -> Hash {
let header = header(); let header = header();
@@ -762,7 +762,7 @@ pub(crate) mod tests {
fn authorites_are_cached() { fn authorites_are_cached() {
let db = LightStorage::new_test(); let db = LightStorage::new_test();
fn run_checks(db: &LightStorage<Block>, max: u64, checks: &[(u64, Option<Vec<AuthorityId>>)]) { fn run_checks(db: &LightStorage<Block>, max: u64, checks: &[(u64, Option<Vec<AuthorityIdFor<Block>>>)]) {
for (at, expected) in checks.iter().take_while(|(at, _)| *at <= max) { for (at, expected) in checks.iter().take_while(|(at, _)| *at <= max) {
let actual = db.cache().authorities_at(BlockId::Number(*at)); let actual = db.cache().authorities_at(BlockId::Number(*at));
assert_eq!(*expected, actual); assert_eq!(*expected, actual);
+2 -3
View File
@@ -17,9 +17,8 @@
//! Substrate Client data backend //! Substrate Client data backend
use error; use error;
use primitives::AuthorityId;
use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap}; use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap};
use runtime_primitives::traits::{Block as BlockT, NumberFor}; use runtime_primitives::traits::{AuthorityIdFor, Block as BlockT, NumberFor};
use state_machine::backend::Backend as StateBackend; use state_machine::backend::Backend as StateBackend;
use state_machine::ChangesTrieStorage as StateChangesTrieStorage; use state_machine::ChangesTrieStorage as StateChangesTrieStorage;
use hash_db::Hasher; use hash_db::Hasher;
@@ -67,7 +66,7 @@ pub trait BlockImportOperation<Block, H> where
/// Append authorities set to the transaction. This is a set of parent block (set which /// Append authorities set to the transaction. This is a set of parent block (set which
/// has been used to check justification of this block). /// has been used to check justification of this block).
fn update_authorities(&mut self, authorities: Vec<AuthorityId>); fn update_authorities(&mut self, authorities: Vec<AuthorityIdFor<Block>>);
/// Inject storage data into the database. /// Inject storage data into the database.
fn update_storage(&mut self, update: <Self::State as StateBackend<H>>::Transaction) -> error::Result<()>; fn update_storage(&mut self, update: <Self::State as StateBackend<H>>::Transaction) -> error::Result<()>;
/// Inject storage data into the database replacing any existing data. /// Inject storage data into the database replacing any existing data.
+2 -3
View File
@@ -16,8 +16,7 @@
//! Substrate blockchain trait //! Substrate blockchain trait
use primitives::AuthorityId; use runtime_primitives::traits::{AuthorityIdFor, Block as BlockT, Header as HeaderT, NumberFor};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::Justification; use runtime_primitives::Justification;
@@ -90,7 +89,7 @@ pub trait Backend<Block: BlockT>: HeaderBackend<Block> {
/// Blockchain optional data cache. /// Blockchain optional data cache.
pub trait Cache<Block: BlockT>: Send + Sync { pub trait Cache<Block: BlockT>: Send + Sync {
/// Returns the set of authorities, that was active at given block or None if there's no entry in the cache. /// Returns the set of authorities, that was active at given block or None if there's no entry in the cache.
fn authorities_at(&self, block: BlockId<Block>) -> Option<Vec<AuthorityId>>; fn authorities_at(&self, block: BlockId<Block>) -> Option<Vec<AuthorityIdFor<Block>>>;
} }
/// Block import outcome /// Block import outcome
+6 -7
View File
@@ -20,7 +20,6 @@ use std::{marker::PhantomData, collections::{HashSet, BTreeMap}, sync::Arc};
use error::Error; use error::Error;
use futures::sync::mpsc; use futures::sync::mpsc;
use parking_lot::{Mutex, RwLock}; use parking_lot::{Mutex, RwLock};
use primitives::AuthorityId;
use runtime_primitives::{ use runtime_primitives::{
Justification, Justification,
generic::{BlockId, SignedBlock}, generic::{BlockId, SignedBlock},
@@ -28,7 +27,7 @@ use runtime_primitives::{
use consensus::{Error as ConsensusError, ErrorKind as ConsensusErrorKind, ImportBlock, ImportResult, BlockOrigin, ForkChoiceStrategy}; use consensus::{Error as ConsensusError, ErrorKind as ConsensusErrorKind, ImportBlock, ImportResult, BlockOrigin, ForkChoiceStrategy};
use runtime_primitives::traits::{ use runtime_primitives::traits::{
Block as BlockT, Header as HeaderT, Zero, As, NumberFor, CurrentHeight, BlockNumberToHash, Block as BlockT, Header as HeaderT, Zero, As, NumberFor, CurrentHeight, BlockNumberToHash,
ApiRef, ProvideRuntimeApi, Digest, DigestItem, ApiRef, ProvideRuntimeApi, Digest, DigestItem, AuthorityIdFor
}; };
use runtime_primitives::BuildStorage; use runtime_primitives::BuildStorage;
use runtime_api::{Core as CoreAPI, CallRuntimeAt, ConstructRuntimeApi}; use runtime_api::{Core as CoreAPI, CallRuntimeAt, ConstructRuntimeApi};
@@ -281,11 +280,11 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
} }
/// Get the set of authorities at a given block. /// Get the set of authorities at a given block.
pub fn authorities_at(&self, id: &BlockId<Block>) -> error::Result<Vec<AuthorityId>> { pub fn authorities_at(&self, id: &BlockId<Block>) -> error::Result<Vec<AuthorityIdFor<Block>>> {
match self.backend.blockchain().cache().and_then(|cache| cache.authorities_at(*id)) { match self.backend.blockchain().cache().and_then(|cache| cache.authorities_at(*id)) {
Some(cached_value) => Ok(cached_value), Some(cached_value) => Ok(cached_value),
None => self.executor.call(id, "Core_authorities", &[]) None => self.executor.call(id, "Core_authorities", &[])
.and_then(|r| Vec::<AuthorityId>::decode(&mut &r.return_data[..]) .and_then(|r| Vec::<AuthorityIdFor<Block>>::decode(&mut &r.return_data[..])
.ok_or(error::ErrorKind::InvalidAuthoritiesSet.into())) .ok_or(error::ErrorKind::InvalidAuthoritiesSet.into()))
} }
} }
@@ -541,7 +540,7 @@ impl<B, E, Block, RA> Client<B, E, Block, RA> where
import_headers: PrePostHeader<Block::Header>, import_headers: PrePostHeader<Block::Header>,
justification: Option<Justification>, justification: Option<Justification>,
body: Option<Vec<Block::Extrinsic>>, body: Option<Vec<Block::Extrinsic>>,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
finalized: bool, finalized: bool,
aux: Vec<(Vec<u8>, Option<Vec<u8>>)>, aux: Vec<(Vec<u8>, Option<Vec<u8>>)>,
fork_choice: ForkChoiceStrategy, fork_choice: ForkChoiceStrategy,
@@ -1030,7 +1029,7 @@ impl<B, E, Block, RA> consensus::BlockImport<Block> for Client<B, E, Block, RA>
fn import_block( fn import_block(
&self, &self,
import_block: ImportBlock<Block>, import_block: ImportBlock<Block>,
new_authorities: Option<Vec<AuthorityId>>, new_authorities: Option<Vec<AuthorityIdFor<Block>>>,
) -> Result<ImportResult, Self::Error> { ) -> Result<ImportResult, Self::Error> {
use runtime_primitives::traits::Digest; use runtime_primitives::traits::Digest;
@@ -1098,7 +1097,7 @@ impl<B, E, Block, RA> consensus::Authorities<Block> for Client<B, E, Block, RA>
Block: BlockT<Hash=H256>, Block: BlockT<Hash=H256>,
{ {
type Error = Error; type Error = Error;
fn authorities(&self, at: &BlockId<Block>) -> Result<Vec<AuthorityId>, Self::Error> { fn authorities(&self, at: &BlockId<Block>) -> Result<Vec<AuthorityIdFor<Block>>, Self::Error> {
self.authorities_at(at).map_err(|e| e.into()) self.authorities_at(at).map_err(|e| e.into())
} }
} }
+9 -9
View File
@@ -22,10 +22,10 @@ use parking_lot::RwLock;
use error; use error;
use backend::{self, NewBlockState}; use backend::{self, NewBlockState};
use light; use light;
use primitives::{AuthorityId, storage::well_known_keys}; use primitives::storage::well_known_keys;
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Zero, use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, Zero,
NumberFor, As, Digest, DigestItem}; NumberFor, As, Digest, DigestItem, AuthorityIdFor};
use runtime_primitives::{Justification, StorageMap, ChildrenStorageMap}; use runtime_primitives::{Justification, StorageMap, ChildrenStorageMap};
use blockchain::{self, BlockStatus, HeaderBackend}; use blockchain::{self, BlockStatus, HeaderBackend};
use state_machine::backend::{Backend as StateBackend, InMemory, Consolidate}; use state_machine::backend::{Backend as StateBackend, InMemory, Consolidate};
@@ -108,7 +108,7 @@ pub struct Blockchain<Block: BlockT> {
struct Cache<Block: BlockT> { struct Cache<Block: BlockT> {
storage: Arc<RwLock<BlockchainStorage<Block>>>, storage: Arc<RwLock<BlockchainStorage<Block>>>,
authorities_at: RwLock<HashMap<Block::Hash, Option<Vec<AuthorityId>>>>, authorities_at: RwLock<HashMap<Block::Hash, Option<Vec<AuthorityIdFor<Block>>>>>,
} }
impl<Block: BlockT + Clone> Clone for Blockchain<Block> { impl<Block: BlockT + Clone> Clone for Blockchain<Block> {
@@ -368,7 +368,7 @@ impl<Block: BlockT> light::blockchain::Storage<Block> for Blockchain<Block>
fn import_header( fn import_header(
&self, &self,
header: Block::Header, header: Block::Header,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
state: NewBlockState, state: NewBlockState,
aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>, aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
) -> error::Result<()> { ) -> error::Result<()> {
@@ -409,7 +409,7 @@ impl<Block: BlockT> light::blockchain::Storage<Block> for Blockchain<Block>
/// In-memory operation. /// In-memory operation.
pub struct BlockImportOperation<Block: BlockT, H: Hasher> { pub struct BlockImportOperation<Block: BlockT, H: Hasher> {
pending_block: Option<PendingBlock<Block>>, pending_block: Option<PendingBlock<Block>>,
pending_authorities: Option<Vec<AuthorityId>>, pending_authorities: Option<Vec<AuthorityIdFor<Block>>>,
old_state: InMemory<H>, old_state: InMemory<H>,
new_state: Option<InMemory<H>>, new_state: Option<InMemory<H>>,
changes_trie_update: Option<MemoryDB<H>>, changes_trie_update: Option<MemoryDB<H>>,
@@ -444,7 +444,7 @@ where
Ok(()) Ok(())
} }
fn update_authorities(&mut self, authorities: Vec<AuthorityId>) { fn update_authorities(&mut self, authorities: Vec<AuthorityIdFor<Block>>) {
self.pending_authorities = Some(authorities); self.pending_authorities = Some(authorities);
} }
@@ -632,13 +632,13 @@ where
{} {}
impl<Block: BlockT> Cache<Block> { impl<Block: BlockT> Cache<Block> {
fn insert(&self, at: Block::Hash, authorities: Option<Vec<AuthorityId>>) { fn insert(&self, at: Block::Hash, authorities: Option<Vec<AuthorityIdFor<Block>>>) {
self.authorities_at.write().insert(at, authorities); self.authorities_at.write().insert(at, authorities);
} }
} }
impl<Block: BlockT> blockchain::Cache<Block> for Cache<Block> { impl<Block: BlockT> blockchain::Cache<Block> for Cache<Block> {
fn authorities_at(&self, block: BlockId<Block>) -> Option<Vec<AuthorityId>> { fn authorities_at(&self, block: BlockId<Block>) -> Option<Vec<AuthorityIdFor<Block>>> {
let hash = match block { let hash = match block {
BlockId::Hash(hash) => hash, BlockId::Hash(hash) => hash,
BlockId::Number(number) => self.storage.read().hashes.get(&number).cloned()?, BlockId::Number(number) => self.storage.read().hashes.get(&number).cloned()?,
@@ -652,7 +652,7 @@ impl<Block: BlockT> blockchain::Cache<Block> for Cache<Block> {
pub fn cache_authorities_at<Block: BlockT>( pub fn cache_authorities_at<Block: BlockT>(
blockchain: &Blockchain<Block>, blockchain: &Blockchain<Block>,
at: Block::Hash, at: Block::Hash,
authorities: Option<Vec<AuthorityId>> authorities: Option<Vec<AuthorityIdFor<Block>>>
) { ) {
blockchain.cache.insert(at, authorities); blockchain.cache.insert(at, authorities);
} }
+3 -4
View File
@@ -21,10 +21,9 @@ use std::sync::{Arc, Weak};
use futures::{Future, IntoFuture}; use futures::{Future, IntoFuture};
use parking_lot::RwLock; use parking_lot::RwLock;
use primitives::AuthorityId;
use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap}; use runtime_primitives::{generic::BlockId, Justification, StorageMap, ChildrenStorageMap};
use state_machine::{Backend as StateBackend, InMemoryChangesTrieStorage, TrieBackend}; use state_machine::{Backend as StateBackend, InMemoryChangesTrieStorage, TrieBackend};
use runtime_primitives::traits::{Block as BlockT, NumberFor}; use runtime_primitives::traits::{Block as BlockT, NumberFor, AuthorityIdFor};
use in_mem; use in_mem;
use backend::{AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState}; use backend::{AuxStore, Backend as ClientBackend, BlockImportOperation, RemoteBackend, NewBlockState};
@@ -44,7 +43,7 @@ pub struct Backend<S, F> {
/// Light block (header and justification) import operation. /// Light block (header and justification) import operation.
pub struct ImportOperation<Block: BlockT, S, F> { pub struct ImportOperation<Block: BlockT, S, F> {
header: Option<Block::Header>, header: Option<Block::Header>,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
leaf_state: NewBlockState, leaf_state: NewBlockState,
aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>, aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
_phantom: ::std::marker::PhantomData<(S, F)>, _phantom: ::std::marker::PhantomData<(S, F)>,
@@ -185,7 +184,7 @@ where
Ok(()) Ok(())
} }
fn update_authorities(&mut self, authorities: Vec<AuthorityId>) { fn update_authorities(&mut self, authorities: Vec<AuthorityIdFor<Block>>) {
self.authorities = Some(authorities); self.authorities = Some(authorities);
} }
@@ -21,9 +21,8 @@ use std::sync::Weak;
use futures::{Future, IntoFuture}; use futures::{Future, IntoFuture};
use parking_lot::Mutex; use parking_lot::Mutex;
use primitives::AuthorityId;
use runtime_primitives::{Justification, generic::BlockId}; use runtime_primitives::{Justification, generic::BlockId};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT,NumberFor, Zero}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero, AuthorityIdFor};
use backend::{AuxStore, NewBlockState}; use backend::{AuxStore, NewBlockState};
use blockchain::{Backend as BlockchainBackend, BlockStatus, Cache as BlockchainCache, use blockchain::{Backend as BlockchainBackend, BlockStatus, Cache as BlockchainCache,
@@ -41,7 +40,7 @@ pub trait Storage<Block: BlockT>: AuxStore + BlockchainHeaderBackend<Block> {
fn import_header( fn import_header(
&self, &self,
header: Block::Header, header: Block::Header,
authorities: Option<Vec<AuthorityId>>, authorities: Option<Vec<AuthorityIdFor<Block>>>,
state: NewBlockState, state: NewBlockState,
aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>, aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
) -> ClientResult<()>; ) -> ClientResult<()>;
@@ -227,7 +226,7 @@ pub mod tests {
fn import_header( fn import_header(
&self, &self,
_header: Header, _header: Header,
_authorities: Option<Vec<AuthorityId>>, _authorities: Option<Vec<AuthorityIdFor<Block>>>,
_state: NewBlockState, _state: NewBlockState,
_aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>, _aux_ops: Vec<(Vec<u8>, Option<Vec<u8>>)>,
) -> ClientResult<()> { ) -> ClientResult<()> {
+3 -3
View File
@@ -21,7 +21,7 @@
pub use state_machine::OverlayedChanges; pub use state_machine::OverlayedChanges;
#[doc(hidden)] #[doc(hidden)]
pub use runtime_primitives::{ pub use runtime_primitives::{
traits::{Block as BlockT, GetNodeBlockType, GetRuntimeBlockType, ApiRef, RuntimeApiInfo}, traits::{AuthorityIdFor, Block as BlockT, GetNodeBlockType, GetRuntimeBlockType, ApiRef, RuntimeApiInfo},
generic::BlockId, transaction_validity::TransactionValidity generic::BlockId, transaction_validity::TransactionValidity
}; };
#[doc(hidden)] #[doc(hidden)]
@@ -34,7 +34,7 @@ pub use codec::{Encode, Decode};
#[cfg(feature = "std")] #[cfg(feature = "std")]
use error; use error;
use rstd::vec::Vec; use rstd::vec::Vec;
use primitives::{AuthorityId, OpaqueMetadata}; use primitives::OpaqueMetadata;
/// Something that can be constructed to a runtime api. /// Something that can be constructed to a runtime api.
@@ -91,7 +91,7 @@ decl_runtime_apis! {
/// Returns the version of the runtime. /// Returns the version of the runtime.
fn version() -> RuntimeVersion; fn version() -> RuntimeVersion;
/// Returns the authorities. /// Returns the authorities.
fn authorities() -> Vec<AuthorityId>; fn authorities() -> Vec<AuthorityIdFor<Block>>;
/// Execute the given block. /// Execute the given block.
fn execute_block(block: Block); fn execute_block(block: Block);
/// Initialise a block with the given header. /// Initialise a block with the given header.
+11 -11
View File
@@ -67,8 +67,8 @@ use client::ChainHead;
use client::block_builder::api::BlockBuilder as BlockBuilderApi; use client::block_builder::api::BlockBuilder as BlockBuilderApi;
use consensus_common::{ImportBlock, BlockOrigin}; use consensus_common::{ImportBlock, BlockOrigin};
use runtime_primitives::{generic, generic::BlockId, Justification, BasicInherentData}; use runtime_primitives::{generic, generic::BlockId, Justification, BasicInherentData};
use runtime_primitives::traits::{Block, Header, Digest, DigestItemFor, ProvideRuntimeApi}; use runtime_primitives::traits::{Block, Header, Digest, DigestItemFor, DigestItem, ProvideRuntimeApi};
use primitives::{AuthorityId, ed25519}; use primitives::{Ed25519AuthorityId, ed25519};
use futures::{Stream, Future, IntoFuture, future::{self, Either}}; use futures::{Stream, Future, IntoFuture, future::{self, Either}};
use tokio::timer::Timeout; use tokio::timer::Timeout;
@@ -91,7 +91,7 @@ pub trait Network: Clone {
} }
/// Get slot author for given block along with authorities. /// Get slot author for given block along with authorities.
fn slot_author(slot_num: u64, authorities: &[AuthorityId]) -> Option<AuthorityId> { fn slot_author(slot_num: u64, authorities: &[Ed25519AuthorityId]) -> Option<Ed25519AuthorityId> {
if authorities.is_empty() { return None } if authorities.is_empty() { return None }
let idx = slot_num % (authorities.len() as u64); let idx = slot_num % (authorities.len() as u64);
@@ -168,7 +168,7 @@ pub fn start_aura_thread<B, C, E, I, SO, Error>(
I: BlockImport<B> + Send + Sync + 'static, I: BlockImport<B> + Send + Sync + 'static,
Error: From<C::Error> + From<I::Error> + 'static, Error: From<C::Error> + From<I::Error> + 'static,
SO: SyncOracle + Send + Clone + 'static, SO: SyncOracle + Send + Clone + 'static,
DigestItemFor<B>: CompatibleDigestItem + 'static, DigestItemFor<B>: CompatibleDigestItem + DigestItem<AuthorityId=Ed25519AuthorityId> + 'static,
Error: ::std::error::Error + Send + From<::consensus_common::Error> + 'static, Error: ::std::error::Error + Send + From<::consensus_common::Error> + 'static,
{ {
use tokio::runtime::current_thread::Runtime; use tokio::runtime::current_thread::Runtime;
@@ -211,7 +211,7 @@ pub fn start_aura<B, C, E, I, SO, Error>(
I: BlockImport<B>, I: BlockImport<B>,
Error: From<C::Error> + From<I::Error>, Error: From<C::Error> + From<I::Error>,
SO: SyncOracle + Send + Clone, SO: SyncOracle + Send + Clone,
DigestItemFor<B>: CompatibleDigestItem, DigestItemFor<B>: CompatibleDigestItem + DigestItem<AuthorityId=Ed25519AuthorityId>,
Error: ::std::error::Error + Send + 'static + From<::consensus_common::Error>, Error: ::std::error::Error + Send + 'static + From<::consensus_common::Error>,
{ {
let make_authorship = move || { let make_authorship = move || {
@@ -266,7 +266,7 @@ pub fn start_aura<B, C, E, I, SO, Error>(
slot_num, timestamp); slot_num, timestamp);
// we are the slot author. make a block and sign it. // we are the slot author. make a block and sign it.
let proposer = match env.init(&chain_head, &authorities, pair.clone()) { let proposer = match env.init(&chain_head, &authorities) {
Ok(p) => p, Ok(p) => p,
Err(e) => { Err(e) => {
warn!("Unable to author block in slot {:?}: {:?}", slot_num, e); warn!("Unable to author block in slot {:?}: {:?}", slot_num, e);
@@ -373,7 +373,7 @@ enum CheckedHeader<H> {
/// if it's successful, returns the pre-header, the slot number, and the signat. /// if it's successful, returns the pre-header, the slot number, and the signat.
// //
// FIXME: needs misbehavior types - https://github.com/paritytech/substrate/issues/1018 // FIXME: needs misbehavior types - https://github.com/paritytech/substrate/issues/1018
fn check_header<B: Block>(slot_now: u64, mut header: B::Header, hash: B::Hash, authorities: &[AuthorityId]) fn check_header<B: Block>(slot_now: u64, mut header: B::Header, hash: B::Hash, authorities: &[Ed25519AuthorityId])
-> Result<CheckedHeader<B::Header>, String> -> Result<CheckedHeader<B::Header>, String>
where DigestItemFor<B>: CompatibleDigestItem where DigestItemFor<B>: CompatibleDigestItem
{ {
@@ -446,7 +446,7 @@ impl<B: Block> ExtraVerification<B> for NothingExtra {
impl<B: Block, C, E, MakeInherent, Inherent> Verifier<B> for AuraVerifier<C, E, MakeInherent> where impl<B: Block, C, E, MakeInherent, Inherent> Verifier<B> for AuraVerifier<C, E, MakeInherent> where
C: Authorities<B> + BlockImport<B> + ProvideRuntimeApi + Send + Sync, C: Authorities<B> + BlockImport<B> + ProvideRuntimeApi + Send + Sync,
C::Api: BlockBuilderApi<B, Inherent>, C::Api: BlockBuilderApi<B, Inherent>,
DigestItemFor<B>: CompatibleDigestItem, DigestItemFor<B>: CompatibleDigestItem + DigestItem<AuthorityId=Ed25519AuthorityId>,
E: ExtraVerification<B>, E: ExtraVerification<B>,
MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync, MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync,
{ {
@@ -456,7 +456,7 @@ impl<B: Block, C, E, MakeInherent, Inherent> Verifier<B> for AuraVerifier<C, E,
header: B::Header, header: B::Header,
justification: Option<Justification>, justification: Option<Justification>,
mut body: Option<Vec<B::Extrinsic>>, mut body: Option<Vec<B::Extrinsic>>,
) -> Result<(ImportBlock<B>, Option<Vec<AuthorityId>>), String> { ) -> Result<(ImportBlock<B>, Option<Vec<Ed25519AuthorityId>>), String> {
use runtime_primitives::CheckInherentError; use runtime_primitives::CheckInherentError;
const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60; const MAX_TIMESTAMP_DRIFT_SECS: u64 = 60;
@@ -600,7 +600,7 @@ pub fn import_queue<B, C, E, MakeInherent, Inherent>(
B: Block, B: Block,
C: Authorities<B> + BlockImport<B,Error=ConsensusError> + ProvideRuntimeApi + Send + Sync, C: Authorities<B> + BlockImport<B,Error=ConsensusError> + ProvideRuntimeApi + Send + Sync,
C::Api: BlockBuilderApi<B, Inherent>, C::Api: BlockBuilderApi<B, Inherent>,
DigestItemFor<B>: CompatibleDigestItem, DigestItemFor<B>: CompatibleDigestItem + DigestItem<AuthorityId=Ed25519AuthorityId>,
E: ExtraVerification<B>, E: ExtraVerification<B>,
MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync, MakeInherent: Fn(u64, u64) -> Inherent + Send + Sync,
{ {
@@ -633,7 +633,7 @@ mod tests {
type Proposer = DummyProposer; type Proposer = DummyProposer;
type Error = Error; type Error = Error;
fn init(&self, parent_header: &<TestBlock as BlockT>::Header, _authorities: &[AuthorityId], _sign_with: Arc<ed25519::Pair>) fn init(&self, parent_header: &<TestBlock as BlockT>::Header, _authorities: &[Ed25519AuthorityId])
-> Result<DummyProposer, Error> -> Result<DummyProposer, Error>
{ {
Ok(DummyProposer(parent_header.number + 1, self.0.clone())) Ok(DummyProposer(parent_header.number + 1, self.0.clone()))
@@ -16,8 +16,7 @@
//! Block import helpers. //! Block import helpers.
use primitives::AuthorityId; use runtime_primitives::traits::{AuthorityIdFor, Block as BlockT, Header as HeaderT, DigestItemFor};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, DigestItemFor};
use runtime_primitives::Justification; use runtime_primitives::Justification;
use std::borrow::Cow; use std::borrow::Cow;
@@ -146,6 +145,6 @@ pub trait BlockImport<B: BlockT> {
/// Import a Block alongside the new authorities valid form this block forward /// Import a Block alongside the new authorities valid form this block forward
fn import_block(&self, fn import_block(&self,
block: ImportBlock<B>, block: ImportBlock<B>,
new_authorities: Option<Vec<AuthorityId>> new_authorities: Option<Vec<AuthorityIdFor<B>>>
) -> Result<ImportResult, Self::Error>; ) -> Result<ImportResult, Self::Error>;
} }
+2 -2
View File
@@ -44,13 +44,13 @@ error_chain! {
} }
/// Error checking signature /// Error checking signature
InvalidSignature(s: ::primitives::ed25519::Signature, a: ::primitives::AuthorityId) { InvalidSignature(s: ::primitives::ed25519::Signature, a: ::primitives::Ed25519AuthorityId) {
description("Message signature is invalid"), description("Message signature is invalid"),
display("Message signature {:?} by {:?} is invalid.", s, a), display("Message signature {:?} by {:?} is invalid.", s, a),
} }
/// Account is not an authority. /// Account is not an authority.
InvalidAuthority(a: ::primitives::AuthorityId) { InvalidAuthority(a: ::primitives::Ed25519AuthorityId) {
description("Message sender is not a valid authority"), description("Message sender is not a valid authority"),
display("Message sender {:?} is not a valid authority.", a), display("Message sender {:?} is not a valid authority.", a),
} }
@@ -29,10 +29,9 @@ use std::collections::{HashSet, VecDeque};
use std::sync::Arc; use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use parking_lot::{Condvar, Mutex, RwLock}; use parking_lot::{Condvar, Mutex, RwLock};
use primitives::AuthorityId;
use runtime_primitives::Justification; use runtime_primitives::Justification;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero, AuthorityIdFor};
use error::Error as ConsensusError; use error::Error as ConsensusError;
@@ -68,7 +67,7 @@ pub trait Verifier<B: BlockT>: Send + Sync + Sized {
header: B::Header, header: B::Header,
justification: Option<Justification>, justification: Option<Justification>,
body: Option<Vec<B::Extrinsic>> body: Option<Vec<B::Extrinsic>>
) -> Result<(ImportBlock<B>, Option<Vec<AuthorityId>>), String>; ) -> Result<(ImportBlock<B>, Option<Vec<AuthorityIdFor<B>>>), String>;
} }
/// Blocks import queue API. /// Blocks import queue API.
+4 -6
View File
@@ -40,9 +40,8 @@ extern crate error_chain;
use std::sync::Arc; use std::sync::Arc;
use primitives::{ed25519, AuthorityId};
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::Block; use runtime_primitives::traits::{AuthorityIdFor, Block};
use futures::prelude::*; use futures::prelude::*;
pub mod offline_tracker; pub mod offline_tracker;
@@ -60,7 +59,7 @@ pub use block_import::{BlockImport, ImportBlock, BlockOrigin, ImportResult, Fork
/// Trait for getting the authorities at a given block. /// Trait for getting the authorities at a given block.
pub trait Authorities<B: Block> { pub trait Authorities<B: Block> {
type Error: ::std::error::Error + Send + 'static; /// Get the authorities at the given block. type Error: ::std::error::Error + Send + 'static; /// Get the authorities at the given block.
fn authorities(&self, at: &BlockId<B>) -> Result<Vec<AuthorityId>, Self::Error>; fn authorities(&self, at: &BlockId<B>) -> Result<Vec<AuthorityIdFor<B>>, Self::Error>;
} }
/// Environment producer for a Consensus instance. Creates proposer instance and communication streams. /// Environment producer for a Consensus instance. Creates proposer instance and communication streams.
@@ -71,9 +70,8 @@ pub trait Environment<B: Block, ConsensusData> {
type Error: From<Error>; type Error: From<Error>;
/// Initialize the proposal logic on top of a specific header. Provide /// Initialize the proposal logic on top of a specific header. Provide
/// the authorities at that header, and a local key to sign any additional /// the authorities at that header.
/// consensus messages with as well. fn init(&self, parent_header: &B::Header, authorities: &[AuthorityIdFor<B>])
fn init(&self, parent_header: &B::Header, authorities: &[AuthorityId], sign_with: Arc<ed25519::Pair>)
-> Result<Self::Proposer, Self::Error>; -> Result<Self::Proposer, Self::Error>;
} }
@@ -16,8 +16,6 @@
//! Tracks offline validators. //! Tracks offline validators.
use primitives::AuthorityId;
use std::collections::HashMap; use std::collections::HashMap;
use std::time::{Instant, Duration}; use std::time::{Instant, Duration};
@@ -55,11 +53,11 @@ impl Observed {
} }
/// Tracks offline validators and can issue a report for those offline. /// Tracks offline validators and can issue a report for those offline.
pub struct OfflineTracker { pub struct OfflineTracker<AuthorityId> {
observed: HashMap<AuthorityId, Observed>, observed: HashMap<AuthorityId, Observed>,
} }
impl OfflineTracker { impl<AuthorityId: Eq + Clone + std::hash::Hash> OfflineTracker<AuthorityId> {
/// Create a new tracker. /// Create a new tracker.
pub fn new() -> Self { pub fn new() -> Self {
OfflineTracker { observed: HashMap::new() } OfflineTracker { observed: HashMap::new() }
@@ -114,10 +112,11 @@ impl OfflineTracker {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use primitives::Ed25519AuthorityId;
#[test] #[test]
fn validator_offline() { fn validator_offline() {
let mut tracker = OfflineTracker::new(); let mut tracker = OfflineTracker::<Ed25519AuthorityId>::new();
let v = [0; 32].into(); let v = [0; 32].into();
let v2 = [1; 32].into(); let v2 = [1; 32].into();
let v3 = [2; 32].into(); let v3 = [2; 32].into();
@@ -34,7 +34,7 @@ extern crate substrate_client as client;
extern crate sr_std as rstd; extern crate sr_std as rstd;
use substrate_primitives::AuthorityId; use substrate_primitives::Ed25519AuthorityId;
use sr_primitives::traits::{DigestFor, NumberFor}; use sr_primitives::traits::{DigestFor, NumberFor};
use rstd::vec::Vec; use rstd::vec::Vec;
@@ -43,7 +43,7 @@ use rstd::vec::Vec;
#[derive(Clone, Encode, Decode)] #[derive(Clone, Encode, Decode)]
pub struct ScheduledChange<N> { pub struct ScheduledChange<N> {
/// The new authorities after the change, along with their respective weights. /// The new authorities after the change, along with their respective weights.
pub next_authorities: Vec<(AuthorityId, u64)>, pub next_authorities: Vec<(Ed25519AuthorityId, u64)>,
/// The number of blocks to delay. /// The number of blocks to delay.
pub delay: N, pub delay: N,
} }
@@ -97,6 +97,6 @@ decl_runtime_apis! {
/// Get the current GRANDPA authorities and weights. This should not change except /// Get the current GRANDPA authorities and weights. This should not change except
/// for when changes are scheduled and the corresponding delay has passed. /// for when changes are scheduled and the corresponding delay has passed.
fn grandpa_authorities() -> Vec<(AuthorityId, u64)>; fn grandpa_authorities() -> Vec<(Ed25519AuthorityId, u64)>;
} }
} }
@@ -17,7 +17,7 @@
//! Utilities for dealing with authorities, authority sets, and handoffs. //! Utilities for dealing with authorities, authority sets, and handoffs.
use parking_lot::RwLock; use parking_lot::RwLock;
use substrate_primitives::AuthorityId; use substrate_primitives::Ed25519AuthorityId;
use std::cmp::Ord; use std::cmp::Ord;
use std::collections::HashMap; use std::collections::HashMap;
@@ -38,7 +38,7 @@ impl<H, N> Clone for SharedAuthoritySet<H, N> {
impl<H, N> SharedAuthoritySet<H, N> { impl<H, N> SharedAuthoritySet<H, N> {
/// The genesis authority set. /// The genesis authority set.
pub(crate) fn genesis(initial: Vec<(AuthorityId, u64)>) -> Self { pub(crate) fn genesis(initial: Vec<(Ed25519AuthorityId, u64)>) -> Self {
SharedAuthoritySet { SharedAuthoritySet {
inner: Arc::new(RwLock::new(AuthoritySet::genesis(initial))) inner: Arc::new(RwLock::new(AuthoritySet::genesis(initial)))
} }
@@ -66,7 +66,7 @@ where
} }
/// Get the current authorities and their weights (for the current set ID). /// Get the current authorities and their weights (for the current set ID).
pub(crate) fn current_authorities(&self) -> HashMap<AuthorityId, u64> { pub(crate) fn current_authorities(&self) -> HashMap<Ed25519AuthorityId, u64> {
self.inner.read().current_authorities.iter().cloned().collect() self.inner.read().current_authorities.iter().cloned().collect()
} }
} }
@@ -89,14 +89,14 @@ pub(crate) struct Status<H, N> {
/// A set of authorities. /// A set of authorities.
#[derive(Debug, Clone, Encode, Decode)] #[derive(Debug, Clone, Encode, Decode)]
pub(crate) struct AuthoritySet<H, N> { pub(crate) struct AuthoritySet<H, N> {
current_authorities: Vec<(AuthorityId, u64)>, current_authorities: Vec<(Ed25519AuthorityId, u64)>,
set_id: u64, set_id: u64,
pending_changes: Vec<PendingChange<H, N>>, pending_changes: Vec<PendingChange<H, N>>,
} }
impl<H, N> AuthoritySet<H, N> { impl<H, N> AuthoritySet<H, N> {
/// Get a genesis set with given authorities. /// Get a genesis set with given authorities.
pub(crate) fn genesis(initial: Vec<(AuthorityId, u64)>) -> Self { pub(crate) fn genesis(initial: Vec<(Ed25519AuthorityId, u64)>) -> Self {
AuthoritySet { AuthoritySet {
current_authorities: initial, current_authorities: initial,
set_id: 0, set_id: 0,
@@ -105,7 +105,7 @@ impl<H, N> AuthoritySet<H, N> {
} }
/// Get the current set id and a reference to the current authority set. /// Get the current set id and a reference to the current authority set.
pub(crate) fn current(&self) -> (u64, &[(AuthorityId, u64)]) { pub(crate) fn current(&self) -> (u64, &[(Ed25519AuthorityId, u64)]) {
(self.set_id, &self.current_authorities[..]) (self.set_id, &self.current_authorities[..])
} }
} }
@@ -249,7 +249,7 @@ where
#[derive(Debug, Clone, Encode, Decode, PartialEq)] #[derive(Debug, Clone, Encode, Decode, PartialEq)]
pub(crate) struct PendingChange<H, N> { pub(crate) struct PendingChange<H, N> {
/// The new authorities and weights to apply. /// The new authorities and weights to apply.
pub(crate) next_authorities: Vec<(AuthorityId, u64)>, pub(crate) next_authorities: Vec<(Ed25519AuthorityId, u64)>,
/// How deep in the finalized chain the announcing block must be /// How deep in the finalized chain the announcing block must be
/// before the change is applied. /// before the change is applied.
pub(crate) finalization_depth: N, pub(crate) finalization_depth: N,
@@ -20,7 +20,7 @@
use futures::prelude::*; use futures::prelude::*;
use futures::sync::mpsc; use futures::sync::mpsc;
use codec::{Encode, Decode}; use codec::{Encode, Decode};
use substrate_primitives::{ed25519, AuthorityId}; use substrate_primitives::{ed25519, Ed25519AuthorityId};
use runtime_primitives::traits::Block as BlockT; use runtime_primitives::traits::Block as BlockT;
use {Error, Network, Message, SignedMessage, Commit, CompactCommit}; use {Error, Network, Message, SignedMessage, Commit, CompactCommit};
@@ -34,7 +34,7 @@ fn localized_payload<E: Encode>(round: u64, set_id: u64, message: &E) -> Vec<u8>
// check a message. // check a message.
pub(crate) fn check_message_sig<Block: BlockT>( pub(crate) fn check_message_sig<Block: BlockT>(
message: &Message<Block>, message: &Message<Block>,
id: &AuthorityId, id: &Ed25519AuthorityId,
signature: &ed25519::Signature, signature: &ed25519::Signature,
round: u64, round: u64,
set_id: u64, set_id: u64,
@@ -55,7 +55,7 @@ pub(crate) fn checked_message_stream<Block: BlockT, S>(
round: u64, round: u64,
set_id: u64, set_id: u64,
inner: S, inner: S,
voters: Arc<HashMap<AuthorityId, u64>>, voters: Arc<HashMap<Ed25519AuthorityId, u64>>,
) )
-> impl Stream<Item=SignedMessage<Block>,Error=Error> where -> impl Stream<Item=SignedMessage<Block>,Error=Error> where
S: Stream<Item=Vec<u8>,Error=()> S: Stream<Item=Vec<u8>,Error=()>
@@ -92,7 +92,7 @@ pub(crate) fn checked_message_stream<Block: BlockT, S>(
struct OutgoingMessages<Block: BlockT, N: Network> { struct OutgoingMessages<Block: BlockT, N: Network> {
round: u64, round: u64,
set_id: u64, set_id: u64,
locals: Option<(Arc<ed25519::Pair>, AuthorityId)>, locals: Option<(Arc<ed25519::Pair>, Ed25519AuthorityId)>,
sender: mpsc::UnboundedSender<SignedMessage<Block>>, sender: mpsc::UnboundedSender<SignedMessage<Block>>,
network: N, network: N,
} }
@@ -143,7 +143,7 @@ pub(crate) fn outgoing_messages<Block: BlockT, N: Network>(
round: u64, round: u64,
set_id: u64, set_id: u64,
local_key: Option<Arc<ed25519::Pair>>, local_key: Option<Arc<ed25519::Pair>>,
voters: Arc<HashMap<AuthorityId, u64>>, voters: Arc<HashMap<Ed25519AuthorityId, u64>>,
network: N, network: N,
) -> ( ) -> (
impl Stream<Item=SignedMessage<Block>,Error=Error>, impl Stream<Item=SignedMessage<Block>,Error=Error>,
@@ -151,7 +151,7 @@ pub(crate) fn outgoing_messages<Block: BlockT, N: Network>(
) { ) {
let locals = local_key.and_then(|pair| { let locals = local_key.and_then(|pair| {
let public = pair.public(); let public = pair.public();
let id = AuthorityId(public.0); let id = Ed25519AuthorityId(public.0);
if voters.contains_key(&id) { if voters.contains_key(&id) {
Some((pair, id)) Some((pair, id))
} else { } else {
@@ -177,7 +177,7 @@ pub(crate) fn outgoing_messages<Block: BlockT, N: Network>(
fn check_compact_commit<Block: BlockT>( fn check_compact_commit<Block: BlockT>(
msg: CompactCommit<Block>, msg: CompactCommit<Block>,
voters: &HashMap<AuthorityId, u64>, voters: &HashMap<Ed25519AuthorityId, u64>,
round: u64, round: u64,
set_id: u64, set_id: u64,
) -> Option<CompactCommit<Block>> { ) -> Option<CompactCommit<Block>> {
@@ -216,7 +216,7 @@ fn check_compact_commit<Block: BlockT>(
pub(crate) fn checked_commit_stream<Block: BlockT, S>( pub(crate) fn checked_commit_stream<Block: BlockT, S>(
set_id: u64, set_id: u64,
inner: S, inner: S,
voters: Arc<HashMap<AuthorityId, u64>>, voters: Arc<HashMap<Ed25519AuthorityId, u64>>,
) )
-> impl Stream<Item=(u64, CompactCommit<Block>),Error=Error> where -> impl Stream<Item=(u64, CompactCommit<Block>),Error=Error> where
S: Stream<Item=Vec<u8>,Error=()> S: Stream<Item=Vec<u8>,Error=()>
+18 -13
View File
@@ -92,10 +92,11 @@ use codec::{Encode, Decode};
use consensus_common::{BlockImport, Error as ConsensusError, ErrorKind as ConsensusErrorKind, ImportBlock, ImportResult, Authorities}; use consensus_common::{BlockImport, Error as ConsensusError, ErrorKind as ConsensusErrorKind, ImportBlock, ImportResult, Authorities};
use runtime_primitives::traits::{ use runtime_primitives::traits::{
NumberFor, Block as BlockT, Header as HeaderT, DigestFor, ProvideRuntimeApi, Hash as HashT, NumberFor, Block as BlockT, Header as HeaderT, DigestFor, ProvideRuntimeApi, Hash as HashT,
DigestItemFor, DigestItem,
}; };
use fg_primitives::GrandpaApi; use fg_primitives::GrandpaApi;
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use substrate_primitives::{ed25519, H256, AuthorityId, Blake2Hasher}; use substrate_primitives::{ed25519, H256, Ed25519AuthorityId, Blake2Hasher};
use tokio::timer::Delay; use tokio::timer::Delay;
use grandpa::Error as GrandpaError; use grandpa::Error as GrandpaError;
@@ -138,7 +139,7 @@ pub type SignedMessage<Block> = grandpa::SignedMessage<
<Block as BlockT>::Hash, <Block as BlockT>::Hash,
NumberFor<Block>, NumberFor<Block>,
ed25519::Signature, ed25519::Signature,
AuthorityId, Ed25519AuthorityId,
>; >;
/// A prevote message for this chain's block type. /// A prevote message for this chain's block type.
pub type Prevote<Block> = grandpa::Prevote<<Block as BlockT>::Hash, NumberFor<Block>>; pub type Prevote<Block> = grandpa::Prevote<<Block as BlockT>::Hash, NumberFor<Block>>;
@@ -149,14 +150,14 @@ pub type Commit<Block> = grandpa::Commit<
<Block as BlockT>::Hash, <Block as BlockT>::Hash,
NumberFor<Block>, NumberFor<Block>,
ed25519::Signature, ed25519::Signature,
AuthorityId Ed25519AuthorityId
>; >;
/// A compact commit message for this chain's block type. /// A compact commit message for this chain's block type.
pub type CompactCommit<Block> = grandpa::CompactCommit< pub type CompactCommit<Block> = grandpa::CompactCommit<
<Block as BlockT>::Hash, <Block as BlockT>::Hash,
NumberFor<Block>, NumberFor<Block>,
ed25519::Signature, ed25519::Signature,
AuthorityId Ed25519AuthorityId
>; >;
/// Configuration for the GRANDPA service. /// Configuration for the GRANDPA service.
@@ -306,7 +307,7 @@ impl<B, E, Block: BlockT<Hash=H256>, RA> BlockStatus<Block> for Arc<Client<B, E,
/// The environment we run GRANDPA in. /// The environment we run GRANDPA in.
struct Environment<B, E, Block: BlockT, N: Network, RA> { struct Environment<B, E, Block: BlockT, N: Network, RA> {
inner: Arc<Client<B, E, Block, RA>>, inner: Arc<Client<B, E, Block, RA>>,
voters: Arc<HashMap<AuthorityId, u64>>, voters: Arc<HashMap<Ed25519AuthorityId, u64>>,
config: Config, config: Config,
authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>, authority_set: SharedAuthoritySet<Block::Hash, NumberFor<Block>>,
network: N, network: N,
@@ -381,7 +382,7 @@ struct NewAuthoritySet<H, N> {
canon_number: N, canon_number: N,
canon_hash: H, canon_hash: H,
set_id: u64, set_id: u64,
authorities: Vec<(AuthorityId, u64)>, authorities: Vec<(Ed25519AuthorityId, u64)>,
} }
/// Signals either an early exit of a voter or an error. /// Signals either an early exit of a voter or an error.
@@ -432,7 +433,7 @@ impl<B, E, Block: BlockT<Hash=H256>, N, RA> voter::Environment<Block::Hash, Numb
NumberFor<Block>: BlockNumberOps, NumberFor<Block>: BlockNumberOps,
{ {
type Timer = Box<dyn Future<Item = (), Error = Self::Error> + Send>; type Timer = Box<dyn Future<Item = (), Error = Self::Error> + Send>;
type Id = AuthorityId; type Id = Ed25519AuthorityId;
type Signature = ed25519::Signature; type Signature = ed25519::Signature;
// regular round message streams // regular round message streams
@@ -611,7 +612,7 @@ impl<Block: BlockT<Hash=H256>> GrandpaJustification<Block> {
fn decode_and_verify( fn decode_and_verify(
encoded: Vec<u8>, encoded: Vec<u8>,
set_id: u64, set_id: u64,
voters: &HashMap<AuthorityId, u64>, voters: &HashMap<Ed25519AuthorityId, u64>,
) -> Result<GrandpaJustification<Block>, ClientError> where ) -> Result<GrandpaJustification<Block>, ClientError> where
NumberFor<Block>: grandpa::BlockNumberOps, NumberFor<Block>: grandpa::BlockNumberOps,
{ {
@@ -830,13 +831,14 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, PRA> BlockImport<Block>
B: Backend<Block, Blake2Hasher> + 'static, B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync, E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestFor<Block>: Encode, DigestFor<Block>: Encode,
DigestItemFor<Block>: DigestItem<AuthorityId=Ed25519AuthorityId>,
RA: Send + Sync, RA: Send + Sync,
PRA: ProvideRuntimeApi, PRA: ProvideRuntimeApi,
PRA::Api: GrandpaApi<Block>, PRA::Api: GrandpaApi<Block>,
{ {
type Error = ConsensusError; type Error = ConsensusError;
fn import_block(&self, mut block: ImportBlock<Block>, new_authorities: Option<Vec<AuthorityId>>) fn import_block(&self, mut block: ImportBlock<Block>, new_authorities: Option<Vec<Ed25519AuthorityId>>)
-> Result<ImportResult, Self::Error> -> Result<ImportResult, Self::Error>
{ {
use authorities::PendingChange; use authorities::PendingChange;
@@ -1030,10 +1032,11 @@ impl<B, E, Block: BlockT<Hash=H256>, RA, PRA> Authorities<Block> for GrandpaBloc
where where
B: Backend<Block, Blake2Hasher> + 'static, B: Backend<Block, Blake2Hasher> + 'static,
E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync, E: CallExecutor<Block, Blake2Hasher> + 'static + Clone + Send + Sync,
DigestItemFor<Block>: DigestItem<AuthorityId=Ed25519AuthorityId>,
{ {
type Error = <Client<B, E, Block, RA> as Authorities<Block>>::Error; type Error = <Client<B, E, Block, RA> as Authorities<Block>>::Error;
fn authorities(&self, at: &BlockId<Block>) -> Result<Vec<AuthorityId>, Self::Error> { fn authorities(&self, at: &BlockId<Block>) -> Result<Vec<Ed25519AuthorityId>, Self::Error> {
self.inner.authorities_at(at) self.inner.authorities_at(at)
} }
} }
@@ -1158,16 +1161,16 @@ pub fn block_import<B, E, Block: BlockT<Hash=H256>, RA, PRA>(
fn committer_communication<Block: BlockT<Hash=H256>, B, E, N, RA>( fn committer_communication<Block: BlockT<Hash=H256>, B, E, N, RA>(
set_id: u64, set_id: u64,
voters: &Arc<HashMap<AuthorityId, u64>>, voters: &Arc<HashMap<Ed25519AuthorityId, u64>>,
client: &Arc<Client<B, E, Block, RA>>, client: &Arc<Client<B, E, Block, RA>>,
network: &N, network: &N,
) -> ( ) -> (
impl Stream< impl Stream<
Item = (u64, ::grandpa::CompactCommit<H256, NumberFor<Block>, ed25519::Signature, AuthorityId>), Item = (u64, ::grandpa::CompactCommit<H256, NumberFor<Block>, ed25519::Signature, Ed25519AuthorityId>),
Error = ExitOrError<H256, NumberFor<Block>>, Error = ExitOrError<H256, NumberFor<Block>>,
>, >,
impl Sink< impl Sink<
SinkItem = (u64, ::grandpa::Commit<H256, NumberFor<Block>, ed25519::Signature, AuthorityId>), SinkItem = (u64, ::grandpa::Commit<H256, NumberFor<Block>, ed25519::Signature, Ed25519AuthorityId>),
SinkError = ExitOrError<H256, NumberFor<Block>>, SinkError = ExitOrError<H256, NumberFor<Block>>,
>, >,
) where ) where
@@ -1176,6 +1179,7 @@ fn committer_communication<Block: BlockT<Hash=H256>, B, E, N, RA>(
N: Network, N: Network,
RA: Send + Sync, RA: Send + Sync,
NumberFor<Block>: BlockNumberOps, NumberFor<Block>: BlockNumberOps,
DigestItemFor<Block>: DigestItem<AuthorityId=Ed25519AuthorityId>,
{ {
// verification stream // verification stream
let commit_in = ::communication::checked_commit_stream::<Block, _>( let commit_in = ::communication::checked_commit_stream::<Block, _>(
@@ -1217,6 +1221,7 @@ pub fn run_grandpa<B, E, Block: BlockT<Hash=H256>, N, RA>(
N::In: Send + 'static, N::In: Send + 'static,
NumberFor<Block>: BlockNumberOps, NumberFor<Block>: BlockNumberOps,
DigestFor<Block>: Encode, DigestFor<Block>: Encode,
DigestItemFor<Block>: DigestItem<AuthorityId=Ed25519AuthorityId>,
RA: Send + Sync + 'static, RA: Send + Sync + 'static,
{ {
use futures::future::{self, Loop as FutureLoop}; use futures::future::{self, Loop as FutureLoop};
+6 -6
View File
@@ -230,12 +230,12 @@ impl Network for MessageRouting {
#[derive(Default, Clone)] #[derive(Default, Clone)]
struct TestApi { struct TestApi {
genesis_authorities: Vec<(AuthorityId, u64)>, genesis_authorities: Vec<(Ed25519AuthorityId, u64)>,
scheduled_changes: Arc<Mutex<HashMap<Hash, ScheduledChange<BlockNumber>>>>, scheduled_changes: Arc<Mutex<HashMap<Hash, ScheduledChange<BlockNumber>>>>,
} }
impl TestApi { impl TestApi {
fn new(genesis_authorities: Vec<(AuthorityId, u64)>) -> Self { fn new(genesis_authorities: Vec<(Ed25519AuthorityId, u64)>) -> Self {
TestApi { TestApi {
genesis_authorities, genesis_authorities,
scheduled_changes: Arc::new(Mutex::new(HashMap::new())), scheduled_changes: Arc::new(Mutex::new(HashMap::new())),
@@ -260,7 +260,7 @@ impl Core<Block> for RuntimeApi {
unimplemented!("Not required for testing!") unimplemented!("Not required for testing!")
} }
fn authorities(&self, _: &BlockId<Block>) -> Result<Vec<AuthorityId>> { fn authorities(&self, _: &BlockId<Block>) -> Result<Vec<Ed25519AuthorityId>> {
unimplemented!("Not required for testing!") unimplemented!("Not required for testing!")
} }
@@ -300,7 +300,7 @@ impl GrandpaApi<Block> for RuntimeApi {
fn grandpa_authorities( fn grandpa_authorities(
&self, &self,
at: &BlockId<Block> at: &BlockId<Block>
) -> Result<Vec<(AuthorityId, u64)>> { ) -> Result<Vec<(Ed25519AuthorityId, u64)>> {
if at == &BlockId::Number(0) { if at == &BlockId::Number(0) {
Ok(self.inner.genesis_authorities.clone()) Ok(self.inner.genesis_authorities.clone())
} else { } else {
@@ -325,9 +325,9 @@ impl GrandpaApi<Block> for RuntimeApi {
const TEST_GOSSIP_DURATION: Duration = Duration::from_millis(500); const TEST_GOSSIP_DURATION: Duration = Duration::from_millis(500);
const TEST_ROUTING_INTERVAL: Duration = Duration::from_millis(50); const TEST_ROUTING_INTERVAL: Duration = Duration::from_millis(50);
fn make_ids(keys: &[Keyring]) -> Vec<(AuthorityId, u64)> { fn make_ids(keys: &[Keyring]) -> Vec<(Ed25519AuthorityId, u64)> {
keys.iter() keys.iter()
.map(|key| AuthorityId(key.to_raw_public())) .map(|key| Ed25519AuthorityId(key.to_raw_public()))
.map(|id| (id, 1)) .map(|id| (id, 1))
.collect() .collect()
} }
@@ -27,7 +27,7 @@ use futures::prelude::*;
use futures::stream::Fuse; use futures::stream::Fuse;
use parking_lot::Mutex; use parking_lot::Mutex;
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, NumberFor};
use substrate_primitives::AuthorityId; use substrate_primitives::Ed25519AuthorityId;
use tokio::timer::Interval; use tokio::timer::Interval;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
@@ -181,7 +181,7 @@ impl<Block: BlockT, Status, I, M> Stream for UntilImported<Block, Status, I, M>
} }
} }
fn warn_authority_wrong_target<H: ::std::fmt::Display>(hash: H, id: AuthorityId) { fn warn_authority_wrong_target<H: ::std::fmt::Display>(hash: H, id: Ed25519AuthorityId) {
warn!( warn!(
target: "afg", target: "afg",
"Authority {:?} signed GRANDPA message with \ "Authority {:?} signed GRANDPA message with \
+4 -4
View File
@@ -20,16 +20,16 @@ use client::{self, Client as SubstrateClient, ClientInfo, BlockStatus, CallExecu
use client::error::Error; use client::error::Error;
use client::light::fetcher::ChangesProof; use client::light::fetcher::ChangesProof;
use consensus::{BlockImport, Error as ConsensusError}; use consensus::{BlockImport, Error as ConsensusError};
use runtime_primitives::traits::{Block as BlockT, Header as HeaderT}; use runtime_primitives::traits::{Block as BlockT, Header as HeaderT, AuthorityIdFor};
use runtime_primitives::generic::{BlockId}; use runtime_primitives::generic::{BlockId};
use consensus::{ImportBlock, ImportResult}; use consensus::{ImportBlock, ImportResult};
use runtime_primitives::Justification; use runtime_primitives::Justification;
use primitives::{H256, Blake2Hasher, AuthorityId}; use primitives::{H256, Blake2Hasher};
/// Local client abstraction for the network. /// Local client abstraction for the network.
pub trait Client<Block: BlockT>: Send + Sync { pub trait Client<Block: BlockT>: Send + Sync {
/// Import a new block. Parent is supposed to be existing in the blockchain. /// Import a new block. Parent is supposed to be existing in the blockchain.
fn import(&self, block: ImportBlock<Block>, new_authorities: Option<Vec<AuthorityId>>) fn import(&self, block: ImportBlock<Block>, new_authorities: Option<Vec<AuthorityIdFor<Block>>>)
-> Result<ImportResult, ConsensusError>; -> Result<ImportResult, ConsensusError>;
/// Get blockchain info. /// Get blockchain info.
@@ -77,7 +77,7 @@ impl<B, E, Block, RA> Client<Block> for SubstrateClient<B, E, Block, RA> where
Block: BlockT<Hash=H256>, Block: BlockT<Hash=H256>,
RA: Send + Sync RA: Send + Sync
{ {
fn import(&self, block: ImportBlock<Block>, new_authorities: Option<Vec<AuthorityId>>) fn import(&self, block: ImportBlock<Block>, new_authorities: Option<Vec<AuthorityIdFor<Block>>>)
-> Result<ImportResult, ConsensusError> -> Result<ImportResult, ConsensusError>
{ {
(self as &SubstrateClient<B, E, Block, RA>).import_block(block, new_authorities) (self as &SubstrateClient<B, E, Block, RA>).import_block(block, new_authorities)
+2 -3
View File
@@ -29,9 +29,8 @@ use client;
use client::block_builder::BlockBuilder; use client::block_builder::BlockBuilder;
use runtime_primitives::Justification; use runtime_primitives::Justification;
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use runtime_primitives::traits::{Block as BlockT, Zero}; use runtime_primitives::traits::{Block as BlockT, Zero, AuthorityIdFor};
use io::SyncIo; use io::SyncIo;
use primitives::AuthorityId;
use protocol::{Context, Protocol, ProtocolContext}; use protocol::{Context, Protocol, ProtocolContext};
use config::ProtocolConfig; use config::ProtocolConfig;
use service::{NetworkLink, TransactionPool}; use service::{NetworkLink, TransactionPool};
@@ -92,7 +91,7 @@ impl<B: BlockT> Verifier<B> for PassThroughVerifier {
header: B::Header, header: B::Header,
justification: Option<Justification>, justification: Option<Justification>,
body: Option<Vec<B::Extrinsic>> body: Option<Vec<B::Extrinsic>>
) -> Result<(ImportBlock<B>, Option<Vec<AuthorityId>>), String> { ) -> Result<(ImportBlock<B>, Option<Vec<AuthorityIdFor<B>>>), String> {
Ok((ImportBlock { Ok((ImportBlock {
origin, origin,
header, header,
+14 -14
View File
@@ -20,17 +20,17 @@ use H256;
/// An identifier for an authority in the consensus algorithm. The same size as ed25519::Public. /// An identifier for an authority in the consensus algorithm. The same size as ed25519::Public.
#[derive(Clone, Copy, PartialEq, Eq, Default, Encode, Decode)] #[derive(Clone, Copy, PartialEq, Eq, Default, Encode, Decode)]
pub struct AuthorityId(pub [u8; 32]); pub struct Ed25519AuthorityId(pub [u8; 32]);
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl ::std::fmt::Display for AuthorityId { impl ::std::fmt::Display for Ed25519AuthorityId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", ::ed25519::Public(self.0).to_ss58check()) write!(f, "{}", ::ed25519::Public(self.0).to_ss58check())
} }
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl ::std::fmt::Debug for AuthorityId { impl ::std::fmt::Debug for Ed25519AuthorityId {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
let h = format!("{}", ::hexdisplay::HexDisplay::from(&self.0)); let h = format!("{}", ::hexdisplay::HexDisplay::from(&self.0));
write!(f, "{} ({}…{})", ::ed25519::Public(self.0).to_ss58check(), &h[0..8], &h[60..]) write!(f, "{} ({}…{})", ::ed25519::Public(self.0).to_ss58check(), &h[0..8], &h[60..])
@@ -38,57 +38,57 @@ impl ::std::fmt::Debug for AuthorityId {
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl ::std::hash::Hash for AuthorityId { impl ::std::hash::Hash for Ed25519AuthorityId {
fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) { fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state); self.0.hash(state);
} }
} }
impl AsRef<[u8; 32]> for AuthorityId { impl AsRef<[u8; 32]> for Ed25519AuthorityId {
fn as_ref(&self) -> &[u8; 32] { fn as_ref(&self) -> &[u8; 32] {
&self.0 &self.0
} }
} }
impl AsRef<[u8]> for AuthorityId { impl AsRef<[u8]> for Ed25519AuthorityId {
fn as_ref(&self) -> &[u8] { fn as_ref(&self) -> &[u8] {
&self.0[..] &self.0[..]
} }
} }
impl Into<[u8; 32]> for AuthorityId { impl Into<[u8; 32]> for Ed25519AuthorityId {
fn into(self) -> [u8; 32] { fn into(self) -> [u8; 32] {
self.0 self.0
} }
} }
impl From<[u8; 32]> for AuthorityId { impl From<[u8; 32]> for Ed25519AuthorityId {
fn from(a: [u8; 32]) -> Self { fn from(a: [u8; 32]) -> Self {
AuthorityId(a) Ed25519AuthorityId(a)
} }
} }
impl AsRef<AuthorityId> for AuthorityId { impl AsRef<Ed25519AuthorityId> for Ed25519AuthorityId {
fn as_ref(&self) -> &AuthorityId { fn as_ref(&self) -> &Ed25519AuthorityId {
&self &self
} }
} }
impl Into<H256> for AuthorityId { impl Into<H256> for Ed25519AuthorityId {
fn into(self) -> H256 { fn into(self) -> H256 {
self.0.into() self.0.into()
} }
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl Serialize for AuthorityId { impl Serialize for Ed25519AuthorityId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
::ed25519::serialize(&self, serializer) ::ed25519::serialize(&self, serializer)
} }
} }
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl<'de> Deserialize<'de> for AuthorityId { impl<'de> Deserialize<'de> for Ed25519AuthorityId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
::ed25519::deserialize(deserializer) ::ed25519::deserialize(deserializer)
} }
+6 -6
View File
@@ -21,7 +21,7 @@
use untrusted; use untrusted;
use blake2_rfc; use blake2_rfc;
use ring::{rand, signature}; use ring::{rand, signature};
use {hash::H512, AuthorityId}; use {hash::H512, Ed25519AuthorityId};
use base58::{ToBase58, FromBase58}; use base58::{ToBase58, FromBase58};
#[cfg(feature = "std")] #[cfg(feature = "std")]
@@ -169,14 +169,14 @@ impl AsRef<Pair> for Pair {
} }
} }
impl Into<AuthorityId> for Public { impl Into<Ed25519AuthorityId> for Public {
fn into(self) -> AuthorityId { fn into(self) -> Ed25519AuthorityId {
AuthorityId(self.0) Ed25519AuthorityId(self.0)
} }
} }
impl From<AuthorityId> for Public { impl From<Ed25519AuthorityId> for Public {
fn from(id: AuthorityId) -> Self { fn from(id: Ed25519AuthorityId) -> Self {
Public(id.0) Public(id.0)
} }
} }
+1 -1
View File
@@ -109,7 +109,7 @@ mod tests;
pub use self::hash::{H160, H256, H512, convert_hash}; pub use self::hash::{H160, H256, H512, convert_hash};
pub use self::uint::U256; pub use self::uint::U256;
pub use authority_id::AuthorityId; pub use authority_id::Ed25519AuthorityId;
pub use changes_trie::ChangesTrieConfiguration; pub use changes_trie::ChangesTrieConfiguration;
pub use hash_db::Hasher; pub use hash_db::Hasher;
@@ -4,9 +4,8 @@ extern crate sr_primitives as runtime_primitives;
extern crate substrate_primitives as primitives; extern crate substrate_primitives as primitives;
extern crate substrate_test_client as test_client; extern crate substrate_test_client as test_client;
use runtime_primitives::traits::{GetNodeBlockType, Block as BlockT}; use runtime_primitives::traits::{GetNodeBlockType, Block as BlockT, AuthorityIdFor};
use runtime_primitives::generic::BlockId; use runtime_primitives::generic::BlockId;
use primitives::AuthorityId;
use substrate_client::runtime_api::{self, RuntimeApiInfo}; use substrate_client::runtime_api::{self, RuntimeApiInfo};
use substrate_client::error::Result; use substrate_client::error::Result;
use test_client::runtime::Block; use test_client::runtime::Block;
@@ -57,7 +56,7 @@ impl_runtime_apis! {
fn version() -> runtime_api::RuntimeVersion { fn version() -> runtime_api::RuntimeVersion {
unimplemented!() unimplemented!()
} }
fn authorities() -> Vec<AuthorityId> { fn authorities() -> Vec<AuthorityIdFor<Block>> {
unimplemented!() unimplemented!()
} }
fn execute_block(_: Block) { fn execute_block(_: Block) {
@@ -19,7 +19,7 @@
use rstd::prelude::*; use rstd::prelude::*;
use codec::{Decode, Encode, Codec, Input}; use codec::{Decode, Encode, Codec, Input};
use traits::{self, Member, DigestItem as DigestItemT, MaybeSerializeDebug}; use traits::{self, Member, DigestItem as DigestItemT, MaybeSerializeDebug, MaybeHash};
use substrate_primitives::hash::H512 as Signature; use substrate_primitives::hash::H512 as Signature;
@@ -124,7 +124,7 @@ impl<Hash, AuthorityId> DigestItem<Hash, AuthorityId> {
impl< impl<
Hash: Codec + Member + MaybeSerializeDebug, Hash: Codec + Member + MaybeSerializeDebug,
AuthorityId: Codec + Member + MaybeSerializeDebug AuthorityId: Codec + Member + MaybeSerializeDebug + MaybeHash
> traits::DigestItem for DigestItem<Hash, AuthorityId> { > traits::DigestItem for DigestItem<Hash, AuthorityId> {
type Hash = Hash; type Hash = Hash;
type AuthorityId = AuthorityId; type AuthorityId = AuthorityId;
+21 -3
View File
@@ -19,12 +19,30 @@
use serde::{Serialize, Serializer, Deserialize, de::Error as DeError, Deserializer}; use serde::{Serialize, Serializer, Deserialize, de::Error as DeError, Deserializer};
use std::{fmt::Debug, ops::Deref, fmt}; use std::{fmt::Debug, ops::Deref, fmt};
use codec::{Codec, Encode, Decode}; use codec::{Codec, Encode, Decode};
use traits::{self, Checkable, Applyable, BlakeTwo256}; use traits::{self, Checkable, Applyable, BlakeTwo256, Convert};
use generic::DigestItem as GenDigestItem; use generic::DigestItem as GenDigestItem;
pub use substrate_primitives::{H256, AuthorityId}; pub use substrate_primitives::{H256, Ed25519AuthorityId};
use substrate_primitives::U256;
pub type DigestItem = GenDigestItem<H256, u64>; #[derive(Default, PartialEq, Eq, Clone, Decode, Encode, Debug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct UintAuthorityId(pub u64);
impl Into<Ed25519AuthorityId> for UintAuthorityId {
fn into(self) -> Ed25519AuthorityId {
let bytes: [u8; 32] = U256::from(self.0).into();
Ed25519AuthorityId(bytes)
}
}
pub struct ConvertUintAuthorityId;
impl Convert<u64, UintAuthorityId> for ConvertUintAuthorityId {
fn convert(a: u64) -> UintAuthorityId {
UintAuthorityId(a)
}
}
pub type DigestItem = GenDigestItem<H256, Ed25519AuthorityId>;
#[derive(Default, PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode)] #[derive(Default, PartialEq, Eq, Clone, Serialize, Debug, Encode, Decode)]
pub struct Digest { pub struct Digest {
+13 -1
View File
@@ -413,6 +413,16 @@ pub trait MaybeDisplay {}
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
impl<T> MaybeDisplay for T {} impl<T> MaybeDisplay for T {}
#[cfg(feature = "std")]
pub trait MaybeHash: ::rstd::hash::Hash {}
#[cfg(feature = "std")]
impl<T: ::rstd::hash::Hash> MaybeHash for T {}
#[cfg(not(feature = "std"))]
pub trait MaybeHash {}
#[cfg(not(feature = "std"))]
impl<T> MaybeHash for T {}
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub trait MaybeDecode: ::codec::Decode {} pub trait MaybeDecode: ::codec::Decode {}
#[cfg(feature = "std")] #[cfg(feature = "std")]
@@ -500,6 +510,8 @@ pub type NumberFor<B> = <<B as Block>::Header as Header>::Number;
pub type DigestFor<B> = <<B as Block>::Header as Header>::Digest; pub type DigestFor<B> = <<B as Block>::Header as Header>::Digest;
/// Extract the digest item type for a block. /// Extract the digest item type for a block.
pub type DigestItemFor<B> = <DigestFor<B> as Digest>::Item; pub type DigestItemFor<B> = <DigestFor<B> as Digest>::Item;
/// Extract the authority ID type for a block.
pub type AuthorityIdFor<B> = <DigestItemFor<B> as DigestItem>::AuthorityId;
/// A "checkable" piece of information, used by the standard Substrate Executive in order to /// A "checkable" piece of information, used by the standard Substrate Executive in order to
/// check the validity of a piece of extrinsic information, usually by verifying the signature. /// check the validity of a piece of extrinsic information, usually by verifying the signature.
@@ -575,7 +587,7 @@ pub trait Digest: Member + MaybeSerializeDebugButNotDeserialize + Default {
/// If the runtime does not supports some 'system' items, use `()` as a stub. /// If the runtime does not supports some 'system' items, use `()` as a stub.
pub trait DigestItem: Codec + Member + MaybeSerializeDebugButNotDeserialize { pub trait DigestItem: Codec + Member + MaybeSerializeDebugButNotDeserialize {
type Hash: Member + MaybeSerializeDebugButNotDeserialize; type Hash: Member + MaybeSerializeDebugButNotDeserialize;
type AuthorityId: Member + MaybeSerializeDebugButNotDeserialize; type AuthorityId: Member + MaybeSerializeDebugButNotDeserialize + MaybeHash + codec::Encode + codec::Decode;
/// Returns Some if the entry is the `AuthoritiesChange` entry. /// Returns Some if the entry is the `AuthoritiesChange` entry.
fn as_authorities_change(&self) -> Option<&[Self::AuthorityId]>; fn as_authorities_change(&self) -> Option<&[Self::AuthorityId]>;
@@ -19,23 +19,23 @@
use std::collections::HashMap; use std::collections::HashMap;
use runtime_io::twox_128; use runtime_io::twox_128;
use codec::{Encode, KeyedVec, Joiner}; use codec::{Encode, KeyedVec, Joiner};
use primitives::{AuthorityId, ChangesTrieConfiguration}; use primitives::{Ed25519AuthorityId, ChangesTrieConfiguration};
use primitives::storage::well_known_keys; use primitives::storage::well_known_keys;
use runtime_primitives::traits::Block; use runtime_primitives::traits::Block;
/// Configuration of a general Substrate test genesis block. /// Configuration of a general Substrate test genesis block.
pub struct GenesisConfig { pub struct GenesisConfig {
pub changes_trie_config: Option<ChangesTrieConfiguration>, pub changes_trie_config: Option<ChangesTrieConfiguration>,
pub authorities: Vec<AuthorityId>, pub authorities: Vec<Ed25519AuthorityId>,
pub balances: Vec<(AuthorityId, u64)>, pub balances: Vec<(Ed25519AuthorityId, u64)>,
} }
impl GenesisConfig { impl GenesisConfig {
pub fn new_simple(authorities: Vec<AuthorityId>, balance: u64) -> Self { pub fn new_simple(authorities: Vec<Ed25519AuthorityId>, balance: u64) -> Self {
Self::new(false, authorities, balance) Self::new(false, authorities, balance)
} }
pub fn new(support_changes_trie: bool, authorities: Vec<AuthorityId>, balance: u64) -> Self { pub fn new(support_changes_trie: bool, authorities: Vec<Ed25519AuthorityId>, balance: u64) -> Self {
GenesisConfig { GenesisConfig {
changes_trie_config: match support_changes_trie { changes_trie_config: match support_changes_trie {
true => Some(super::changes_trie_config()), true => Some(super::changes_trie_config()),
+3 -4
View File
@@ -61,8 +61,7 @@ use runtime_primitives::{
}; };
use runtime_version::RuntimeVersion; use runtime_version::RuntimeVersion;
pub use primitives::hash::H256; pub use primitives::hash::H256;
use primitives::AuthorityId; use primitives::{Ed25519AuthorityId, OpaqueMetadata};
use primitives::OpaqueMetadata;
#[cfg(any(feature = "std", test))] #[cfg(any(feature = "std", test))]
use runtime_version::NativeVersion; use runtime_version::NativeVersion;
use consensus_aura::api as aura_api; use consensus_aura::api as aura_api;
@@ -143,7 +142,7 @@ pub type BlockNumber = u64;
/// Index of a transaction. /// Index of a transaction.
pub type Index = u64; pub type Index = u64;
/// The item of a block digest. /// The item of a block digest.
pub type DigestItem = runtime_primitives::generic::DigestItem<H256, u64>; pub type DigestItem = runtime_primitives::generic::DigestItem<H256, Ed25519AuthorityId>;
/// The digest of a block. /// The digest of a block.
pub type Digest = runtime_primitives::generic::Digest<DigestItem>; pub type Digest = runtime_primitives::generic::Digest<DigestItem>;
/// A test block. /// A test block.
@@ -197,7 +196,7 @@ impl_runtime_apis! {
version() version()
} }
fn authorities() -> Vec<AuthorityId> { fn authorities() -> Vec<Ed25519AuthorityId> {
system::authorities() system::authorities()
} }
+4 -4
View File
@@ -25,7 +25,7 @@ use runtime_primitives::generic;
use runtime_primitives::{ApplyError, ApplyOutcome, ApplyResult, transaction_validity::TransactionValidity}; use runtime_primitives::{ApplyError, ApplyOutcome, ApplyResult, transaction_validity::TransactionValidity};
use codec::{KeyedVec, Encode}; use codec::{KeyedVec, Encode};
use super::{AccountId, BlockNumber, Extrinsic, H256 as Hash, Block, Header, Digest}; use super::{AccountId, BlockNumber, Extrinsic, H256 as Hash, Block, Header, Digest};
use primitives::{Blake2Hasher}; use primitives::{Ed25519AuthorityId, Blake2Hasher};
use primitives::storage::well_known_keys; use primitives::storage::well_known_keys;
const NONCE_OF: &[u8] = b"nonce:"; const NONCE_OF: &[u8] = b"nonce:";
@@ -51,7 +51,7 @@ pub fn nonce_of(who: AccountId) -> u64 {
} }
/// Get authorities ar given block. /// Get authorities ar given block.
pub fn authorities() -> Vec<::primitives::AuthorityId> { pub fn authorities() -> Vec<Ed25519AuthorityId> {
let len: u32 = storage::unhashed::get(well_known_keys::AUTHORITY_COUNT) let len: u32 = storage::unhashed::get(well_known_keys::AUTHORITY_COUNT)
.expect("There are always authorities in test-runtime"); .expect("There are always authorities in test-runtime");
(0..len) (0..len)
@@ -94,7 +94,7 @@ pub fn execute_block(block: Block) {
// check digest // check digest
let mut digest = Digest::default(); let mut digest = Digest::default();
if let Some(storage_changes_root) = storage_changes_root(header.parent_hash.into(), header.number - 1) { if let Some(storage_changes_root) = storage_changes_root(header.parent_hash.into(), header.number - 1) {
digest.push(generic::DigestItem::ChangesTrieRoot::<Hash, u64>(storage_changes_root.into())); digest.push(generic::DigestItem::ChangesTrieRoot(storage_changes_root.into()));
} }
assert!(digest == header.digest, "Header digest items must match that calculated."); assert!(digest == header.digest, "Header digest items must match that calculated.");
} }
@@ -164,7 +164,7 @@ pub fn finalise_block() -> Header {
let mut digest = Digest::default(); let mut digest = Digest::default();
if let Some(storage_changes_root) = storage_changes_root { if let Some(storage_changes_root) = storage_changes_root {
digest.push(generic::DigestItem::ChangesTrieRoot::<Hash, u64>(storage_changes_root)); digest.push(generic::DigestItem::ChangesTrieRoot(storage_changes_root));
} }
Header { Header {
+4 -4
View File
@@ -16,7 +16,7 @@
//! Substrate chain configurations. //! Substrate chain configurations.
use primitives::{AuthorityId, ed25519}; use primitives::{Ed25519AuthorityId, ed25519};
use node_primitives::AccountId; use node_primitives::AccountId;
use node_runtime::{ConsensusConfig, CouncilSeatsConfig, CouncilVotingConfig, DemocracyConfig, use node_runtime::{ConsensusConfig, CouncilSeatsConfig, CouncilVotingConfig, DemocracyConfig,
SessionConfig, StakingConfig, TimestampConfig, BalancesConfig, TreasuryConfig, SessionConfig, StakingConfig, TimestampConfig, BalancesConfig, TreasuryConfig,
@@ -158,7 +158,7 @@ pub fn staging_testnet_config() -> ChainSpec {
} }
/// Helper function to generate AuthorityID from seed /// Helper function to generate AuthorityID from seed
pub fn get_authority_id_from_seed(seed: &str) -> AuthorityId { pub fn get_authority_id_from_seed(seed: &str) -> Ed25519AuthorityId {
let padded_seed = pad_seed(seed); let padded_seed = pad_seed(seed);
// NOTE from ed25519 impl: // NOTE from ed25519 impl:
// prefer pkcs#8 unless security doesn't matter -- this is used primarily for tests. // prefer pkcs#8 unless security doesn't matter -- this is used primarily for tests.
@@ -167,9 +167,9 @@ pub fn get_authority_id_from_seed(seed: &str) -> AuthorityId {
/// Helper function to create GenesisConfig for testing /// Helper function to create GenesisConfig for testing
pub fn testnet_genesis( pub fn testnet_genesis(
initial_authorities: Vec<AuthorityId>, initial_authorities: Vec<Ed25519AuthorityId>,
upgrade_key: AccountId, upgrade_key: AccountId,
endowed_accounts: Option<Vec<AuthorityId>>, endowed_accounts: Option<Vec<Ed25519AuthorityId>>,
) -> GenesisConfig { ) -> GenesisConfig {
let endowed_accounts = endowed_accounts.unwrap_or_else(|| { let endowed_accounts = endowed_accounts.unwrap_or_else(|| {
vec![ vec![
+1 -1
View File
@@ -56,7 +56,7 @@ pub type Balance = u128;
/// The Ed25519 pub key of an session that belongs to an authority of the chain. This is /// The Ed25519 pub key of an session that belongs to an authority of the chain. This is
/// exactly equivalent to what the substrate calls an "authority". /// exactly equivalent to what the substrate calls an "authority".
pub type SessionKey = primitives::AuthorityId; pub type SessionKey = primitives::Ed25519AuthorityId;
/// Index of a transaction in the chain. /// Index of a transaction in the chain.
pub type Index = u64; pub type Index = u64;
+3 -3
View File
@@ -18,7 +18,7 @@
#![cfg(test)] #![cfg(test)]
use primitives::{BuildStorage, testing::{Digest, DigestItem, Header}}; use primitives::{BuildStorage, testing::{Digest, DigestItem, Header, UintAuthorityId}};
use runtime_io; use runtime_io;
use substrate_primitives::{H256, Blake2Hasher}; use substrate_primitives::{H256, Blake2Hasher};
use {Trait, Module, consensus, system, timestamp}; use {Trait, Module, consensus, system, timestamp};
@@ -34,7 +34,7 @@ pub struct Test;
impl consensus::Trait for Test { impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1; const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem; type Log = DigestItem;
type SessionKey = u64; type SessionKey = UintAuthorityId;
type InherentOfflineReport = (); type InherentOfflineReport = ();
} }
@@ -66,7 +66,7 @@ pub fn new_test_ext(authorities: Vec<u64>) -> runtime_io::TestExternalities<Blak
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0; let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
t.extend(consensus::GenesisConfig::<Test>{ t.extend(consensus::GenesisConfig::<Test>{
code: vec![], code: vec![],
authorities, authorities: authorities.into_iter().map(|a| UintAuthorityId(a)).collect(),
}.build_storage().unwrap().0); }.build_storage().unwrap().0);
t.extend(timestamp::GenesisConfig::<Test>{ t.extend(timestamp::GenesisConfig::<Test>{
period: 1, period: 1,
+3 -3
View File
@@ -143,12 +143,12 @@ impl<SessionKey: Member> RawLog<SessionKey> {
// Implementation for tests outside of this crate. // Implementation for tests outside of this crate.
#[cfg(any(feature = "std", test))] #[cfg(any(feature = "std", test))]
impl<N> From<RawLog<N>> for primitives::testing::DigestItem where N: Into<u64> { impl<N> From<RawLog<N>> for primitives::testing::DigestItem where N: Into<substrate_primitives::Ed25519AuthorityId> {
fn from(log: RawLog<N>) -> primitives::testing::DigestItem { fn from(log: RawLog<N>) -> primitives::testing::DigestItem {
match log { match log {
RawLog::AuthoritiesChange(authorities) => RawLog::AuthoritiesChange(authorities) =>
primitives::generic::DigestItem::AuthoritiesChange primitives::generic::DigestItem::AuthoritiesChange(
::<substrate_primitives::H256, u64>(authorities.into_iter() authorities.into_iter()
.map(Into::into).collect()), .map(Into::into).collect()),
} }
} }
+3 -3
View File
@@ -18,7 +18,7 @@
#![cfg(test)] #![cfg(test)]
use primitives::{BuildStorage, testing::{Digest, DigestItem, Header}}; use primitives::{BuildStorage, testing::{Digest, DigestItem, Header, UintAuthorityId}};
use runtime_io; use runtime_io;
use substrate_primitives::{H256, Blake2Hasher}; use substrate_primitives::{H256, Blake2Hasher};
use {GenesisConfig, Trait, Module, system}; use {GenesisConfig, Trait, Module, system};
@@ -33,7 +33,7 @@ pub struct Test;
impl Trait for Test { impl Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1; const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem; type Log = DigestItem;
type SessionKey = u64; type SessionKey = UintAuthorityId;
type InherentOfflineReport = ::InstantFinalityReportVec<()>; type InherentOfflineReport = ::InstantFinalityReportVec<()>;
} }
impl system::Trait for Test { impl system::Trait for Test {
@@ -53,7 +53,7 @@ pub fn new_test_ext(authorities: Vec<u64>) -> runtime_io::TestExternalities<Blak
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0; let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
t.extend(GenesisConfig::<Test>{ t.extend(GenesisConfig::<Test>{
code: vec![], code: vec![],
authorities, authorities: authorities.into_iter().map(|a| UintAuthorityId(a)).collect(),
}.build_storage().unwrap().0); }.build_storage().unwrap().0);
t.into() t.into()
} }
+5 -6
View File
@@ -18,21 +18,20 @@
#![cfg(test)] #![cfg(test)]
use primitives::{generic, testing, traits::{OnFinalise, ProvideInherent}}; use primitives::{generic, testing::{self, UintAuthorityId}, traits::{OnFinalise, ProvideInherent}};
use runtime_io::with_externalities; use runtime_io::with_externalities;
use substrate_primitives::H256;
use mock::{Consensus, System, new_test_ext}; use mock::{Consensus, System, new_test_ext};
#[test] #[test]
fn authorities_change_logged() { fn authorities_change_logged() {
with_externalities(&mut new_test_ext(vec![1, 2, 3]), || { with_externalities(&mut new_test_ext(vec![1, 2, 3]), || {
System::initialise(&1, &Default::default(), &Default::default()); System::initialise(&1, &Default::default(), &Default::default());
Consensus::set_authorities(&[4, 5, 6]); Consensus::set_authorities(&[UintAuthorityId(4), UintAuthorityId(5), UintAuthorityId(6)]);
Consensus::on_finalise(1); Consensus::on_finalise(1);
let header = System::finalise(); let header = System::finalise();
assert_eq!(header.digest, testing::Digest { assert_eq!(header.digest, testing::Digest {
logs: vec![ logs: vec![
generic::DigestItem::AuthoritiesChange::<H256, u64>(vec![4, 5, 6]), generic::DigestItem::AuthoritiesChange(vec![UintAuthorityId(4).into(), UintAuthorityId(5).into(), UintAuthorityId(6).into()]),
], ],
}); });
}); });
@@ -54,8 +53,8 @@ fn authorities_change_is_not_logged_when_not_changed() {
fn authorities_change_is_not_logged_when_changed_back_to_original() { fn authorities_change_is_not_logged_when_changed_back_to_original() {
with_externalities(&mut new_test_ext(vec![1, 2, 3]), || { with_externalities(&mut new_test_ext(vec![1, 2, 3]), || {
System::initialise(&1, &Default::default(), &Default::default()); System::initialise(&1, &Default::default(), &Default::default());
Consensus::set_authorities(&[4, 5, 6]); Consensus::set_authorities(&[UintAuthorityId(4), UintAuthorityId(5), UintAuthorityId(6)]);
Consensus::set_authorities(&[1, 2, 3]); Consensus::set_authorities(&[UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
Consensus::on_finalise(1); Consensus::on_finalise(1);
let header = System::finalise(); let header = System::finalise();
assert_eq!(header.digest, testing::Digest { assert_eq!(header.digest, testing::Digest {
+3 -3
View File
@@ -61,7 +61,7 @@ use runtime_support::dispatch::Result;
use runtime_support::storage::StorageValue; use runtime_support::storage::StorageValue;
use runtime_support::storage::unhashed::StorageVec; use runtime_support::storage::unhashed::StorageVec;
use primitives::traits::{CurrentHeight, Convert}; use primitives::traits::{CurrentHeight, Convert};
use substrate_primitives::AuthorityId; use substrate_primitives::Ed25519AuthorityId;
use system::ensure_signed; use system::ensure_signed;
use primitives::traits::MaybeSerializeDebug; use primitives::traits::MaybeSerializeDebug;
@@ -105,7 +105,7 @@ impl<N: Clone, SessionKey> RawLog<N, SessionKey> {
} }
impl<N, SessionKey> GrandpaChangeSignal<N> for RawLog<N, SessionKey> impl<N, SessionKey> GrandpaChangeSignal<N> for RawLog<N, SessionKey>
where N: Clone, SessionKey: Clone + Into<AuthorityId>, where N: Clone, SessionKey: Clone + Into<Ed25519AuthorityId>,
{ {
fn as_signal(&self) -> Option<ScheduledChange<N>> { fn as_signal(&self) -> Option<ScheduledChange<N>> {
RawLog::as_signal(self).map(|(delay, next_authorities)| ScheduledChange { RawLog::as_signal(self).map(|(delay, next_authorities)| ScheduledChange {
@@ -243,7 +243,7 @@ impl<T: Trait> Module<T> {
} }
} }
impl<T: Trait> Module<T> where AuthorityId: core::convert::From<<T as Trait>::SessionKey> { impl<T: Trait> Module<T> where Ed25519AuthorityId: core::convert::From<<T as Trait>::SessionKey> {
/// See if the digest contains any scheduled change. /// See if the digest contains any scheduled change.
pub fn scrape_digest_change(log: &Log<T>) pub fn scrape_digest_change(log: &Log<T>)
-> Option<ScheduledChange<T::BlockNumber>> -> Option<ScheduledChange<T::BlockNumber>>
+12 -12
View File
@@ -248,8 +248,8 @@ mod tests {
use runtime_io::with_externalities; use runtime_io::with_externalities;
use substrate_primitives::{H256, Blake2Hasher}; use substrate_primitives::{H256, Blake2Hasher};
use primitives::BuildStorage; use primitives::BuildStorage;
use primitives::traits::{Identity, BlakeTwo256}; use primitives::traits::BlakeTwo256;
use primitives::testing::{Digest, DigestItem, Header}; use primitives::testing::{Digest, DigestItem, Header, UintAuthorityId, ConvertUintAuthorityId};
impl_outer_origin!{ impl_outer_origin!{
pub enum Origin for Test {} pub enum Origin for Test {}
@@ -260,7 +260,7 @@ mod tests {
impl consensus::Trait for Test { impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1; const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem; type Log = DigestItem;
type SessionKey = u64; type SessionKey = UintAuthorityId;
type InherentOfflineReport = (); type InherentOfflineReport = ();
} }
impl system::Trait for Test { impl system::Trait for Test {
@@ -281,7 +281,7 @@ mod tests {
type OnTimestampSet = (); type OnTimestampSet = ();
} }
impl Trait for Test { impl Trait for Test {
type ConvertAccountIdToSessionKey = Identity; type ConvertAccountIdToSessionKey = ConvertUintAuthorityId;
type OnSessionChange = (); type OnSessionChange = ();
type Event = (); type Event = ();
} }
@@ -294,7 +294,7 @@ mod tests {
let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0; let mut t = system::GenesisConfig::<Test>::default().build_storage().unwrap().0;
t.extend(consensus::GenesisConfig::<Test>{ t.extend(consensus::GenesisConfig::<Test>{
code: vec![], code: vec![],
authorities: vec![1, 2, 3], authorities: vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)],
}.build_storage().unwrap().0); }.build_storage().unwrap().0);
t.extend(timestamp::GenesisConfig::<Test>{ t.extend(timestamp::GenesisConfig::<Test>{
period: 5, period: 5,
@@ -309,7 +309,7 @@ mod tests {
#[test] #[test]
fn simple_setup_should_work() { fn simple_setup_should_work() {
with_externalities(&mut new_test_ext(), || { with_externalities(&mut new_test_ext(), || {
assert_eq!(Consensus::authorities(), vec![1, 2, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1).into(), UintAuthorityId(2).into(), UintAuthorityId(3).into()]);
assert_eq!(Session::length(), 2); assert_eq!(Session::length(), 2);
assert_eq!(Session::validators(), vec![1, 2, 3]); assert_eq!(Session::validators(), vec![1, 2, 3]);
}); });
@@ -405,25 +405,25 @@ mod tests {
// Block 1: No change // Block 1: No change
System::set_block_number(1); System::set_block_number(1);
Session::check_rotate_session(1); Session::check_rotate_session(1);
assert_eq!(Consensus::authorities(), vec![1, 2, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
// Block 2: Session rollover, but no change. // Block 2: Session rollover, but no change.
System::set_block_number(2); System::set_block_number(2);
Session::check_rotate_session(2); Session::check_rotate_session(2);
assert_eq!(Consensus::authorities(), vec![1, 2, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
// Block 3: Set new key for validator 2; no visible change. // Block 3: Set new key for validator 2; no visible change.
System::set_block_number(3); System::set_block_number(3);
assert_ok!(Session::set_key(Origin::signed(2), 5)); assert_ok!(Session::set_key(Origin::signed(2), UintAuthorityId(5)));
assert_eq!(Consensus::authorities(), vec![1, 2, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
Session::check_rotate_session(3); Session::check_rotate_session(3);
assert_eq!(Consensus::authorities(), vec![1, 2, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]);
// Block 4: Session rollover, authority 2 changes. // Block 4: Session rollover, authority 2 changes.
System::set_block_number(4); System::set_block_number(4);
Session::check_rotate_session(4); Session::check_rotate_session(4);
assert_eq!(Consensus::authorities(), vec![1, 5, 3]); assert_eq!(Consensus::authorities(), vec![UintAuthorityId(1), UintAuthorityId(5), UintAuthorityId(3)]);
}); });
} }
} }
+4 -4
View File
@@ -19,8 +19,8 @@
#![cfg(test)] #![cfg(test)]
use primitives::BuildStorage; use primitives::BuildStorage;
use primitives::{Perbill, traits::Identity}; use primitives::Perbill;
use primitives::testing::{Digest, DigestItem, Header}; use primitives::testing::{Digest, DigestItem, Header, UintAuthorityId, ConvertUintAuthorityId};
use substrate_primitives::{H256, Blake2Hasher}; use substrate_primitives::{H256, Blake2Hasher};
use runtime_io; use runtime_io;
use {GenesisConfig, Module, Trait, consensus, session, system, timestamp, balances}; use {GenesisConfig, Module, Trait, consensus, session, system, timestamp, balances};
@@ -35,7 +35,7 @@ pub struct Test;
impl consensus::Trait for Test { impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1; const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem; type Log = DigestItem;
type SessionKey = u64; type SessionKey = UintAuthorityId;
type InherentOfflineReport = (); type InherentOfflineReport = ();
} }
impl system::Trait for Test { impl system::Trait for Test {
@@ -58,7 +58,7 @@ impl balances::Trait for Test {
type Event = (); type Event = ();
} }
impl session::Trait for Test { impl session::Trait for Test {
type ConvertAccountIdToSessionKey = Identity; type ConvertAccountIdToSessionKey = ConvertUintAuthorityId;
type OnSessionChange = Staking; type OnSessionChange = Staking;
type Event = (); type Event = ();
} }
+1 -2
View File
@@ -176,8 +176,7 @@ impl<Hash: Member> RawLog<Hash> {
impl From<RawLog<substrate_primitives::H256>> for primitives::testing::DigestItem { impl From<RawLog<substrate_primitives::H256>> for primitives::testing::DigestItem {
fn from(log: RawLog<substrate_primitives::H256>) -> primitives::testing::DigestItem { fn from(log: RawLog<substrate_primitives::H256>) -> primitives::testing::DigestItem {
match log { match log {
RawLog::ChangesTrieRoot(root) => primitives::generic::DigestItem::ChangesTrieRoot RawLog::ChangesTrieRoot(root) => primitives::generic::DigestItem::ChangesTrieRoot(root),
::<substrate_primitives::H256, u64>(root),
} }
} }
} }
+2 -2
View File
@@ -190,7 +190,7 @@ mod tests {
use substrate_primitives::H256; use substrate_primitives::H256;
use runtime_primitives::BuildStorage; use runtime_primitives::BuildStorage;
use runtime_primitives::traits::BlakeTwo256; use runtime_primitives::traits::BlakeTwo256;
use runtime_primitives::testing::{Digest, DigestItem, Header}; use runtime_primitives::testing::{Digest, DigestItem, Header, UintAuthorityId};
impl_outer_origin! { impl_outer_origin! {
pub enum Origin for Test {} pub enum Origin for Test {}
@@ -213,7 +213,7 @@ mod tests {
impl consensus::Trait for Test { impl consensus::Trait for Test {
const NOTE_OFFLINE_POSITION: u32 = 1; const NOTE_OFFLINE_POSITION: u32 = 1;
type Log = DigestItem; type Log = DigestItem;
type SessionKey = u64; type SessionKey = UintAuthorityId;
type InherentOfflineReport = (); type InherentOfflineReport = ();
} }
impl Trait for Test { impl Trait for Test {