mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-11 03:41:06 +00:00
Lean BEEFY to Full BEEFY - don't skip (older) mandatory blocks and import justifications (#11821)
* client/beefy: don't accept vote for older rounds
* client/beefy: clean up and reorg the worker struct
* client/beefy: first step towards Full BEEFY
The first step from Lean->Full BEEFY is to have the worker
enforce uninterrupted line of BEEFY finalized mandatory blocks.
There is one mandatory block per session (the first block in the
session). As such, votes processing and votes generation now
enforces that all mandatory blocks are finalized in strict
monotonically increasing sequence and no block 'N' will be worked
on if there is any GRANDPA finalized but BEEFY non-final mandatory
block 'M', where 'M < N'.
Implementation details:
- Introduced 'VoterOracle' to separate the voting decisions logic,
and track new/pending sessions.
- New sessions get queued up with the worker operating either:
1. up-to-date - all mandatory blocks leading up to current GRANDPA
finalized: queue has ONE element, the 'current session' where
`mandatory_done == true`,
2. lagging behind GRANDPA: queue has [1, N] elements, where all
`mandatory_done == false`.
In this state, everytime a session gets its mandatory block
BEEFY finalized, the session is popped off the queue,
eventually getting to operating mode `1. up-to-date`.
- Votes get triaged and those that fall withing the `VoterOracle`
allowed window get processed, the others get dropped if stale,
or buffered for later processing (when they reach the window).
- Worker general code was also updated to fall in one of two roles:
1. react to external events and change internal 'state',
2. generate events/votes based on internal 'state'.
Signed-off-by: acatangiu <adrian@parity.io>
* client/beefy: sketch idea for block import and sync
Signed-off-by: acatangiu <adrian@parity.io>
* client/beefy: add BEEFY block import
* client/beefy: process justifications from block import
* client/beefy: add TODOs for sync protocol
* client/beefy: add more docs and comments
* client/beefy-rpc: fix RPC error
* client/beefy: verify justification validity on block import
* client/beefy: more tests
* client/beefy: small fixes
- first handle and note the self vote before gossiping it,
- don't shortcircuit on err when processing pending votes.
* client/beefy: remove invalid justifications at block import
* todo: beefy block import tests
* RFC: ideas for multiple justifications per block
* Revert "RFC: ideas for multiple justifications per block"
This reverts commit 8256fb07d3124db69daf252720b3c0208202624d.
* client/beefy: append justif to backend on block import
* client/beefy: groundwork for block import test
* client/beefy: groundwork2 for block import test
* client/beefy: groundwork3 for block import test
* client/beefy: add block import test
* client/beefy: add required trait bounds to block import builder
* remove client from beefy block import, backend gets the job done
Signed-off-by: acatangiu <adrian@parity.io>
This commit is contained in:
Generated
+2
@@ -440,6 +440,7 @@ dependencies = [
|
||||
name = "beefy-gadget"
|
||||
version = "4.0.0-dev"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"beefy-primitives",
|
||||
"fnv",
|
||||
"futures",
|
||||
@@ -448,6 +449,7 @@ dependencies = [
|
||||
"log",
|
||||
"parity-scale-codec",
|
||||
"parking_lot 0.12.0",
|
||||
"sc-block-builder",
|
||||
"sc-chain-spec",
|
||||
"sc-client-api",
|
||||
"sc-consensus",
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "BEEFY Client gadget for substrate"
|
||||
homepage = "https://substrate.io"
|
||||
|
||||
[dependencies]
|
||||
async-trait = "0.1.50"
|
||||
codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] }
|
||||
fnv = "1.0.6"
|
||||
futures = "0.3"
|
||||
@@ -22,6 +23,7 @@ beefy-primitives = { version = "4.0.0-dev", path = "../../primitives/beefy" }
|
||||
prometheus = { package = "substrate-prometheus-endpoint", version = "0.10.0-dev", path = "../../utils/prometheus" }
|
||||
sc-chain-spec = { version = "4.0.0-dev", path = "../../client/chain-spec" }
|
||||
sc-client-api = { version = "4.0.0-dev", path = "../api" }
|
||||
sc-consensus = { version = "0.10.0-dev", path = "../consensus/common" }
|
||||
sc-finality-grandpa = { version = "0.10.0-dev", path = "../../client/finality-grandpa" }
|
||||
sc-keystore = { version = "4.0.0-dev", path = "../keystore" }
|
||||
sc-network = { version = "0.10.0-dev", path = "../network" }
|
||||
@@ -42,7 +44,7 @@ serde = "1.0.136"
|
||||
strum = { version = "0.24.1", features = ["derive"] }
|
||||
tempfile = "3.1.0"
|
||||
tokio = "1.17.0"
|
||||
sc-consensus = { version = "0.10.0-dev", path = "../consensus/common" }
|
||||
sc-block-builder = { version = "0.10.0-dev", path = "../block-builder" }
|
||||
sc-network-test = { version = "0.8.0", path = "../network/test" }
|
||||
sp-finality-grandpa = { version = "4.0.0-dev", path = "../../primitives/finality-grandpa" }
|
||||
sp-keyring = { version = "6.0.0", path = "../../primitives/keyring" }
|
||||
|
||||
@@ -164,8 +164,9 @@ where
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use beefy_gadget::notification::{
|
||||
BeefyBestBlockStream, BeefySignedCommitment, BeefySignedCommitmentSender,
|
||||
use beefy_gadget::{
|
||||
justification::BeefySignedCommitment,
|
||||
notification::{BeefyBestBlockStream, BeefySignedCommitmentSender},
|
||||
};
|
||||
use beefy_primitives::{known_payload_ids, Payload};
|
||||
use codec::{Decode, Encode};
|
||||
|
||||
@@ -29,7 +29,7 @@ pub struct EncodedSignedCommitment(sp_core::Bytes);
|
||||
|
||||
impl EncodedSignedCommitment {
|
||||
pub fn new<Block>(
|
||||
signed_commitment: beefy_gadget::notification::BeefySignedCommitment<Block>,
|
||||
signed_commitment: beefy_gadget::justification::BeefySignedCommitment<Block>,
|
||||
) -> Self
|
||||
where
|
||||
Block: BlockT,
|
||||
|
||||
@@ -24,8 +24,12 @@ use std::fmt::Debug;
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum Error {
|
||||
#[error("Backend: {0}")]
|
||||
Backend(String),
|
||||
#[error("Keystore error: {0}")]
|
||||
Keystore(String),
|
||||
#[error("Signature error: {0}")]
|
||||
Signature(String),
|
||||
#[error("Session uninitialized")]
|
||||
UninitSession,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) 2021-2022 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 beefy_primitives::{crypto::Signature, BeefyApi, VersionedFinalityProof, BEEFY_ENGINE_ID};
|
||||
use codec::Encode;
|
||||
use log::error;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use sp_api::{ProvideRuntimeApi, TransactionFor};
|
||||
use sp_blockchain::{well_known_cache_keys, HeaderBackend};
|
||||
use sp_consensus::Error as ConsensusError;
|
||||
use sp_runtime::{
|
||||
generic::BlockId,
|
||||
traits::{Block as BlockT, Header as HeaderT, NumberFor},
|
||||
EncodedJustification,
|
||||
};
|
||||
|
||||
use sc_client_api::backend::Backend;
|
||||
use sc_consensus::{BlockCheckParams, BlockImport, BlockImportParams, ImportResult};
|
||||
|
||||
use crate::{
|
||||
justification::decode_and_verify_commitment, notification::BeefySignedCommitmentSender,
|
||||
};
|
||||
|
||||
/// A block-import handler for BEEFY.
|
||||
///
|
||||
/// This scans each imported block for BEEFY justifications and verifies them.
|
||||
/// Wraps a `inner: BlockImport` and ultimately defers to it.
|
||||
///
|
||||
/// When using BEEFY, the block import worker should be using this block import object.
|
||||
pub struct BeefyBlockImport<Block: BlockT, Backend, RuntimeApi, I> {
|
||||
backend: Arc<Backend>,
|
||||
runtime: Arc<RuntimeApi>,
|
||||
inner: I,
|
||||
justification_sender: BeefySignedCommitmentSender<Block>,
|
||||
}
|
||||
|
||||
impl<Block: BlockT, BE, Runtime, I: Clone> Clone for BeefyBlockImport<Block, BE, Runtime, I> {
|
||||
fn clone(&self) -> Self {
|
||||
BeefyBlockImport {
|
||||
backend: self.backend.clone(),
|
||||
runtime: self.runtime.clone(),
|
||||
inner: self.inner.clone(),
|
||||
justification_sender: self.justification_sender.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block: BlockT, BE, Runtime, I> BeefyBlockImport<Block, BE, Runtime, I> {
|
||||
/// Create a new BeefyBlockImport.
|
||||
pub fn new(
|
||||
backend: Arc<BE>,
|
||||
runtime: Arc<Runtime>,
|
||||
inner: I,
|
||||
justification_sender: BeefySignedCommitmentSender<Block>,
|
||||
) -> BeefyBlockImport<Block, BE, Runtime, I> {
|
||||
BeefyBlockImport { backend, runtime, inner, justification_sender }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Block, BE, Runtime, I> BeefyBlockImport<Block, BE, Runtime, I>
|
||||
where
|
||||
Block: BlockT,
|
||||
BE: Backend<Block>,
|
||||
Runtime: ProvideRuntimeApi<Block>,
|
||||
Runtime::Api: BeefyApi<Block> + Send + Sync,
|
||||
{
|
||||
fn decode_and_verify(
|
||||
&self,
|
||||
encoded: &EncodedJustification,
|
||||
number: NumberFor<Block>,
|
||||
hash: <Block as BlockT>::Hash,
|
||||
) -> Result<VersionedFinalityProof<NumberFor<Block>, Signature>, ConsensusError> {
|
||||
let block_id = BlockId::hash(hash);
|
||||
let validator_set = self
|
||||
.runtime
|
||||
.runtime_api()
|
||||
.validator_set(&block_id)
|
||||
.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
|
||||
.ok_or_else(|| ConsensusError::ClientImport("Unknown validator set".to_string()))?;
|
||||
|
||||
decode_and_verify_commitment::<Block>(&encoded[..], number, &validator_set)
|
||||
}
|
||||
|
||||
/// Import BEEFY justification: Send it to worker for processing and also append it to backend.
|
||||
///
|
||||
/// This function assumes:
|
||||
/// - `justification` is verified and valid,
|
||||
/// - the block referred by `justification` has been imported _and_ finalized.
|
||||
fn import_beefy_justification_unchecked(
|
||||
&self,
|
||||
number: NumberFor<Block>,
|
||||
justification: VersionedFinalityProof<NumberFor<Block>, Signature>,
|
||||
) {
|
||||
// Append the justification to the block in the backend.
|
||||
if let Err(e) = self.backend.append_justification(
|
||||
BlockId::Number(number),
|
||||
(BEEFY_ENGINE_ID, justification.encode()),
|
||||
) {
|
||||
error!(target: "beefy", "🥩 Error {:?} on appending justification: {:?}", e, justification);
|
||||
}
|
||||
// Send the justification to the BEEFY voter for processing.
|
||||
match justification {
|
||||
// TODO #11838: Should not unpack, these channels should also use
|
||||
// `VersionedFinalityProof`.
|
||||
VersionedFinalityProof::V1(signed_commitment) => self
|
||||
.justification_sender
|
||||
.notify(|| Ok::<_, ()>(signed_commitment))
|
||||
.expect("forwards closure result; the closure always returns Ok; qed."),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<Block, BE, Runtime, I> BlockImport<Block> for BeefyBlockImport<Block, BE, Runtime, I>
|
||||
where
|
||||
Block: BlockT,
|
||||
BE: Backend<Block>,
|
||||
I: BlockImport<
|
||||
Block,
|
||||
Error = ConsensusError,
|
||||
Transaction = sp_api::TransactionFor<Runtime, Block>,
|
||||
> + Send
|
||||
+ Sync,
|
||||
Runtime: ProvideRuntimeApi<Block> + Send + Sync,
|
||||
Runtime::Api: BeefyApi<Block>,
|
||||
{
|
||||
type Error = ConsensusError;
|
||||
type Transaction = TransactionFor<Runtime, Block>;
|
||||
|
||||
async fn import_block(
|
||||
&mut self,
|
||||
mut block: BlockImportParams<Block, Self::Transaction>,
|
||||
new_cache: HashMap<well_known_cache_keys::Id, Vec<u8>>,
|
||||
) -> Result<ImportResult, Self::Error> {
|
||||
let hash = block.post_hash();
|
||||
let number = *block.header.number();
|
||||
|
||||
let beefy_proof = block
|
||||
.justifications
|
||||
.as_mut()
|
||||
.and_then(|just| {
|
||||
let decoded = just
|
||||
.get(BEEFY_ENGINE_ID)
|
||||
.map(|encoded| self.decode_and_verify(encoded, number, hash));
|
||||
// Remove BEEFY justification from the list before giving to `inner`;
|
||||
// we will append it to backend ourselves at the end if all goes well.
|
||||
just.remove(BEEFY_ENGINE_ID);
|
||||
decoded
|
||||
})
|
||||
.transpose()
|
||||
.unwrap_or(None);
|
||||
|
||||
// Run inner block import.
|
||||
let inner_import_result = self.inner.import_block(block, new_cache).await?;
|
||||
|
||||
match (beefy_proof, &inner_import_result) {
|
||||
(Some(proof), ImportResult::Imported(_)) => {
|
||||
let status = self.backend.blockchain().info();
|
||||
if number <= status.finalized_number &&
|
||||
Some(hash) ==
|
||||
self.backend
|
||||
.blockchain()
|
||||
.hash(number)
|
||||
.map_err(|e| ConsensusError::ClientImport(e.to_string()))?
|
||||
{
|
||||
// The proof is valid and the block is imported and final, we can import.
|
||||
self.import_beefy_justification_unchecked(number, proof);
|
||||
} else {
|
||||
error!(
|
||||
target: "beefy",
|
||||
"🥩 Cannot import justification: {:?} for, not yet final, block number {:?}",
|
||||
proof,
|
||||
number,
|
||||
);
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
|
||||
Ok(inner_import_result)
|
||||
}
|
||||
|
||||
async fn check_block(
|
||||
&mut self,
|
||||
block: BlockCheckParams<Block>,
|
||||
) -> Result<ImportResult, Self::Error> {
|
||||
self.inner.check_block(block).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) 2021-2022 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::keystore::BeefyKeystore;
|
||||
use beefy_primitives::{
|
||||
crypto::{AuthorityId, Signature},
|
||||
ValidatorSet, VersionedFinalityProof,
|
||||
};
|
||||
use codec::{Decode, Encode};
|
||||
use sp_consensus::Error as ConsensusError;
|
||||
use sp_runtime::traits::{Block as BlockT, NumberFor};
|
||||
|
||||
/// A commitment with matching BEEFY authorities' signatures.
|
||||
pub type BeefySignedCommitment<Block> =
|
||||
beefy_primitives::SignedCommitment<NumberFor<Block>, beefy_primitives::crypto::Signature>;
|
||||
|
||||
/// Decode and verify a Beefy SignedCommitment.
|
||||
pub(crate) fn decode_and_verify_commitment<Block: BlockT>(
|
||||
encoded: &[u8],
|
||||
target_number: NumberFor<Block>,
|
||||
validator_set: &ValidatorSet<AuthorityId>,
|
||||
) -> Result<VersionedFinalityProof<NumberFor<Block>, Signature>, ConsensusError> {
|
||||
let proof = <VersionedFinalityProof<NumberFor<Block>, Signature>>::decode(&mut &*encoded)
|
||||
.map_err(|_| ConsensusError::InvalidJustification)?;
|
||||
verify_with_validator_set::<Block>(target_number, validator_set, &proof).map(|_| proof)
|
||||
}
|
||||
|
||||
/// Verify the Beefy finality proof against the validator set at the block it was generated.
|
||||
fn verify_with_validator_set<Block: BlockT>(
|
||||
target_number: NumberFor<Block>,
|
||||
validator_set: &ValidatorSet<AuthorityId>,
|
||||
proof: &VersionedFinalityProof<NumberFor<Block>, Signature>,
|
||||
) -> Result<(), ConsensusError> {
|
||||
match proof {
|
||||
VersionedFinalityProof::V1(signed_commitment) => {
|
||||
if signed_commitment.signatures.len() != validator_set.len() ||
|
||||
signed_commitment.commitment.validator_set_id != validator_set.id() ||
|
||||
signed_commitment.commitment.block_number != target_number
|
||||
{
|
||||
return Err(ConsensusError::InvalidJustification)
|
||||
}
|
||||
|
||||
// Arrangement of signatures in the commitment should be in the same order
|
||||
// as validators for that set.
|
||||
let message = signed_commitment.commitment.encode();
|
||||
let valid_signatures = validator_set
|
||||
.validators()
|
||||
.into_iter()
|
||||
.zip(signed_commitment.signatures.iter())
|
||||
.filter(|(id, signature)| {
|
||||
signature
|
||||
.as_ref()
|
||||
.map(|sig| BeefyKeystore::verify(id, sig, &message[..]))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
.count();
|
||||
if valid_signatures >= crate::round::threshold(validator_set.len()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ConsensusError::InvalidJustification)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use beefy_primitives::{known_payload_ids, Commitment, Payload, SignedCommitment};
|
||||
use substrate_test_runtime_client::runtime::Block;
|
||||
|
||||
use super::*;
|
||||
use crate::{keystore::tests::Keyring, tests::make_beefy_ids};
|
||||
|
||||
pub(crate) fn new_signed_commitment(
|
||||
block_num: NumberFor<Block>,
|
||||
validator_set: &ValidatorSet<AuthorityId>,
|
||||
keys: &[Keyring],
|
||||
) -> BeefySignedCommitment<Block> {
|
||||
let commitment = Commitment {
|
||||
payload: Payload::new(known_payload_ids::MMR_ROOT_ID, vec![]),
|
||||
block_number: block_num,
|
||||
validator_set_id: validator_set.id(),
|
||||
};
|
||||
let message = commitment.encode();
|
||||
let signatures = keys.iter().map(|key| Some(key.sign(&message))).collect();
|
||||
SignedCommitment { commitment, signatures }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_verify_with_validator_set() {
|
||||
let keys = &[Keyring::Alice, Keyring::Bob, Keyring::Charlie];
|
||||
let validator_set = ValidatorSet::new(make_beefy_ids(keys), 0).unwrap();
|
||||
|
||||
// build valid justification
|
||||
let block_num = 42;
|
||||
let proof = new_signed_commitment(block_num, &validator_set, keys);
|
||||
|
||||
let good_proof = proof.clone().into();
|
||||
// should verify successfully
|
||||
verify_with_validator_set::<Block>(block_num, &validator_set, &good_proof).unwrap();
|
||||
|
||||
// wrong block number -> should fail verification
|
||||
let good_proof = proof.clone().into();
|
||||
match verify_with_validator_set::<Block>(block_num + 1, &validator_set, &good_proof) {
|
||||
Err(ConsensusError::InvalidJustification) => (),
|
||||
_ => assert!(false, "Expected Err(ConsensusError::InvalidJustification)"),
|
||||
};
|
||||
|
||||
// wrong validator set id -> should fail verification
|
||||
let good_proof = proof.clone().into();
|
||||
let other = ValidatorSet::new(make_beefy_ids(keys), 1).unwrap();
|
||||
match verify_with_validator_set::<Block>(block_num, &other, &good_proof) {
|
||||
Err(ConsensusError::InvalidJustification) => (),
|
||||
_ => assert!(false, "Expected Err(ConsensusError::InvalidJustification)"),
|
||||
};
|
||||
|
||||
// wrong signatures length -> should fail verification
|
||||
let mut bad_proof = proof.clone();
|
||||
// change length of signatures
|
||||
bad_proof.signatures.pop().flatten().unwrap();
|
||||
match verify_with_validator_set::<Block>(block_num + 1, &validator_set, &bad_proof.into()) {
|
||||
Err(ConsensusError::InvalidJustification) => (),
|
||||
_ => assert!(false, "Expected Err(ConsensusError::InvalidJustification)"),
|
||||
};
|
||||
|
||||
// not enough signatures -> should fail verification
|
||||
let mut bad_proof = proof.clone();
|
||||
// remove a signature (but same length)
|
||||
*bad_proof.signatures.first_mut().unwrap() = None;
|
||||
match verify_with_validator_set::<Block>(block_num + 1, &validator_set, &bad_proof.into()) {
|
||||
Err(ConsensusError::InvalidJustification) => (),
|
||||
_ => assert!(false, "Expected Err(ConsensusError::InvalidJustification)"),
|
||||
};
|
||||
|
||||
// not enough _correct_ signatures -> should fail verification
|
||||
let mut bad_proof = proof.clone();
|
||||
// change a signature to a different key
|
||||
*bad_proof.signatures.first_mut().unwrap() =
|
||||
Some(Keyring::Dave.sign(&proof.commitment.encode()));
|
||||
match verify_with_validator_set::<Block>(block_num + 1, &validator_set, &bad_proof.into()) {
|
||||
Err(ConsensusError::InvalidJustification) => (),
|
||||
_ => assert!(false, "Expected Err(ConsensusError::InvalidJustification)"),
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn should_decode_and_verify_commitment() {
|
||||
let keys = &[Keyring::Alice, Keyring::Bob];
|
||||
let validator_set = ValidatorSet::new(make_beefy_ids(keys), 0).unwrap();
|
||||
let block_num = 1;
|
||||
|
||||
// build valid justification
|
||||
let proof = new_signed_commitment(block_num, &validator_set, keys);
|
||||
let versioned_proof: VersionedFinalityProof<NumberFor<Block>, Signature> = proof.into();
|
||||
let encoded = versioned_proof.encode();
|
||||
|
||||
// should successfully decode and verify
|
||||
let verified =
|
||||
decode_and_verify_commitment::<Block>(&encoded, block_num, &validator_set).unwrap();
|
||||
assert_eq!(verified, versioned_proof);
|
||||
}
|
||||
}
|
||||
@@ -16,23 +16,18 @@
|
||||
// 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 std::sync::Arc;
|
||||
|
||||
use beefy_primitives::{BeefyApi, MmrRootHash};
|
||||
use prometheus::Registry;
|
||||
|
||||
use sc_client_api::{Backend, BlockchainEvents, Finalizer};
|
||||
use sc_consensus::BlockImport;
|
||||
use sc_network_gossip::Network as GossipNetwork;
|
||||
|
||||
use sp_api::ProvideRuntimeApi;
|
||||
use sp_blockchain::HeaderBackend;
|
||||
use sp_consensus::SyncOracle;
|
||||
use sp_consensus::{Error as ConsensusError, SyncOracle};
|
||||
use sp_keystore::SyncCryptoStorePtr;
|
||||
use sp_mmr_primitives::MmrApi;
|
||||
use sp_runtime::traits::Block;
|
||||
|
||||
use beefy_primitives::{BeefyApi, MmrRootHash};
|
||||
|
||||
use crate::notification::{BeefyBestBlockSender, BeefySignedCommitmentSender};
|
||||
use std::sync::Arc;
|
||||
|
||||
mod error;
|
||||
mod gossip;
|
||||
@@ -41,11 +36,21 @@ mod metrics;
|
||||
mod round;
|
||||
mod worker;
|
||||
|
||||
pub mod import;
|
||||
pub mod justification;
|
||||
pub mod notification;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use crate::{
|
||||
import::BeefyBlockImport,
|
||||
notification::{
|
||||
BeefyBestBlockSender, BeefyBestBlockStream, BeefySignedCommitmentSender,
|
||||
BeefySignedCommitmentStream,
|
||||
},
|
||||
};
|
||||
|
||||
pub use beefy_protocol_name::standard_name as protocol_standard_name;
|
||||
|
||||
pub(crate) mod beefy_protocol_name {
|
||||
@@ -110,6 +115,68 @@ where
|
||||
// empty
|
||||
}
|
||||
|
||||
/// Links between the block importer, the background voter and the RPC layer,
|
||||
/// to be used by the voter.
|
||||
#[derive(Clone)]
|
||||
pub struct BeefyVoterLinks<B: Block> {
|
||||
// BlockImport -> Voter links
|
||||
/// Stream of BEEFY signed commitments from block import to voter.
|
||||
pub from_block_import_justif_stream: BeefySignedCommitmentStream<B>,
|
||||
|
||||
// Voter -> RPC links
|
||||
/// Sends BEEFY signed commitments from voter to RPC.
|
||||
pub to_rpc_justif_sender: BeefySignedCommitmentSender<B>,
|
||||
/// Sends BEEFY best block hashes from voter to RPC.
|
||||
pub to_rpc_best_block_sender: BeefyBestBlockSender<B>,
|
||||
}
|
||||
|
||||
/// Links used by the BEEFY RPC layer, from the BEEFY background voter.
|
||||
#[derive(Clone)]
|
||||
pub struct BeefyRPCLinks<B: Block> {
|
||||
/// Stream of signed commitments coming from the voter.
|
||||
pub from_voter_justif_stream: BeefySignedCommitmentStream<B>,
|
||||
/// Stream of BEEFY best block hashes coming from the voter.
|
||||
pub from_voter_best_beefy_stream: BeefyBestBlockStream<B>,
|
||||
}
|
||||
|
||||
/// Make block importer and link half necessary to tie the background voter to it.
|
||||
pub fn beefy_block_import_and_links<B, BE, RuntimeApi, I>(
|
||||
wrapped_block_import: I,
|
||||
backend: Arc<BE>,
|
||||
runtime: Arc<RuntimeApi>,
|
||||
) -> (BeefyBlockImport<B, BE, RuntimeApi, I>, BeefyVoterLinks<B>, BeefyRPCLinks<B>)
|
||||
where
|
||||
B: Block,
|
||||
BE: Backend<B>,
|
||||
I: BlockImport<B, Error = ConsensusError, Transaction = sp_api::TransactionFor<RuntimeApi, B>>
|
||||
+ Send
|
||||
+ Sync,
|
||||
RuntimeApi: ProvideRuntimeApi<B> + Send + Sync,
|
||||
RuntimeApi::Api: BeefyApi<B>,
|
||||
{
|
||||
// Voter -> RPC links
|
||||
let (to_rpc_justif_sender, from_voter_justif_stream) =
|
||||
notification::BeefySignedCommitmentStream::<B>::channel();
|
||||
let (to_rpc_best_block_sender, from_voter_best_beefy_stream) =
|
||||
notification::BeefyBestBlockStream::<B>::channel();
|
||||
|
||||
// BlockImport -> Voter links
|
||||
let (to_voter_justif_sender, from_block_import_justif_stream) =
|
||||
notification::BeefySignedCommitmentStream::<B>::channel();
|
||||
|
||||
// BlockImport
|
||||
let import =
|
||||
BeefyBlockImport::new(backend, runtime, wrapped_block_import, to_voter_justif_sender);
|
||||
let voter_links = BeefyVoterLinks {
|
||||
from_block_import_justif_stream,
|
||||
to_rpc_justif_sender,
|
||||
to_rpc_best_block_sender,
|
||||
};
|
||||
let rpc_links = BeefyRPCLinks { from_voter_best_beefy_stream, from_voter_justif_stream };
|
||||
|
||||
(import, voter_links, rpc_links)
|
||||
}
|
||||
|
||||
/// BEEFY gadget initialization parameters.
|
||||
pub struct BeefyParams<B, BE, C, N, R>
|
||||
where
|
||||
@@ -130,16 +197,14 @@ where
|
||||
pub key_store: Option<SyncCryptoStorePtr>,
|
||||
/// Gossip network
|
||||
pub network: N,
|
||||
/// BEEFY signed commitment sender
|
||||
pub signed_commitment_sender: BeefySignedCommitmentSender<B>,
|
||||
/// BEEFY best block sender
|
||||
pub beefy_best_block_sender: BeefyBestBlockSender<B>,
|
||||
/// Minimal delta between blocks, BEEFY should vote for
|
||||
pub min_block_delta: u32,
|
||||
/// Prometheus metric registry
|
||||
pub prometheus_registry: Option<Registry>,
|
||||
/// Chain specific GRANDPA protocol name. See [`beefy_protocol_name::standard_name`].
|
||||
pub protocol_name: std::borrow::Cow<'static, str>,
|
||||
/// Links between the block importer, the background voter and the RPC layer.
|
||||
pub links: BeefyVoterLinks<B>,
|
||||
}
|
||||
|
||||
/// Start the BEEFY gadget.
|
||||
@@ -160,11 +225,10 @@ where
|
||||
runtime,
|
||||
key_store,
|
||||
network,
|
||||
signed_commitment_sender,
|
||||
beefy_best_block_sender,
|
||||
min_block_delta,
|
||||
prometheus_registry,
|
||||
protocol_name,
|
||||
links,
|
||||
} = beefy_params;
|
||||
|
||||
let sync_oracle = network.clone();
|
||||
@@ -194,14 +258,13 @@ where
|
||||
client,
|
||||
backend,
|
||||
runtime,
|
||||
sync_oracle,
|
||||
key_store: key_store.into(),
|
||||
signed_commitment_sender,
|
||||
beefy_best_block_sender,
|
||||
gossip_engine,
|
||||
gossip_validator,
|
||||
min_block_delta,
|
||||
links,
|
||||
metrics,
|
||||
sync_oracle,
|
||||
min_block_delta,
|
||||
};
|
||||
|
||||
let worker = worker::BeefyWorker::<_, _, _, _, _>::new(worker_params);
|
||||
|
||||
@@ -32,8 +32,8 @@ pub(crate) struct Metrics {
|
||||
pub beefy_best_block: Gauge<U64>,
|
||||
/// Next block BEEFY should vote on
|
||||
pub beefy_should_vote_on: Gauge<U64>,
|
||||
/// Number of sessions without a signed commitment
|
||||
pub beefy_skipped_sessions: Counter<U64>,
|
||||
/// Number of sessions with lagging signed commitment on mandatory block
|
||||
pub beefy_lagging_sessions: Counter<U64>,
|
||||
}
|
||||
|
||||
impl Metrics {
|
||||
@@ -65,10 +65,10 @@ impl Metrics {
|
||||
Gauge::new("substrate_beefy_should_vote_on", "Next block, BEEFY should vote on")?,
|
||||
registry,
|
||||
)?,
|
||||
beefy_skipped_sessions: register(
|
||||
beefy_lagging_sessions: register(
|
||||
Counter::new(
|
||||
"substrate_beefy_skipped_sessions",
|
||||
"Number of sessions without a signed commitment",
|
||||
"substrate_beefy_lagging_sessions",
|
||||
"Number of sessions with lagging signed commitment on mandatory block",
|
||||
)?,
|
||||
registry,
|
||||
)?,
|
||||
|
||||
@@ -17,11 +17,9 @@
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use sc_utils::notification::{NotificationSender, NotificationStream, TracingKeyStr};
|
||||
use sp_runtime::traits::{Block as BlockT, NumberFor};
|
||||
use sp_runtime::traits::Block as BlockT;
|
||||
|
||||
/// A commitment with matching BEEFY authorities' signatures.
|
||||
pub type BeefySignedCommitment<Block> =
|
||||
beefy_primitives::SignedCommitment<NumberFor<Block>, beefy_primitives::crypto::Signature>;
|
||||
use crate::justification::BeefySignedCommitment;
|
||||
|
||||
/// The sending half of the notifications channel(s) used to send
|
||||
/// notifications about best BEEFY block from the gadget side.
|
||||
|
||||
@@ -59,7 +59,8 @@ impl RoundTracker {
|
||||
}
|
||||
}
|
||||
|
||||
fn threshold(authorities: usize) -> usize {
|
||||
/// Minimum size of `authorities` subset that produced valid signatures for a block to finalize.
|
||||
pub fn threshold(authorities: usize) -> usize {
|
||||
let faulty = authorities.saturating_sub(1) / 3;
|
||||
authorities - faulty
|
||||
}
|
||||
@@ -70,9 +71,10 @@ fn threshold(authorities: usize) -> usize {
|
||||
/// Does not do any validation on votes or signatures, layers above need to handle that (gossip).
|
||||
pub(crate) struct Rounds<Payload, B: Block> {
|
||||
rounds: BTreeMap<(Payload, NumberFor<B>), RoundTracker>,
|
||||
best_done: Option<NumberFor<B>>,
|
||||
session_start: NumberFor<B>,
|
||||
validator_set: ValidatorSet<Public>,
|
||||
mandatory_done: bool,
|
||||
best_done: Option<NumberFor<B>>,
|
||||
}
|
||||
|
||||
impl<P, B> Rounds<P, B>
|
||||
@@ -81,15 +83,15 @@ where
|
||||
B: Block,
|
||||
{
|
||||
pub(crate) fn new(session_start: NumberFor<B>, validator_set: ValidatorSet<Public>) -> Self {
|
||||
Rounds { rounds: BTreeMap::new(), best_done: None, session_start, validator_set }
|
||||
Rounds {
|
||||
rounds: BTreeMap::new(),
|
||||
session_start,
|
||||
validator_set,
|
||||
mandatory_done: false,
|
||||
best_done: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P, B> Rounds<P, B>
|
||||
where
|
||||
P: Ord + Hash + Clone,
|
||||
B: Block,
|
||||
{
|
||||
pub(crate) fn validator_set_id(&self) -> ValidatorSetId {
|
||||
self.validator_set.id()
|
||||
}
|
||||
@@ -98,8 +100,12 @@ where
|
||||
self.validator_set.validators()
|
||||
}
|
||||
|
||||
pub(crate) fn session_start(&self) -> &NumberFor<B> {
|
||||
&self.session_start
|
||||
pub(crate) fn session_start(&self) -> NumberFor<B> {
|
||||
self.session_start
|
||||
}
|
||||
|
||||
pub(crate) fn mandatory_done(&self) -> bool {
|
||||
self.mandatory_done
|
||||
}
|
||||
|
||||
pub(crate) fn should_self_vote(&self, round: &(P, NumberFor<B>)) -> bool {
|
||||
@@ -113,12 +119,9 @@ where
|
||||
vote: (Public, Signature),
|
||||
self_vote: bool,
|
||||
) -> bool {
|
||||
if Some(round.1.clone()) <= self.best_done {
|
||||
debug!(
|
||||
target: "beefy",
|
||||
"🥩 received vote for old stale round {:?}, ignoring",
|
||||
round.1
|
||||
);
|
||||
let num = round.1;
|
||||
if num < self.session_start || Some(num) <= self.best_done {
|
||||
debug!(target: "beefy", "🥩 received vote for old stale round {:?}, ignoring", num);
|
||||
false
|
||||
} else if !self.validators().iter().any(|id| vote.0 == *id) {
|
||||
debug!(
|
||||
@@ -147,6 +150,7 @@ where
|
||||
// remove this and older (now stale) rounds
|
||||
let signatures = self.rounds.remove(round)?.votes;
|
||||
self.rounds.retain(|&(_, number), _| number > round.1);
|
||||
self.mandatory_done = self.mandatory_done || round.1 == self.session_start;
|
||||
self.best_done = self.best_done.max(Some(round.1));
|
||||
debug!(target: "beefy", "🥩 Concluded round #{}", round.1);
|
||||
|
||||
@@ -160,6 +164,11 @@ where
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_set_mandatory_done(&mut self, done: bool) {
|
||||
self.mandatory_done = done;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -226,7 +235,7 @@ mod tests {
|
||||
let rounds = Rounds::<H256, Block>::new(session_start, validators);
|
||||
|
||||
assert_eq!(42, rounds.validator_set_id());
|
||||
assert_eq!(1, *rounds.session_start());
|
||||
assert_eq!(1, rounds.session_start());
|
||||
assert_eq!(
|
||||
&vec![Keyring::Alice.public(), Keyring::Bob.public(), Keyring::Charlie.public()],
|
||||
rounds.validators()
|
||||
@@ -307,6 +316,43 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_rounds_not_accepted() {
|
||||
sp_tracing::try_init_simple();
|
||||
|
||||
let validators = ValidatorSet::<Public>::new(
|
||||
vec![Keyring::Alice.public(), Keyring::Bob.public(), Keyring::Charlie.public()],
|
||||
42,
|
||||
)
|
||||
.unwrap();
|
||||
let alice = (Keyring::Alice.public(), Keyring::Alice.sign(b"I am committed"));
|
||||
|
||||
let session_start = 10u64.into();
|
||||
let mut rounds = Rounds::<H256, Block>::new(session_start, validators);
|
||||
|
||||
let mut vote = (H256::from_low_u64_le(1), 9);
|
||||
// add vote for previous session, should fail
|
||||
assert!(!rounds.add_vote(&vote, alice.clone(), true));
|
||||
// no votes present
|
||||
assert!(rounds.rounds.is_empty());
|
||||
|
||||
// simulate 11 was concluded
|
||||
rounds.best_done = Some(11);
|
||||
// add votes for current session, but already concluded rounds, should fail
|
||||
vote.1 = 10;
|
||||
assert!(!rounds.add_vote(&vote, alice.clone(), true));
|
||||
vote.1 = 11;
|
||||
assert!(!rounds.add_vote(&vote, alice.clone(), true));
|
||||
// no votes present
|
||||
assert!(rounds.rounds.is_empty());
|
||||
|
||||
// add good vote
|
||||
vote.1 = 12;
|
||||
assert!(rounds.add_vote(&vote, alice, true));
|
||||
// good vote present
|
||||
assert_eq!(rounds.rounds.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_rounds() {
|
||||
sp_tracing::try_init_simple();
|
||||
|
||||
@@ -21,12 +21,15 @@
|
||||
use futures::{future, stream::FuturesUnordered, Future, StreamExt};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{sync::Arc, task::Poll};
|
||||
use std::{collections::HashMap, sync::Arc, task::Poll};
|
||||
use tokio::{runtime::Runtime, time::Duration};
|
||||
|
||||
use sc_chain_spec::{ChainSpec, GenericChainSpec};
|
||||
use sc_client_api::HeaderBackend;
|
||||
use sc_consensus::BoxJustificationImport;
|
||||
use sc_consensus::{
|
||||
BlockImport, BlockImportParams, BoxJustificationImport, ForkChoiceStrategy, ImportResult,
|
||||
ImportedAux,
|
||||
};
|
||||
use sc_keystore::LocalKeystore;
|
||||
use sc_network_test::{
|
||||
Block, BlockImportAdapter, FullPeerConfig, PassThroughVerifier, Peer, PeersClient,
|
||||
@@ -35,7 +38,8 @@ use sc_network_test::{
|
||||
use sc_utils::notification::NotificationReceiver;
|
||||
|
||||
use beefy_primitives::{
|
||||
crypto::AuthorityId, BeefyApi, ConsensusLog, MmrRootHash, ValidatorSet, BEEFY_ENGINE_ID,
|
||||
crypto::{AuthorityId, Signature},
|
||||
BeefyApi, ConsensusLog, MmrRootHash, ValidatorSet, VersionedFinalityProof, BEEFY_ENGINE_ID,
|
||||
KEY_TYPE as BeefyKeyType,
|
||||
};
|
||||
use sp_mmr_primitives::{
|
||||
@@ -47,19 +51,32 @@ use sp_consensus::BlockOrigin;
|
||||
use sp_core::H256;
|
||||
use sp_keystore::{SyncCryptoStore, SyncCryptoStorePtr};
|
||||
use sp_runtime::{
|
||||
codec::Encode, generic::BlockId, traits::Header as HeaderT, BuildStorage, DigestItem, Storage,
|
||||
codec::Encode,
|
||||
generic::BlockId,
|
||||
traits::{Header as HeaderT, NumberFor},
|
||||
BuildStorage, DigestItem, Justifications, Storage,
|
||||
};
|
||||
|
||||
use substrate_test_runtime_client::{runtime::Header, ClientExt};
|
||||
|
||||
use crate::{beefy_protocol_name, keystore::tests::Keyring as BeefyKeyring, notification::*};
|
||||
use crate::{
|
||||
beefy_block_import_and_links, beefy_protocol_name, justification::*,
|
||||
keystore::tests::Keyring as BeefyKeyring, BeefyRPCLinks, BeefyVoterLinks,
|
||||
};
|
||||
|
||||
pub(crate) const BEEFY_PROTOCOL_NAME: &'static str = "/beefy/1";
|
||||
const GOOD_MMR_ROOT: MmrRootHash = MmrRootHash::repeat_byte(0xbf);
|
||||
const BAD_MMR_ROOT: MmrRootHash = MmrRootHash::repeat_byte(0x42);
|
||||
|
||||
type BeefyBlockImport = crate::BeefyBlockImport<
|
||||
Block,
|
||||
substrate_test_runtime_client::Backend,
|
||||
two_validators::TestApi,
|
||||
BlockImportAdapter<PeersClient, sp_api::TransactionFor<two_validators::TestApi, Block>>,
|
||||
>;
|
||||
|
||||
pub(crate) type BeefyValidatorSet = ValidatorSet<AuthorityId>;
|
||||
pub(crate) type BeefyPeer = Peer<PeerData, PeersClient>;
|
||||
pub(crate) type BeefyPeer = Peer<PeerData, BeefyBlockImport>;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Genesis(std::collections::BTreeMap<String, String>);
|
||||
@@ -97,17 +114,10 @@ fn beefy_protocol_name() {
|
||||
assert_eq!(proto_name.to_string(), expected);
|
||||
}
|
||||
|
||||
// TODO: compiler warns us about unused `signed_commitment_stream`, will use in later tests
|
||||
#[allow(dead_code)]
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct BeefyLinkHalf {
|
||||
pub signed_commitment_stream: BeefySignedCommitmentStream<Block>,
|
||||
pub beefy_best_block_stream: BeefyBestBlockStream<Block>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct PeerData {
|
||||
pub(crate) beefy_link_half: Mutex<Option<BeefyLinkHalf>>,
|
||||
pub(crate) beefy_rpc_links: Mutex<Option<BeefyRPCLinks<Block>>>,
|
||||
pub(crate) beefy_voter_links: Mutex<Option<BeefyVoterLinks<Block>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -163,7 +173,7 @@ impl BeefyTestNet {
|
||||
|
||||
impl TestNetFactory for BeefyTestNet {
|
||||
type Verifier = PassThroughVerifier;
|
||||
type BlockImport = PeersClient;
|
||||
type BlockImport = BeefyBlockImport;
|
||||
type PeerData = PeerData;
|
||||
|
||||
fn make_verifier(&self, _client: PeersClient, _: &PeerData) -> Self::Verifier {
|
||||
@@ -178,7 +188,17 @@ impl TestNetFactory for BeefyTestNet {
|
||||
Option<BoxJustificationImport<Block>>,
|
||||
Self::PeerData,
|
||||
) {
|
||||
(client.as_block_import(), None, PeerData::default())
|
||||
let inner = BlockImportAdapter::new(client.clone());
|
||||
let (block_import, voter_links, rpc_links) = beefy_block_import_and_links(
|
||||
inner,
|
||||
client.as_backend(),
|
||||
Arc::new(two_validators::TestApi {}),
|
||||
);
|
||||
let peer_data = PeerData {
|
||||
beefy_rpc_links: Mutex::new(Some(rpc_links)),
|
||||
beefy_voter_links: Mutex::new(Some(voter_links)),
|
||||
};
|
||||
(BlockImportAdapter::new(block_import), None, peer_data)
|
||||
}
|
||||
|
||||
fn peer(&mut self, i: usize) -> &mut BeefyPeer {
|
||||
@@ -333,12 +353,12 @@ where
|
||||
|
||||
let keystore = create_beefy_keystore(*key);
|
||||
|
||||
let (signed_commitment_sender, signed_commitment_stream) =
|
||||
BeefySignedCommitmentStream::<Block>::channel();
|
||||
let (beefy_best_block_sender, beefy_best_block_stream) =
|
||||
BeefyBestBlockStream::<Block>::channel();
|
||||
let beefy_link_half = BeefyLinkHalf { signed_commitment_stream, beefy_best_block_stream };
|
||||
*peer.data.beefy_link_half.lock() = Some(beefy_link_half);
|
||||
let (_, _, peer_data) = net.make_block_import(peer.client().clone());
|
||||
let PeerData { beefy_rpc_links, beefy_voter_links } = peer_data;
|
||||
|
||||
let beefy_voter_links = beefy_voter_links.lock().take();
|
||||
*peer.data.beefy_rpc_links.lock() = beefy_rpc_links.lock().take();
|
||||
*peer.data.beefy_voter_links.lock() = beefy_voter_links.clone();
|
||||
|
||||
let beefy_params = crate::BeefyParams {
|
||||
client: peer.client().as_client(),
|
||||
@@ -346,8 +366,7 @@ where
|
||||
runtime: api.clone(),
|
||||
key_store: Some(keystore),
|
||||
network: peer.network_service().clone(),
|
||||
signed_commitment_sender,
|
||||
beefy_best_block_sender,
|
||||
links: beefy_voter_links.unwrap(),
|
||||
min_block_delta,
|
||||
prometheus_registry: None,
|
||||
protocol_name: BEEFY_PROTOCOL_NAME.into(),
|
||||
@@ -382,11 +401,11 @@ pub(crate) fn get_beefy_streams(
|
||||
let mut best_block_streams = Vec::new();
|
||||
let mut signed_commitment_streams = Vec::new();
|
||||
for peer_id in 0..peers.len() {
|
||||
let beefy_link_half =
|
||||
net.peer(peer_id).data.beefy_link_half.lock().as_ref().unwrap().clone();
|
||||
let BeefyLinkHalf { signed_commitment_stream, beefy_best_block_stream } = beefy_link_half;
|
||||
best_block_streams.push(beefy_best_block_stream.subscribe());
|
||||
signed_commitment_streams.push(signed_commitment_stream.subscribe());
|
||||
let beefy_rpc_links = net.peer(peer_id).data.beefy_rpc_links.lock().clone().unwrap();
|
||||
let BeefyRPCLinks { from_voter_justif_stream, from_voter_best_beefy_stream } =
|
||||
beefy_rpc_links;
|
||||
best_block_streams.push(from_voter_best_beefy_stream.subscribe());
|
||||
signed_commitment_streams.push(from_voter_justif_stream.subscribe());
|
||||
}
|
||||
(best_block_streams, signed_commitment_streams)
|
||||
}
|
||||
@@ -670,3 +689,123 @@ fn correct_beefy_payload() {
|
||||
wait_for_best_beefy_blocks(best_blocks, &net, &mut runtime, &[11]);
|
||||
wait_for_beefy_signed_commitments(signed_commitments, &net, &mut runtime, &[11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beefy_importing_blocks() {
|
||||
use futures::{executor::block_on, future::poll_fn, task::Poll};
|
||||
use sc_block_builder::BlockBuilderProvider;
|
||||
use sc_client_api::BlockBackend;
|
||||
|
||||
sp_tracing::try_init_simple();
|
||||
|
||||
let mut net = BeefyTestNet::new(2, 0);
|
||||
|
||||
let client = net.peer(0).client().clone();
|
||||
let (mut block_import, _, peer_data) = net.make_block_import(client.clone());
|
||||
let PeerData { beefy_rpc_links: _, beefy_voter_links } = peer_data;
|
||||
let justif_stream = beefy_voter_links.lock().take().unwrap().from_block_import_justif_stream;
|
||||
|
||||
let params = |block: Block, justifications: Option<Justifications>| {
|
||||
let mut import = BlockImportParams::new(BlockOrigin::File, block.header);
|
||||
import.justifications = justifications;
|
||||
import.body = Some(block.extrinsics);
|
||||
import.finalized = true;
|
||||
import.fork_choice = Some(ForkChoiceStrategy::LongestChain);
|
||||
import
|
||||
};
|
||||
|
||||
let full_client = client.as_client();
|
||||
let parent_id = BlockId::Number(0);
|
||||
let block_id = BlockId::Number(1);
|
||||
let builder = full_client.new_block_at(&parent_id, Default::default(), false).unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
|
||||
// Import without justifications.
|
||||
let mut justif_recv = justif_stream.subscribe();
|
||||
assert_eq!(
|
||||
block_on(block_import.import_block(params(block.clone(), None), HashMap::new())).unwrap(),
|
||||
ImportResult::Imported(ImportedAux { is_new_best: true, ..Default::default() }),
|
||||
);
|
||||
assert_eq!(
|
||||
block_on(block_import.import_block(params(block, None), HashMap::new())).unwrap(),
|
||||
ImportResult::AlreadyInChain
|
||||
);
|
||||
// Verify no justifications present:
|
||||
{
|
||||
// none in backend,
|
||||
assert!(full_client.justifications(&block_id).unwrap().is_none());
|
||||
// and none sent to BEEFY worker.
|
||||
block_on(poll_fn(move |cx| {
|
||||
assert_eq!(justif_recv.poll_next_unpin(cx), Poll::Pending);
|
||||
Poll::Ready(())
|
||||
}));
|
||||
}
|
||||
|
||||
// Import with valid justification.
|
||||
let parent_id = BlockId::Number(1);
|
||||
let block_num = 2;
|
||||
let keys = &[BeefyKeyring::Alice, BeefyKeyring::Bob];
|
||||
let validator_set = ValidatorSet::new(make_beefy_ids(keys), 0).unwrap();
|
||||
let proof = crate::justification::tests::new_signed_commitment(block_num, &validator_set, keys);
|
||||
let versioned_proof: VersionedFinalityProof<NumberFor<Block>, Signature> = proof.into();
|
||||
let encoded = versioned_proof.encode();
|
||||
let justif = Some(Justifications::from((BEEFY_ENGINE_ID, encoded)));
|
||||
|
||||
let builder = full_client.new_block_at(&parent_id, Default::default(), false).unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
let mut justif_recv = justif_stream.subscribe();
|
||||
assert_eq!(
|
||||
block_on(block_import.import_block(params(block, justif), HashMap::new())).unwrap(),
|
||||
ImportResult::Imported(ImportedAux {
|
||||
bad_justification: false,
|
||||
is_new_best: true,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
// Verify justification successfully imported:
|
||||
{
|
||||
// available in backend,
|
||||
assert!(full_client.justifications(&BlockId::Number(block_num)).unwrap().is_some());
|
||||
// and also sent to BEEFY worker.
|
||||
block_on(poll_fn(move |cx| {
|
||||
match justif_recv.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(_justification)) => (),
|
||||
v => panic!("unexpected value: {:?}", v),
|
||||
}
|
||||
Poll::Ready(())
|
||||
}));
|
||||
}
|
||||
|
||||
// Import with invalid justification (incorrect validator set).
|
||||
let parent_id = BlockId::Number(2);
|
||||
let block_num = 3;
|
||||
let keys = &[BeefyKeyring::Alice];
|
||||
let validator_set = ValidatorSet::new(make_beefy_ids(keys), 1).unwrap();
|
||||
let proof = crate::justification::tests::new_signed_commitment(block_num, &validator_set, keys);
|
||||
let versioned_proof: VersionedFinalityProof<NumberFor<Block>, Signature> = proof.into();
|
||||
let encoded = versioned_proof.encode();
|
||||
let justif = Some(Justifications::from((BEEFY_ENGINE_ID, encoded)));
|
||||
|
||||
let builder = full_client.new_block_at(&parent_id, Default::default(), false).unwrap();
|
||||
let block = builder.build().unwrap().block;
|
||||
let mut justif_recv = justif_stream.subscribe();
|
||||
assert_eq!(
|
||||
block_on(block_import.import_block(params(block, justif), HashMap::new())).unwrap(),
|
||||
ImportResult::Imported(ImportedAux {
|
||||
// Still `false` because we don't want to fail import on bad BEEFY justifications.
|
||||
bad_justification: false,
|
||||
is_new_best: true,
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
// Verify bad justifications was not imported:
|
||||
{
|
||||
// none in backend,
|
||||
assert!(full_client.justifications(&block_id).unwrap().is_none());
|
||||
// and none sent to BEEFY worker.
|
||||
block_on(poll_fn(move |cx| {
|
||||
assert_eq!(justif_recv.poll_next_unpin(cx), Poll::Pending);
|
||||
Poll::Ready(())
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,7 @@ mod sync;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
collections::HashMap,
|
||||
marker::PhantomData,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context as FutureContext, Poll},
|
||||
@@ -567,25 +568,27 @@ impl<T> BlockImportAdapterFull for T where
|
||||
/// This is required as the `TestNetFactory` trait does not distinguish between
|
||||
/// full and light nodes.
|
||||
#[derive(Clone)]
|
||||
pub struct BlockImportAdapter<I> {
|
||||
pub struct BlockImportAdapter<I, Transaction = ()> {
|
||||
inner: I,
|
||||
_phantom: PhantomData<Transaction>,
|
||||
}
|
||||
|
||||
impl<I> BlockImportAdapter<I> {
|
||||
impl<I, Transaction> BlockImportAdapter<I, Transaction> {
|
||||
/// Create a new instance of `Self::Full`.
|
||||
pub fn new(inner: I) -> Self {
|
||||
Self { inner }
|
||||
Self { inner, _phantom: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<I> BlockImport<Block> for BlockImportAdapter<I>
|
||||
impl<I, Transaction> BlockImport<Block> for BlockImportAdapter<I, Transaction>
|
||||
where
|
||||
I: BlockImport<Block, Error = ConsensusError> + Send + Sync,
|
||||
I::Transaction: Send,
|
||||
Transaction: Send + 'static,
|
||||
{
|
||||
type Error = ConsensusError;
|
||||
type Transaction = ();
|
||||
type Transaction = Transaction;
|
||||
|
||||
async fn check_block(
|
||||
&mut self,
|
||||
@@ -596,7 +599,7 @@ where
|
||||
|
||||
async fn import_block(
|
||||
&mut self,
|
||||
block: BlockImportParams<Block, ()>,
|
||||
block: BlockImportParams<Block, Self::Transaction>,
|
||||
cache: HashMap<well_known_cache_keys::Id, Vec<u8>>,
|
||||
) -> Result<ImportResult, Self::Error> {
|
||||
self.inner.import_block(block.clear_storage_changes_and_mutate(), cache).await
|
||||
|
||||
@@ -293,6 +293,12 @@ pub enum VersionedFinalityProof<N, S> {
|
||||
V1(SignedCommitment<N, S>),
|
||||
}
|
||||
|
||||
impl<N, S> From<SignedCommitment<N, S>> for VersionedFinalityProof<N, S> {
|
||||
fn from(commitment: SignedCommitment<N, S>) -> Self {
|
||||
VersionedFinalityProof::V1(commitment)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
|
||||
@@ -151,6 +151,11 @@ impl Justifications {
|
||||
self.iter().find(|j| j.0 == engine_id).map(|j| &j.1)
|
||||
}
|
||||
|
||||
/// Remove the encoded justification for the given consensus engine, if it exists.
|
||||
pub fn remove(&mut self, engine_id: ConsensusEngineId) {
|
||||
self.0.retain(|j| j.0 != engine_id)
|
||||
}
|
||||
|
||||
/// Return a copy of the encoded justification for the given consensus
|
||||
/// engine, if it exists.
|
||||
pub fn into_justification(self, engine_id: ConsensusEngineId) -> Option<EncodedJustification> {
|
||||
|
||||
Reference in New Issue
Block a user