feat: Rebrand Polkadot/Substrate references to PezkuwiChain
This commit systematically rebrands various references from Parity Technologies' Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk. Key changes include: - Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks. - Modified internal documentation and code comments to reflect PezkuwiChain naming and structure. - Replaced direct references to with or specific paths within the for XCM, Pezkuwi, and other modules. - Cleaned up deprecated issue and PR references in various and files, particularly in and modules. - Adjusted image and logo URLs in documentation to point to PezkuwiChain assets. - Removed or rephrased comments related to external Polkadot/Substrate PRs and issues. This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
@@ -0,0 +1,325 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! BABE authority selection and slot claiming.
|
||||
|
||||
use super::{Epoch, AUTHORING_SCORE_LENGTH, AUTHORING_SCORE_VRF_CONTEXT};
|
||||
use codec::Encode;
|
||||
use pezsc_consensus_epochs::Epoch as EpochT;
|
||||
use pezsp_application_crypto::AppCrypto;
|
||||
use pezsp_consensus_babe::{
|
||||
digests::{PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest, SecondaryVRFPreDigest},
|
||||
make_vrf_sign_data, AuthorityId, BabeAuthorityWeight, Randomness, Slot,
|
||||
};
|
||||
use pezsp_core::{
|
||||
crypto::{ByteArray, Wraps},
|
||||
U256,
|
||||
};
|
||||
use pezsp_keystore::KeystorePtr;
|
||||
|
||||
/// Calculates the primary selection threshold for a given authority, taking
|
||||
/// into account `c` (`1 - c` represents the probability of a slot being empty).
|
||||
pub(super) fn calculate_primary_threshold(
|
||||
c: (u64, u64),
|
||||
authorities: &[(AuthorityId, BabeAuthorityWeight)],
|
||||
authority_index: usize,
|
||||
) -> u128 {
|
||||
use num_bigint::BigUint;
|
||||
use num_rational::BigRational;
|
||||
use num_traits::{cast::ToPrimitive, identities::One};
|
||||
|
||||
// Prevent div by zero and out of bounds access.
|
||||
// While Babe's pallet implementation that ships with FRAME performs a sanity check over
|
||||
// configuration parameters, this is not sufficient to guarantee that `c.1` is non-zero
|
||||
// (i.e. third party implementations are possible).
|
||||
if c.1 == 0 || authority_index >= authorities.len() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let c = c.0 as f64 / c.1 as f64;
|
||||
|
||||
let theta = authorities[authority_index].1 as f64 /
|
||||
authorities.iter().map(|(_, weight)| weight).sum::<u64>() as f64;
|
||||
|
||||
assert!(theta > 0.0, "authority with weight 0.");
|
||||
|
||||
// NOTE: in the equation `p = 1 - (1 - c)^theta` the value of `p` is always
|
||||
// capped by `c`. For all practical purposes `c` should always be set to a
|
||||
// value < 0.5, as such in the computations below we should never be near
|
||||
// edge cases like `0.999999`.
|
||||
|
||||
let p = BigRational::from_float(1f64 - (1f64 - c).powf(theta)).expect(
|
||||
"returns None when the given value is not finite; \
|
||||
c is a configuration parameter defined in (0, 1]; \
|
||||
theta must be > 0 if the given authority's weight is > 0; \
|
||||
theta represents the validator's relative weight defined in (0, 1]; \
|
||||
powf will always return values in (0, 1] given both the \
|
||||
base and exponent are in that domain; \
|
||||
qed.",
|
||||
);
|
||||
|
||||
let numer = p.numer().to_biguint().expect(
|
||||
"returns None when the given value is negative; \
|
||||
p is defined as `1 - n` where n is defined in (0, 1]; \
|
||||
p must be a value in [0, 1); \
|
||||
qed.",
|
||||
);
|
||||
|
||||
let denom = p.denom().to_biguint().expect(
|
||||
"returns None when the given value is negative; \
|
||||
p is defined as `1 - n` where n is defined in (0, 1]; \
|
||||
p must be a value in [0, 1); \
|
||||
qed.",
|
||||
);
|
||||
|
||||
((BigUint::one() << 128usize) * numer / denom).to_u128().expect(
|
||||
"returns None if the underlying value cannot be represented with 128 bits; \
|
||||
we start with 2^128 which is one more than can be represented with 128 bits; \
|
||||
we multiple by p which is defined in [0, 1); \
|
||||
the result must be lower than 2^128 by at least one and thus representable with 128 bits; \
|
||||
qed.",
|
||||
)
|
||||
}
|
||||
|
||||
/// Get the expected secondary author for the given slot and with given
|
||||
/// authorities. This should always assign the slot to some authority unless the
|
||||
/// authorities list is empty.
|
||||
pub(super) fn secondary_slot_author(
|
||||
slot: Slot,
|
||||
authorities: &[(AuthorityId, BabeAuthorityWeight)],
|
||||
randomness: Randomness,
|
||||
) -> Option<&AuthorityId> {
|
||||
if authorities.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let rand =
|
||||
U256::from_big_endian(&(randomness, slot).using_encoded(pezsp_crypto_hashing::blake2_256));
|
||||
|
||||
let authorities_len = U256::from(authorities.len());
|
||||
let idx = rand % authorities_len;
|
||||
|
||||
let expected_author = authorities.get(idx.as_u32() as usize).expect(
|
||||
"authorities not empty; index constrained to list length; \
|
||||
this is a valid index; qed",
|
||||
);
|
||||
|
||||
Some(&expected_author.0)
|
||||
}
|
||||
|
||||
/// Claim a secondary slot if it is our turn to propose, returning the
|
||||
/// pre-digest to use when authoring the block, or `None` if it is not our turn
|
||||
/// to propose.
|
||||
fn claim_secondary_slot(
|
||||
slot: Slot,
|
||||
epoch: &Epoch,
|
||||
keys: &[(AuthorityId, usize)],
|
||||
keystore: &KeystorePtr,
|
||||
author_secondary_vrf: bool,
|
||||
) -> Option<(PreDigest, AuthorityId)> {
|
||||
if epoch.authorities.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut epoch_index = epoch.epoch_index;
|
||||
if epoch.end_slot() <= slot {
|
||||
// Slot doesn't strictly belong to the epoch, create a clone with fixed values.
|
||||
epoch_index = epoch.clone_for_slot(slot).epoch_index;
|
||||
}
|
||||
|
||||
let expected_author = secondary_slot_author(slot, &epoch.authorities, epoch.randomness)?;
|
||||
|
||||
for (authority_id, authority_index) in keys {
|
||||
if authority_id == expected_author {
|
||||
let pre_digest = if author_secondary_vrf {
|
||||
let data = make_vrf_sign_data(&epoch.randomness, slot, epoch_index);
|
||||
let result =
|
||||
keystore.sr25519_vrf_sign(AuthorityId::ID, authority_id.as_ref(), &data);
|
||||
if let Ok(Some(vrf_signature)) = result {
|
||||
Some(PreDigest::SecondaryVRF(SecondaryVRFPreDigest {
|
||||
slot,
|
||||
authority_index: *authority_index as u32,
|
||||
vrf_signature,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else if keystore.has_keys(&[(authority_id.to_raw_vec(), AuthorityId::ID)]) {
|
||||
Some(PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
|
||||
slot,
|
||||
authority_index: *authority_index as u32,
|
||||
}))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(pre_digest) = pre_digest {
|
||||
return Some((pre_digest, authority_id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Tries to claim the given slot number. This method starts by trying to claim
|
||||
/// a primary VRF based slot. If we are not able to claim it, then if we have
|
||||
/// secondary slots enabled for the given epoch, we will fallback to trying to
|
||||
/// claim a secondary slot.
|
||||
pub fn claim_slot(
|
||||
slot: Slot,
|
||||
epoch: &Epoch,
|
||||
keystore: &KeystorePtr,
|
||||
) -> Option<(PreDigest, AuthorityId)> {
|
||||
let authorities = epoch
|
||||
.authorities
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, a)| (a.0.clone(), index))
|
||||
.collect::<Vec<_>>();
|
||||
claim_slot_using_keys(slot, epoch, keystore, &authorities)
|
||||
}
|
||||
|
||||
/// Like `claim_slot`, but allows passing an explicit set of key pairs. Useful if we intend
|
||||
/// to make repeated calls for different slots using the same key pairs.
|
||||
pub fn claim_slot_using_keys(
|
||||
slot: Slot,
|
||||
epoch: &Epoch,
|
||||
keystore: &KeystorePtr,
|
||||
keys: &[(AuthorityId, usize)],
|
||||
) -> Option<(PreDigest, AuthorityId)> {
|
||||
claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| {
|
||||
if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() ||
|
||||
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed()
|
||||
{
|
||||
claim_secondary_slot(
|
||||
slot,
|
||||
epoch,
|
||||
keys,
|
||||
keystore,
|
||||
epoch.config.allowed_slots.is_secondary_vrf_slots_allowed(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Claim a primary slot if it is our turn. Returns `None` if it is not our turn.
|
||||
/// This hashes the slot number, epoch, genesis hash, and chain randomness into
|
||||
/// the VRF. If the VRF produces a value less than `threshold`, it is our turn,
|
||||
/// so it returns `Some(_)`. Otherwise, it returns `None`.
|
||||
fn claim_primary_slot(
|
||||
slot: Slot,
|
||||
epoch: &Epoch,
|
||||
c: (u64, u64),
|
||||
keystore: &KeystorePtr,
|
||||
keys: &[(AuthorityId, usize)],
|
||||
) -> Option<(PreDigest, AuthorityId)> {
|
||||
let mut epoch_index = epoch.epoch_index;
|
||||
if epoch.end_slot() <= slot {
|
||||
// Slot doesn't strictly belong to the epoch, create a clone with fixed values.
|
||||
epoch_index = epoch.clone_for_slot(slot).epoch_index;
|
||||
}
|
||||
|
||||
let data = make_vrf_sign_data(&epoch.randomness, slot, epoch_index);
|
||||
|
||||
for (authority_id, authority_index) in keys {
|
||||
let result = keystore.sr25519_vrf_sign(AuthorityId::ID, authority_id.as_ref(), &data);
|
||||
if let Ok(Some(vrf_signature)) = result {
|
||||
let threshold = calculate_primary_threshold(c, &epoch.authorities, *authority_index);
|
||||
|
||||
let can_claim = authority_id
|
||||
.as_inner_ref()
|
||||
.make_bytes::<AUTHORING_SCORE_LENGTH>(
|
||||
AUTHORING_SCORE_VRF_CONTEXT,
|
||||
&data.as_ref(),
|
||||
&vrf_signature.pre_output,
|
||||
)
|
||||
.map(|bytes| u128::from_le_bytes(bytes) < threshold)
|
||||
.unwrap_or_default();
|
||||
|
||||
if can_claim {
|
||||
let pre_digest = PreDigest::Primary(PrimaryPreDigest {
|
||||
slot,
|
||||
authority_index: *authority_index as u32,
|
||||
vrf_signature,
|
||||
});
|
||||
|
||||
return Some((pre_digest, authority_id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pezsp_consensus_babe::{
|
||||
AllowedSlots, AuthorityId, BabeEpochConfiguration, Epoch, RANDOMNESS_LENGTH,
|
||||
};
|
||||
use pezsp_core::{crypto::Pair as _, sr25519::Pair};
|
||||
use pezsp_keystore::testing::MemoryKeystore;
|
||||
|
||||
#[test]
|
||||
fn claim_secondary_plain_slot_works() {
|
||||
let keystore: KeystorePtr = MemoryKeystore::new().into();
|
||||
let valid_public_key = keystore
|
||||
.sr25519_generate_new(AuthorityId::ID, Some(pezsp_core::crypto::DEV_PHRASE))
|
||||
.unwrap();
|
||||
|
||||
let authorities = vec![
|
||||
(AuthorityId::from(Pair::generate().0.public()), 5),
|
||||
(AuthorityId::from(Pair::generate().0.public()), 7),
|
||||
];
|
||||
|
||||
let mut epoch = Epoch {
|
||||
epoch_index: 10,
|
||||
start_slot: 0.into(),
|
||||
duration: 20,
|
||||
authorities: authorities.clone(),
|
||||
randomness: Default::default(),
|
||||
config: BabeEpochConfiguration {
|
||||
c: (3, 10),
|
||||
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
|
||||
},
|
||||
}
|
||||
.into();
|
||||
|
||||
assert!(claim_slot(10.into(), &epoch, &keystore).is_none());
|
||||
|
||||
epoch.authorities.push((valid_public_key.into(), 10));
|
||||
assert_eq!(claim_slot(10.into(), &epoch, &keystore).unwrap().1, valid_public_key.into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secondary_slot_author_selection_works() {
|
||||
let authorities = (0..1000)
|
||||
.map(|i| (AuthorityId::from(Pair::generate().0.public()), i))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let randomness = [3; RANDOMNESS_LENGTH];
|
||||
|
||||
assert_eq!(
|
||||
*secondary_slot_author(100.into(), &authorities, randomness).unwrap(),
|
||||
authorities[167].0
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Schema for BABE epoch changes in the aux-db.
|
||||
|
||||
use codec::{Decode, Encode};
|
||||
use log::info;
|
||||
|
||||
use crate::{migration::EpochV0, Epoch, LOG_TARGET};
|
||||
use pezsc_client_api::backend::AuxStore;
|
||||
use pezsc_consensus_epochs::{
|
||||
migration::{EpochChangesV0For, EpochChangesV1For},
|
||||
EpochChangesFor, SharedEpochChanges,
|
||||
};
|
||||
use pezsp_blockchain::{Error as ClientError, Result as ClientResult};
|
||||
use pezsp_consensus_babe::{BabeBlockWeight, BabeConfiguration};
|
||||
use pezsp_runtime::traits::Block as BlockT;
|
||||
|
||||
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 = 3;
|
||||
|
||||
/// The aux storage key used to store the block weight of the given block hash.
|
||||
pub fn block_weight_key<H: Encode>(block_hash: H) -> Vec<u8> {
|
||||
(b"block_weight", block_hash).encode()
|
||||
}
|
||||
|
||||
fn load_decode<B, T>(backend: &B, key: &[u8]) -> ClientResult<Option<T>>
|
||||
where
|
||||
B: AuxStore,
|
||||
T: Decode,
|
||||
{
|
||||
let corrupt = |e: codec::Error| {
|
||||
ClientError::Backend(format!("BABE DB is corrupted. Decode error: {}", e))
|
||||
};
|
||||
match backend.get_aux(key)? {
|
||||
None => Ok(None),
|
||||
Some(t) => T::decode(&mut &t[..]).map(Some).map_err(corrupt),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load or initialize persistent epoch change data from backend.
|
||||
pub fn load_epoch_changes<Block: BlockT, B: AuxStore>(
|
||||
backend: &B,
|
||||
config: &BabeConfiguration,
|
||||
) -> ClientResult<SharedEpochChanges<Block, Epoch>> {
|
||||
let version = load_decode::<_, u32>(backend, BABE_EPOCH_CHANGES_VERSION)?;
|
||||
|
||||
let maybe_epoch_changes = match version {
|
||||
None =>
|
||||
load_decode::<_, EpochChangesV0For<Block, EpochV0>>(backend, BABE_EPOCH_CHANGES_KEY)?
|
||||
.map(|v0| v0.migrate().map(|_, _, epoch| epoch.migrate(config))),
|
||||
Some(1) =>
|
||||
load_decode::<_, EpochChangesV1For<Block, EpochV0>>(backend, BABE_EPOCH_CHANGES_KEY)?
|
||||
.map(|v1| v1.migrate().map(|_, _, epoch| epoch.migrate(config))),
|
||||
Some(2) => {
|
||||
// v2 still uses `EpochChanges` v1 format but with a different `Epoch` type.
|
||||
load_decode::<_, EpochChangesV1For<Block, Epoch>>(backend, BABE_EPOCH_CHANGES_KEY)?
|
||||
.map(|v2| v2.migrate())
|
||||
},
|
||||
Some(BABE_EPOCH_CHANGES_CURRENT_VERSION) =>
|
||||
load_decode::<_, EpochChangesFor<Block, Epoch>>(backend, BABE_EPOCH_CHANGES_KEY)?,
|
||||
Some(other) =>
|
||||
return Err(ClientError::Backend(format!("Unsupported BABE DB version: {:?}", other))),
|
||||
};
|
||||
|
||||
let epoch_changes =
|
||||
SharedEpochChanges::<Block, Epoch>::new(maybe_epoch_changes.unwrap_or_else(|| {
|
||||
info!(
|
||||
target: LOG_TARGET,
|
||||
"👶 Creating empty BABE epoch changes on what appears to be first startup.",
|
||||
);
|
||||
EpochChangesFor::<Block, Epoch>::default()
|
||||
}));
|
||||
|
||||
// rebalance the tree after deserialization. this isn't strictly necessary
|
||||
// since the tree is now rebalanced on every update operation. but since the
|
||||
// tree wasn't rebalanced initially it's useful to temporarily leave it here
|
||||
// to avoid having to wait until an import for rebalancing.
|
||||
epoch_changes.shared_data().rebalance();
|
||||
|
||||
Ok(epoch_changes)
|
||||
}
|
||||
|
||||
/// Update the epoch changes on disk after a change.
|
||||
pub(crate) fn write_epoch_changes<Block: BlockT, F, R>(
|
||||
epoch_changes: &EpochChangesFor<Block, Epoch>,
|
||||
write_aux: F,
|
||||
) -> R
|
||||
where
|
||||
F: FnOnce(&[(&'static [u8], &[u8])]) -> R,
|
||||
{
|
||||
BABE_EPOCH_CHANGES_CURRENT_VERSION.using_encoded(|version| {
|
||||
let encoded_epoch_changes = epoch_changes.encode();
|
||||
write_aux(&[
|
||||
(BABE_EPOCH_CHANGES_KEY, encoded_epoch_changes.as_slice()),
|
||||
(BABE_EPOCH_CHANGES_VERSION, version),
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
/// Write the cumulative chain-weight of a block ot aux storage.
|
||||
pub(crate) fn write_block_weight<H: Encode, F, R>(
|
||||
block_hash: H,
|
||||
block_weight: BabeBlockWeight,
|
||||
write_aux: F,
|
||||
) -> R
|
||||
where
|
||||
F: FnOnce(&[(Vec<u8>, &[u8])]) -> R,
|
||||
{
|
||||
let key = block_weight_key(block_hash);
|
||||
block_weight.using_encoded(|s| write_aux(&[(key, s)]))
|
||||
}
|
||||
|
||||
/// Load the cumulative chain-weight associated with a block.
|
||||
pub fn load_block_weight<H: Encode, B: AuxStore>(
|
||||
backend: &B,
|
||||
block_hash: H,
|
||||
) -> ClientResult<Option<BabeBlockWeight>> {
|
||||
load_decode(backend, block_weight_key(block_hash).as_slice())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::migration::EpochV0;
|
||||
use fork_tree::ForkTree;
|
||||
use pezsc_consensus_epochs::{EpochHeader, PersistedEpoch, PersistedEpochHeader};
|
||||
use pezsc_network_test::Block as TestBlock;
|
||||
use pezsp_consensus::Error as ConsensusError;
|
||||
use pezsp_consensus_babe::AllowedSlots;
|
||||
use pezsp_core::H256;
|
||||
use pezsp_runtime::traits::NumberFor;
|
||||
use bizinikiwi_test_runtime_client;
|
||||
|
||||
#[test]
|
||||
fn load_decode_from_v0_epoch_changes() {
|
||||
let epoch = EpochV0 {
|
||||
start_slot: 0.into(),
|
||||
authorities: vec![],
|
||||
randomness: [0; 32],
|
||||
epoch_index: 1,
|
||||
duration: 100,
|
||||
};
|
||||
let client = bizinikiwi_test_runtime_client::new();
|
||||
let mut v0_tree = ForkTree::<H256, NumberFor<TestBlock>, _>::new();
|
||||
v0_tree
|
||||
.import::<_, ConsensusError>(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
PersistedEpoch::Regular(epoch),
|
||||
&|_, _| Ok(false), // Test is single item only so this can be set to false.
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
client
|
||||
.insert_aux(
|
||||
&[(
|
||||
BABE_EPOCH_CHANGES_KEY,
|
||||
&EpochChangesV0For::<TestBlock, EpochV0>::from_raw(v0_tree).encode()[..],
|
||||
)],
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(load_decode::<_, u32>(&client, BABE_EPOCH_CHANGES_VERSION).unwrap(), None);
|
||||
|
||||
let epoch_changes = load_epoch_changes::<TestBlock, _>(
|
||||
&client,
|
||||
&BabeConfiguration {
|
||||
slot_duration: 10,
|
||||
epoch_length: 4,
|
||||
c: (3, 10),
|
||||
authorities: Vec::new(),
|
||||
randomness: Default::default(),
|
||||
allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
epoch_changes
|
||||
.shared_data()
|
||||
.tree()
|
||||
.iter()
|
||||
.map(|(_, _, epoch)| epoch.clone())
|
||||
.collect::<Vec<_>>() ==
|
||||
vec![PersistedEpochHeader::Regular(EpochHeader {
|
||||
start_slot: 0.into(),
|
||||
end_slot: 100.into(),
|
||||
})],
|
||||
); // PersistedEpochHeader does not implement Debug, so we use assert! directly.
|
||||
|
||||
write_epoch_changes::<TestBlock, _, _>(&epoch_changes.shared_data(), |values| {
|
||||
client.insert_aux(values, &[]).unwrap();
|
||||
});
|
||||
|
||||
assert_eq!(load_decode::<_, u32>(&client, BABE_EPOCH_CHANGES_VERSION).unwrap(), Some(3));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,79 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::{
|
||||
AuthorityId, BabeAuthorityWeight, BabeConfiguration, BabeEpochConfiguration, Epoch,
|
||||
NextEpochDescriptor, Randomness,
|
||||
};
|
||||
use codec::{Decode, Encode};
|
||||
use pezsc_consensus_epochs::Epoch as EpochT;
|
||||
use pezsp_consensus_slots::Slot;
|
||||
|
||||
/// BABE epoch information, version 0.
|
||||
#[derive(Decode, Encode, PartialEq, Eq, Clone, Debug)]
|
||||
pub struct EpochV0 {
|
||||
/// The epoch index.
|
||||
pub epoch_index: u64,
|
||||
/// The starting slot of the epoch.
|
||||
pub start_slot: Slot,
|
||||
/// The duration of this epoch.
|
||||
pub duration: u64,
|
||||
/// The authorities and their weights.
|
||||
pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>,
|
||||
/// Randomness for this epoch.
|
||||
pub randomness: Randomness,
|
||||
}
|
||||
|
||||
impl EpochT for EpochV0 {
|
||||
type NextEpochDescriptor = NextEpochDescriptor;
|
||||
type Slot = Slot;
|
||||
|
||||
fn increment(&self, descriptor: NextEpochDescriptor) -> EpochV0 {
|
||||
EpochV0 {
|
||||
epoch_index: self.epoch_index + 1,
|
||||
start_slot: self.start_slot + self.duration,
|
||||
duration: self.duration,
|
||||
authorities: descriptor.authorities,
|
||||
randomness: descriptor.randomness,
|
||||
}
|
||||
}
|
||||
|
||||
fn start_slot(&self) -> Slot {
|
||||
self.start_slot
|
||||
}
|
||||
|
||||
fn end_slot(&self) -> Slot {
|
||||
self.start_slot + self.duration
|
||||
}
|
||||
}
|
||||
|
||||
// Implement From<EpochV0> for Epoch
|
||||
impl EpochV0 {
|
||||
/// Migrate the struct to current epoch version.
|
||||
pub fn migrate(self, config: &BabeConfiguration) -> Epoch {
|
||||
pezsp_consensus_babe::Epoch {
|
||||
epoch_index: self.epoch_index,
|
||||
start_slot: self.start_slot,
|
||||
duration: self.duration,
|
||||
authorities: self.authorities,
|
||||
randomness: self.randomness,
|
||||
config: BabeEpochConfiguration { c: config.c, allowed_slots: config.allowed_slots },
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,263 @@
|
||||
// This file is part of Bizinikiwi.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
//! Verification for BABE headers.
|
||||
use crate::{
|
||||
authorship::{calculate_primary_threshold, secondary_slot_author},
|
||||
babe_err, find_pre_digest, BlockT, Epoch, Error, AUTHORING_SCORE_LENGTH,
|
||||
AUTHORING_SCORE_VRF_CONTEXT, LOG_TARGET,
|
||||
};
|
||||
use log::{debug, trace};
|
||||
use pezsc_consensus_epochs::Epoch as EpochT;
|
||||
use pezsc_consensus_slots::CheckedHeader;
|
||||
use pezsp_consensus_babe::{
|
||||
digests::{
|
||||
CompatibleDigestItem, PreDigest, PrimaryPreDigest, SecondaryPlainPreDigest,
|
||||
SecondaryVRFPreDigest,
|
||||
},
|
||||
make_vrf_sign_data, AuthorityPair, AuthoritySignature,
|
||||
};
|
||||
use pezsp_consensus_slots::Slot;
|
||||
use pezsp_core::{
|
||||
crypto::{VrfPublic, Wraps},
|
||||
Pair,
|
||||
};
|
||||
use pezsp_runtime::{traits::Header, DigestItem};
|
||||
|
||||
/// BABE verification parameters
|
||||
pub(super) struct VerificationParams<'a, B: 'a + BlockT> {
|
||||
/// The header being verified.
|
||||
pub(super) header: B::Header,
|
||||
/// 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.
|
||||
pub(super) slot_now: Slot,
|
||||
/// Epoch descriptor of the epoch this block _should_ be under, if it's valid.
|
||||
pub(super) epoch: &'a Epoch,
|
||||
}
|
||||
|
||||
/// Check a header has been signed by the right key. If the slot is too far in
|
||||
/// the future, an error will be returned. If successful, returns the pre-header
|
||||
/// and the digest item containing the seal.
|
||||
///
|
||||
/// The seal must be the last digest. Otherwise, the whole header is considered
|
||||
/// unsigned. This is required for security and must not be changed.
|
||||
///
|
||||
/// This digest item will always return `Some` when used with `as_babe_pre_digest`.
|
||||
///
|
||||
/// The given header can either be from a primary or secondary slot assignment,
|
||||
/// with each having different validation logic.
|
||||
pub(super) fn check_header<B: BlockT + Sized>(
|
||||
params: VerificationParams<B>,
|
||||
) -> Result<CheckedHeader<B::Header, VerifiedHeaderInfo>, Error<B>> {
|
||||
let VerificationParams { mut header, pre_digest, slot_now, epoch } = params;
|
||||
|
||||
let pre_digest = pre_digest.map(Ok).unwrap_or_else(|| find_pre_digest::<B>(&header))?;
|
||||
|
||||
trace!(target: LOG_TARGET, "Checking header");
|
||||
let seal = header
|
||||
.digest_mut()
|
||||
.pop()
|
||||
.ok_or_else(|| babe_err(Error::HeaderUnsealed(header.hash())))?;
|
||||
|
||||
let sig = seal
|
||||
.as_babe_seal()
|
||||
.ok_or_else(|| babe_err(Error::HeaderBadSeal(header.hash())))?;
|
||||
|
||||
// the pre-hash of the header doesn't include the seal
|
||||
// and that's what we sign
|
||||
let pre_hash = header.hash();
|
||||
|
||||
if pre_digest.slot() > slot_now {
|
||||
header.digest_mut().push(seal);
|
||||
return Ok(CheckedHeader::Deferred(header, pre_digest.slot()));
|
||||
}
|
||||
|
||||
match &pre_digest {
|
||||
PreDigest::Primary(primary) => {
|
||||
debug!(
|
||||
target: LOG_TARGET,
|
||||
"Verifying primary block #{} at slot: {}",
|
||||
header.number(),
|
||||
primary.slot,
|
||||
);
|
||||
|
||||
check_primary_header::<B>(pre_hash, primary, sig, epoch, epoch.config.c)?;
|
||||
},
|
||||
PreDigest::SecondaryPlain(secondary)
|
||||
if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() =>
|
||||
{
|
||||
debug!(
|
||||
target: LOG_TARGET,
|
||||
"Verifying secondary plain block #{} at slot: {}",
|
||||
header.number(),
|
||||
secondary.slot,
|
||||
);
|
||||
|
||||
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: LOG_TARGET,
|
||||
"Verifying secondary VRF block #{} at slot: {}",
|
||||
header.number(),
|
||||
secondary.slot,
|
||||
);
|
||||
|
||||
check_secondary_vrf_header::<B>(pre_hash, secondary, sig, epoch)?;
|
||||
},
|
||||
_ => return Err(babe_err(Error::SecondarySlotAssignmentsDisabled)),
|
||||
}
|
||||
|
||||
let info = VerifiedHeaderInfo { seal };
|
||||
Ok(CheckedHeader::Checked(header, info))
|
||||
}
|
||||
|
||||
pub(super) struct VerifiedHeaderInfo {
|
||||
pub(super) seal: DigestItem,
|
||||
}
|
||||
|
||||
/// Check a primary slot proposal header. We validate that the given header is
|
||||
/// properly signed by the expected authority, and that the contained VRF proof
|
||||
/// is valid. Additionally, the weight of this block must increase compared to
|
||||
/// its parent since it is a primary block.
|
||||
fn check_primary_header<B: BlockT + Sized>(
|
||||
pre_hash: B::Hash,
|
||||
pre_digest: &PrimaryPreDigest,
|
||||
signature: AuthoritySignature,
|
||||
epoch: &Epoch,
|
||||
c: (u64, u64),
|
||||
) -> Result<(), Error<B>> {
|
||||
let authority_id = &epoch
|
||||
.authorities
|
||||
.get(pre_digest.authority_index as usize)
|
||||
.ok_or(Error::SlotAuthorNotFound)?
|
||||
.0;
|
||||
let mut epoch_index = epoch.epoch_index;
|
||||
|
||||
if epoch.end_slot() <= pre_digest.slot {
|
||||
// Slot doesn't strictly belong to this epoch, create a clone with fixed values.
|
||||
epoch_index = epoch.clone_for_slot(pre_digest.slot).epoch_index;
|
||||
}
|
||||
|
||||
if !AuthorityPair::verify(&signature, pre_hash, authority_id) {
|
||||
return Err(babe_err(Error::BadSignature(pre_hash)));
|
||||
}
|
||||
|
||||
let data = make_vrf_sign_data(&epoch.randomness, pre_digest.slot, epoch_index);
|
||||
|
||||
if !authority_id.as_inner_ref().vrf_verify(&data, &pre_digest.vrf_signature) {
|
||||
return Err(babe_err(Error::VrfVerificationFailed));
|
||||
}
|
||||
|
||||
let threshold =
|
||||
calculate_primary_threshold(c, &epoch.authorities, pre_digest.authority_index as usize);
|
||||
|
||||
let score = authority_id
|
||||
.as_inner_ref()
|
||||
.make_bytes::<AUTHORING_SCORE_LENGTH>(
|
||||
AUTHORING_SCORE_VRF_CONTEXT,
|
||||
&data.as_ref(),
|
||||
&pre_digest.vrf_signature.pre_output,
|
||||
)
|
||||
.map(u128::from_le_bytes)
|
||||
.map_err(|_| babe_err(Error::VrfVerificationFailed))?;
|
||||
|
||||
if score >= threshold {
|
||||
return Err(babe_err(Error::VrfThresholdExceeded(threshold)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check a secondary slot proposal header. We validate that the given header is
|
||||
/// 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_plain_header<B: BlockT>(
|
||||
pre_hash: B::Hash,
|
||||
pre_digest: &SecondaryPlainPreDigest,
|
||||
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, &epoch.authorities, epoch.randomness)
|
||||
.ok_or(Error::NoSecondaryAuthorExpected)?;
|
||||
|
||||
let author = &epoch
|
||||
.authorities
|
||||
.get(pre_digest.authority_index as usize)
|
||||
.ok_or(Error::SlotAuthorNotFound)?
|
||||
.0;
|
||||
|
||||
if expected_author != author {
|
||||
return Err(Error::InvalidAuthor(expected_author.clone(), author.clone()));
|
||||
}
|
||||
|
||||
if !AuthorityPair::verify(&signature, pre_hash.as_ref(), author) {
|
||||
return Err(Error::BadSignature(pre_hash));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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, &epoch.authorities, epoch.randomness)
|
||||
.ok_or(Error::NoSecondaryAuthorExpected)?;
|
||||
|
||||
let author = &epoch
|
||||
.authorities
|
||||
.get(pre_digest.authority_index as usize)
|
||||
.ok_or(Error::SlotAuthorNotFound)?
|
||||
.0;
|
||||
|
||||
if expected_author != author {
|
||||
return Err(Error::InvalidAuthor(expected_author.clone(), author.clone()));
|
||||
}
|
||||
|
||||
let mut epoch_index = epoch.epoch_index;
|
||||
if epoch.end_slot() <= pre_digest.slot {
|
||||
// Slot doesn't strictly belong to this epoch, create a clone with fixed values.
|
||||
epoch_index = epoch.clone_for_slot(pre_digest.slot).epoch_index;
|
||||
}
|
||||
|
||||
if !AuthorityPair::verify(&signature, pre_hash.as_ref(), author) {
|
||||
return Err(Error::BadSignature(pre_hash));
|
||||
}
|
||||
|
||||
let data = make_vrf_sign_data(&epoch.randomness, pre_digest.slot, epoch_index);
|
||||
|
||||
if !author.as_inner_ref().vrf_verify(&data, &pre_digest.vrf_signature) {
|
||||
return Err(Error::VrfVerificationFailed);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user