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,79 @@
|
||||
[package]
|
||||
name = "pezsc-consensus-babe"
|
||||
version = "0.34.0"
|
||||
authors.workspace = true
|
||||
description = "BABE consensus algorithm for bizinikiwi"
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
documentation = "https://docs.rs/pezsc-consensus-babe"
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
codec = { features = ["derive"], workspace = true, default-features = true }
|
||||
fork-tree = { workspace = true, default-features = true }
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true, default-features = true }
|
||||
num-bigint = { workspace = true }
|
||||
num-rational = { workspace = true }
|
||||
num-traits = { workspace = true, default-features = true }
|
||||
parking_lot = { workspace = true, default-features = true }
|
||||
prometheus-endpoint = { workspace = true, default-features = true }
|
||||
pezsc-client-api = { workspace = true, default-features = true }
|
||||
pezsc-consensus = { workspace = true, default-features = true }
|
||||
pezsc-consensus-epochs = { workspace = true, default-features = true }
|
||||
pezsc-consensus-slots = { workspace = true, default-features = true }
|
||||
pezsc-telemetry = { workspace = true, default-features = true }
|
||||
pezsc-transaction-pool-api = { workspace = true, default-features = true }
|
||||
pezsp-api = { workspace = true, default-features = true }
|
||||
pezsp-application-crypto = { workspace = true, default-features = true }
|
||||
pezsp-block-builder = { workspace = true, default-features = true }
|
||||
pezsp-blockchain = { workspace = true, default-features = true }
|
||||
pezsp-consensus = { workspace = true, default-features = true }
|
||||
pezsp-consensus-babe = { workspace = true, default-features = true }
|
||||
pezsp-consensus-slots = { workspace = true, default-features = true }
|
||||
pezsp-core = { workspace = true, default-features = true }
|
||||
pezsp-crypto-hashing = { workspace = true, default-features = true }
|
||||
pezsp-inherents = { workspace = true, default-features = true }
|
||||
pezsp-keystore = { workspace = true, default-features = true }
|
||||
pezsp-runtime = { workspace = true, default-features = true }
|
||||
pezsp-timestamp = { workspace = true, default-features = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pezsc-block-builder = { workspace = true, default-features = true }
|
||||
pezsc-network-test = { workspace = true }
|
||||
pezsp-keyring = { workspace = true, default-features = true }
|
||||
pezsp-tracing = { workspace = true, default-features = true }
|
||||
bizinikiwi-test-runtime-client = { workspace = true }
|
||||
tokio = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
runtime-benchmarks = [
|
||||
"pezsc-block-builder/runtime-benchmarks",
|
||||
"pezsc-client-api/runtime-benchmarks",
|
||||
"pezsc-consensus-epochs/runtime-benchmarks",
|
||||
"pezsc-consensus-slots/runtime-benchmarks",
|
||||
"pezsc-consensus/runtime-benchmarks",
|
||||
"pezsc-network-test/runtime-benchmarks",
|
||||
"pezsc-transaction-pool-api/runtime-benchmarks",
|
||||
"pezsp-api/runtime-benchmarks",
|
||||
"pezsp-block-builder/runtime-benchmarks",
|
||||
"pezsp-blockchain/runtime-benchmarks",
|
||||
"pezsp-consensus-babe/runtime-benchmarks",
|
||||
"pezsp-consensus-slots/runtime-benchmarks",
|
||||
"pezsp-consensus/runtime-benchmarks",
|
||||
"pezsp-inherents/runtime-benchmarks",
|
||||
"pezsp-keyring/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
"pezsp-timestamp/runtime-benchmarks",
|
||||
"bizinikiwi-test-runtime-client/runtime-benchmarks",
|
||||
]
|
||||
@@ -0,0 +1,48 @@
|
||||
# BABE (Blind Assignment for Blockchain Extension)
|
||||
|
||||
BABE is a slot-based block production mechanism which uses a VRF PRNG to
|
||||
randomly perform the slot allocation. On every slot, all the authorities
|
||||
generate a new random number with the VRF function and if it is lower than a
|
||||
given threshold (which is proportional to their weight/stake) they have a
|
||||
right to produce a block. The proof of the VRF function execution will be
|
||||
used by other peer to validate the legitimacy of the slot claim.
|
||||
|
||||
The engine is also responsible for collecting entropy on-chain which will be
|
||||
used to seed the given VRF PRNG. An epoch is a contiguous number of slots
|
||||
under which we will be using the same authority set. During an epoch all VRF
|
||||
outputs produced as a result of block production will be collected on an
|
||||
on-chain randomness pool. Epoch changes are announced one epoch in advance,
|
||||
i.e. when ending epoch N, we announce the parameters (randomness,
|
||||
authorities, etc.) for epoch N+2.
|
||||
|
||||
Since the slot assignment is randomized, it is possible that a slot is
|
||||
assigned to multiple validators in which case we will have a temporary fork,
|
||||
or that a slot is assigned to no validator in which case no block is
|
||||
produced. Which means that block times are not deterministic.
|
||||
|
||||
The protocol has a parameter `c` [0, 1] for which `1 - c` is the probability
|
||||
of a slot being empty. The choice of this parameter affects the security of
|
||||
the protocol relating to maximum tolerable network delays.
|
||||
|
||||
In addition to the VRF-based slot assignment described above, which we will
|
||||
call primary slots, the engine also supports a deterministic secondary slot
|
||||
assignment. Primary slots take precedence over secondary slots, when
|
||||
authoring the node starts by trying to claim a primary slot and falls back
|
||||
to a secondary slot claim attempt. The secondary slot assignment is done
|
||||
by picking the authority at index:
|
||||
|
||||
`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 teyrchains.
|
||||
|
||||
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.
|
||||
|
||||
An in-depth description and analysis of the protocol can be found here:
|
||||
<https://research.web3.foundation/PezkuwiChain/protocols/block-production/Babe>
|
||||
|
||||
License: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
@@ -0,0 +1,60 @@
|
||||
[package]
|
||||
name = "pezsc-consensus-babe-rpc"
|
||||
version = "0.34.0"
|
||||
authors.workspace = true
|
||||
description = "RPC extensions for the BABE consensus algorithm"
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
readme = "README.md"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
targets = ["x86_64-unknown-linux-gnu"]
|
||||
|
||||
[dependencies]
|
||||
futures = { workspace = true }
|
||||
jsonrpsee = { features = [
|
||||
"client-core",
|
||||
"macros",
|
||||
"server-core",
|
||||
], workspace = true }
|
||||
pezsc-consensus-babe = { workspace = true, default-features = true }
|
||||
pezsc-consensus-epochs = { workspace = true, default-features = true }
|
||||
pezsc-rpc-api = { workspace = true, default-features = true }
|
||||
serde = { features = ["derive"], workspace = true, default-features = true }
|
||||
pezsp-api = { workspace = true, default-features = true }
|
||||
pezsp-application-crypto = { workspace = true, default-features = true }
|
||||
pezsp-blockchain = { workspace = true, default-features = true }
|
||||
pezsp-consensus = { workspace = true, default-features = true }
|
||||
pezsp-consensus-babe = { workspace = true, default-features = true }
|
||||
pezsp-core = { workspace = true, default-features = true }
|
||||
pezsp-keystore = { workspace = true, default-features = true }
|
||||
pezsp-runtime = { workspace = true, default-features = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pezsc-consensus = { workspace = true, default-features = true }
|
||||
pezsc-transaction-pool-api = { workspace = true, default-features = true }
|
||||
pezsp-keyring = { workspace = true, default-features = true }
|
||||
bizinikiwi-test-runtime-client = { workspace = true }
|
||||
tokio = { workspace = true, default-features = true }
|
||||
|
||||
[features]
|
||||
runtime-benchmarks = [
|
||||
"pezsc-consensus-babe/runtime-benchmarks",
|
||||
"pezsc-consensus-epochs/runtime-benchmarks",
|
||||
"pezsc-consensus/runtime-benchmarks",
|
||||
"pezsc-rpc-api/runtime-benchmarks",
|
||||
"pezsc-transaction-pool-api/runtime-benchmarks",
|
||||
"pezsp-api/runtime-benchmarks",
|
||||
"pezsp-blockchain/runtime-benchmarks",
|
||||
"pezsp-consensus-babe/runtime-benchmarks",
|
||||
"pezsp-consensus/runtime-benchmarks",
|
||||
"pezsp-keyring/runtime-benchmarks",
|
||||
"pezsp-runtime/runtime-benchmarks",
|
||||
"bizinikiwi-test-runtime-client/runtime-benchmarks",
|
||||
]
|
||||
@@ -0,0 +1,3 @@
|
||||
RPC api for babe.
|
||||
|
||||
License: GPL-3.0-or-later WITH Classpath-exception-2.0
|
||||
@@ -0,0 +1,282 @@
|
||||
// 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/>.
|
||||
|
||||
//! RPC api for babe.
|
||||
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use futures::TryFutureExt;
|
||||
use jsonrpsee::{
|
||||
core::async_trait,
|
||||
proc_macros::rpc,
|
||||
types::{ErrorObject, ErrorObjectOwned},
|
||||
Extensions,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use pezsc_consensus_babe::{authorship, BabeWorkerHandle};
|
||||
use pezsc_consensus_epochs::Epoch as EpochT;
|
||||
use pezsc_rpc_api::{check_if_safe, UnsafeRpcError};
|
||||
use pezsp_api::ProvideRuntimeApi;
|
||||
use pezsp_application_crypto::AppCrypto;
|
||||
use pezsp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};
|
||||
use pezsp_consensus::{Error as ConsensusError, SelectChain};
|
||||
use pezsp_consensus_babe::{digests::PreDigest, AuthorityId, BabeApi as BabeRuntimeApi};
|
||||
use pezsp_core::crypto::ByteArray;
|
||||
use pezsp_keystore::KeystorePtr;
|
||||
use pezsp_runtime::traits::{Block as BlockT, Header as _};
|
||||
|
||||
const BABE_ERROR: i32 = 9000;
|
||||
|
||||
/// Provides rpc methods for interacting with Babe.
|
||||
#[rpc(client, server)]
|
||||
pub trait BabeApi {
|
||||
/// Returns data about which slots (primary or secondary) can be claimed in the current epoch
|
||||
/// with the keys in the keystore.
|
||||
#[method(name = "babe_epochAuthorship", with_extensions)]
|
||||
async fn epoch_authorship(&self) -> Result<HashMap<AuthorityId, EpochAuthorship>, Error>;
|
||||
}
|
||||
|
||||
/// Provides RPC methods for interacting with Babe.
|
||||
pub struct Babe<B: BlockT, C, SC> {
|
||||
/// shared reference to the client.
|
||||
client: Arc<C>,
|
||||
/// A handle to the BABE worker for issuing requests.
|
||||
babe_worker_handle: BabeWorkerHandle<B>,
|
||||
/// shared reference to the Keystore
|
||||
keystore: KeystorePtr,
|
||||
/// The SelectChain strategy
|
||||
select_chain: SC,
|
||||
}
|
||||
|
||||
impl<B: BlockT, C, SC> Babe<B, C, SC> {
|
||||
/// Creates a new instance of the Babe Rpc handler.
|
||||
pub fn new(
|
||||
client: Arc<C>,
|
||||
babe_worker_handle: BabeWorkerHandle<B>,
|
||||
keystore: KeystorePtr,
|
||||
select_chain: SC,
|
||||
) -> Self {
|
||||
Self { client, babe_worker_handle, keystore, select_chain }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B: BlockT, C, SC> BabeApiServer for Babe<B, C, SC>
|
||||
where
|
||||
B: BlockT,
|
||||
C: ProvideRuntimeApi<B>
|
||||
+ HeaderBackend<B>
|
||||
+ HeaderMetadata<B, Error = BlockChainError>
|
||||
+ 'static,
|
||||
C::Api: BabeRuntimeApi<B>,
|
||||
SC: SelectChain<B> + Clone + 'static,
|
||||
{
|
||||
async fn epoch_authorship(
|
||||
&self,
|
||||
ext: &Extensions,
|
||||
) -> Result<HashMap<AuthorityId, EpochAuthorship>, Error> {
|
||||
check_if_safe(ext)?;
|
||||
|
||||
let best_header = self.select_chain.best_chain().map_err(Error::SelectChain).await?;
|
||||
|
||||
let epoch_start = self
|
||||
.client
|
||||
.runtime_api()
|
||||
.current_epoch_start(best_header.hash())
|
||||
.map_err(|_| Error::FetchEpoch)?;
|
||||
|
||||
let epoch = self
|
||||
.babe_worker_handle
|
||||
.epoch_data_for_child_of(best_header.hash(), *best_header.number(), epoch_start)
|
||||
.await
|
||||
.map_err(|_| Error::FetchEpoch)?;
|
||||
|
||||
let (epoch_start, epoch_end) = (epoch.start_slot(), epoch.end_slot());
|
||||
let mut claims: HashMap<AuthorityId, EpochAuthorship> = HashMap::new();
|
||||
|
||||
let keys = {
|
||||
epoch
|
||||
.authorities
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, a)| {
|
||||
if self.keystore.has_keys(&[(a.0.to_raw_vec(), AuthorityId::ID)]) {
|
||||
Some((a.0.clone(), i))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
for slot in *epoch_start..*epoch_end {
|
||||
if let Some((claim, key)) =
|
||||
authorship::claim_slot_using_keys(slot.into(), &epoch, &self.keystore, &keys)
|
||||
{
|
||||
match claim {
|
||||
PreDigest::Primary { .. } => {
|
||||
claims.entry(key).or_default().primary.push(slot);
|
||||
},
|
||||
PreDigest::SecondaryPlain { .. } => {
|
||||
claims.entry(key).or_default().secondary.push(slot);
|
||||
},
|
||||
PreDigest::SecondaryVRF { .. } => {
|
||||
claims.entry(key).or_default().secondary_vrf.push(slot.into());
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Ok(claims)
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds information about the `slot`'s that can be claimed by a given key.
|
||||
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
|
||||
pub struct EpochAuthorship {
|
||||
/// the array of primary slots that can be claimed
|
||||
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>,
|
||||
}
|
||||
|
||||
/// Top-level error type for the RPC handler.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Failed to fetch the current best header.
|
||||
#[error("Failed to fetch the current best header: {0}")]
|
||||
SelectChain(ConsensusError),
|
||||
/// Failed to fetch epoch data.
|
||||
#[error("Failed to fetch epoch data")]
|
||||
FetchEpoch,
|
||||
/// Consensus error
|
||||
#[error(transparent)]
|
||||
Consensus(#[from] ConsensusError),
|
||||
/// Errors that can be formatted as a String
|
||||
#[error("{0}")]
|
||||
StringError(String),
|
||||
/// Call to an unsafe RPC was denied.
|
||||
#[error(transparent)]
|
||||
UnsafeRpcCalled(#[from] UnsafeRpcError),
|
||||
}
|
||||
|
||||
impl From<Error> for ErrorObjectOwned {
|
||||
fn from(error: Error) -> Self {
|
||||
match error {
|
||||
Error::SelectChain(e) => ErrorObject::owned(BABE_ERROR + 1, e.to_string(), None::<()>),
|
||||
Error::FetchEpoch => ErrorObject::owned(BABE_ERROR + 2, error.to_string(), None::<()>),
|
||||
Error::Consensus(e) => ErrorObject::owned(BABE_ERROR + 3, e.to_string(), None::<()>),
|
||||
Error::StringError(e) => ErrorObject::owned(BABE_ERROR + 4, e, None::<()>),
|
||||
Error::UnsafeRpcCalled(e) => e.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pezsc_consensus_babe::ImportQueueParams;
|
||||
use pezsc_rpc_api::DenyUnsafe;
|
||||
use pezsc_transaction_pool_api::{OffchainTransactionPoolFactory, RejectAllTxPool};
|
||||
use pezsp_consensus_babe::inherents::InherentDataProvider;
|
||||
use pezsp_core::{crypto::key_types::BABE, testing::TaskExecutor};
|
||||
use pezsp_keyring::Sr25519Keyring;
|
||||
use pezsp_keystore::{testing::MemoryKeystore, Keystore};
|
||||
use bizinikiwi_test_runtime_client::{
|
||||
runtime::Block, Backend, DefaultTestClientBuilderExt, TestClient, TestClientBuilder,
|
||||
TestClientBuilderExt,
|
||||
};
|
||||
|
||||
fn create_keystore(authority: Sr25519Keyring) -> KeystorePtr {
|
||||
let keystore = MemoryKeystore::new();
|
||||
keystore
|
||||
.sr25519_generate_new(BABE, Some(&authority.to_seed()))
|
||||
.expect("Creates authority key");
|
||||
keystore.into()
|
||||
}
|
||||
|
||||
fn test_babe_rpc_module() -> Babe<Block, TestClient, pezsc_consensus::LongestChain<Backend, Block>>
|
||||
{
|
||||
let builder = TestClientBuilder::new();
|
||||
let (client, longest_chain) = builder.build_with_longest_chain();
|
||||
let client = Arc::new(client);
|
||||
let task_executor = TaskExecutor::new();
|
||||
let keystore = create_keystore(Sr25519Keyring::Alice);
|
||||
|
||||
let config = pezsc_consensus_babe::configuration(&*client).expect("config available");
|
||||
let slot_duration = config.slot_duration();
|
||||
|
||||
let (block_import, link) = pezsc_consensus_babe::block_import(
|
||||
config.clone(),
|
||||
client.clone(),
|
||||
client.clone(),
|
||||
move |_, _| async move {
|
||||
Ok((InherentDataProvider::from_timestamp_and_slot_duration(
|
||||
0.into(),
|
||||
slot_duration,
|
||||
),))
|
||||
},
|
||||
longest_chain.clone(),
|
||||
OffchainTransactionPoolFactory::new(RejectAllTxPool::default()),
|
||||
)
|
||||
.expect("can initialize block-import");
|
||||
|
||||
let (_, babe_worker_handle) = pezsc_consensus_babe::import_queue(ImportQueueParams {
|
||||
link: link.clone(),
|
||||
block_import: block_import.clone(),
|
||||
justification_import: None,
|
||||
client: client.clone(),
|
||||
slot_duration,
|
||||
spawner: &task_executor,
|
||||
registry: None,
|
||||
telemetry: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
Babe::new(client.clone(), babe_worker_handle, keystore, longest_chain)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn epoch_authorship_works() {
|
||||
let babe_rpc = test_babe_rpc_module();
|
||||
let mut api = babe_rpc.into_rpc();
|
||||
api.extensions_mut().insert(DenyUnsafe::No);
|
||||
|
||||
let request = r#"{"jsonrpc":"2.0","id":1,"method":"babe_epochAuthorship","params":[]}"#;
|
||||
let (response, _) = api.raw_json_request(request, 1).await.unwrap();
|
||||
let expected = r#"{"jsonrpc":"2.0","id":1,"result":{"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY":{"primary":[0],"secondary":[],"secondary_vrf":[1,2,4]}}}"#;
|
||||
|
||||
assert_eq!(response, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn epoch_authorship_is_unsafe() {
|
||||
let babe_rpc = test_babe_rpc_module();
|
||||
let mut api = babe_rpc.into_rpc();
|
||||
api.extensions_mut().insert(DenyUnsafe::Yes);
|
||||
|
||||
let request = r#"{"jsonrpc":"2.0","method":"babe_epochAuthorship","params":[],"id":1}"#;
|
||||
let (response, _) = api.raw_json_request(request, 1).await.unwrap();
|
||||
let expected = r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"RPC call is unsafe to be called externally"}}"#;
|
||||
|
||||
assert_eq!(response, expected);
|
||||
}
|
||||
}
|
||||
@@ -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