Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

babe: report equivocations #6362

Merged
merged 33 commits into from
Jul 4, 2020
Merged
Show file tree
Hide file tree
Changes from 14 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.
Jump to
Jump to file
Failed to load files.
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.

39 changes: 38 additions & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,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 @@ -820,7 +835,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 @@ -997,6 +1012,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,
andresilva marked this conversation as resolved.
Show resolved Hide resolved
) -> 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(());
}
andresilva marked this conversation as resolved.
Show resolved Hide resolved

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.
andresilva marked this conversation as resolved.
Show resolved Hide resolved
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::SpawnBlocking,
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
1 change: 1 addition & 0 deletions client/consensus/slots/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ sc-client-api = { version = "2.0.0-rc3", path = "../../api" }
sp-core = { version = "2.0.0-rc3", path = "../../../primitives/core" }
sp-application-crypto = { version = "2.0.0-rc3", path = "../../../primitives/application-crypto" }
sp-blockchain = { version = "2.0.0-rc3", path = "../../../primitives/blockchain" }
sp-consensus-slots = { version = "0.8.0-rc3", path = "../../../primitives/consensus/slots" }
sp-runtime = { version = "2.0.0-rc3", path = "../../../primitives/runtime" }
sp-state-machine = { version = "0.8.0-rc3", path = "../../../primitives/state-machine" }
sp-api = { version = "2.0.0-rc3", path = "../../../primitives/api" }
Expand Down
35 changes: 6 additions & 29 deletions client/consensus/slots/src/aux_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use codec::{Encode, Decode};
use sc_client_api::backend::AuxStore;
use sp_blockchain::{Result as ClientResult, Error as ClientError};
use sp_consensus_slots::EquivocationProof;
use sp_runtime::traits::Header;

const SLOT_HEADER_MAP_KEY: &[u8] = b"slot_header_map";
Expand All @@ -44,31 +45,6 @@ fn load_decode<C, T>(backend: &C, key: &[u8]) -> ClientResult<Option<T>>
}
}

/// Represents an equivocation proof.
#[derive(Debug, Clone)]
pub struct EquivocationProof<H> {
slot: u64,
fst_header: H,
snd_header: H,
}

impl<H> EquivocationProof<H> {
/// Get the slot number where the equivocation happened.
pub fn slot(&self) -> u64 {
self.slot
}

/// Get the first header involved in the equivocation.
pub fn fst_header(&self) -> &H {
&self.fst_header
}

/// Get the second header involved in the equivocation.
pub fn snd_header(&self) -> &H {
&self.snd_header
}
}

/// Checks if the header is an equivocation and returns the proof in that case.
///
/// Note: it detects equivocations only when slot_now - slot <= MAX_SLOT_CAPACITY.
Expand All @@ -78,7 +54,7 @@ pub fn check_equivocation<C, H, P>(
slot: u64,
header: &H,
signer: &P,
) -> ClientResult<Option<EquivocationProof<H>>>
) -> ClientResult<Option<EquivocationProof<H, P>>>
where
H: Header,
C: AuxStore,
Expand Down Expand Up @@ -114,9 +90,10 @@ pub fn check_equivocation<C, H, P>(
// 2) with different hash
if header.hash() != prev_header.hash() {
return Ok(Some(EquivocationProof {
slot, // 3) and mentioning the same slot.
fst_header: prev_header.clone(),
snd_header: header.clone(),
slot_number: slot,
offender: signer.clone(),
first_header: prev_header.clone(),
second_header: header.clone(),
}));
} else {
// We don't need to continue in case of duplicated header,
Expand Down