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

babe: secondary blocks with VRF #5501

Merged
merged 37 commits into from
Apr 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
3517a80
babe: secondary blocks with VRF
sorpaas Apr 2, 2020
ae38673
Fix node runtime compile
sorpaas Apr 2, 2020
13aa495
Fix test-utils runtime interface
sorpaas Apr 2, 2020
c264025
Fix babe tests
sorpaas Apr 2, 2020
936253c
typo: v == 2
sorpaas Apr 3, 2020
5383f4d
babe: support online configuration upgrades
sorpaas Apr 3, 2020
2c91a14
Fix rpc tests
sorpaas Apr 3, 2020
06adbb9
Fix runtime version tests
sorpaas Apr 3, 2020
c1b502c
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas Apr 3, 2020
8185b91
Switch to use NextConfigDescriptor instead of changing runtime interface
sorpaas Apr 7, 2020
e9c57dd
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas Apr 7, 2020
559b895
Fix tests
sorpaas Apr 7, 2020
9402233
Merge branch 'master' into sp-epoch-config
sorpaas Apr 8, 2020
682e3b7
epoch-changes: map function that allows converting with different epo…
sorpaas Apr 8, 2020
fc8d9fe
Add migration script for the epoch config change
sorpaas Apr 8, 2020
7a65f26
Merge branch 'sp-epoch-config' of https://github.com/paritytech/subst…
sorpaas Apr 8, 2020
9a23a79
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas Apr 19, 2020
0c52d85
Fix docs for PrimaryAndSecondaryVRFSlots
sorpaas Apr 19, 2020
6a032b8
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas Apr 20, 2020
d978b67
Merge branch 'master' into sp-epoch-config
sorpaas Apr 20, 2020
d825d45
Add docs of `SecondaryVRF` in babe crate
sorpaas Apr 20, 2020
df540a4
babe-primitives: Secondary -> SecondaryPlain
sorpaas Apr 20, 2020
42360ec
babe-client: Secondary -> SecondaryPlain
sorpaas Apr 20, 2020
5144e80
Fix migration tests
sorpaas Apr 20, 2020
bd102bc
Merge branch 'sp-epoch-config' of https://github.com/paritytech/subst…
sorpaas Apr 20, 2020
e049b81
test-utils-runtime: Secondary -> SecondaryPlain
sorpaas Apr 20, 2020
904df04
Fix missing name change in test-utils-runtime
sorpaas Apr 20, 2020
abba6a5
Fix migration: Epoch should be EpochV0
sorpaas Apr 20, 2020
ee72297
Update client/consensus/babe/src/lib.rs
sorpaas Apr 20, 2020
52bc6f9
Fix new epochChanges version
sorpaas Apr 20, 2020
60f4f80
Merge branch 'sp-epoch-config' of https://github.com/paritytech/subst…
sorpaas Apr 20, 2020
4e9490d
Merge branch 'sp-epoch-config' into sp-aura-vrf
sorpaas Apr 20, 2020
3b889a3
Fix babe-primitives naming changes
sorpaas Apr 20, 2020
6cf220a
Fix merge issues in babe-client
sorpaas Apr 20, 2020
2d1295e
Merge branch 'master' of https://github.com/paritytech/substrate into…
sorpaas Apr 23, 2020
4c12ea8
Merge branch 'master' into sp-aura-vrf
andresilva Apr 24, 2020
b2e9eba
Merge branch 'master' into sp-aura-vrf
andresilva Apr 24, 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
2 changes: 1 addition & 1 deletion bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,7 +803,7 @@ impl_runtime_apis! {
c: PRIMARY_PROBABILITY,
genesis_authorities: Babe::authorities(),
randomness: Babe::randomness(),
secondary_slots: true,
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
}
}

Expand Down
9 changes: 7 additions & 2 deletions client/consensus/babe/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,12 @@ impl<B, C, SC> BabeApi for BabeRPCHandler<B, C, SC>
PreDigest::Primary { .. } => {
claims.entry(key.public()).or_default().primary.push(slot_number);
}
PreDigest::Secondary { .. } => {
PreDigest::SecondaryPlain { .. } => {
claims.entry(key.public()).or_default().secondary.push(slot_number);
}
PreDigest::SecondaryVRF { .. } => {
claims.entry(key.public()).or_default().secondary_vrf.push(slot_number);
},
};
}
}
Expand All @@ -144,6 +147,8 @@ pub struct EpochAuthorship {
primary: Vec<u64>,
/// the array of secondary slots that can be claimed
secondary: Vec<u64>,
/// The array of secondary VRF slots that can be claimed.
secondary_vrf: Vec<u64>,
}

/// Errors encountered by the RPC
Expand Down Expand Up @@ -236,7 +241,7 @@ mod tests {

io.extend_with(BabeApi::to_delegate(handler));
let request = r#"{"jsonrpc":"2.0","method":"babe_epochAuthorship","params": [],"id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":{"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY":{"primary":[0],"secondary":[1,2,4]}},"id":1}"#;
let response = r#"{"jsonrpc":"2.0","result":{"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY":{"primary":[0],"secondary":[1,2,4],"secondary_vrf":[]}},"id":1}"#;

assert_eq!(Some(response.into()), io.handle_request_sync(request));
}
Expand Down
45 changes: 34 additions & 11 deletions client/consensus/babe/src/authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ use sp_consensus_babe::{
AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX,
SlotNumber, AuthorityPair,
};
use sp_consensus_babe::digests::{PreDigest, PrimaryPreDigest, SecondaryPreDigest};
use sp_consensus_babe::digests::{
PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest, SecondaryVRFPreDigest,
};
use sp_consensus_vrf::schnorrkel::{VRFOutput, VRFProof};
use sp_core::{U256, blake2_256};
use codec::Encode;
Expand Down Expand Up @@ -105,18 +107,20 @@ pub(super) fn make_transcript(
/// to propose.
fn claim_secondary_slot(
slot_number: SlotNumber,
authorities: &[(AuthorityId, BabeAuthorityWeight)],
epoch: &Epoch,
keystore: &KeyStorePtr,
randomness: [u8; 32],
author_secondary_vrf: bool,
) -> Option<(PreDigest, AuthorityPair)> {
let Epoch { authorities, randomness, epoch_index, .. } = epoch;

if authorities.is_empty() {
return None;
}

let expected_author = super::authorship::secondary_slot_author(
slot_number,
authorities,
randomness,
*randomness,
)?;

let keystore = keystore.read();
Expand All @@ -128,10 +132,27 @@ fn claim_secondary_slot(
})
{
if pair.public() == *expected_author {
let pre_digest = PreDigest::Secondary(SecondaryPreDigest {
slot_number,
authority_index: authority_index as u32,
});
let pre_digest = if author_secondary_vrf {
let transcript = super::authorship::make_transcript(
randomness,
slot_number,
*epoch_index,
);

let s = get_keypair(&pair).vrf_sign(transcript);

PreDigest::SecondaryVRF(SecondaryVRFPreDigest {
slot_number,
vrf_output: VRFOutput(s.0.to_output()),
vrf_proof: VRFProof(s.1),
authority_index: authority_index as u32,
})
} else {
PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
slot_number,
authority_index: authority_index as u32,
})
};

return Some((pre_digest, pair));
}
Expand All @@ -151,12 +172,14 @@ pub fn claim_slot(
) -> Option<(PreDigest, AuthorityPair)> {
claim_primary_slot(slot_number, epoch, epoch.config.c, keystore)
.or_else(|| {
if epoch.config.secondary_slots {
if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() ||
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed()
{
claim_secondary_slot(
slot_number,
&epoch.authorities,
&epoch,
keystore,
epoch.randomness,
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed(),
)
} else {
None
Expand Down
4 changes: 2 additions & 2 deletions client/consensus/babe/src/aux_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ mod test {
use substrate_test_runtime_client;
use sp_core::H256;
use sp_runtime::traits::NumberFor;
use sp_consensus_babe::BabeGenesisConfiguration;
use sp_consensus_babe::{AllowedSlots, BabeGenesisConfiguration};
use sc_consensus_epochs::{PersistedEpoch, PersistedEpochHeader, EpochHeader};
use sp_consensus::Error as ConsensusError;
use sc_network_test::Block as TestBlock;
Expand Down Expand Up @@ -182,7 +182,7 @@ mod test {
c: (3, 10),
genesis_authorities: Vec::new(),
randomness: Default::default(),
secondary_slots: true,
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
},
).unwrap();

Expand Down
38 changes: 31 additions & 7 deletions client/consensus/babe/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@
//!
//! `blake2_256(epoch_randomness ++ slot_number) % authorities_len`.
//!
//! The secondary slots supports either a `SecondaryPlain` or `SecondaryVRF`
//! variant. Comparing with `SecondaryPlain` variant, the `SecondaryVRF` variant
//! generates an additional VRF output. The output is not included in beacon
//! randomness, but can be consumed by parachains.
//!
//! The fork choice rule is weight-based, where weight equals the number of
//! primary blocks in the chain. We will pick the heaviest chain (more primary
//! blocks) and will go with the longest one in case of a tie.
Expand All @@ -64,8 +69,8 @@ pub use sp_consensus_babe::{
AuthorityId, AuthorityPair, AuthoritySignature,
BabeAuthorityWeight, VRF_OUTPUT_LENGTH,
digests::{
CompatibleDigestItem, NextEpochDescriptor, NextConfigDescriptor,
PreDigest, PrimaryPreDigest, SecondaryPreDigest,
CompatibleDigestItem, NextEpochDescriptor, NextConfigDescriptor, PreDigest,
PrimaryPreDigest, SecondaryPlainPreDigest,
},
};
pub use sp_consensus::SyncOracle;
Expand Down Expand Up @@ -184,7 +189,7 @@ impl Epoch {
randomness: genesis_config.randomness.clone(),
config: BabeEpochConfiguration {
c: genesis_config.c,
secondary_slots: genesis_config.secondary_slots,
allowed_slots: genesis_config.allowed_slots,
},
}
}
Expand Down Expand Up @@ -279,7 +284,26 @@ impl Config {
C: AuxStore + ProvideRuntimeApi<B>, C::Api: BabeApi<B, Error = sp_blockchain::Error>,
{
trace!(target: "babe", "Getting slot duration");
match sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| a.configuration(b)).map(Self) {
match sc_consensus_slots::SlotDuration::get_or_compute(client, |a, b| {
let has_api_v1 = a.has_api_with::<dyn BabeApi<B, Error = sp_blockchain::Error>, _>(
&b, |v| v == 1,
)?;
let has_api_v2 = a.has_api_with::<dyn BabeApi<B, Error = sp_blockchain::Error>, _>(
&b, |v| v == 2,
)?;

if has_api_v1 {
#[allow(deprecated)] {
Ok(a.configuration_before_version_2(b)?.into())
}
} else if has_api_v2 {
a.configuration(b)
} else {
Err(sp_blockchain::Error::VersionInvalid(
"Unsupported or invalid BabeApi version".to_string()
))
}
}).map(Self) {
Ok(s) => Ok(s),
Err(s) => {
warn!(target: "babe", "Failed to get slot duration");
Expand Down Expand Up @@ -583,7 +607,7 @@ fn find_pre_digest<B: BlockT>(header: &B::Header) -> Result<PreDigest, Error<B>>
// genesis block doesn't contain a pre digest so let's generate a
// dummy one to not break any invariants in the rest of the code
if header.number().is_zero() {
return Ok(PreDigest::Secondary(SecondaryPreDigest {
return Ok(PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
slot_number: 0,
authority_index: 0,
}));
Expand Down Expand Up @@ -1044,7 +1068,7 @@ impl<Block, Client, Inner> BlockImport<Block> for BabeBlockImport<Block, Client,
let epoch_config = next_config_digest.unwrap_or_else(
|| viable_epoch.as_ref().config.clone()
);

// restrict info logging during initial sync to avoid spam
let log_level = if block.origin == BlockOrigin::NetworkInitialSync {
log::Level::Debug
Expand All @@ -1053,7 +1077,7 @@ impl<Block, Client, Inner> BlockImport<Block> for BabeBlockImport<Block, Client,
};

log!(target: "babe",
log_level,
log_level,
"👶 New epoch {} launching at block {} (block slot {} >= start slot {}).",
viable_epoch.as_ref().epoch_index,
hash,
Expand Down
2 changes: 1 addition & 1 deletion client/consensus/babe/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl EpochV0 {
randomness: self.randomness,
config: BabeEpochConfiguration {
c: config.c,
secondary_slots: config.secondary_slots,
allowed_slots: config.allowed_slots,
},
}
}
Expand Down
10 changes: 5 additions & 5 deletions client/consensus/babe/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use super::*;
use authorship::claim_slot;

use sp_consensus_babe::{AuthorityPair, SlotNumber};
use sp_consensus_babe::{AuthorityPair, SlotNumber, AllowedSlots};
use sc_block_builder::{BlockBuilder, BlockBuilderProvider};
use sp_consensus::{
NoNetwork as DummyOracle, Proposal, RecordProof,
Expand Down Expand Up @@ -507,7 +507,7 @@ fn can_author_block() {
duration: 100,
config: BabeEpochConfiguration {
c: (3, 10),
secondary_slots: true,
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
},
};

Expand All @@ -517,7 +517,7 @@ fn can_author_block() {
c: (3, 10),
genesis_authorities: Vec::new(),
randomness: [0; 32],
secondary_slots: true,
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
};

// with secondary slots enabled it should never be empty
Expand All @@ -528,7 +528,7 @@ fn can_author_block() {

// otherwise with only vrf-based primary slots we might need to try a couple
// of times.
config.secondary_slots = false;
config.allowed_slots = AllowedSlots::PrimarySlots;
loop {
match claim_slot(i, &epoch, &keystore) {
None => i += 1,
Expand Down Expand Up @@ -557,7 +557,7 @@ fn propose_and_import_block<Transaction>(
let pre_digest = sp_runtime::generic::Digest {
logs: vec![
Item::babe_pre_digest(
PreDigest::Secondary(SecondaryPreDigest {
PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
authority_index: 0,
slot_number,
}),
Expand Down
71 changes: 60 additions & 11 deletions client/consensus/babe/src/verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use sp_runtime::{traits::Header, traits::DigestItemFor};
use sp_core::{Pair, Public};
use sp_consensus_babe::{AuthoritySignature, SlotNumber, AuthorityPair, AuthorityId};
use sp_consensus_babe::digests::{
PreDigest, PrimaryPreDigest, SecondaryPreDigest, CompatibleDigestItem
PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest, SecondaryVRFPreDigest,
CompatibleDigestItem
};
use sc_consensus_slots::CheckedHeader;
use log::{debug, trace};
Expand All @@ -28,15 +29,15 @@ use super::authorship::{make_transcript, calculate_primary_threshold, check_prim

/// BABE verification parameters
pub(super) struct VerificationParams<'a, B: 'a + BlockT> {
/// the header being verified.
/// The header being verified.
pub(super) header: B::Header,
/// the pre-digest of the header being verified. this is optional - if prior
/// The pre-digest of the header being verified. this is optional - if prior
/// verification code had to read it, it can be included here to avoid duplicate
/// work.
pub(super) pre_digest: Option<PreDigest>,
/// the slot number of the current time.
/// The slot number of the current time.
pub(super) slot_now: SlotNumber,
/// epoch descriptor of the epoch this block _should_ be under, if it's valid.
/// Epoch descriptor of the epoch this block _should_ be under, if it's valid.
pub(super) epoch: &'a Epoch,
}

Expand Down Expand Up @@ -102,10 +103,18 @@ pub(super) fn check_header<B: BlockT + Sized>(
epoch.config.c,
)?;
},
PreDigest::Secondary(secondary) if epoch.config.secondary_slots => {
debug!(target: "babe", "Verifying Secondary block");

check_secondary_header::<B>(
PreDigest::SecondaryPlain(secondary) if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() => {
debug!(target: "babe", "Verifying Secondary plain block");
check_secondary_plain_header::<B>(
pre_hash,
secondary,
sig,
&epoch,
)?;
},
PreDigest::SecondaryVRF(secondary) if epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() => {
debug!(target: "babe", "Verifying Secondary VRF block");
check_secondary_vrf_header::<B>(
pre_hash,
secondary,
sig,
Expand Down Expand Up @@ -179,9 +188,9 @@ fn check_primary_header<B: BlockT + Sized>(
/// properly signed by the expected authority, which we have a deterministic way
/// of computing. Additionally, the weight of this block must stay the same
/// compared to its parent since it is a secondary block.
fn check_secondary_header<B: BlockT>(
fn check_secondary_plain_header<B: BlockT>(
pre_hash: B::Hash,
pre_digest: &SecondaryPreDigest,
pre_digest: &SecondaryPlainPreDigest,
signature: AuthoritySignature,
epoch: &Epoch,
) -> Result<(), Error<B>> {
Expand All @@ -205,3 +214,43 @@ fn check_secondary_header<B: BlockT>(
Err(Error::BadSignature(pre_hash))
}
}

/// Check a secondary VRF slot proposal header.
fn check_secondary_vrf_header<B: BlockT>(
pre_hash: B::Hash,
pre_digest: &SecondaryVRFPreDigest,
signature: AuthoritySignature,
epoch: &Epoch,
) -> Result<(), Error<B>> {
// check the signature is valid under the expected authority and
// chain state.
let expected_author = secondary_slot_author(
pre_digest.slot_number,
&epoch.authorities,
epoch.randomness,
).ok_or_else(|| Error::NoSecondaryAuthorExpected)?;

let author = &epoch.authorities[pre_digest.authority_index as usize].0;

if expected_author != author {
return Err(Error::InvalidAuthor(expected_author.clone(), author.clone()));
}

if AuthorityPair::verify(&signature, pre_hash.as_ref(), author) {
let transcript = make_transcript(
&epoch.randomness,
pre_digest.slot_number,
epoch.epoch_index,
);

schnorrkel::PublicKey::from_bytes(author.as_slice()).and_then(|p| {
p.vrf_verify(transcript, &pre_digest.vrf_output, &pre_digest.vrf_proof)
}).map_err(|s| {
babe_err(Error::VRFVerificationFailed(s))
})?;

Ok(())
} else {
Err(Error::BadSignature(pre_hash))
}
}
Loading