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 17 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
527e971
slots: create primitives crate for consensus slots
andresilva Jun 3, 2020
4ffdc8a
offences: add method to check if an offence is unknown
andresilva Jun 8, 2020
94084aa
babe: initial equivocation reporting implementation
andresilva Jun 8, 2020
8759f02
babe: organize imports
andresilva Jun 8, 2020
54ceef3
babe: working equivocation reporting
andresilva Jun 11, 2020
af2e58b
babe: add slot number to equivocation proof
andresilva Jun 15, 2020
4b573fb
session: move duplicate traits to session primitives
andresilva Jun 15, 2020
f20c07f
babe: move equivocation stuff to its own file
andresilva Jun 15, 2020
1215653
offences: fix test
andresilva Jun 15, 2020
03f5b71
session: don't have primitives depend on frame_support
andresilva Jun 15, 2020
17ea089
babe: use opaque type for key owner proof
andresilva Jun 15, 2020
d243323
babe: cleanup client equivocation reporting
andresilva Jun 15, 2020
237689e
babe: cleanup equivocation code in pallet
andresilva Jun 15, 2020
760996a
babe: allow sending signed equivocation reports
andresilva Jun 15, 2020
5464a0a
node: fix compilation
andresilva Jun 16, 2020
585f80b
fix test compilation
andresilva Jun 16, 2020
26bfb4f
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jun 16, 2020
0f22701
babe: return bool on check_equivocation_proof
andresilva Jun 22, 2020
81ce38f
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jun 22, 2020
95b29be
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jun 24, 2020
e8467c4
babe: add test for equivocation reporting
andresilva Jun 30, 2020
187008a
babe: add more tests
andresilva Jun 30, 2020
ae68282
babe: add test for validate unsigned
andresilva Jun 30, 2020
db83144
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jun 30, 2020
17a0141
babe: take slot number in generate_key_ownership_proof API
andresilva Jun 30, 2020
27dc893
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jul 1, 2020
a1db90c
babe: add benchmark for equivocation proof checking
andresilva Jul 1, 2020
f88e5e6
session: add benchmark for membership proof checking
andresilva Jul 1, 2020
15b1000
offences: fix babe benchmark
andresilva Jul 1, 2020
8a5e0bc
babe: add weights based on benchmark results
andresilva Jul 1, 2020
d53a277
babe: adjust weights after benchmarking on reference hardware
andresilva Jul 2, 2020
4b1b2ce
Merge branch 'master' into andre/report-babe-equivocations
andresilva Jul 2, 2020
dbc9ee2
babe: reorder checks in check_and_report_equivocation
andresilva Jul 3, 2020
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
13 changes: 13 additions & 0 deletions Cargo.lock

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

10 changes: 8 additions & 2 deletions bin/node/cli/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ macro_rules! new_full_start {
let (grandpa_block_import, grandpa_link) = grandpa::block_import(
client.clone(),
&(client.clone() as Arc<_>),
select_chain,
select_chain.clone(),
)?;
let justification_import = grandpa_block_import.clone();

Expand All @@ -93,6 +93,7 @@ macro_rules! new_full_start {
Some(Box::new(justification_import)),
None,
client,
select_chain,
Copy link
Contributor

Choose a reason for hiding this comment

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

@andresilva Do light clients need a select chain instance? Is this something we could turn into an Option?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think this can be turned into an option. This was added to fetch some data required for submitting equivocation reports, which the light clients won't do for now as only block authors submit them.

inherent_data_providers.clone(),
spawn_task_handle,
prometheus_registry,
Expand Down Expand Up @@ -347,14 +348,18 @@ pub fn new_light(config: Configuration)
client,
backend,
fetcher,
_select_chain,
mut select_chain,
_tx_pool,
spawn_task_handle,
registry,
| {
let select_chain = select_chain.take()
.ok_or_else(|| sc_service::Error::SelectChainRequired)?;

let fetch_checker = fetcher
.map(|fetcher| fetcher.checker().clone())
.ok_or_else(|| "Trying to start light import queue without active fetch checker")?;

let grandpa_block_import = grandpa::light_block_import(
client.clone(),
backend,
Expand All @@ -378,6 +383,7 @@ pub fn new_light(config: Configuration)
None,
Some(Box::new(finality_proof_import)),
client.clone(),
select_chain,
inherent_data_providers.clone(),
spawn_task_handle,
registry,
Expand Down
39 changes: 38 additions & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,21 @@ impl pallet_babe::Trait for Runtime {
type EpochDuration = EpochDuration;
type ExpectedBlockTime = ExpectedBlockTime;
type EpochChangeTrigger = pallet_babe::ExternalTrigger;

type KeyOwnerProofSystem = Historical;

type KeyOwnerProof = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::Proof;

type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(
KeyTypeId,
pallet_babe::AuthorityId,
)>>::IdentificationTuple;

type HandleEquivocation =
pallet_babe::EquivocationHandler<Self::KeyOwnerIdentification, Offences>;
}

parameter_types! {
Expand Down Expand Up @@ -809,7 +824,7 @@ construct_runtime!(
{
System: frame_system::{Module, Call, Config, Storage, Event<T>},
Utility: pallet_utility::{Module, Call, Event},
Babe: pallet_babe::{Module, Call, Storage, Config, Inherent(Timestamp)},
Babe: pallet_babe::{Module, Call, Storage, Config, Inherent(Timestamp), ValidateUnsigned},
Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},
Authorship: pallet_authorship::{Module, Call, Storage, Inherent},
Indices: pallet_indices::{Module, Call, Storage, Config<T>, Event<T>},
Expand Down Expand Up @@ -986,6 +1001,28 @@ impl_runtime_apis! {
fn current_epoch_start() -> sp_consensus_babe::SlotNumber {
Babe::current_epoch_start()
}

fn generate_key_ownership_proof(
authority_id: sp_consensus_babe::AuthorityId,
) -> Option<sp_consensus_babe::OpaqueKeyOwnershipProof> {
use codec::Encode;

Historical::prove((sp_consensus_babe::KEY_TYPE, authority_id))
.map(|p| p.encode())
.map(sp_consensus_babe::OpaqueKeyOwnershipProof::new)
}

fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: sp_consensus_babe::EquivocationProof<<Block as BlockT>::Header>,
key_owner_proof: sp_consensus_babe::OpaqueKeyOwnershipProof,
) -> Option<()> {
let key_owner_proof = key_owner_proof.decode()?;

Babe::submit_unsigned_equivocation_report(
equivocation_proof,
key_owner_proof,
)
}
}

impl sp_authority_discovery::AuthorityDiscoveryApi<Block> for Runtime {
Expand Down
4 changes: 2 additions & 2 deletions client/consensus/aura/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,8 @@ fn check_header<C, B: BlockT, P: Pair>(
info!(
"Slot author is equivocating at slot {} with headers {:?} and {:?}",
slot_num,
equivocation_proof.fst_header().hash(),
equivocation_proof.snd_header().hash(),
equivocation_proof.first_header.hash(),
equivocation_proof.second_header.hash(),
);
}

Expand Down
133 changes: 105 additions & 28 deletions client/consensus/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -720,27 +720,29 @@ impl<Block: BlockT> BabeLink<Block> {
}

/// A verifier for Babe blocks.
pub struct BabeVerifier<Block: BlockT, Client> {
pub struct BabeVerifier<Block: BlockT, Client, SelectChain> {
client: Arc<Client>,
select_chain: SelectChain,
inherent_data_providers: sp_inherents::InherentDataProviders,
config: Config,
epoch_changes: SharedEpochChanges<Block, Epoch>,
time_source: TimeSource,
}

impl<Block, Client> BabeVerifier<Block, Client>
where
Block: BlockT,
Client: HeaderBackend<Block> + HeaderMetadata<Block> + ProvideRuntimeApi<Block>,
Client::Api: BlockBuilderApi<Block, Error = sp_blockchain::Error>,
impl<Block, Client, SelectChain> BabeVerifier<Block, Client, SelectChain>
where
Block: BlockT,
Client: AuxStore + HeaderBackend<Block> + HeaderMetadata<Block> + ProvideRuntimeApi<Block>,
Client::Api: BlockBuilderApi<Block, Error = sp_blockchain::Error>
+ BabeApi<Block, Error = sp_blockchain::Error>,
SelectChain: sp_consensus::SelectChain<Block>,
{
fn check_inherents(
&self,
block: Block,
block_id: BlockId<Block>,
inherent_data: InherentData,
) -> Result<(), Error<Block>>
{
) -> Result<(), Error<Block>> {
let inherent_res = self.client.runtime_api().check_inherents(
&block_id,
block,
Expand All @@ -757,13 +759,95 @@ impl<Block, Client> BabeVerifier<Block, Client>
Ok(())
}
}

fn check_and_report_equivocation(
&self,
slot_now: SlotNumber,
slot: SlotNumber,
header: &Block::Header,
author: &AuthorityId,
origin: &BlockOrigin,
) -> Result<(), Error<Block>> {
// check if authorship of this header is an equivocation and return a proof if so.
let equivocation_proof =
match check_equivocation(&*self.client, slot_now, slot, header, author)
.map_err(Error::Client)?
{
Some(proof) => proof,
None => return Ok(()),
};

// don't report any equivocations during initial sync
// as they are most likely stale.
if *origin == BlockOrigin::NetworkInitialSync {
return Ok(());
}

info!(
"Slot author {:?} is equivocating at slot {} with headers {:?} and {:?}",
author,
slot,
equivocation_proof.first_header.hash(),
equivocation_proof.second_header.hash(),
);

// get the best block on which we will build and send the equivocation report.
let best_id = self
.select_chain
.best_chain()
.map(|h| BlockId::Hash(h.hash()))
.map_err(|e| Error::Client(e.into()))?;

// generate a key ownership proof. we start by trying to generate the
// key owernship proof at the parent of the equivocating header, this
// will make sure that proof generation is successful since it happens
// during the on-going session (i.e. session keys are available in the
// state to be able to generate the proof). this might fail if the
// equivocation happens on the first block of the session, in which case
// its parent would be on the previous session. if generation on the
// parent header fails we try with best block as well.
let generate_key_owner_proof = |block_id: &BlockId<Block>| {
self.client
.runtime_api()
.generate_key_ownership_proof(block_id, equivocation_proof.offender.clone())
.map_err(Error::Client)
};

let parent_id = BlockId::Hash(*header.parent_hash());
let key_owner_proof = match generate_key_owner_proof(&parent_id)? {
Some(proof) => proof,
None => match generate_key_owner_proof(&best_id)? {
Some(proof) => proof,
None => {
debug!(target: "babe", "Equivocation offender is not part of the authority set.");
return Ok(());
}
},
};

// submit equivocation report at best block.
self.client
.runtime_api()
.submit_report_equivocation_unsigned_extrinsic(
&best_id,
equivocation_proof,
key_owner_proof,
)
.map_err(Error::Client)?;

info!(target: "babe", "Submitted equivocation report for author {:?}", author);

Ok(())
}
}

impl<Block, Client> Verifier<Block> for BabeVerifier<Block, Client> where
impl<Block, Client, SelectChain> Verifier<Block> for BabeVerifier<Block, Client, SelectChain>
where
Block: BlockT,
Client: HeaderMetadata<Block, Error = sp_blockchain::Error> + HeaderBackend<Block> + ProvideRuntimeApi<Block>
+ Send + Sync + AuxStore + ProvideCache<Block>,
+ Send + Sync + AuxStore + ProvideCache<Block>,
Client::Api: BlockBuilderApi<Block, Error = sp_blockchain::Error> + BabeApi<Block, Error = sp_blockchain::Error>,
SelectChain: sp_consensus::SelectChain<Block>,
{
fn verify(
&mut self,
Expand Down Expand Up @@ -824,28 +908,18 @@ impl<Block, Client> Verifier<Block> for BabeVerifier<Block, Client> where
CheckedHeader::Checked(pre_header, verified_info) => {
let babe_pre_digest = verified_info.pre_digest.as_babe_pre_digest()
.expect("check_header always returns a pre-digest digest item; qed");

let slot_number = babe_pre_digest.slot_number();

let author = verified_info.author;

// the header is valid but let's check if there was something else already
// proposed at the same slot by the given author
if let Some(equivocation_proof) = check_equivocation(
&*self.client,
// proposed at the same slot by the given author. if there was, we will
// report the equivocation to the runtime.
self.check_and_report_equivocation(
slot_now,
babe_pre_digest.slot_number(),
slot_number,
&header,
&author,
).map_err(|e| e.to_string())? {
info!(
"Slot author {:?} is equivocating at slot {} with headers {:?} and {:?}",
author,
babe_pre_digest.slot_number(),
equivocation_proof.fst_header().hash(),
equivocation_proof.snd_header().hash(),
);
}
&verified_info.author,
&origin,
)?;

// if the body is passed through, we need to use the runtime
// to check that the internally-set timestamp in the inherents
Expand Down Expand Up @@ -1284,12 +1358,13 @@ pub fn block_import<Client, Block: BlockT, I>(
///
/// The block import object provided must be the `BabeBlockImport` or a wrapper
/// of it, otherwise crucial import logic will be omitted.
pub fn import_queue<Block: BlockT, Client, Inner>(
pub fn import_queue<Block: BlockT, Client, SelectChain, Inner>(
babe_link: BabeLink<Block>,
block_import: Inner,
justification_import: Option<BoxJustificationImport<Block>>,
finality_proof_import: Option<BoxFinalityProofImport<Block>>,
client: Arc<Client>,
select_chain: SelectChain,
inherent_data_providers: InherentDataProviders,
spawner: &impl sp_core::traits::SpawnNamed,
registry: Option<&Registry>,
Expand All @@ -1299,11 +1374,13 @@ pub fn import_queue<Block: BlockT, Client, Inner>(
Client: ProvideRuntimeApi<Block> + ProvideCache<Block> + Send + Sync + AuxStore + 'static,
Client: HeaderBackend<Block> + HeaderMetadata<Block, Error = sp_blockchain::Error>,
Client::Api: BlockBuilderApi<Block> + BabeApi<Block> + ApiExt<Block, Error = sp_blockchain::Error>,
SelectChain: sp_consensus::SelectChain<Block> + 'static,
{
register_babe_inherent_data_provider(&inherent_data_providers, babe_link.config.slot_duration)?;

let verifier = BabeVerifier {
client,
select_chain,
inherent_data_providers,
config: babe_link.config,
epoch_changes: babe_link.epoch_changes,
Expand Down
Loading