referrerpolicy=no-referrer-when-downgrade

sc_consensus_beefy/
justification.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use codec::DecodeAll;
20use sp_application_crypto::RuntimeAppPublic;
21use sp_consensus::Error as ConsensusError;
22use sp_consensus_beefy::{
23	AuthorityIdBound, KnownSignature, ValidatorSet, ValidatorSetId, VersionedFinalityProof,
24};
25use sp_runtime::traits::{Block as BlockT, NumberFor};
26
27/// A finality proof with matching BEEFY authorities' signatures.
28pub type BeefyVersionedFinalityProof<Block, AuthorityId> =
29	VersionedFinalityProof<NumberFor<Block>, <AuthorityId as RuntimeAppPublic>::Signature>;
30
31pub(crate) fn proof_block_num_and_set_id<Block: BlockT, AuthorityId: AuthorityIdBound>(
32	proof: &BeefyVersionedFinalityProof<Block, AuthorityId>,
33) -> (NumberFor<Block>, ValidatorSetId) {
34	match proof {
35		VersionedFinalityProof::V1(sc) => {
36			(sc.commitment.block_number, sc.commitment.validator_set_id)
37		},
38	}
39}
40
41/// Decode and verify a Beefy FinalityProof.
42pub(crate) fn decode_and_verify_finality_proof<Block: BlockT, AuthorityId: AuthorityIdBound>(
43	encoded: &[u8],
44	target_number: NumberFor<Block>,
45	validator_set: &ValidatorSet<AuthorityId>,
46) -> Result<BeefyVersionedFinalityProof<Block, AuthorityId>, (ConsensusError, u32)> {
47	let proof = <BeefyVersionedFinalityProof<Block, AuthorityId>>::decode_all(&mut &*encoded)
48		.map_err(|_| (ConsensusError::InvalidJustification, 0))?;
49	verify_with_validator_set::<Block, AuthorityId>(target_number, validator_set, &proof)?;
50	Ok(proof)
51}
52
53/// Verify the Beefy finality proof against the validator set at the block it was generated.
54pub(crate) fn verify_with_validator_set<'a, Block: BlockT, AuthorityId: AuthorityIdBound>(
55	target_number: NumberFor<Block>,
56	validator_set: &'a ValidatorSet<AuthorityId>,
57	proof: &'a BeefyVersionedFinalityProof<Block, AuthorityId>,
58) -> Result<
59	Vec<KnownSignature<&'a AuthorityId, &'a <AuthorityId as RuntimeAppPublic>::Signature>>,
60	(ConsensusError, u32),
61> {
62	match proof {
63		VersionedFinalityProof::V1(signed_commitment) => {
64			let signatories =
65				signed_commitment.verify_signatures::<_>(target_number, validator_set).map_err(
66					|checked_signatures| (ConsensusError::InvalidJustification, checked_signatures),
67				)?;
68
69			if signatories.len() >= crate::round::threshold(validator_set.len()) {
70				Ok(signatories)
71			} else {
72				Err((
73					ConsensusError::InvalidJustification,
74					signed_commitment.signature_count() as u32,
75				))
76			}
77		},
78	}
79}
80
81#[cfg(test)]
82pub(crate) mod tests {
83	use codec::Encode;
84	use sp_consensus_beefy::{
85		ecdsa_crypto, known_payloads, test_utils::Keyring, Commitment, Payload, SignedCommitment,
86		VersionedFinalityProof,
87	};
88	use substrate_test_runtime_client::runtime::Block;
89
90	use super::*;
91	use crate::tests::make_beefy_ids;
92
93	pub(crate) fn new_finality_proof(
94		block_num: NumberFor<Block>,
95		validator_set: &ValidatorSet<ecdsa_crypto::AuthorityId>,
96		keys: &[Keyring<ecdsa_crypto::AuthorityId>],
97	) -> BeefyVersionedFinalityProof<Block, ecdsa_crypto::AuthorityId> {
98		let commitment = Commitment {
99			payload: Payload::from_single_entry(known_payloads::MMR_ROOT_ID, vec![]),
100			block_number: block_num,
101			validator_set_id: validator_set.id(),
102		};
103		let message = commitment.encode();
104		let signatures = keys.iter().map(|key| Some(key.sign(&message))).collect();
105		VersionedFinalityProof::V1(SignedCommitment { commitment, signatures })
106	}
107
108	#[test]
109	fn should_verify_with_validator_set() {
110		let keys = &[Keyring::Alice, Keyring::Bob, Keyring::Charlie];
111		let validator_set = ValidatorSet::new(make_beefy_ids(keys), 0).unwrap();
112
113		// build valid justification
114		let block_num = 42;
115		let proof = new_finality_proof(block_num, &validator_set, keys);
116
117		let good_proof = proof.clone().into();
118		// should verify successfully
119		verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
120			block_num,
121			&validator_set,
122			&good_proof,
123		)
124		.unwrap();
125
126		// wrong block number -> should fail verification
127		let good_proof = proof.clone().into();
128		match verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
129			block_num + 1,
130			&validator_set,
131			&good_proof,
132		) {
133			Err((ConsensusError::InvalidJustification, 0)) => (),
134			e => assert!(false, "Got unexpected {:?}", e),
135		};
136
137		// wrong validator set id -> should fail verification
138		let good_proof = proof.clone().into();
139		let other = ValidatorSet::new(make_beefy_ids(keys), 1).unwrap();
140		match verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
141			block_num,
142			&other,
143			&good_proof,
144		) {
145			Err((ConsensusError::InvalidJustification, 0)) => (),
146			e => assert!(false, "Got unexpected {:?}", e),
147		};
148
149		// wrong signatures length -> should fail verification
150		let mut bad_proof = proof.clone();
151		// change length of signatures
152		let bad_signed_commitment = match bad_proof {
153			VersionedFinalityProof::V1(ref mut sc) => sc,
154		};
155		bad_signed_commitment.signatures.pop().flatten().unwrap();
156		match verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
157			block_num + 1,
158			&validator_set,
159			&bad_proof.into(),
160		) {
161			Err((ConsensusError::InvalidJustification, 0)) => (),
162			e => assert!(false, "Got unexpected {:?}", e),
163		};
164
165		// not enough signatures -> should fail verification
166		let mut bad_proof = proof.clone();
167		let bad_signed_commitment = match bad_proof {
168			VersionedFinalityProof::V1(ref mut sc) => sc,
169		};
170		// remove a signature (but same length)
171		*bad_signed_commitment.signatures.first_mut().unwrap() = None;
172		match verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
173			block_num,
174			&validator_set,
175			&bad_proof.into(),
176		) {
177			Err((ConsensusError::InvalidJustification, 2)) => (),
178			e => assert!(false, "Got unexpected {:?}", e),
179		};
180
181		// not enough _correct_ signatures -> should fail verification
182		let mut bad_proof = proof.clone();
183		let bad_signed_commitment = match bad_proof {
184			VersionedFinalityProof::V1(ref mut sc) => sc,
185		};
186		// change a signature to a different key
187		*bad_signed_commitment.signatures.first_mut().unwrap() = Some(
188			Keyring::<ecdsa_crypto::AuthorityId>::Dave
189				.sign(&bad_signed_commitment.commitment.encode()),
190		);
191		match verify_with_validator_set::<Block, ecdsa_crypto::AuthorityId>(
192			block_num,
193			&validator_set,
194			&bad_proof.into(),
195		) {
196			Err((ConsensusError::InvalidJustification, 3)) => (),
197			e => assert!(false, "Got unexpected {:?}", e),
198		};
199	}
200
201	#[test]
202	fn should_decode_and_verify_finality_proof() {
203		let keys = &[Keyring::Alice, Keyring::Bob];
204		let validator_set = ValidatorSet::new(make_beefy_ids(keys), 0).unwrap();
205		let block_num = 1;
206
207		// build valid justification
208		let proof = new_finality_proof(block_num, &validator_set, keys);
209		let versioned_proof: BeefyVersionedFinalityProof<Block, ecdsa_crypto::AuthorityId> =
210			proof.into();
211		let encoded = versioned_proof.encode();
212
213		// should successfully decode and verify
214		let verified = decode_and_verify_finality_proof::<Block, ecdsa_crypto::AuthorityId>(
215			&encoded,
216			block_num,
217			&validator_set,
218		)
219		.unwrap();
220		assert_eq!(verified, versioned_proof);
221	}
222}