referrerpolicy=no-referrer-when-downgrade

cumulus_aura_authorizer_utils/
token.rs

1// This file is part of Cumulus.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use alloc::vec::Vec;
19use codec::{Decode, Encode};
20use primitive_types::H256;
21
22use crate::{config::AuthConfig, merkle::verify_collator_proof, SignatureVerifier};
23
24/// Raw 32-byte collator public key.
25pub type CollatorKey = [u8; 32];
26
27/// A collator's signature over an authorization token's signing payload.
28///
29/// Encoded as 64 raw bytes.
30pub type CollatorSignature = [u8; 64];
31
32#[derive(Clone, Debug, Encode, Decode)]
33pub struct AuthToken {
34	/// Merkle proof for `key` to be at the correct index in [`AuthConfig::collator_set_root`].
35	///
36	/// The leaf index is determined by the round-robin logic for the slot.
37	pub proof: Vec<H256>,
38
39	/// Key of the collator that authored the work package.
40	pub key: CollatorKey,
41
42	/// Signature by the `key` over the work-package signing hash (see
43	/// [`crate::WorkPackageBody::signing_hash`]).
44	pub signature: CollatorSignature,
45}
46
47/// Authorization token validation failed.
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum TokenError {
50	BadCollatorSetProof,
51	BadCollatorSignature,
52}
53
54impl AuthToken {
55	/// Verify that `key` sits at zero-based leaf index `collator_index` of the collator-set tree.
56	///
57	/// Use [`crate::build_collator_proof`] to generate a valid proof.
58	pub fn check_proof(&self, config: &AuthConfig, collator_index: u32) -> Result<(), TokenError> {
59		verify_collator_proof(
60			&config.collator_set_root,
61			&self.proof,
62			config.collator_set_size.get(),
63			collator_index,
64			&self.key,
65		)
66		.then_some(())
67		.ok_or(TokenError::BadCollatorSetProof)
68	}
69
70	/// Verify the signature over the work-package signing hash (see
71	/// [`crate::WorkPackageBody::signing_hash`]) using `S`.
72	pub fn check_signature<S: SignatureVerifier>(
73		&self,
74		work_package_hash: H256,
75	) -> Result<(), TokenError> {
76		S::verify(&self.key, &self.signature, work_package_hash.as_bytes())
77			.then_some(())
78			.ok_or(TokenError::BadCollatorSignature)
79	}
80}
81
82#[cfg(test)]
83mod tests {
84	use super::*;
85	use crate::{
86		signing::SigningPayload,
87		tests::{fixture, Verifier},
88	};
89
90	#[test]
91	fn check_signature_arguments_works() {
92		let (_, token, package) = fixture();
93		assert!(token.check_signature::<Verifier>(SigningPayload::from(&package).hash()).is_ok());
94	}
95
96	#[test]
97	fn check_signature_changed_arguments_errors() {
98		let (_, token, package) = fixture();
99		let hash = SigningPayload::from(&package).hash();
100
101		for field in 0..4 {
102			let mut forged = token.clone();
103			let mut payload = hash;
104
105			match field {
106				0 => forged.key[0] ^= 1,
107				1 => forged.signature[0] ^= 1,
108				2 => forged.signature[63] ^= 1,
109				_ => payload.0[0] ^= 1,
110			}
111
112			assert!(matches!(
113				forged.check_signature::<Verifier>(payload),
114				Err(TokenError::BadCollatorSignature)
115			));
116		}
117	}
118
119	#[test]
120	fn check_proof_large_sets_works() {
121		let (mut config, mut token, _) = fixture();
122		for (size, siblings) in [(1u32 << 31, 31), ((1u32 << 31) + 1, 1), (u32::MAX, 31)] {
123			config.collator_set_size = core::num::NonZero::new(size).unwrap();
124			let index = size - 1;
125			token.proof = alloc::vec![H256::zero(); siblings];
126			let mut current = sp_crypto_hashing::blake2_256(&token.key);
127
128			// The rightmost leaf is promoted or takes the right branch at each level.
129			for sibling in &token.proof {
130				let mut pair = [0; 64];
131				pair[..32].copy_from_slice(sibling.as_bytes());
132				pair[32..].copy_from_slice(&current);
133				current = sp_crypto_hashing::blake2_256(&pair);
134			}
135
136			config.collator_set_root = H256::from(current);
137			assert!(token.check_proof(&config, index).is_ok());
138			assert!(matches!(
139				token.check_proof(&config, index - 1),
140				Err(TokenError::BadCollatorSetProof)
141			));
142		}
143	}
144}