referrerpolicy=no-referrer-when-downgrade

cumulus_aura_authorizer_utils/
signing.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 jam_types::{
19	AuthConfig, BoundedVec, CodeHash, Encode as JamEncode, MaxWorkItems, RefineContext, ServiceId,
20	WorkItem, WorkPackage,
21};
22use primitive_types::H256;
23
24use crate::WorkPackageBody;
25
26/// Domain separator for the token-free work-package hash signed by AURA collators.
27pub const WORK_PACKAGE_SIGN_CTX: &[u8] = b"jam:parachain-service:aura:work-package:v1";
28
29/// Borrowed view of the work-package fields covered by the collator signature.
30///
31/// JAM-encodes the code host, authorizer code hash, refinement context, authorizer config,
32/// and work items after [`WORK_PACKAGE_SIGN_CTX`], then hashes them with Blake2b-256.
33/// The authorization token is excluded because it contains the signature.
34#[derive(JamEncode)]
35pub(crate) struct SigningPayload<'a> {
36	auth_code_host: ServiceId,
37	auth_code_hash: &'a CodeHash,
38	context: &'a RefineContext,
39	auth_config: &'a AuthConfig,
40	items: &'a BoundedVec<WorkItem, MaxWorkItems>,
41}
42
43impl<'a> From<&'a WorkPackage> for SigningPayload<'a> {
44	fn from(package: &'a WorkPackage) -> Self {
45		// Keep this exhaustive so new fields require an explicit signing decision.
46		let WorkPackage { authorization: _, auth_code_host, authorizer, context, items } = package;
47
48		Self {
49			auth_code_host: *auth_code_host,
50			auth_code_hash: &authorizer.code_hash,
51			context,
52			auth_config: &authorizer.config,
53			items,
54		}
55	}
56}
57
58impl<'a> From<&'a WorkPackageBody> for SigningPayload<'a> {
59	fn from(package: &'a WorkPackageBody) -> Self {
60		// Keep this exhaustive so new fields require an explicit signing decision.
61		let WorkPackageBody { auth_code_host, authorizer, context, items } = package;
62
63		Self {
64			auth_code_host: *auth_code_host,
65			auth_code_hash: &authorizer.code_hash,
66			context,
67			auth_config: &authorizer.config,
68			items,
69		}
70	}
71}
72
73impl SigningPayload<'_> {
74	pub(crate) fn hash(&self) -> H256 {
75		hash_signing_payload(&self.encode())
76	}
77}
78
79/// Hash the token-free work-package fields signed by the collator.
80pub fn signable_work_package_hash(package: &WorkPackage) -> H256 {
81	SigningPayload::from(package).hash()
82}
83
84/// Hash the JAM-encoded tuple of code host, authorizer code hash, refinement context,
85/// authorizer config, and work items, with the AURA domain separator.
86pub(crate) fn hash_signing_payload(payload: &[u8]) -> H256 {
87	let mut state = blake2b_simd::Params::new().hash_length(32).to_state();
88	state.update(WORK_PACKAGE_SIGN_CTX);
89	state.update(payload);
90
91	H256::from_slice(state.finalize().as_bytes())
92}
93
94#[cfg(test)]
95mod tests {
96	use super::*;
97	use alloc::vec;
98
99	#[test]
100	fn signing_payload_signed_fields_works() {
101		let (_, _, package) = crate::tests::fixture();
102		let original = SigningPayload::from(&package).hash();
103
104		let mutations: [(&str, fn(&mut WorkPackage)); 12] = [
105			("code host", |p| p.auth_code_host += 1),
106			("authorizer code", |p| p.authorizer.code_hash.0[0] ^= 1),
107			("authorizer config", |p| {
108				p.authorizer.config = vec![1].try_into().expect("one byte fits")
109			}),
110			("anchor", |p| p.context.anchor.0[0] ^= 1),
111			("anchor slot", |p| p.context.anchor_slot += 1),
112			("state root", |p| p.context.state_root.0[0] ^= 1),
113			("beefy root", |p| p.context.beefy_root.0[0] ^= 1),
114			("lookup anchor", |p| p.context.lookup_anchor.0[0] ^= 1),
115			("lookup slot", |p| p.context.lookup_anchor_slot += 1),
116			("lookup state root", |p| p.context.lookup_anchor_state_root.0[0] ^= 1),
117			("prerequisites", |p| {
118				p.context.prerequisites.insert([1; 32].into());
119			}),
120			("work items", |p| {
121				p.items = vec![jam_types::WorkItem {
122					service: 1,
123					code_hash: Default::default(),
124					refine_gas_limit: 1,
125					accumulate_gas_limit: 1,
126					export_count: 0,
127					payload: vec![0; 36].into(),
128					import_segments: Default::default(),
129					extrinsics: Default::default(),
130				}]
131				.try_into()
132				.expect("one work item fits");
133			}),
134		];
135
136		for (field, mutate) in mutations {
137			let mut changed = package.clone();
138			mutate(&mut changed);
139
140			assert_ne!(SigningPayload::from(&changed).hash(), original, "unsigned field: {field}");
141		}
142	}
143
144	#[test]
145	fn signing_payload_excludes_authorization_works() {
146		let (_, _, mut package) = crate::tests::fixture();
147		let original = SigningPayload::from(&package).hash();
148
149		package.authorization = vec![1, 2, 3].try_into().expect("three bytes fit");
150
151		assert_eq!(SigningPayload::from(&package).hash(), original);
152	}
153
154	#[test]
155	fn signing_payload_item_fields_works() {
156		let (_, _, mut package) = crate::tests::fixture();
157
158		let item = jam_types::WorkItem {
159			service: 1,
160			code_hash: Default::default(),
161			refine_gas_limit: 1,
162			accumulate_gas_limit: 1,
163			export_count: 0,
164			payload: vec![0; 36].into(),
165			import_segments: Default::default(),
166			extrinsics: Default::default(),
167		};
168
169		package.items = vec![item.clone()].try_into().expect("one work item fits");
170		let original = SigningPayload::from(&package).hash();
171
172		let mutations: [(&str, fn(&mut jam_types::WorkItem)); 8] = [
173			("service", |i| i.service += 1),
174			("code hash", |i| i.code_hash.0[0] ^= 1),
175			("refine gas", |i| i.refine_gas_limit += 1),
176			("accumulate gas", |i| i.accumulate_gas_limit += 1),
177			("export count", |i| i.export_count += 1),
178			("payload", |i| i.payload = vec![1].try_into().expect("one byte fits")),
179			("imports", |i| {
180				i.import_segments = vec![jam_types::ImportSpec {
181					root: jam_types::RootIdentifier::Direct(Default::default()),
182					index: 1,
183				}]
184				.try_into()
185				.expect("one import fits");
186			}),
187			("extrinsics", |i| {
188				i.extrinsics = vec![jam_types::ExtrinsicSpec { hash: Default::default(), len: 1 }]
189					.try_into()
190					.expect("one extrinsic fits");
191			}),
192		];
193
194		for (field, mutate) in mutations {
195			let mut changed = item.clone();
196			mutate(&mut changed);
197			package.items = vec![changed].try_into().expect("one work item fits");
198
199			assert_ne!(
200				SigningPayload::from(&package).hash(),
201				original,
202				"unsigned item field: {field}"
203			);
204		}
205
206		let mut second = item.clone();
207		second.service += 1;
208
209		package.items = vec![item.clone(), second.clone()].try_into().expect("two work items fit");
210		let ordered = SigningPayload::from(&package).hash();
211
212		package.items = vec![second, item].try_into().expect("two work items fit");
213
214		assert_ne!(SigningPayload::from(&package).hash(), ordered);
215	}
216}