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 34 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
8 changes: 4 additions & 4 deletions bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
// and set impl_version to 0. If only runtime
// implementation changes and behavior does not, then leave spec_version as
// is and increment impl_version.
spec_version: 243,
spec_version: 244,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
Expand Down Expand Up @@ -789,19 +789,19 @@ impl_runtime_apis! {
}

impl sp_consensus_babe::BabeApi<Block> for Runtime {
fn configuration() -> sp_consensus_babe::BabeConfiguration {
fn configuration() -> sp_consensus_babe::BabeGenesisConfiguration {
// The choice of `c` parameter (where `1 - c` represents the
// probability of a slot being empty), is done in accordance to the
// slot duration and expected target block time, for safely
// resisting network delays of maximum two seconds.
// <https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results>
sp_consensus_babe::BabeConfiguration {
sp_consensus_babe::BabeGenesisConfiguration {
slot_duration: Babe::slot_duration(),
epoch_length: EpochDuration::get(),
c: PRIMARY_PROBABILITY,
genesis_authorities: Babe::authorities(),
randomness: Babe::randomness(),
secondary_slots: true,
allowed_slots: sp_consensus_babe::AllowedSlots::PrimaryAndSecondaryPlainSlots,
}
}

Expand Down
13 changes: 9 additions & 4 deletions client/consensus/babe/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,17 @@ impl<B, C, SC> BabeApi for BabeRPCHandler<B, C, SC>

for slot_number in epoch_start..epoch_end {
let epoch = epoch_data(&shared_epoch, &client, &babe_config, slot_number, &select_chain)?;
if let Some((claim, key)) = authorship::claim_slot(slot_number, &epoch, &babe_config, &keystore) {
if let Some((claim, key)) = authorship::claim_slot(slot_number, &epoch, &keystore) {
match claim {
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 @@ -184,7 +189,7 @@ fn epoch_data<B, C, SC>(
&parent.hash(),
parent.number().clone(),
slot_number,
|slot| babe_config.genesis_epoch(slot),
|slot| Epoch::genesis(&babe_config, slot),
)
.map_err(|e| Error::Consensus(ConsensusError::ChainLookup(format!("{:?}", e))))?
.ok_or(Error::Consensus(ConsensusError::InvalidAuthoritiesSet))
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
50 changes: 36 additions & 14 deletions client/consensus/babe/src/authorship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@
use merlin::Transcript;
use sp_consensus_babe::{
AuthorityId, BabeAuthorityWeight, BABE_ENGINE_ID, BABE_VRF_PREFIX,
SlotNumber, AuthorityPair, BabeConfiguration
SlotNumber, AuthorityPair,
};
use sp_consensus_babe::digests::{
PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest, SecondaryVRFPreDigest,
};
use sp_consensus_babe::digests::{PreDigest, PrimaryPreDigest, SecondaryPreDigest};
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 @@ -147,17 +168,18 @@ fn claim_secondary_slot(
pub fn claim_slot(
slot_number: SlotNumber,
epoch: &Epoch,
config: &BabeConfiguration,
keystore: &KeyStorePtr,
) -> Option<(PreDigest, AuthorityPair)> {
claim_primary_slot(slot_number, epoch, config.c, keystore)
claim_primary_slot(slot_number, epoch, epoch.config.c, keystore)
.or_else(|| {
if 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
35 changes: 25 additions & 10 deletions client/consensus/babe/src/aux_schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ use codec::{Decode, Encode};
use sc_client_api::backend::AuxStore;
use sp_blockchain::{Result as ClientResult, Error as ClientError};
use sp_runtime::traits::Block as BlockT;
use sp_consensus_babe::BabeBlockWeight;
use sp_consensus_babe::{BabeBlockWeight, BabeGenesisConfiguration};
use sc_consensus_epochs::{EpochChangesFor, SharedEpochChanges, migration::EpochChangesForV0};
use crate::Epoch;
use crate::{Epoch, migration::EpochV0};

const BABE_EPOCH_CHANGES_VERSION: &[u8] = b"babe_epoch_changes_version";
const BABE_EPOCH_CHANGES_KEY: &[u8] = b"babe_epoch_changes";
const BABE_EPOCH_CHANGES_CURRENT_VERSION: u32 = 1;
const BABE_EPOCH_CHANGES_CURRENT_VERSION: u32 = 2;

fn block_weight_key<H: Encode>(block_hash: H) -> Vec<u8> {
(b"block_weight", block_hash).encode()
Expand All @@ -53,14 +53,19 @@ fn load_decode<B, T>(backend: &B, key: &[u8]) -> ClientResult<Option<T>>
/// Load or initialize persistent epoch change data from backend.
pub(crate) fn load_epoch_changes<Block: BlockT, B: AuxStore>(
backend: &B,
config: &BabeGenesisConfiguration,
) -> ClientResult<SharedEpochChanges<Block, Epoch>> {
let version = load_decode::<_, u32>(backend, BABE_EPOCH_CHANGES_VERSION)?;

let maybe_epoch_changes = match version {
None => load_decode::<_, EpochChangesForV0<Block, Epoch>>(
None => load_decode::<_, EpochChangesForV0<Block, EpochV0>>(
backend,
BABE_EPOCH_CHANGES_KEY,
)?.map(|v0| v0.migrate()),
)?.map(|v0| v0.migrate().map(|_, _, epoch| epoch.migrate(config))),
Some(1) => load_decode::<_, EpochChangesFor<Block, EpochV0>>(
backend,
BABE_EPOCH_CHANGES_KEY,
)?.map(|v1| v1.map(|_, _, epoch| epoch.migrate(config))),
Some(BABE_EPOCH_CHANGES_CURRENT_VERSION) => load_decode::<_, EpochChangesFor<Block, Epoch>>(
backend,
BABE_EPOCH_CHANGES_KEY,
Expand Down Expand Up @@ -131,18 +136,19 @@ pub(crate) fn load_block_weight<H: Encode, B: AuxStore>(
#[cfg(test)]
mod test {
use super::*;
use crate::Epoch;
use crate::migration::EpochV0;
use fork_tree::ForkTree;
use substrate_test_runtime_client;
use sp_core::H256;
use sp_runtime::traits::NumberFor;
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;

#[test]
fn load_decode_from_v0_epoch_changes() {
let epoch = Epoch {
let epoch = EpochV0 {
start_slot: 0,
authorities: vec![],
randomness: [0; 32],
Expand All @@ -160,7 +166,7 @@ mod test {

client.insert_aux(
&[(BABE_EPOCH_CHANGES_KEY,
&EpochChangesForV0::<TestBlock, Epoch>::from_raw(v0_tree).encode()[..])],
&EpochChangesForV0::<TestBlock, EpochV0>::from_raw(v0_tree).encode()[..])],
&[],
).unwrap();

Expand All @@ -169,7 +175,16 @@ mod test {
None,
);

let epoch_changes = load_epoch_changes::<TestBlock, _>(&client).unwrap();
let epoch_changes = load_epoch_changes::<TestBlock, _>(
&client, &BabeGenesisConfiguration {
slot_duration: 10,
epoch_length: 4,
c: (3, 10),
genesis_authorities: Vec::new(),
randomness: Default::default(),
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
},
).unwrap();

assert!(
epoch_changes.lock()
Expand All @@ -192,7 +207,7 @@ mod test {

assert_eq!(
load_decode::<_, u32>(&client, BABE_EPOCH_CHANGES_VERSION).unwrap(),
Some(1),
Some(2),
);
}
}
Loading