Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

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

58 changes: 43 additions & 15 deletions client/consensus/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
#![forbid(missing_docs, unsafe_code)]
use std::{
sync::Arc, time::Duration, thread, marker::PhantomData, hash::Hash, fmt::Debug, pin::Pin,
collections::HashMap
collections::HashMap, convert::{TryFrom, TryInto},
};

use futures::prelude::*;
Expand All @@ -52,11 +52,18 @@ use sp_blockchain::{
ProvideCache, HeaderBackend,
};
use sp_block_builder::BlockBuilder as BlockBuilderApi;
use sp_runtime::{generic::{BlockId, OpaqueDigestItemId}, Justification};
use sp_core::crypto::Public;
use sp_application_crypto::{AppKey, AppPublic};
use sp_runtime::{
generic::{BlockId, OpaqueDigestItemId},
Justification,
};
use sp_runtime::traits::{Block as BlockT, Header, DigestItemFor, Zero, Member};
use sp_api::ProvideRuntimeApi;

use sp_core::crypto::Pair;
use sp_core::{
traits::BareCryptoStore,
crypto::Pair
Comment thread
rakanalh marked this conversation as resolved.
Outdated
};
use sp_inherents::{InherentDataProviders, InherentData};
use sp_timestamp::{
TimestampInherentData, InherentType as TimestampInherent, InherentError as TIError
Expand Down Expand Up @@ -150,8 +157,8 @@ pub fn start_aura<B, C, SC, E, I, P, SO, CAW, Error>(
E: Environment<B, Error = Error> + Send + Sync + 'static,
E::Proposer: Proposer<B, Error = Error, Transaction = sp_api::TransactionFor<C, B>>,
P: Pair + Send + Sync,
P::Public: Hash + Member + Encode + Decode,
P::Signature: Hash + Member + Encode + Decode,
P::Public: AppPublic + Hash + Member + Encode + Decode,
P::Signature: TryFrom<Vec<u8>> + Hash + Member + Encode + Decode,
I: BlockImport<B, Transaction = sp_api::TransactionFor<C, B>> + Send + Sync + 'static,
Error: std::error::Error + Send + From<sp_consensus::Error> + 'static,
SO: SyncOracle + Send + Sync + Clone,
Expand Down Expand Up @@ -199,8 +206,8 @@ impl<B, C, E, I, P, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for AuraW
E::Proposer: Proposer<B, Error = Error, Transaction = sp_api::TransactionFor<C, B>>,
I: BlockImport<B, Transaction = sp_api::TransactionFor<C, B>> + Send + Sync + 'static,
P: Pair + Send + Sync,
P::Public: Member + Encode + Decode + Hash,
P::Signature: Member + Encode + Decode + Hash + Debug,
P::Public: AppPublic + Public + Member + Encode + Decode + Hash,
P::Signature: TryFrom<Vec<u8>> + Member + Encode + Decode + Hash + Debug,
SO: SyncOracle + Send + Clone,
Error: std::error::Error + Send + From<sp_consensus::Error> + 'static,
{
Expand All @@ -212,6 +219,7 @@ impl<B, C, E, I, P, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for AuraW
type Proposer = E::Proposer;
type Claim = P;
Comment thread
rakanalh marked this conversation as resolved.
Outdated
type EpochData = Vec<AuthorityId<P>>;
type Public = P::Public;
Comment thread
rakanalh marked this conversation as resolved.
Outdated

fn logging_target(&self) -> &'static str {
"aura"
Expand Down Expand Up @@ -257,18 +265,38 @@ impl<B, C, E, I, P, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for AuraW
]
}

fn publickey_from_claim(&self, claim: &Self::Claim) -> Self::Public {
Comment thread
rakanalh marked this conversation as resolved.
Outdated
claim.public()
}

fn block_import_params(&self) -> Box<dyn Fn(
B::Header,
&B::Hash,
Vec<B::Extrinsic>,
StorageChanges<sp_api::TransactionFor<C, B>, B>,
Self::Claim,
Self::Public,
Self::EpochData,
) -> sp_consensus::BlockImportParams<B, sp_api::TransactionFor<C, B>> + Send> {
Box::new(|header, header_hash, body, storage_changes, pair, _epoch| {
) -> Result<sp_consensus::BlockImportParams<B, sp_api::TransactionFor<C, B>>, sp_consensus::Error> + Send + 'static> {
let keystore = self.keystore.clone();
Box::new(move |header, header_hash, body, storage_changes, public, _epoch| {
// sign the pre-sealed hash of the block and then
// add it to a digest item.
let signature = pair.sign(header_hash.as_ref());
let public_type_pair = public.to_public_crypto_pair();
let public = public.to_raw_vec();
let signature = keystore.read()
.sign_with(
Comment thread
bkchr marked this conversation as resolved.
<AuthorityId<Self::Claim> as AppKey>::ID,
&public_type_pair,
header_hash.as_ref()
)
.map_err(|e| sp_consensus::Error::CannotSign(
public.clone(), e.to_string(),
))?;
let signature = signature.clone().try_into()
.map_err(|_| sp_consensus::Error::InvalidSignature(
signature, public
))?;

let signature_digest_item = <DigestItemFor<B> as CompatibleDigestItem<P>>::aura_seal(signature);

let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
Expand All @@ -277,7 +305,7 @@ impl<B, C, E, I, P, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for AuraW
import_block.storage_changes = Some(storage_changes);
import_block.fork_choice = Some(ForkChoiceStrategy::LongestChain);

import_block
Ok(import_block)
})
}

Expand Down Expand Up @@ -331,8 +359,8 @@ impl<B: BlockT, C, E, I, P, Error, SO> SlotWorker<B> for AuraWorker<C, E, I, P,
E::Proposer: Proposer<B, Error = Error, Transaction = sp_api::TransactionFor<C, B>>,
I: BlockImport<B, Transaction = sp_api::TransactionFor<C, B>> + Send + Sync + 'static,
P: Pair + Send + Sync,
P::Public: Member + Encode + Decode + Hash,
P::Signature: Member + Encode + Decode + Hash + Debug,
P::Public: AppPublic + Member + Encode + Decode + Hash,
P::Signature: TryFrom<Vec<u8>> + Member + Encode + Decode + Hash + Debug,
SO: SyncOracle + Send + Sync + Clone,
Error: std::error::Error + Send + From<sp_consensus::Error> + 'static,
{
Expand Down
41 changes: 33 additions & 8 deletions client/consensus/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,25 @@ pub use sp_consensus_babe::{
pub use sp_consensus::SyncOracle;
use std::{
collections::HashMap, sync::Arc, u64, pin::Pin, time::{Instant, Duration},
any::Any, borrow::Cow
any::Any, borrow::Cow, convert::TryInto,
};
use sp_consensus::{ImportResult, CanAuthorWith};
use sp_consensus::import_queue::{
BoxJustificationImport, BoxFinalityProofImport,
};
use sp_core::crypto::Public;
Comment thread
rakanalh marked this conversation as resolved.
Outdated
use sp_application_crypto::AppKey;
use sp_runtime::{
generic::{BlockId, OpaqueDigestItemId}, Justification,
traits::{Block as BlockT, Header, DigestItemFor, Zero},
};
use sp_api::{ProvideRuntimeApi, NumberFor};
use sc_keystore::KeyStorePtr;
use parking_lot::Mutex;
use sp_core::Pair;
use sp_core::{
traits::BareCryptoStore,
Pair
};
use sp_inherents::{InherentDataProviders, InherentData};
use sc_telemetry::{telemetry, CONSENSUS_TRACE, CONSENSUS_DEBUG};
use sp_consensus::{
Expand Down Expand Up @@ -447,6 +452,7 @@ impl<B, C, E, I, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for BabeWork
>>;
type Proposer = E::Proposer;
type BlockImport = I;
type Public = AuthorityId;

fn logging_target(&self) -> &'static str {
"babe"
Expand Down Expand Up @@ -510,19 +516,38 @@ impl<B, C, E, I, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for BabeWork
]
}

fn publickey_from_claim(&self, claim: &Self::Claim) -> Self::Public {
claim.1.public()
}

fn block_import_params(&self) -> Box<dyn Fn(
B::Header,
&B::Hash,
Vec<B::Extrinsic>,
StorageChanges<I::Transaction, B>,
Self::Claim,
Self::Public,
Self::EpochData,
) -> sp_consensus::BlockImportParams<B, I::Transaction> + Send> {
Box::new(|header, header_hash, body, storage_changes, (_, pair), epoch_descriptor| {
) -> Result<sp_consensus::BlockImportParams<B, I::Transaction>, sp_consensus::Error> + Send + 'static> {
let keystore = self.keystore.clone();
Box::new(move |header, header_hash, body, storage_changes, public, epoch_descriptor| {
// sign the pre-sealed hash of the block and then
// add it to a digest item.
let signature = pair.sign(header_hash.as_ref());
let digest_item = <DigestItemFor<B> as CompatibleDigestItem>::babe_seal(signature);
let public_type_pair = public.clone().into();
let public = public.to_raw_vec();
let signature = keystore.read()
.sign_with(
<AuthorityId as AppKey>::ID,
&public_type_pair,
header_hash.as_ref()
)
.map_err(|e| sp_consensus::Error::CannotSign(
public.clone(), e.to_string(),
))?;
let signature: AuthoritySignature = signature.clone().try_into()
.map_err(|_| sp_consensus::Error::InvalidSignature(
signature, public
))?;
let digest_item = <DigestItemFor<B> as CompatibleDigestItem>::babe_seal(signature.into());

let mut import_block = BlockImportParams::new(BlockOrigin::Own, header);
import_block.post_digests.push(digest_item);
Expand All @@ -533,7 +558,7 @@ impl<B, C, E, I, Error, SO> sc_consensus_slots::SimpleSlotWorker<B> for BabeWork
Box::new(BabeIntermediate::<B> { epoch_descriptor }) as Box<dyn Any>,
);

import_block
Ok(import_block)
})
}

Expand Down
1 change: 1 addition & 0 deletions client/consensus/slots/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"]
codec = { package = "parity-scale-codec", version = "1.3.0" }
sc-client-api = { version = "2.0.0-dev", path = "../../api" }
sp-core = { version = "2.0.0-dev", path = "../../../primitives/core" }
sp-application-crypto = { version = "2.0.0-dev", path = "../../../primitives/application-crypto" }
sp-blockchain = { version = "2.0.0-dev", path = "../../../primitives/blockchain" }
sp-runtime = { version = "2.0.0-dev", path = "../../../primitives/runtime" }
sp-state-machine = { version = "0.8.0-dev", path = "../../../primitives/state-machine" }
Expand Down
33 changes: 25 additions & 8 deletions client/consensus/slots/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use futures::{prelude::*, future::{self, Either}};
use futures_timer::Delay;
use sp_inherents::{InherentData, InherentDataProviders};
use log::{debug, error, info, warn};
use sp_application_crypto::AppPublic;
use sp_runtime::generic::BlockId;
use sp_runtime::traits::{Block as BlockT, Header, HashFor, NumberFor};
use sp_api::{ProvideRuntimeApi, ApiRef};
Expand Down Expand Up @@ -80,6 +81,9 @@ pub trait SimpleSlotWorker<B: BlockT> {
/// Data associated with a slot claim.
type Claim: Send + 'static;

/// Authority public key
type Public: AppPublic;

/// Epoch data necessary for authoring.
type EpochData: Send + 'static;

Expand Down Expand Up @@ -112,20 +116,25 @@ pub trait SimpleSlotWorker<B: BlockT> {
claim: &Self::Claim,
) -> Vec<sp_runtime::DigestItem<B::Hash>>;

/// Extract the claim's authority public key
fn publickey_from_claim(
&self,
claim: &Self::Claim,
) -> Self::Public;

/// Returns a function which produces a `BlockImportParams`.
fn block_import_params(&self) -> Box<
dyn Fn(
B::Header,
&B::Hash,
Vec<B::Extrinsic>,
StorageChanges<<Self::BlockImport as BlockImport<B>>::Transaction, B>,
Self::Claim,
Self::Public,
Self::EpochData,
) -> sp_consensus::BlockImportParams<
B,
<Self::BlockImport as BlockImport<B>>::Transaction
>
+ Send
) -> Result<
Comment thread
gnunicorn marked this conversation as resolved.
sp_consensus::BlockImportParams<B, <Self::BlockImport as BlockImport<B>>::Transaction>,
sp_consensus::Error
> + Send + 'static
>;

/// Whether to force authoring if offline.
Expand Down Expand Up @@ -214,6 +223,8 @@ pub trait SimpleSlotWorker<B: BlockT> {
Some(claim) => claim,
};

let pubkey = self.publickey_from_claim(&claim);

debug!(
target: self.logging_target(), "Starting authorship at slot {}; timestamp = {}",
slot_number,
Expand Down Expand Up @@ -273,7 +284,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
let block_import = self.block_import();
let logging_target = self.logging_target();

Box::pin(proposal_work.map_ok(move |(proposal, claim)| {
Box::pin(proposal_work.and_then(move |(proposal, _claim)| {
let (header, body) = proposal.block.deconstruct();
let header_num = *header.number();
let header_hash = header.hash();
Expand All @@ -284,10 +295,15 @@ pub trait SimpleSlotWorker<B: BlockT> {
&header_hash,
body,
proposal.storage_changes,
claim,
pubkey,
epoch_data,
);

let block_import_params = match block_import_params {
Ok(params) => params,
Err(e) => return future::err(e),
};

info!(
"🔖 Pre-sealed block for proposal at {}. Hash now {:?}, previously {:?}.",
header_num,
Expand All @@ -312,6 +328,7 @@ pub trait SimpleSlotWorker<B: BlockT> {
"hash" => ?parent_hash, "err" => ?err,
);
}
future::ready(Ok(()))
}))
}
}
Expand Down
14 changes: 13 additions & 1 deletion primitives/application-crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ pub use codec;
#[cfg(feature = "std")]
pub use serde;
#[doc(hidden)]
pub use sp_std::{ops::Deref, vec::Vec};
pub use sp_std::{
convert::TryFrom,
ops::Deref,
vec::Vec,
};

pub mod ed25519;
pub mod sr25519;
Expand Down Expand Up @@ -456,6 +460,14 @@ macro_rules! app_crypto_signature_common {
impl $crate::AppSignature for Signature {
type Generic = $sig;
}

impl $crate::TryFrom<$crate::Vec<u8>> for Signature {
type Error = ();

fn try_from(data: $crate::Vec<u8>) -> Result<Self, Self::Error> {
Ok(<$sig>::try_from(data.as_slice())?.into())
}
}
}
}

Expand Down
7 changes: 5 additions & 2 deletions primitives/consensus/common/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

//! Error types in Consensus
use sp_version::RuntimeVersion;
use sp_core::ed25519::{Public, Signature};
use sp_core::ed25519::Public;
use std::error;

/// Result type alias.
Expand Down Expand Up @@ -48,7 +48,7 @@ pub enum Error {
CannotPropose,
/// Error checking signature
#[display(fmt="Message signature {:?} by {:?} is invalid.", _0, _1)]
InvalidSignature(Signature, Public),
InvalidSignature(Vec<u8>, Vec<u8>),
/// Invalid authorities set received from the runtime.
#[display(fmt="Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet,
Expand Down Expand Up @@ -79,6 +79,9 @@ pub enum Error {
#[display(fmt="Chain lookup failed: {}", _0)]
#[from(ignore)]
ChainLookup(String),
/// Signing failed
#[display(fmt="Failed to sign using key: {:?}. Reason: {}", _0, _1)]
CannotSign(Vec<u8>, String)
}

impl error::Error for Error {
Expand Down
1 change: 1 addition & 0 deletions primitives/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ documentation = "https://docs.rs/sp-core"
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
derive_more = "0.99.2"
sp-std = { version = "2.0.0-dev", default-features = false, path = "../std" }
codec = { package = "parity-scale-codec", version = "1.3.0", default-features = false, features = ["derive"] }
log = { version = "0.4.8", default-features = false }
Expand Down
Loading