mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-05-30 08:11:03 +00:00
Initial version of bridging pallets as git subtree (#2458)
* Initial version of bridges pallet as subtree of https://github.com/paritytech/parity-bridges-common Added `Bridges subtree files` pr review rule * Squashed 'bridges/' content from commit d30927c08 git-subtree-dir: bridges git-subtree-split: d30927c089bd9e73092d1ec1a62895603cb277a3 * Updated REAMDE.md and BRIDGES.md (inspired by original https://github.com/paritytech/polkadot/blob/d22eb62fe40e55e15eb91d375f48cc540d83a47e/BRIDGES.md) * Squashed 'bridges/' changes from d30927c08..d3970944b d3970944b Small simplifications (#2050) git-subtree-dir: bridges git-subtree-split: d3970944b0cfc4ea5226225e1ca07dab234c3556 * Squashed 'bridges/' changes from d3970944b..2180797fb 2180797fb Removed CODEOWNERS (#2051) git-subtree-dir: bridges git-subtree-split: 2180797fbf8a990490c67853dcffd81bc8dd083c * Squashed 'bridges/' changes from 2180797fbf..4850aac8ce 4850aac8ce Removed relayer_account: &AccountId from MessageDispatch (#2080) 8c8adafd54 Revert "Fix max-size messages at test chains (#2064)" (#2077) c01a63efd8 Fixed off-by-one when confirming rewards in messages pallet (#2075) a298be96aa Update subxt dependencies (#2072) c0eef51eab Fix max-size messages at test chains (#2064) 3a658e3697 Messages relay fixes (#2073) 0022b5ab22 Slash relayers for invalid transactions (#2025) 198104007f Bump enumflags2 from 0.7.5 to 0.7.7 9229b257e5 [ci] Fix rules for docker build (#2069) 660d791390 [ci] Update buildah command and version (#2058) e4535c0ca4 fix the way latest_confirmed_nonce_at_source is "calculated" (#2067) dbc2d37590 select nothing if we have already selected nonces to submit or have submitted something (#2065) a7eedd21fe [relay-substrate-client] Bump jsonrpsee (#2066) 8875d5aeae Bump clap from 4.2.2 to 4.2.4 25f9cf55e2 Another use of RangeInclusiveExt::checked_len() (#2060) 4942c12a5f submit lane unblock transactions from relay (#2030) c0325d3c9c Test deployments fixes (#2057) fc7b9b7ed7 Use the new matrix server (#2056) 63bcb5c10b Fixed delivery alert rule (#2052) git-subtree-dir: bridges git-subtree-split: 4850aac8ce6c34e5ca6246b88cd14c873a879cba * Squashed 'bridges/' changes from 4850aac8ce..66aaf0dd23 66aaf0dd23 Nits (#2083) git-subtree-dir: bridges git-subtree-split: 66aaf0dd239dde40b64264061a77c921e2c82568 * Squashed 'bridges/' changes from 66aaf0dd23..557ecbcecc 557ecbcecc Fix sized messages (Follow-up on #2064) (#2103) 54f587a066 Add weight of refund extension post_dispatch to the weights of messages pallet (#2089) 5b1626f8c4 fix pallet param for nightly benchmarks check (#2099) ae44c6b7a1 Add millau specific messages weights (#2097) 6ad0bd1f1e Add integrity tests to rialto parachain runtiime (#2096) 6919556de5 Bump tokio from 1.27.0 to 1.28.0 58795fcb75 Bump clap from 4.2.4 to 4.2.5 01bf31085b Bump scale-info from 2.5.0 to 2.6.0 8fe383240d Bump anyhow from 1.0.70 to 1.0.71 8d94e82ad5 deployments: add new BEEFY metrics and alarms (#2090) e9a4749e7e Bump wasmtime from 6.0.1 to 6.0.2 9d9936c0d9 Bump wasmtime from 6.0.1 to 6.0.2 in /tools/runtime-codegen 5d77cd7bee Add more logs to relayer and message pallets (#2082) 75fbb9d3ef Update comment (#2081) 9904d09cf6 Benchmarks for new relayers pallet calls (#2040) git-subtree-dir: bridges git-subtree-split: 557ecbcecc585547b744a5ac9fb8d7f3b9de4521 * fmt * Squashed 'bridges/' changes from 557ecbcecc..04b3dda6aa 04b3dda6aa Remove from subtree (#2111) f8ff15e7e7 Add `MessagesPalletInstance` for integrity tests (#2107) 92ccef58e6 Use generated runtimes for BHR/BHW (#2106) b33e0a585b Fix comment (#2105) git-subtree-dir: bridges git-subtree-split: 04b3dda6aa38599e612ff637710b6d2cff275ef3 * ".git/.scripts/commands/fmt/fmt.sh" --------- Co-authored-by: parity-processbot <>
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "bp-header-chain"
|
||||
description = "A common interface for describing what a bridge pallet should be able to do."
|
||||
version = "0.1.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2021"
|
||||
license = "GPL-3.0-or-later WITH Classpath-exception-2.0"
|
||||
|
||||
[dependencies]
|
||||
codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false }
|
||||
finality-grandpa = { version = "0.16.2", default-features = false }
|
||||
scale-info = { version = "2.6.0", default-features = false, features = ["derive"] }
|
||||
serde = { version = "1.0", optional = true }
|
||||
|
||||
# Bridge dependencies
|
||||
|
||||
bp-runtime = { path = "../runtime", default-features = false }
|
||||
|
||||
# Substrate Dependencies
|
||||
|
||||
frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-consensus-grandpa = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
bp-test-utils = { path = "../test-utils" }
|
||||
hex = "0.4"
|
||||
hex-literal = "0.4"
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = [
|
||||
"bp-runtime/std",
|
||||
"codec/std",
|
||||
"finality-grandpa/std",
|
||||
"serde/std",
|
||||
"frame-support/std",
|
||||
"scale-info/std",
|
||||
"sp-core/std",
|
||||
"sp-consensus-grandpa/std",
|
||||
"sp-runtime/std",
|
||||
"sp-std/std",
|
||||
]
|
||||
@@ -0,0 +1,390 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common 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.
|
||||
|
||||
// Parity Bridges Common 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 Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Pallet for checking GRANDPA Finality Proofs.
|
||||
//!
|
||||
//! Adapted copy of substrate/client/finality-grandpa/src/justification.rs. If origin
|
||||
//! will ever be moved to the sp_consensus_grandpa, we should reuse that implementation.
|
||||
|
||||
use crate::ChainWithGrandpa;
|
||||
|
||||
use bp_runtime::{BlockNumberOf, Chain, HashOf};
|
||||
use codec::{Decode, Encode, MaxEncodedLen};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use frame_support::RuntimeDebug;
|
||||
use scale_info::TypeInfo;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthoritySignature, SetId};
|
||||
use sp_runtime::{traits::Header as HeaderT, SaturatedConversion};
|
||||
use sp_std::{
|
||||
collections::{btree_map::BTreeMap, btree_set::BTreeSet},
|
||||
prelude::*,
|
||||
};
|
||||
|
||||
/// A GRANDPA Justification is a proof that a given header was finalized
|
||||
/// at a certain height and with a certain set of authorities.
|
||||
///
|
||||
/// This particular proof is used to prove that headers on a bridged chain
|
||||
/// (so not our chain) have been finalized correctly.
|
||||
#[derive(Encode, Decode, RuntimeDebug, Clone, PartialEq, Eq, TypeInfo)]
|
||||
pub struct GrandpaJustification<Header: HeaderT> {
|
||||
/// The round (voting period) this justification is valid for.
|
||||
pub round: u64,
|
||||
/// The set of votes for the chain which is to be finalized.
|
||||
pub commit:
|
||||
finality_grandpa::Commit<Header::Hash, Header::Number, AuthoritySignature, AuthorityId>,
|
||||
/// A proof that the chain of blocks in the commit are related to each other.
|
||||
pub votes_ancestries: Vec<Header>,
|
||||
}
|
||||
|
||||
impl<H: HeaderT> GrandpaJustification<H> {
|
||||
/// Returns reasonable size of justification using constants from the provided chain.
|
||||
///
|
||||
/// An imprecise analogue of `MaxEncodedLen` implementation. We don't use it for
|
||||
/// any precise calculations - that's just an estimation.
|
||||
pub fn max_reasonable_size<C>(required_precommits: u32) -> u32
|
||||
where
|
||||
C: Chain<Header = H> + ChainWithGrandpa,
|
||||
{
|
||||
// we don't need precise results here - just estimations, so some details
|
||||
// are removed from computations (e.g. bytes required to encode vector length)
|
||||
|
||||
// structures in `finality_grandpa` crate are not implementing `MaxEncodedLength`, so
|
||||
// here's our estimation for the `finality_grandpa::Commit` struct size
|
||||
//
|
||||
// precommit is: hash + number
|
||||
// signed precommit is: precommit + signature (64b) + authority id
|
||||
// commit is: hash + number + vec of signed precommits
|
||||
let signed_precommit_size: u32 = BlockNumberOf::<C>::max_encoded_len()
|
||||
.saturating_add(HashOf::<C>::max_encoded_len().saturated_into())
|
||||
.saturating_add(64)
|
||||
.saturating_add(AuthorityId::max_encoded_len().saturated_into())
|
||||
.saturated_into();
|
||||
let max_expected_signed_commit_size = signed_precommit_size
|
||||
.saturating_mul(required_precommits)
|
||||
.saturating_add(BlockNumberOf::<C>::max_encoded_len().saturated_into())
|
||||
.saturating_add(HashOf::<C>::max_encoded_len().saturated_into());
|
||||
|
||||
// justification is a signed GRANDPA commit, `votes_ancestries` vector and round number
|
||||
let max_expected_votes_ancestries_size = C::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY
|
||||
.saturating_mul(C::AVERAGE_HEADER_SIZE_IN_JUSTIFICATION);
|
||||
|
||||
8u32.saturating_add(max_expected_signed_commit_size)
|
||||
.saturating_add(max_expected_votes_ancestries_size)
|
||||
}
|
||||
}
|
||||
|
||||
impl<H: HeaderT> crate::FinalityProof<H::Number> for GrandpaJustification<H> {
|
||||
fn target_header_number(&self) -> H::Number {
|
||||
self.commit.target_number
|
||||
}
|
||||
}
|
||||
|
||||
/// Justification verification error.
|
||||
#[derive(Eq, RuntimeDebug, PartialEq)]
|
||||
pub enum Error {
|
||||
/// Failed to decode justification.
|
||||
JustificationDecode,
|
||||
/// Justification is finalizing unexpected header.
|
||||
InvalidJustificationTarget,
|
||||
/// Justification contains redundant votes.
|
||||
RedundantVotesInJustification,
|
||||
/// Justification contains unknown authority precommit.
|
||||
UnknownAuthorityVote,
|
||||
/// Justification contains duplicate authority precommit.
|
||||
DuplicateAuthorityVote,
|
||||
/// The authority has provided an invalid signature.
|
||||
InvalidAuthoritySignature,
|
||||
/// The justification contains precommit for header that is not a descendant of the commit
|
||||
/// header.
|
||||
PrecommitIsNotCommitDescendant,
|
||||
/// The cumulative weight of all votes in the justification is not enough to justify commit
|
||||
/// header finalization.
|
||||
TooLowCumulativeWeight,
|
||||
/// The justification contains extra (unused) headers in its `votes_ancestries` field.
|
||||
ExtraHeadersInVotesAncestries,
|
||||
}
|
||||
|
||||
/// Given GRANDPA authorities set size, return number of valid authorities votes that the
|
||||
/// justification must have to be valid.
|
||||
///
|
||||
/// This function assumes that all authorities have the same vote weight.
|
||||
pub fn required_justification_precommits(authorities_set_length: u32) -> u32 {
|
||||
authorities_set_length - authorities_set_length.saturating_sub(1) / 3
|
||||
}
|
||||
|
||||
/// Decode justification target.
|
||||
pub fn decode_justification_target<Header: HeaderT>(
|
||||
raw_justification: &[u8],
|
||||
) -> Result<(Header::Hash, Header::Number), Error> {
|
||||
GrandpaJustification::<Header>::decode(&mut &*raw_justification)
|
||||
.map(|justification| (justification.commit.target_hash, justification.commit.target_number))
|
||||
.map_err(|_| Error::JustificationDecode)
|
||||
}
|
||||
|
||||
/// Verify and optimize given justification by removing unknown and duplicate votes.
|
||||
pub fn verify_and_optimize_justification<Header: HeaderT>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: GrandpaJustification<Header>,
|
||||
) -> Result<GrandpaJustification<Header>, Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
let mut optimizer = OptimizationCallbacks(Vec::new());
|
||||
verify_justification_with_callbacks(
|
||||
finalized_target,
|
||||
authorities_set_id,
|
||||
authorities_set,
|
||||
&justification,
|
||||
&mut optimizer,
|
||||
)?;
|
||||
Ok(optimizer.optimize(justification))
|
||||
}
|
||||
|
||||
/// Verify that justification, that is generated by given authority set, finalizes given header.
|
||||
pub fn verify_justification<Header: HeaderT>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: &GrandpaJustification<Header>,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
verify_justification_with_callbacks(
|
||||
finalized_target,
|
||||
authorities_set_id,
|
||||
authorities_set,
|
||||
justification,
|
||||
&mut StrictVerificationCallbacks,
|
||||
)
|
||||
}
|
||||
|
||||
/// Verification callbacks.
|
||||
trait VerificationCallbacks {
|
||||
/// Called when we see a precommit from unknown authority.
|
||||
fn on_unkown_authority(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
/// Called when we see a precommit with duplicate vote from known authority.
|
||||
fn on_duplicate_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
/// Called when we see a precommit after we've collected enough votes from authorities.
|
||||
fn on_redundant_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
/// Verification callbacks that reject all unknown, duplicate or redundant votes.
|
||||
struct StrictVerificationCallbacks;
|
||||
|
||||
impl VerificationCallbacks for StrictVerificationCallbacks {
|
||||
fn on_unkown_authority(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::UnknownAuthorityVote)
|
||||
}
|
||||
|
||||
fn on_duplicate_authority_vote(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::DuplicateAuthorityVote)
|
||||
}
|
||||
|
||||
fn on_redundant_authority_vote(&mut self, _precommit_idx: usize) -> Result<(), Error> {
|
||||
Err(Error::RedundantVotesInJustification)
|
||||
}
|
||||
}
|
||||
|
||||
/// Verification callbacks for justification optimization.
|
||||
struct OptimizationCallbacks(Vec<usize>);
|
||||
|
||||
impl OptimizationCallbacks {
|
||||
fn optimize<Header: HeaderT>(
|
||||
self,
|
||||
mut justification: GrandpaJustification<Header>,
|
||||
) -> GrandpaJustification<Header> {
|
||||
for invalid_precommit_idx in self.0.into_iter().rev() {
|
||||
justification.commit.precommits.remove(invalid_precommit_idx);
|
||||
}
|
||||
justification
|
||||
}
|
||||
}
|
||||
|
||||
impl VerificationCallbacks for OptimizationCallbacks {
|
||||
fn on_unkown_authority(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_duplicate_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_redundant_authority_vote(&mut self, precommit_idx: usize) -> Result<(), Error> {
|
||||
self.0.push(precommit_idx);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify that justification, that is generated by given authority set, finalizes given header.
|
||||
fn verify_justification_with_callbacks<Header: HeaderT, C: VerificationCallbacks>(
|
||||
finalized_target: (Header::Hash, Header::Number),
|
||||
authorities_set_id: SetId,
|
||||
authorities_set: &VoterSet<AuthorityId>,
|
||||
justification: &GrandpaJustification<Header>,
|
||||
callbacks: &mut C,
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
Header::Number: finality_grandpa::BlockNumberOps,
|
||||
{
|
||||
// ensure that it is justification for the expected header
|
||||
if (justification.commit.target_hash, justification.commit.target_number) != finalized_target {
|
||||
return Err(Error::InvalidJustificationTarget)
|
||||
}
|
||||
|
||||
let threshold = authorities_set.threshold().0.into();
|
||||
let mut chain = AncestryChain::new(&justification.votes_ancestries);
|
||||
let mut signature_buffer = Vec::new();
|
||||
let mut votes = BTreeSet::new();
|
||||
let mut cumulative_weight = 0u64;
|
||||
|
||||
for (precommit_idx, signed) in justification.commit.precommits.iter().enumerate() {
|
||||
// if we have collected enough precommits, we probabably want to fail/remove extra
|
||||
// precommits
|
||||
if cumulative_weight >= threshold {
|
||||
callbacks.on_redundant_authority_vote(precommit_idx)?;
|
||||
continue
|
||||
}
|
||||
|
||||
// authority must be in the set
|
||||
let authority_info = match authorities_set.get(&signed.id) {
|
||||
Some(authority_info) => authority_info,
|
||||
None => {
|
||||
callbacks.on_unkown_authority(precommit_idx)?;
|
||||
continue
|
||||
},
|
||||
};
|
||||
|
||||
// check if authority has already voted in the same round.
|
||||
//
|
||||
// there's a lot of code in `validate_commit` and `import_precommit` functions inside
|
||||
// `finality-grandpa` crate (mostly related to reporting equivocations). But the only thing
|
||||
// that we care about is that only first vote from the authority is accepted
|
||||
if !votes.insert(signed.id.clone()) {
|
||||
callbacks.on_duplicate_authority_vote(precommit_idx)?;
|
||||
continue
|
||||
}
|
||||
|
||||
// everything below this line can't just `continue`, because state is already altered
|
||||
|
||||
// precommits aren't allowed for block lower than the target
|
||||
if signed.precommit.target_number < justification.commit.target_number {
|
||||
return Err(Error::PrecommitIsNotCommitDescendant)
|
||||
}
|
||||
// all precommits must be descendants of target block
|
||||
chain = chain
|
||||
.ensure_descendant(&justification.commit.target_hash, &signed.precommit.target_hash)?;
|
||||
// since we know now that the precommit target is the descendant of the justification
|
||||
// target, we may increase 'weight' of the justification target
|
||||
//
|
||||
// there's a lot of code in the `VoteGraph::insert` method inside `finality-grandpa` crate,
|
||||
// but in the end it is only used to find GHOST, which we don't care about. The only thing
|
||||
// that we care about is that the justification target has enough weight
|
||||
cumulative_weight = cumulative_weight.checked_add(authority_info.weight().0.into()).expect(
|
||||
"sum of weights of ALL authorities is expected not to overflow - this is guaranteed by\
|
||||
existence of VoterSet;\
|
||||
the order of loop conditions guarantees that we can account vote from same authority\
|
||||
multiple times;\
|
||||
thus we'll never overflow the u64::MAX;\
|
||||
qed",
|
||||
);
|
||||
|
||||
// verify authority signature
|
||||
if !sp_consensus_grandpa::check_message_signature_with_buffer(
|
||||
&finality_grandpa::Message::Precommit(signed.precommit.clone()),
|
||||
&signed.id,
|
||||
&signed.signature,
|
||||
justification.round,
|
||||
authorities_set_id,
|
||||
&mut signature_buffer,
|
||||
) {
|
||||
return Err(Error::InvalidAuthoritySignature)
|
||||
}
|
||||
}
|
||||
|
||||
// check that there are no extra headers in the justification
|
||||
if !chain.unvisited.is_empty() {
|
||||
return Err(Error::ExtraHeadersInVotesAncestries)
|
||||
}
|
||||
|
||||
// check that the cumulative weight of validators voted for the justification target (or one
|
||||
// of its descendents) is larger than required threshold.
|
||||
if cumulative_weight >= threshold {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::TooLowCumulativeWeight)
|
||||
}
|
||||
}
|
||||
|
||||
/// Votes ancestries with useful methods.
|
||||
#[derive(RuntimeDebug)]
|
||||
pub struct AncestryChain<Header: HeaderT> {
|
||||
/// Header hash => parent header hash mapping.
|
||||
pub parents: BTreeMap<Header::Hash, Header::Hash>,
|
||||
/// Hashes of headers that were not visited by `is_ancestor` method.
|
||||
pub unvisited: BTreeSet<Header::Hash>,
|
||||
}
|
||||
|
||||
impl<Header: HeaderT> AncestryChain<Header> {
|
||||
/// Create new ancestry chain.
|
||||
pub fn new(ancestry: &[Header]) -> AncestryChain<Header> {
|
||||
let mut parents = BTreeMap::new();
|
||||
let mut unvisited = BTreeSet::new();
|
||||
for ancestor in ancestry {
|
||||
let hash = ancestor.hash();
|
||||
let parent_hash = *ancestor.parent_hash();
|
||||
parents.insert(hash, parent_hash);
|
||||
unvisited.insert(hash);
|
||||
}
|
||||
AncestryChain { parents, unvisited }
|
||||
}
|
||||
|
||||
/// Returns `Ok(_)` if `precommit_target` is a descendant of the `commit_target` block and
|
||||
/// `Err(_)` otherwise.
|
||||
pub fn ensure_descendant(
|
||||
mut self,
|
||||
commit_target: &Header::Hash,
|
||||
precommit_target: &Header::Hash,
|
||||
) -> Result<Self, Error> {
|
||||
let mut current_hash = *precommit_target;
|
||||
loop {
|
||||
if current_hash == *commit_target {
|
||||
break
|
||||
}
|
||||
|
||||
let is_visited_before = !self.unvisited.remove(¤t_hash);
|
||||
current_hash = match self.parents.get(¤t_hash) {
|
||||
Some(parent_hash) => {
|
||||
if is_visited_before {
|
||||
// `Some(parent_hash)` means that the `current_hash` is in the `parents`
|
||||
// container `is_visited_before` means that it has been visited before in
|
||||
// some of previous calls => since we assume that previous call has finished
|
||||
// with `true`, this also will be finished with `true`
|
||||
return Ok(self)
|
||||
}
|
||||
|
||||
*parent_hash
|
||||
},
|
||||
None => return Err(Error::PrecommitIsNotCommitDescendant),
|
||||
};
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common 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.
|
||||
|
||||
// Parity Bridges Common 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 Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Defines traits which represent a common interface for Substrate pallets which want to
|
||||
//! incorporate bridge functionality.
|
||||
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
|
||||
use bp_runtime::{
|
||||
BasicOperatingMode, Chain, HashOf, HasherOf, HeaderOf, RawStorageProof, StorageProofChecker,
|
||||
StorageProofError,
|
||||
};
|
||||
use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen};
|
||||
use core::{clone::Clone, cmp::Eq, default::Default, fmt::Debug};
|
||||
use frame_support::PalletError;
|
||||
use scale_info::TypeInfo;
|
||||
#[cfg(feature = "std")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sp_consensus_grandpa::{AuthorityList, ConsensusLog, SetId, GRANDPA_ENGINE_ID};
|
||||
use sp_runtime::{traits::Header as HeaderT, Digest, RuntimeDebug};
|
||||
use sp_std::boxed::Box;
|
||||
|
||||
pub mod justification;
|
||||
pub mod storage_keys;
|
||||
|
||||
/// Header chain error.
|
||||
#[derive(Clone, Decode, Encode, Eq, PartialEq, PalletError, Debug, TypeInfo)]
|
||||
pub enum HeaderChainError {
|
||||
/// Header with given hash is missing from the chain.
|
||||
UnknownHeader,
|
||||
/// Storage proof related error.
|
||||
StorageProof(StorageProofError),
|
||||
}
|
||||
|
||||
/// Header data that we're storing on-chain.
|
||||
///
|
||||
/// Even though we may store full header, our applications (XCM) only use couple of header
|
||||
/// fields. Extracting those values makes on-chain storage and PoV smaller, which is good.
|
||||
#[derive(Clone, Decode, Encode, Eq, MaxEncodedLen, PartialEq, RuntimeDebug, TypeInfo)]
|
||||
pub struct StoredHeaderData<Number, Hash> {
|
||||
/// Header number.
|
||||
pub number: Number,
|
||||
/// Header state root.
|
||||
pub state_root: Hash,
|
||||
}
|
||||
|
||||
/// Stored header data builder.
|
||||
pub trait StoredHeaderDataBuilder<Number, Hash> {
|
||||
/// Build header data from self.
|
||||
fn build(&self) -> StoredHeaderData<Number, Hash>;
|
||||
}
|
||||
|
||||
impl<H: HeaderT> StoredHeaderDataBuilder<H::Number, H::Hash> for H {
|
||||
fn build(&self) -> StoredHeaderData<H::Number, H::Hash> {
|
||||
StoredHeaderData { number: *self.number(), state_root: *self.state_root() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Substrate header chain, abstracted from the way it is stored.
|
||||
pub trait HeaderChain<C: Chain> {
|
||||
/// Returns state (storage) root of given finalized header.
|
||||
fn finalized_header_state_root(header_hash: HashOf<C>) -> Option<HashOf<C>>;
|
||||
/// Parse storage proof using finalized header.
|
||||
fn parse_finalized_storage_proof<R>(
|
||||
header_hash: HashOf<C>,
|
||||
storage_proof: RawStorageProof,
|
||||
parse: impl FnOnce(StorageProofChecker<HasherOf<C>>) -> R,
|
||||
) -> Result<R, HeaderChainError> {
|
||||
let state_root = Self::finalized_header_state_root(header_hash)
|
||||
.ok_or(HeaderChainError::UnknownHeader)?;
|
||||
let storage_proof_checker = bp_runtime::StorageProofChecker::new(state_root, storage_proof)
|
||||
.map_err(HeaderChainError::StorageProof)?;
|
||||
|
||||
Ok(parse(storage_proof_checker))
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that can be used as a parameter in a dispatchable function.
|
||||
///
|
||||
/// When using `decl_module` all arguments for call functions must implement this trait.
|
||||
pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {}
|
||||
impl<T> Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {}
|
||||
|
||||
/// A GRANDPA Authority List and ID.
|
||||
#[derive(Default, Encode, Eq, Decode, RuntimeDebug, PartialEq, Clone, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct AuthoritySet {
|
||||
/// List of GRANDPA authorities for the current round.
|
||||
pub authorities: AuthorityList,
|
||||
/// Monotonic identifier of the current GRANDPA authority set.
|
||||
pub set_id: SetId,
|
||||
}
|
||||
|
||||
impl AuthoritySet {
|
||||
/// Create a new GRANDPA Authority Set.
|
||||
pub fn new(authorities: AuthorityList, set_id: SetId) -> Self {
|
||||
Self { authorities, set_id }
|
||||
}
|
||||
}
|
||||
|
||||
/// Data required for initializing the GRANDPA bridge pallet.
|
||||
///
|
||||
/// The bridge needs to know where to start its sync from, and this provides that initial context.
|
||||
#[derive(Default, Encode, Decode, RuntimeDebug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
|
||||
pub struct InitializationData<H: HeaderT> {
|
||||
/// The header from which we should start syncing.
|
||||
pub header: Box<H>,
|
||||
/// The initial authorities of the pallet.
|
||||
pub authority_list: AuthorityList,
|
||||
/// The ID of the initial authority set.
|
||||
pub set_id: SetId,
|
||||
/// Pallet operating mode.
|
||||
pub operating_mode: BasicOperatingMode,
|
||||
}
|
||||
|
||||
/// Abstract finality proof that is justifying block finality.
|
||||
pub trait FinalityProof<Number>: Clone + Send + Sync + Debug {
|
||||
/// Return number of header that this proof is generated for.
|
||||
fn target_header_number(&self) -> Number;
|
||||
}
|
||||
|
||||
/// A trait that provides helper methods for querying the consensus log.
|
||||
pub trait ConsensusLogReader {
|
||||
/// Returns true if digest contains item that schedules authorities set change.
|
||||
fn schedules_authorities_change(digest: &Digest) -> bool;
|
||||
}
|
||||
|
||||
/// A struct that provides helper methods for querying the GRANDPA consensus log.
|
||||
pub struct GrandpaConsensusLogReader<Number>(sp_std::marker::PhantomData<Number>);
|
||||
|
||||
impl<Number: Codec> GrandpaConsensusLogReader<Number> {
|
||||
pub fn find_authorities_change(
|
||||
digest: &Digest,
|
||||
) -> Option<sp_consensus_grandpa::ScheduledChange<Number>> {
|
||||
// find the first consensus digest with the right ID which converts to
|
||||
// the right kind of consensus log.
|
||||
digest
|
||||
.convert_first(|log| log.consensus_try_to(&GRANDPA_ENGINE_ID))
|
||||
.and_then(|log| match log {
|
||||
ConsensusLog::ScheduledChange(change) => Some(change),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<Number: Codec> ConsensusLogReader for GrandpaConsensusLogReader<Number> {
|
||||
fn schedules_authorities_change(digest: &Digest) -> bool {
|
||||
GrandpaConsensusLogReader::<Number>::find_authorities_change(digest).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimized version of `pallet-bridge-grandpa::Call` that can be used without a runtime.
|
||||
#[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)]
|
||||
#[allow(non_camel_case_types)]
|
||||
pub enum BridgeGrandpaCall<Header: HeaderT> {
|
||||
/// `pallet-bridge-grandpa::Call::submit_finality_proof`
|
||||
#[codec(index = 0)]
|
||||
submit_finality_proof {
|
||||
finality_target: Box<Header>,
|
||||
justification: justification::GrandpaJustification<Header>,
|
||||
},
|
||||
/// `pallet-bridge-grandpa::Call::initialize`
|
||||
#[codec(index = 1)]
|
||||
initialize { init_data: InitializationData<Header> },
|
||||
}
|
||||
|
||||
/// The `BridgeGrandpaCall` used by a chain.
|
||||
pub type BridgeGrandpaCallOf<C> = BridgeGrandpaCall<HeaderOf<C>>;
|
||||
|
||||
/// Substrate-based chain that is using direct GRANDPA finality.
|
||||
///
|
||||
/// Keep in mind that parachains are relying on relay chain GRANDPA, so they should not implement
|
||||
/// this trait.
|
||||
pub trait ChainWithGrandpa: Chain {
|
||||
/// Name of the bridge GRANDPA pallet (used in `construct_runtime` macro call) that is deployed
|
||||
/// at some other chain to bridge with this `ChainWithGrandpa`.
|
||||
///
|
||||
/// We assume that all chains that are bridging with this `ChainWithGrandpa` are using
|
||||
/// the same name.
|
||||
const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str;
|
||||
|
||||
/// Max number of GRANDPA authorities at the chain.
|
||||
///
|
||||
/// This is a strict constant. If bridged chain will have more authorities than that,
|
||||
/// the GRANDPA bridge pallet may halt.
|
||||
const MAX_AUTHORITIES_COUNT: u32;
|
||||
|
||||
/// Max reasonable number of headers in `votes_ancestries` vector of the GRANDPA justification.
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit justifications with more headers in its
|
||||
/// ancestry and the pallet will accept such justification. The limit is only used to compute
|
||||
/// maximal refund amount and submitting justifications which exceed the limit, may be costly
|
||||
/// to submitter.
|
||||
const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32;
|
||||
|
||||
/// Maximal size of the chain header. The header may be the header that enacts new GRANDPA
|
||||
/// authorities set (so it has large digest inside).
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit larger headers and the pallet will accept
|
||||
/// the call. The limit is only used to compute maximal refund amount and doing calls which
|
||||
/// exceed the limit, may be costly to submitter.
|
||||
const MAX_HEADER_SIZE: u32;
|
||||
|
||||
/// Average size of the chain header from justification ancestry. We don't expect to see there
|
||||
/// headers that change GRANDPA authorities set (GRANDPA will probably be able to finalize at
|
||||
/// least one additional header per session on non test chains), so this is average size of
|
||||
/// headers that aren't changing the set.
|
||||
///
|
||||
/// This isn't a strict limit. The relay may submit justifications with larger headers in its
|
||||
/// ancestry and the pallet will accept the call. The limit is only used to compute maximal
|
||||
/// refund amount and doing calls which exceed the limit, may be costly to submitter.
|
||||
const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common 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.
|
||||
|
||||
// Parity Bridges Common 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 Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Storage keys of bridge GRANDPA pallet.
|
||||
|
||||
/// Name of the `IsHalted` storage value.
|
||||
pub const PALLET_OPERATING_MODE_VALUE_NAME: &str = "PalletOperatingMode";
|
||||
/// Name of the `BestFinalized` storage value.
|
||||
pub const BEST_FINALIZED_VALUE_NAME: &str = "BestFinalized";
|
||||
/// Name of the `CurrentAuthoritySet` storage value.
|
||||
pub const CURRENT_AUTHORITY_SET_VALUE_NAME: &str = "CurrentAuthoritySet";
|
||||
|
||||
use sp_core::storage::StorageKey;
|
||||
|
||||
/// Storage key of the `PalletOperatingMode` variable in the runtime storage.
|
||||
pub fn pallet_operating_mode_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
PALLET_OPERATING_MODE_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the `CurrentAuthoritySet` variable in the runtime storage.
|
||||
pub fn current_authority_set_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
CURRENT_AUTHORITY_SET_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Storage key of the best finalized header number and hash value in the runtime storage.
|
||||
pub fn best_finalized_key(pallet_prefix: &str) -> StorageKey {
|
||||
StorageKey(
|
||||
bp_runtime::storage_value_final_key(
|
||||
pallet_prefix.as_bytes(),
|
||||
BEST_FINALIZED_VALUE_NAME.as_bytes(),
|
||||
)
|
||||
.to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hex_literal::hex;
|
||||
|
||||
#[test]
|
||||
fn pallet_operating_mode_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = pallet_operating_mode_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388de0f4cf0917788d791142ff6c1f216e7b3").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_authority_set_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = current_authority_set_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388de24a7b8b5717ea33346fa595a66ccbcb0").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn best_finalized_key_computed_properly() {
|
||||
// If this test fails, then something has been changed in module storage that is breaking
|
||||
// compatibility with previous pallet.
|
||||
let storage_key = best_finalized_key("BridgeGrandpa").0;
|
||||
assert_eq!(
|
||||
storage_key,
|
||||
hex!("0b06f475eddb98cf933a12262e0388dea4ebafdd473c549fdb24c5c991c5591c").to_vec(),
|
||||
"Unexpected storage key: {}",
|
||||
hex::encode(&storage_key),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common 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.
|
||||
|
||||
// Parity Bridges Common 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 Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Tests inside this module are made to ensure that our custom justification verification
|
||||
//! implementation works similar to the [`finality_grandpa::validate_commit`] and explicitly
|
||||
//! show where we behave different.
|
||||
//!
|
||||
//! Some of tests in this module may partially duplicate tests from `justification.rs`,
|
||||
//! but their purpose is different.
|
||||
|
||||
use bp_header_chain::justification::{verify_justification, Error, GrandpaJustification};
|
||||
use bp_test_utils::{
|
||||
header_id, make_justification_for_header, signed_precommit, test_header, Account,
|
||||
JustificationGeneratorParams, ALICE, BOB, CHARLIE, DAVE, EVE, FERDIE, TEST_GRANDPA_SET_ID,
|
||||
};
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use sp_consensus_grandpa::{AuthorityId, AuthorityWeight};
|
||||
use sp_runtime::traits::Header as HeaderT;
|
||||
|
||||
type TestHeader = sp_runtime::testing::Header;
|
||||
type TestHash = <TestHeader as HeaderT>::Hash;
|
||||
type TestNumber = <TestHeader as HeaderT>::Number;
|
||||
|
||||
/// Implementation of `finality_grandpa::Chain` that is used in tests.
|
||||
struct AncestryChain(bp_header_chain::justification::AncestryChain<TestHeader>);
|
||||
|
||||
impl AncestryChain {
|
||||
fn new(ancestry: &[TestHeader]) -> Self {
|
||||
Self(bp_header_chain::justification::AncestryChain::new(ancestry))
|
||||
}
|
||||
}
|
||||
|
||||
impl finality_grandpa::Chain<TestHash, TestNumber> for AncestryChain {
|
||||
fn ancestry(
|
||||
&self,
|
||||
base: TestHash,
|
||||
block: TestHash,
|
||||
) -> Result<Vec<TestHash>, finality_grandpa::Error> {
|
||||
let mut route = Vec::new();
|
||||
let mut current_hash = block;
|
||||
loop {
|
||||
if current_hash == base {
|
||||
break
|
||||
}
|
||||
match self.0.parents.get(¤t_hash).cloned() {
|
||||
Some(parent_hash) => {
|
||||
current_hash = parent_hash;
|
||||
route.push(current_hash);
|
||||
},
|
||||
_ => return Err(finality_grandpa::Error::NotDescendent),
|
||||
}
|
||||
}
|
||||
route.pop(); // remove the base
|
||||
|
||||
Ok(route)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a full set of accounts.
|
||||
fn full_accounts_set() -> Vec<(Account, AuthorityWeight)> {
|
||||
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1), (EVE, 1)]
|
||||
}
|
||||
|
||||
/// Get a full set of GRANDPA authorities.
|
||||
fn full_voter_set() -> VoterSet<AuthorityId> {
|
||||
VoterSet::new(full_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w))).unwrap()
|
||||
}
|
||||
|
||||
/// Get a minimal set of accounts.
|
||||
fn minimal_accounts_set() -> Vec<(Account, AuthorityWeight)> {
|
||||
// there are 5 accounts in the full set => we need 2/3 + 1 accounts, which results in 4 accounts
|
||||
vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1), (DAVE, 1)]
|
||||
}
|
||||
|
||||
/// Get a minimal subset of GRANDPA authorities that have enough cumulative vote weight to justify a
|
||||
/// header finality.
|
||||
pub fn minimal_voter_set() -> VoterSet<AuthorityId> {
|
||||
VoterSet::new(minimal_accounts_set().iter().map(|(id, w)| (AuthorityId::from(*id), *w)))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Make a valid GRANDPA justification with sensible defaults.
|
||||
pub fn make_default_justification(header: &TestHeader) -> GrandpaJustification<TestHeader> {
|
||||
make_justification_for_header(JustificationGeneratorParams {
|
||||
header: header.clone(),
|
||||
authorities: minimal_accounts_set(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
// the `finality_grandpa::validate_commit` function has two ways to report an unsuccessful
|
||||
// commit validation:
|
||||
//
|
||||
// 1) to return `Err()` (which only may happen if `finality_grandpa::Chain` implementation
|
||||
// returns an error);
|
||||
// 2) to return `Ok(validation_result)` if `validation_result.is_valid()` is false.
|
||||
//
|
||||
// Our implementation would just return error in both cases.
|
||||
|
||||
#[test]
|
||||
fn same_result_when_precommit_target_has_lower_number_than_commit_target() {
|
||||
let mut justification = make_default_justification(&test_header(1));
|
||||
// the number of header in precommit (0) is lower than number of header in commit (1)
|
||||
justification.commit.precommits[0].precommit.target_number = 0;
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::PrecommitIsNotCommitDescendant),
|
||||
);
|
||||
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_result_when_precommit_target_is_not_descendant_of_commit_target() {
|
||||
let not_descendant = test_header::<TestHeader>(10);
|
||||
let mut justification = make_default_justification(&test_header(1));
|
||||
// the route from header of commit (1) to header of precommit (10) is missing from
|
||||
// the votes ancestries
|
||||
justification.commit.precommits[0].precommit.target_number = *not_descendant.number();
|
||||
justification.commit.precommits[0].precommit.target_hash = not_descendant.hash();
|
||||
justification.votes_ancestries.push(not_descendant);
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::PrecommitIsNotCommitDescendant),
|
||||
);
|
||||
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_result_when_there_are_not_enough_cumulative_weight_to_finalize_commit_target() {
|
||||
// just remove one authority from the minimal set and we shall not reach the threshold
|
||||
let mut authorities_set = minimal_accounts_set();
|
||||
authorities_set.pop();
|
||||
let justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: authorities_set,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// our implementation returns an error
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::TooLowCumulativeWeight),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == false`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!result.is_valid());
|
||||
}
|
||||
|
||||
// tests below are our differences with the original implementation
|
||||
|
||||
#[test]
|
||||
fn different_result_when_justification_contains_duplicate_vote() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the justification may contain exactly the same vote (i.e. same precommit and same signature)
|
||||
// multiple times && it isn't treated as an error by original implementation
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(justification.commit.precommits[0].clone());
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_authority_equivocates_once_in_a_round() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the justification original implementation allows authority to submit two different
|
||||
// votes in a single round, of which only first is 'accepted'
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_authority_equivocates_twice_in_a_round() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// there's some code in the original implementation that should return an error when
|
||||
// same authority submits more than two different votes in a single round:
|
||||
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/lib.rs#L473
|
||||
// but there's also a code that prevents this from happening:
|
||||
// https://github.com/paritytech/finality-grandpa/blob/6aeea2d1159d0f418f0b86e70739f2130629ca09/src/round.rs#L287
|
||||
// => so now we are also just ignoring all votes from the same authority, except the first one
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
let prev_last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&ALICE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
justification.commit.precommits.push(prev_last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::DuplicateAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_there_are_more_than_enough_votes() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the reference implementation just keep verifying signatures even if we have
|
||||
// collected enough votes. We are not
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&EVE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::RedundantVotesInJustification),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_results_when_there_is_a_vote_of_unknown_authority() {
|
||||
let mut justification = make_justification_for_header(JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
authorities: minimal_accounts_set(),
|
||||
ancestors: 0,
|
||||
..Default::default()
|
||||
});
|
||||
// the reference implementation just keep verifying signatures even if we have
|
||||
// collected enough votes. We are not
|
||||
let last_precommit = justification.commit.precommits.pop().unwrap();
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&FERDIE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
justification.commit.precommits.push(last_precommit);
|
||||
|
||||
// our implementation fails
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&full_voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::UnknownAuthorityVote),
|
||||
);
|
||||
// original implementation returns `Ok(validation_result)`
|
||||
// with `validation_result.is_valid() == true`.
|
||||
let result = finality_grandpa::validate_commit(
|
||||
&justification.commit,
|
||||
&full_voter_set(),
|
||||
&AncestryChain::new(&justification.votes_ancestries),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// Copyright 2020-2021 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Parity Bridges Common.
|
||||
|
||||
// Parity Bridges Common 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.
|
||||
|
||||
// Parity Bridges Common 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 Parity Bridges Common. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Tests for Grandpa Justification code.
|
||||
|
||||
use bp_header_chain::justification::{
|
||||
required_justification_precommits, verify_and_optimize_justification, verify_justification,
|
||||
Error,
|
||||
};
|
||||
use bp_test_utils::*;
|
||||
|
||||
type TestHeader = sp_runtime::testing::Header;
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted() {
|
||||
let authorities = vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)];
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone(),
|
||||
ancestors: 7,
|
||||
forks: 3,
|
||||
};
|
||||
|
||||
let justification = make_justification_for_header::<TestHeader>(params.clone());
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
|
||||
assert_eq!(justification.commit.precommits.len(), authorities.len());
|
||||
assert_eq!(justification.votes_ancestries.len(), params.ancestors as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted_with_single_fork() {
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: vec![(ALICE, 1), (BOB, 1), (CHARLIE, 1)],
|
||||
ancestors: 5,
|
||||
forks: 1,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_justification_accepted_with_arbitrary_number_of_authorities() {
|
||||
use finality_grandpa::voter_set::VoterSet;
|
||||
use sp_consensus_grandpa::AuthorityId;
|
||||
|
||||
let n = 15;
|
||||
let required_signatures = required_justification_precommits(n as _);
|
||||
let authorities = accounts(n).iter().map(|k| (*k, 1)).collect::<Vec<_>>();
|
||||
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone().into_iter().take(required_signatures as _).collect(),
|
||||
ancestors: n.into(),
|
||||
forks: required_signatures,
|
||||
};
|
||||
|
||||
let authorities = authorities
|
||||
.iter()
|
||||
.map(|(id, w)| (AuthorityId::from(*id), *w))
|
||||
.collect::<Vec<(AuthorityId, _)>>();
|
||||
let voter_set = VoterSet::new(authorities).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set,
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Ok(()),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_target_rejected() {
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(2),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_default_justification::<TestHeader>(&test_header(1)),
|
||||
),
|
||||
Err(Error::InvalidJustificationTarget),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_commit_rejected() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.clear();
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::ExtraHeadersInVotesAncestries),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_authority_signature_rejected() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits[0].signature =
|
||||
sp_core::crypto::UncheckedFrom::unchecked_from([1u8; 64]);
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::InvalidAuthoritySignature),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_with_invalid_precommit_ancestry() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.votes_ancestries.push(test_header(10));
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&justification,
|
||||
),
|
||||
Err(Error::ExtraHeadersInVotesAncestries),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn justification_is_invalid_if_we_dont_meet_threshold() {
|
||||
// Need at least three authorities to sign off or else the voter set threshold can't be reached
|
||||
let authorities = vec![(ALICE, 1), (BOB, 1)];
|
||||
|
||||
let params = JustificationGeneratorParams {
|
||||
header: test_header(1),
|
||||
round: TEST_GRANDPA_ROUND,
|
||||
set_id: TEST_GRANDPA_SET_ID,
|
||||
authorities: authorities.clone(),
|
||||
ancestors: 2 * authorities.len() as u32,
|
||||
forks: 2,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
verify_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
&make_justification_for_header::<TestHeader>(params)
|
||||
),
|
||||
Err(Error::TooLowCumulativeWeight),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optimizer_does_noting_with_minimal_justification() {
|
||||
let justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&bp_test_utils::Account(42),
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification
|
||||
.commit
|
||||
.precommits
|
||||
.push(justification.commit.precommits.first().cloned().unwrap());
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redundant_authority_votes_are_removed_by_optimizer() {
|
||||
let mut justification = make_default_justification::<TestHeader>(&test_header(1));
|
||||
justification.commit.precommits.push(signed_precommit::<TestHeader>(
|
||||
&EVE,
|
||||
header_id::<TestHeader>(1),
|
||||
justification.round,
|
||||
TEST_GRANDPA_SET_ID,
|
||||
));
|
||||
|
||||
let num_precommits_before = justification.commit.precommits.len();
|
||||
let justification = verify_and_optimize_justification::<TestHeader>(
|
||||
header_id::<TestHeader>(1),
|
||||
TEST_GRANDPA_SET_ID,
|
||||
&voter_set(),
|
||||
justification,
|
||||
)
|
||||
.unwrap();
|
||||
let num_precommits_after = justification.commit.precommits.len();
|
||||
|
||||
assert_eq!(num_precommits_before - 1, num_precommits_after);
|
||||
}
|
||||
Reference in New Issue
Block a user