referrerpolicy=no-referrer-when-downgrade

pallet_validator_set_announcer/
lib.rs

1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// 	http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Validator Set Announcer pallet.
17//!
18//! Applies the validator set of each era locally and hands it to [`Config::Sender`] for the other
19//! system chains. Meant for the chain that runs `pallet-staking-async`, typically Asset Hub.
20//!
21//! ## Overview
22//!
23//! The runtime calls [`Pallet::announce`] when a new era becomes active. It stores the set in the
24//! local `pallet-validator-collators`. If the receiver accepts it, the pallet hands the set to the
25//! sender once for every destination in [`Config::Destinations`] and deposits
26//! [`Event::AnnouncementSent`] or [`Event::AnnouncementFailed`] for each. A set the receiver
27//! rejects is reported with [`Event::AnnouncementRejected`] and not sent. Acceptance by the sender
28//! means the message was queued for delivery. Execution on the destination is not acknowledged.
29//!
30//! The pallet holds no storage. A failed send is not retried: every error an HRMP enqueue can
31//! return persists for the rest of the era, and the next era's announcement carries the full set
32//! again.
33
34#![cfg_attr(not(feature = "std"), no_std)]
35
36extern crate alloc;
37
38use frame_support::Parameter;
39use sp_staking::EraIndex;
40
41pub use pallet::*;
42
43/// Sends a validator set to one destination.
44pub trait SendValidatorSet<AccountId> {
45	/// Identifies a destination.
46	type Destination: Parameter;
47
48	/// Hand the validator set of `era` to the transport for `destination`.
49	///
50	/// `Ok` means the set was accepted for delivery, not that the destination applied it.
51	#[allow(clippy::result_unit_err)]
52	fn send(
53		destination: &Self::Destination,
54		era: EraIndex,
55		validators: &[AccountId],
56	) -> Result<(), ()>;
57
58	/// The encoded size of what [`Self::send`] sends to `destination`.
59	///
60	/// By default the encoded `era` and `validators`, as if the transport added nothing: an XCM
61	/// envelope adds a few bytes. Checked against [`Self::max_message_size`] in the pallet's
62	/// `integrity_test`.
63	#[cfg(feature = "std")]
64	fn message_size(
65		_destination: &Self::Destination,
66		era: EraIndex,
67		validators: &[AccountId],
68	) -> usize
69	where
70		AccountId: codec::Encode,
71	{
72		codec::Encode::encoded_size(&(era, validators))
73	}
74
75	/// The largest message the transport accepts for `destination`, `None` without a limit.
76	#[cfg(feature = "std")]
77	fn max_message_size(_destination: &Self::Destination) -> Option<usize> {
78		None
79	}
80
81	/// Prepare `destination` so that [`Self::send`] succeeds in benchmarks.
82	#[cfg(feature = "runtime-benchmarks")]
83	fn ensure_successful_send(_destination: &Self::Destination) {}
84}
85
86impl<AccountId> SendValidatorSet<AccountId> for () {
87	type Destination = ();
88
89	fn send(_: &(), _: EraIndex, _: &[AccountId]) -> Result<(), ()> {
90		Err(())
91	}
92}
93
94/// The destination type of the configured sender.
95pub type DestinationOf<T> = <<T as Config>::Sender as SendValidatorSet<
96	<T as frame_system::Config>::AccountId,
97>>::Destination;
98
99#[cfg(test)]
100mod mock;
101
102#[cfg(test)]
103mod tests;
104
105#[cfg(feature = "runtime-benchmarks")]
106mod benchmarking;
107pub mod weights;
108
109#[frame_support::pallet]
110pub mod pallet {
111	pub use crate::weights::WeightInfo;
112	use crate::{DestinationOf, SendValidatorSet};
113	use alloc::vec::Vec;
114	use frame_support::pallet_prelude::*;
115	use sp_staking::EraIndex;
116
117	#[pallet::pallet]
118	pub struct Pallet<T>(_);
119
120	/// Configuration trait of this pallet.
121	#[pallet::config]
122	pub trait Config:
123		pallet_validator_collators::Config + frame_system::Config<RuntimeEvent: From<Event<Self>>>
124	{
125		/// Sends an announced set to one destination.
126		type Sender: SendValidatorSet<Self::AccountId>;
127
128		/// The other system chains every announced set is sent to. This chain is served through
129		/// the receiver directly.
130		///
131		/// Every send is charged the weight measured for the first entry, so no entry may cost
132		/// more to send than it.
133		type Destinations: Get<Vec<DestinationOf<Self>>>;
134
135		/// Weight information for this pallet.
136		type WeightInfo: WeightInfo;
137	}
138
139	#[pallet::event]
140	#[pallet::generate_deposit(pub(super) fn deposit_event)]
141	pub enum Event<T: Config> {
142		/// The sender accepted the set of `era` for `destination`. Delivery and execution there
143		/// are not confirmed.
144		AnnouncementSent { destination: DestinationOf<T>, era: EraIndex },
145		/// The sender did not accept the set of `era` for `destination`. It is not retried.
146		AnnouncementFailed { destination: DestinationOf<T>, era: EraIndex },
147		/// The set of `era` was not announced because it was rejected with `error`.
148		AnnouncementRejected { era: EraIndex, error: DispatchError },
149	}
150
151	#[pallet::hooks]
152	impl<T: Config> Hooks<frame_system::pallet_prelude::BlockNumberFor<T>> for Pallet<T> {
153		fn integrity_test() {
154			let validators = <T as pallet_validator_collators::Config>::MaxValidators::get();
155			let announce = Self::announce_weight(validators);
156			let max_block = <T as frame_system::Config>::BlockWeights::get().max_block;
157			assert!(
158				announce.all_lte(max_block),
159				"announcing {validators} validators weighs {announce:?}, above the block {max_block:?}"
160			);
161
162			#[cfg(feature = "std")]
163			{
164				let accounts = (0..validators)
165					.map(|i| {
166						T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::new(
167							&i.encode(),
168						))
169						.expect("infinite input decodes into an account; qed")
170					})
171					.collect::<Vec<_>>();
172				for destination in T::Destinations::get() {
173					let Some(max) = T::Sender::max_message_size(&destination) else { continue };
174					let size = T::Sender::message_size(&destination, EraIndex::MAX, &accounts);
175					assert!(
176						size <= max,
177						"announcing {validators} validators to {destination:?} is {size} bytes, above \
178						 the limit of {max}"
179					);
180				}
181			}
182		}
183	}
184
185	impl<T: Config> Pallet<T> {
186		/// Store the validator set of `era` locally and send it once to every destination.
187		///
188		/// A rejected set is reported with [`Event::AnnouncementRejected`] and not sent.
189		pub fn announce(era: EraIndex, validators: &[T::AccountId]) -> DispatchResult {
190			pallet_validator_collators::Pallet::<T>::receive_validator_set(
191				era,
192				validators.iter().cloned(),
193			)
194			.inspect_err(|&error| {
195				Self::deposit_event(Event::AnnouncementRejected { era, error });
196			})?;
197			for destination in T::Destinations::get() {
198				Self::send_to(destination, era, validators);
199			}
200			Ok(())
201		}
202
203		/// Upper bound of the weight of [`Self::announce`] for `validators` validators.
204		pub fn announce_weight(validators: u32) -> Weight {
205			let sends = T::Destinations::get().len() as u64;
206			<T as Config>::WeightInfo::announce(validators).saturating_add(
207				<T as Config>::WeightInfo::send_announcement(validators).saturating_mul(sends),
208			)
209		}
210
211		pub(crate) fn send_to(
212			destination: DestinationOf<T>,
213			era: EraIndex,
214			validators: &[T::AccountId],
215		) {
216			let event = match T::Sender::send(&destination, era, validators) {
217				Ok(()) => Event::AnnouncementSent { destination, era },
218				Err(()) => Event::AnnouncementFailed { destination, era },
219			};
220			Self::deposit_event(event);
221		}
222	}
223}