pallet_validator_collators/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 Collators pallet.
17//!
18//! Stores the validator set announced by the chain that runs `pallet-staking-async`, typically
19//! Asset Hub, and offers it as a session manager, so the relay-chain validators of the current era
20//! collate on a system parachain.
21//!
22//! ## Overview
23//!
24//! The announcing chain sends the active validator set of each era, tagged with the era index of
25//! `pallet-staking-async`.
26//! This pallet stores the latest set, received through `set_validators` from [`Config::SetOrigin`]
27//! or from another pallet through [`Pallet::receive_validator_set`]. It rejects a set whose era
28//! is not newer than the stored one, or that has more validators than [`Config::MaxValidators`].
29//!
30//! The pallet is a [`pallet_session::SessionManager`]. At every session rotation it returns the
31//! stored validators that have registered local session keys, checked with
32//! [`Config::ValidatorRegistration`], and records the returned list in [`DrawnCollators`]. The
33//! runtime may combine this pallet with `pallet-collator-selection` through
34//! [`pallet_session::UnionSessionManager`], so invulnerables and candidates keep collating next to
35//! the validators.
36//!
37//! [`MaxCollators`] optionally caps how many validators are returned. Governance can start with a
38//! low cap and raise it in steps, or lower it again, to roll out validator collators gradually.
39//! The pallet draws the validators at random at the first forced rotation after a set
40//! arrives or the cap changes, and returns them until the next draw. The draw shuffles the whole
41//! set with a seed made of the genesis hash, the era and the relay chain epoch randomness cached in
42//! [`EpochRandomness`], then keeps the first validators with registered keys up to the cap. Every
43//! validator with keys has the same chance to be drawn in each era. A cap change draws again from
44//! the stored set, so the drawn validators can change. Every draw takes its seed from the
45//! randomness cached at the time of the draw. The seed includes the genesis hash, so each chain
46//! draws independently from the same set. A drawn validator that removes its keys is dropped at
47//! the next rotation and its place stays empty, and a validator that registers keys after the draw
48//! waits, until the next set or cap change. Each set, so each era, gets a new draw, which is
49//! enacted at the second forced rotation with no notice, so a validator with keys must already
50//! run a synced collator node to collate when drawn.
51//!
52//! Until governance sets it, the cap is [`Config::DefaultMaxCollators`].
53//!
54//! The pallet implements [`cumulus_pallet_parachain_system::OnSystemEvent`]. The runtime must
55//! include it in the `OnSystemEvent` of `cumulus-pallet-parachain-system`, alone or in a tuple
56//! with other handlers, to keep [`EpochRandomness`] up to date from the relay chain state proof.
57//! The runtime should also return the keys of [`Pallet::relay_keys_to_prove`] from
58//! [`KeyToIncludeInRelayProof`](cumulus_primitives_core::KeyToIncludeInRelayProof), so collators
59//! include the randomness key in the proof.
60//! The draw runs in the session rotation, before the block's own proof is processed, so it uses
61//! the value cached by the previous block.
62//! A block whose proof lacks the trie nodes of the randomness key, or holds a value that does not
63//! decode, is invalid. A proof that shows the key absent, as before the relay chain's first epoch
64//! change, caches the zero value a draw without randomness uses.
65//! Without the `OnSystemEvent` wiring, every draw uses a zero randomness value and logs an error.
66//!
67//! The stored set is the one staking elected for the era. The relay chain enacts only the elected
68//! validators with relay-chain session keys, and each system chain returns only those with keys
69//! registered there, so a returned collator is not necessarily an active relay-chain validator.
70//!
71//! The pallet is also a [`pallet_session::ShouldEndSession`]. Pallet-session queues a new set at
72//! one rotation and enacts it at the next. When a set arrives, or the cap changes while a set is
73//! stored, the pallet forces two rotations in the following two blocks, so the change is in force
74//! without waiting for the regular period. The regular rotations given by
75//! [`Config::PeriodicSession`] continue as before.
76//!
77//! The returned validators author blocks like any collator, so a `pallet-collator-selection` event
78//! handler pays them from its pot and records them in `LastAuthoredBlock`.
79//!
80//! The pallet is also a `pallet_authorship::EventHandler` and counts the blocks each author
81//! produces in [`AuthoredBlocks`]. At a report-time, it removes the counts of the authors outside
82//! the stored set, and hands the counts of the others to [`Config::BlockReporter`] in one call. The
83//! reporter delivers them to the chain that runs `pallet-staking-async` + `points-convertor`, where
84//! they become era points. A report has at most one entry per validator of the stored set, and the
85//! pallet's `integrity_test` checks that [`Config::MaxValidators`] entries fit the reporter's
86//! [`ReportAuthoredBlocks::max_message_size`], so a full report is never too large to send and is
87//! not split. If the reporter rejects it, the counts of ONLY the _currently stored validators_ are
88//! kept for the next report, so [`AuthoredBlocks`] never holds more than the stored set plus the
89//! authors since the last report. Without a stored set every count is dropped.
90//!
91//! A report runs in every block whose number is a multiple of [`ReportPeriod`], and once per
92//! stored set shortly before the expected end of its era. The pallet records the arrival time of
93//! each set in [`ExternalSetReceivedAt`], from [`Config::UnixTime`], and expects the era to end
94//! [`ExpectedEraDuration`] after it. The early report runs in the first block at or after
95//! [`ReportMargin`] before that end, so that in a normal era the counts reach the chain that runs
96//! `pallet-staking-async` before the era rotates. The margin used is at most
97//! [`Config::MaxReportMargin`] and at most half of [`ExpectedEraDuration`]. The early report
98//! removes [`ExternalSetReceivedAt`] and is not retried: if the reporter rejects it, its counts go
99//! out with the next [`ReportPeriod`] report. The periodic report also covers eras that end earlier
100//! or later than expected, a set that never arrives, and the time before the first set arrives. If
101//! both reports fall in the same block, the pallet reports once.
102//!
103//! A runtime must configure `pallet-collator-selection`'s `KickThreshold` to exceed two Aura
104//! rounds of the merged list, [`Config::MaxValidators`] plus the invulnerables and candidates,
105//! times the blocks the chain produces per Aura slot. A change of the list length at a session
106//! boundary can delay a collator's next turn by up to one more round. Otherwise bonded candidates
107//! are kicked as stale between their slots. [`Config::MaxValidators`] rather than the cap is the
108//! bound, since the cap can be raised or removed without a runtime upgrade.
109//! `parachains_common::impls::KickThreshold` derives such a value.
110//!
111//! ## TODO
112//!
113//! - Dropping validators that author no blocks for a session, judged among the drawn validators
114//! under a cap.
115//! - (Only if a need is established) Propagating relay-chain offences to the collator set.
116//! - Under a cap, revisit the redraw period and notice once operators have run collators. A draw
117//! per era without notice is the first step, with operators expected to run a synced collator
118//! node all the time. Options: redraw every few eras or sessions, keep a drawn validator for
119//! several eras while it stays in the active set, and announce the drawn validators before they
120//! collate so they can sync a node. Open points: the time a node needs to sync, and refilling the
121//! place of a drawn validator that leaves the active set, which needs notice too.
122
123#![cfg_attr(not(feature = "std"), no_std)]
124
125extern crate alloc;
126
127pub use pallet::*;
128
129#[cfg(test)]
130mod mock;
131
132#[cfg(test)]
133mod tests;
134
135#[cfg(feature = "runtime-benchmarks")]
136mod benchmarking;
137pub mod migrations;
138#[cfg(any(test, feature = "runtime-benchmarks"))]
139mod relay_proof;
140pub mod weights;
141
142const LOG_TARGET: &str = "runtime::validator-collators";
143
144/// Delivers the block counts of one report.
145pub trait ReportAuthoredBlocks<AccountId> {
146 /// Hand over the number of blocks each account authored.
147 ///
148 /// `Ok` means the counts were accepted for delivery or credited, not that a remote chain
149 /// applied them.
150 #[allow(clippy::result_unit_err)]
151 fn report(blocks: &[(AccountId, u32)]) -> Result<(), ()>;
152
153 /// The encoded size of what [`Self::report`] sends for `blocks`.
154 ///
155 /// By default the encoded `blocks`, as if the transport added nothing: an XCM envelope adds a
156 /// few bytes. Checked against [`Self::max_message_size`] in the pallet's `integrity_test`.
157 #[cfg(feature = "std")]
158 fn message_size(blocks: &[(AccountId, u32)]) -> usize
159 where
160 AccountId: codec::Encode,
161 {
162 codec::Encode::encoded_size(blocks)
163 }
164
165 /// The largest message the transport accepts, `None` without a limit, as for a local credit.
166 #[cfg(feature = "std")]
167 fn max_message_size() -> Option<usize> {
168 None
169 }
170
171 /// Prepare the runtime so that [`Self::report`] succeeds for `blocks` in benchmarks.
172 #[cfg(feature = "runtime-benchmarks")]
173 fn ensure_successful_report(_blocks: &[(AccountId, u32)]) {}
174}
175
176/// Discards the counts.
177impl<AccountId> ReportAuthoredBlocks<AccountId> for () {
178 fn report(_: &[(AccountId, u32)]) -> Result<(), ()> {
179 Ok(())
180 }
181}
182
183#[frame_support::pallet]
184pub mod pallet {
185 pub use crate::weights::WeightInfo;
186 use crate::ReportAuthoredBlocks;
187 use alloc::{collections::BTreeSet, vec, vec::Vec};
188 use cumulus_pallet_parachain_system::{
189 relay_state_snapshot::{Error as RelayProofError, ReadEntryErr},
190 OnSystemEvent, RelayChainStateProof,
191 };
192 use cumulus_primitives_core::{
193 relay_chain::well_known_keys, PersistedValidationData, RelayStorageKey,
194 };
195 use frame_support::{
196 dispatch::DispatchClass,
197 pallet_prelude::*,
198 storage::with_storage_layer,
199 traits::{EnsureOrigin, UnixTime, ValidatorRegistration},
200 weights::WeightMeter,
201 BoundedBTreeSet,
202 };
203 use frame_system::pallet_prelude::*;
204 use pallet_session::{SessionManager, ShouldEndSession};
205 use rand::{seq::SliceRandom, SeedableRng};
206 use rand_chacha::ChaCha20Rng;
207 use sp_runtime::{
208 traits::{BlakeTwo256, Hash, Saturating, Zero},
209 SaturatedConversion,
210 };
211 use sp_staking::{EraIndex, SessionIndex};
212
213 /// A validator set received for an era.
214 #[frame_support::stored]
215 pub struct EraValidatorSet<AccountId, MaxValidators: Get<u32>> {
216 /// The era the set belongs to.
217 pub era: EraIndex,
218 /// The validator stashes of that era.
219 pub validators: BoundedBTreeSet<AccountId, MaxValidators>,
220 }
221
222 /// The collators returned for a session from the validator set of `era`.
223 ///
224 /// Always a subset of the [`EraValidatorSet`] of the same `era`, which need not be the one in
225 /// [`ExternalValidatorSet`] any more.
226 #[frame_support::stored]
227 pub struct EraCollators<AccountId, MaxValidators: Get<u32>> {
228 /// The era of the set the collators were taken from.
229 pub era: EraIndex,
230 /// The collators, in drawn order.
231 pub collators: BoundedVec<AccountId, MaxValidators>,
232 }
233
234 /// How many validators of the stored set are drawn as collators.
235 #[frame_support::stored]
236 #[derive(Copy)]
237 pub enum CollatorDraw {
238 /// Every validator with registered keys.
239 #[codec(index = 0)]
240 All,
241 /// Up to this many validators with registered keys.
242 #[codec(index = 1)]
243 UpTo(u32),
244 /// No validator.
245 #[codec(index = 2)]
246 None,
247 }
248
249 impl CollatorDraw {
250 /// The largest number of validators drawn.
251 pub fn limit(self) -> u32 {
252 match self {
253 Self::None => 0,
254 Self::UpTo(max) => max,
255 Self::All => u32::MAX,
256 }
257 }
258 }
259
260 /// Progress of the two rotations that bring a received set into force.
261 #[derive(
262 Clone, Copy, Eq, PartialEq, Default, Encode, Decode, Debug, TypeInfo, MaxEncodedLen,
263 )]
264 pub enum RotationState {
265 /// No forced rotation is pending.
266 #[default]
267 Idle,
268 /// A set was received and the next rotation queues it.
269 AwaitingQueue,
270 /// The set is queued and the next rotation enacts it.
271 AwaitingEnactment,
272 }
273
274 #[pallet::pallet]
275 #[pallet::storage_version(crate::migrations::STORAGE_VERSION)]
276 pub struct Pallet<T>(_);
277
278 /// Configuration trait of this pallet.
279 #[pallet::config]
280 pub trait Config: frame_system::Config<RuntimeEvent: From<Event<Self>>> {
281 /// Origin allowed to submit a validator set.
282 type SetOrigin: EnsureOrigin<Self::RuntimeOrigin>;
283
284 /// Origin allowed to change [`MaxCollators`], [`ReportPeriod`], [`ExpectedEraDuration`]
285 /// and [`ReportMargin`].
286 type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
287
288 /// Lookup of registered session keys.
289 type ValidatorRegistration: ValidatorRegistration<Self::AccountId>;
290
291 /// Maximum number of validators in a received set.
292 #[pallet::constant]
293 type MaxValidators: Get<u32>;
294
295 /// Maximum number of entries of [`AuthoredBlocks`] that one report reads.
296 ///
297 /// Authors are counted between two reports: the validators of the stored set, and the
298 /// other collators of the chain, such as invulnerables and candidates. A sensible value is
299 /// [`Config::MaxValidators`], plus the maximum number of other collators the chain may
300 /// have, plus a small buffer for the authors that leave the collators before the next
301 /// report. Entries beyond it wait for the next report. The `integrity_test` checks that a
302 /// report of this many entries fits a block.
303 #[pallet::constant]
304 type MaxEntriesPerReport: Get<u32>;
305
306 /// The regular session rotation rule kept next to the forced rotations.
307 type PeriodicSession: ShouldEndSession<BlockNumberFor<Self>>;
308
309 /// Hands the block counts of one report to the chain that credits them.
310 type BlockReporter: ReportAuthoredBlocks<Self::AccountId>;
311
312 /// Value of [`MaxCollators`] until governance sets it.
313 ///
314 /// A runtime upgrade that changes it keeps the collators drawn under the previous value
315 /// until the next draw, unless the upgrade sets [`PendingRotation`] to
316 /// [`RotationState::AwaitingQueue`].
317 #[pallet::constant]
318 type DefaultMaxCollators: Get<CollatorDraw>;
319
320 /// Number of blocks between two reports until governance sets [`ReportPeriod`].
321 #[pallet::constant]
322 type DefaultReportPeriod: Get<BlockNumberFor<Self>>;
323
324 /// Wall clock time, to time the report before the expected end of an era.
325 type UnixTime: UnixTime;
326
327 /// Value of [`ExpectedEraDuration`] until governance sets it, in milliseconds.
328 #[pallet::constant]
329 type DefaultExpectedEraDuration: Get<u64>;
330
331 /// Value of [`ReportMargin`] until governance sets it, in milliseconds.
332 #[pallet::constant]
333 type DefaultReportMargin: Get<u64>;
334
335 /// Largest value [`Pallet::set_report_margin`] accepts, in milliseconds.
336 ///
337 /// A stored [`ReportMargin`] above it, as after a runtime upgrade that lowers it, is used
338 /// up to it.
339 #[pallet::constant]
340 type MaxReportMargin: Get<u64>;
341
342 /// Weight information for extrinsics in this pallet.
343 type WeightInfo: WeightInfo;
344 }
345
346 /// The latest received validator set.
347 #[pallet::storage]
348 pub type ExternalValidatorSet<T: Config> =
349 StorageValue<_, EraValidatorSet<T::AccountId, T::MaxValidators>, OptionQuery>;
350
351 /// Time at which we received the last [`ExternalValidatorSet`], in milliseconds. Removed when
352 /// the report before the expected end of its era is made.
353 #[pallet::storage]
354 pub type ExternalSetReceivedAt<T: Config> = StorageValue<_, u64, OptionQuery>;
355
356 /// How many validators are returned as collators, see [`CollatorDraw`]. Only validators with
357 /// keys count against the cap. It is [`Config::DefaultMaxCollators`] until
358 /// [`Pallet::set_max_collators`] stores a value.
359 ///
360 /// The cap applies before the union with the other session manager. A validator that the
361 /// other session manager also returns takes a place under the cap without adding a collator.
362 ///
363 /// The merged list becomes Aura's authority list, which Aura writes into the block header
364 /// whenever it changes, and the relay chain rejects a header above its head-data limit. Size
365 /// the cap so that the merged list, invulnerables and candidates included, keeps a
366 /// session-change header within that limit.
367 ///
368 /// The validators are drawn at random, see [`DrawnCollators`].
369 ///
370 /// A change with a stored set forces two rotations. The first draws [`DrawnCollators`] again
371 /// from the stored set, so the drawn validators can change. The change is in force two blocks
372 /// later. Removing the cap returns every validator of the stored set with registered keys.
373 #[pallet::storage]
374 pub type MaxCollators<T: Config> =
375 StorageValue<_, CollatorDraw, ValueQuery, <T as Config>::DefaultMaxCollators>;
376
377 /// The collators last returned to pallet-session, taken from [`ExternalValidatorSet`].
378 ///
379 /// Written at every session rotation, and holds only validators that had registered keys at
380 /// that rotation. It is the draw made at the first rotation after a set arrives or
381 /// the cap changes, and each later rotation returns it again without the validators that have
382 /// removed their keys since. `None` when the last rotation returned no list, as before the
383 /// first set arrives.
384 ///
385 /// Pallet-session queues the returned list at one rotation and enacts it at the next, so this
386 /// is ahead of the session validators while [`PendingRotation`] is
387 /// [`RotationState::AwaitingEnactment`].
388 ///
389 /// While [`PendingRotation`] is [`RotationState::AwaitingQueue`] it still belongs to the
390 /// previous set or cap: it can be of an older era, missing before the first draw, and not a
391 /// subset of [`ExternalValidatorSet`]. Otherwise it belongs to the era of
392 /// [`ExternalValidatorSet`] and is a subset of it, of at most [`MaxCollators`] validators.
393 #[pallet::storage]
394 pub type DrawnCollators<T: Config> =
395 StorageValue<_, EraCollators<T::AccountId, T::MaxValidators>, OptionQuery>;
396
397 /// Progress of the forced rotations for the latest received set.
398 #[pallet::storage]
399 pub type PendingRotation<T: Config> = StorageValue<_, RotationState, ValueQuery>;
400
401 /// The relay chain randomness of one epoch ago, read from the relay chain state proof of every
402 /// block and written when it changes.
403 #[pallet::storage]
404 pub type EpochRandomness<T: Config> = StorageValue<_, [u8; 32], OptionQuery>;
405
406 /// Number of blocks between two reports of [`AuthoredBlocks`]. A report is made in every
407 /// block whose number is a multiple of it.
408 #[pallet::storage]
409 pub type ReportPeriod<T: Config> =
410 StorageValue<_, BlockNumberFor<T>, ValueQuery, T::DefaultReportPeriod>;
411
412 /// Blocks authored since the last report, per author.
413 #[pallet::storage]
414 pub type AuthoredBlocks<T: Config> =
415 CountedStorageMap<_, Twox64Concat, T::AccountId, u32, ValueQuery>;
416
417 /// Expected time from the arrival of a validator set to the end of its era, in milliseconds.
418 #[pallet::storage]
419 pub type ExpectedEraDuration<T: Config> =
420 StorageValue<_, u64, ValueQuery, T::DefaultExpectedEraDuration>;
421
422 /// Time before the expected end of an era at which the counts are reported, in milliseconds.
423 /// Used up to [`Config::MaxReportMargin`] and up to half of [`ExpectedEraDuration`].
424 #[pallet::storage]
425 pub type ReportMargin<T: Config> = StorageValue<_, u64, ValueQuery, T::DefaultReportMargin>;
426
427 #[pallet::event]
428 #[pallet::generate_deposit(pub(super) fn deposit_event)]
429 pub enum Event<T: Config> {
430 /// A validator set was stored for an era.
431 ValidatorSetReceived { era: EraIndex, count: u32 },
432 /// The maximum number of validator collators was changed.
433 MaxCollatorsSet { max: CollatorDraw },
434 /// No external set is stored, so no validators were returned for the session, with or
435 /// without a cap. This happens in the sessions after this pallet is added to a runtime and
436 /// before the first set arrives, so it is not an `UnexpectedKind`.
437 NothingToDraw,
438 /// `drawn_len` of the `external_len` validators of the set of `era`, all with registered
439 /// keys, were returned for a session and recorded in [`DrawnCollators`]. `new_external` is
440 /// `true` at the first rotation after a set arrives or the cap changes, and `false` at the
441 /// later ones, which return the previous draw again.
442 CollatorsDrawn { era: EraIndex, external_len: u32, drawn_len: u32, new_external: bool },
443 /// The number of blocks between two reports was changed.
444 ReportPeriodSet { period: BlockNumberFor<T> },
445 /// The block counts of `authors` authors were removed. The `reported` of them in the
446 /// stored set were handed to the reporter and the others were dropped.
447 BlocksReported { authors: u32, reported: u32 },
448 /// The reporter rejected the block counts. The counts of the `kept` authors in the stored
449 /// set are kept for the next report, and those of the `dropped` other authors were
450 /// removed.
451 BlocksReportFailed { kept: u32, dropped: u32 },
452 /// The expected time from the arrival of a set to the end of its era was changed.
453 ExpectedEraDurationSet { duration: u64 },
454 /// The time before the expected end of an era at which the counts are reported was
455 /// changed.
456 ReportMarginSet { margin: u64 },
457 /// Something that should never happen happened. See [`UnexpectedKind`].
458 Unexpected(UnexpectedKind),
459 }
460
461 /// The kinds of [`Event::Unexpected`].
462 #[derive(Clone, Encode, Decode, DecodeWithMemTracking, PartialEq, TypeInfo, Debug)]
463 pub enum UnexpectedKind {
464 /// We expected a previously drawn set, but none was found.
465 NoPreviousDrawSet,
466 /// The stored validator set does not decode, so no validators were returned for the
467 /// session.
468 StoredSetUndecodable,
469 }
470
471 #[pallet::error]
472 pub enum Error<T> {
473 /// The era of the set is not newer than the era of the stored set.
474 StaleEra,
475 /// The set has more validators than [`Config::MaxValidators`].
476 TooManyValidators,
477 /// The report period must be greater than zero.
478 ZeroReportPeriod,
479 /// The expected era duration must be greater than zero.
480 ZeroExpectedEraDuration,
481 /// The report margin must be greater than zero.
482 ZeroReportMargin,
483 /// The report margin is above [`Config::MaxReportMargin`].
484 ReportMarginTooHigh,
485 }
486
487 #[pallet::hooks]
488 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
489 /// Charges the read of [`PendingRotation`] by [`ShouldEndSession::should_end_session`],
490 /// which pallet-session makes in every block without charging it.
491 fn on_initialize(_: BlockNumberFor<T>) -> Weight {
492 T::DbWeight::get().reads(1)
493 }
494
495 /// Reports [`AuthoredBlocks`] at every multiple of [`ReportPeriod`] (`periodic_send` in the
496 /// code), and once per stored set when [`ReportMargin`] or less remains until
497 /// [`ExternalSetReceivedAt`] plus [`ExpectedEraDuration`] (`early_send` in the code).
498 ///
499 /// The early report removes [`ExternalSetReceivedAt`], so it is made once per set and not
500 /// retried. If the reporter rejects it, the counts go out with the next [`ReportPeriod`]
501 /// report. Both rules in the same block make one report.
502 ///
503 /// It runs after the inherents, so the timestamp is the one of this block. A report that
504 /// does not fit `meter` is not made: an early report stays due and is made in the next
505 /// block it fits, and the counts of a periodic report go out with the next report. During
506 /// a multi-block migration no report is made, and the counts are kept.
507 fn on_poll(now: BlockNumberFor<T>, meter: &mut WeightMeter) {
508 // the base-weight, as per the benchmarks, is everything minus the report.
509 let base_weight = T::WeightInfo::on_poll();
510 if !meter.can_consume(base_weight) {
511 return;
512 }
513
514 let early_send = ExternalSetReceivedAt::<T>::get().is_some_and(|received_at| {
515 let duration = ExpectedEraDuration::<T>::get();
516 let margin =
517 ReportMargin::<T>::get().min(T::MaxReportMargin::get()).min(duration / 2);
518 let now_ms: u64 = T::UnixTime::now().as_millis().saturated_into();
519 now_ms >= received_at.saturating_add(duration.saturating_sub(margin))
520 });
521 let periodic_send = {
522 let period = ReportPeriod::<T>::get();
523 !period.is_zero() && (now % period).is_zero()
524 };
525
526 if !early_send && !periodic_send {
527 // nothing should be sent, we're done.
528 meter.consume(base_weight);
529 return;
530 }
531
532 // either periodic send, or early send, which we don't care to distinguish anymore, and
533 // just send the report.
534 let authors = AuthoredBlocks::<T>::count().min(T::MaxEntriesPerReport::get());
535 let report_weight = Self::report_weight(authors);
536 if !meter.can_consume(base_weight.saturating_add(report_weight)) {
537 log::warn!(
538 target: crate::LOG_TARGET,
539 "the report of authored blocks does not fit the block, postponing it"
540 );
541 meter.consume(base_weight);
542 return;
543 }
544
545 // Remove the arrival only once the report is made, so the early report is made once
546 // per set. Removing it sooner would lose an early report that does not fit `meter`,
547 // which stays due for the next block.
548 if early_send {
549 ExternalSetReceivedAt::<T>::kill();
550 }
551 Self::report_blocks(authors);
552 meter.consume(base_weight.saturating_add(report_weight));
553 }
554
555 fn integrity_test() {
556 assert!(
557 !T::DefaultReportPeriod::get().is_zero(),
558 "`DefaultReportPeriod` must not be zero"
559 );
560 assert!(
561 T::DefaultExpectedEraDuration::get() > 0,
562 "`DefaultExpectedEraDuration` must not be zero"
563 );
564 let margin = T::DefaultReportMargin::get();
565 assert!(
566 margin > 0 && margin <= T::MaxReportMargin::get(),
567 "`DefaultReportMargin` must not be zero and at most `MaxReportMargin`"
568 );
569 let max_items = T::MaxEntriesPerReport::get();
570 assert!(
571 max_items >= T::MaxValidators::get(),
572 "`MaxEntriesPerReport` must leave room for every validator of a set"
573 );
574 // `on_poll` postpones a report that does not fit, so one that does not fit an empty
575 // block is never made.
576 let report = T::WeightInfo::on_poll().saturating_add(Self::report_weight(max_items));
577 let max_block = T::BlockWeights::get().max_block;
578 assert!(
579 report.all_lte(max_block),
580 "a report of {max_items} authors weighs {report:?}, above the block {max_block:?}"
581 );
582
583 #[cfg(feature = "std")]
584 if let Some(max) = T::BlockReporter::max_message_size() {
585 // biggest possible report we could send.
586 let entries = (0..T::MaxValidators::get())
587 .map(|i| {
588 let who = T::AccountId::decode(
589 &mut sp_runtime::traits::TrailingZeroInput::new(&i.encode()),
590 )
591 .expect("infinite input decodes into an account; qed");
592 (who, u32::MAX)
593 })
594 .collect::<Vec<_>>();
595 let size = T::BlockReporter::message_size(&entries);
596 assert!(
597 size <= max,
598 "a report of {} entries is {size} bytes, above the limit of {max}",
599 entries.len()
600 );
601 }
602 }
603
604 #[cfg(feature = "try-runtime")]
605 fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
606 Self::do_try_state()
607 }
608 }
609
610 #[pallet::call]
611 impl<T: Config> Pallet<T> {
612 /// Store the validator set of `era`.
613 #[pallet::call_index(0)]
614 #[pallet::weight(T::WeightInfo::set_validators(validators.len() as u32))]
615 pub fn set_validators(
616 origin: OriginFor<T>,
617 era: EraIndex,
618 validators: BoundedBTreeSet<T::AccountId, T::MaxValidators>,
619 ) -> DispatchResult {
620 T::SetOrigin::ensure_origin(origin)?;
621 Self::do_receive_validator_set(era, validators)
622 }
623
624 /// Set the maximum number of validators returned as collators.
625 ///
626 /// With a stored set, the change forces two rotations and the first draws
627 /// [`DrawnCollators`] again, so the drawn validators can change.
628 #[pallet::call_index(1)]
629 #[pallet::weight(T::WeightInfo::set_max_collators())]
630 pub fn set_max_collators(origin: OriginFor<T>, max: CollatorDraw) -> DispatchResult {
631 T::UpdateOrigin::ensure_origin(origin)?;
632 MaxCollators::<T>::set(max);
633 if ExternalValidatorSet::<T>::exists() {
634 PendingRotation::<T>::put(RotationState::AwaitingQueue);
635 }
636 Self::deposit_event(Event::MaxCollatorsSet { max });
637 Ok(())
638 }
639
640 /// Set the number of blocks between two reports of the authored blocks.
641 ///
642 /// The next report is made at the next multiple of `period`.
643 #[pallet::call_index(2)]
644 #[pallet::weight(T::WeightInfo::set_report_period())]
645 pub fn set_report_period(
646 origin: OriginFor<T>,
647 period: BlockNumberFor<T>,
648 ) -> DispatchResult {
649 T::UpdateOrigin::ensure_origin(origin)?;
650 ensure!(!period.is_zero(), Error::<T>::ZeroReportPeriod);
651 ReportPeriod::<T>::put(period);
652 Self::deposit_event(Event::ReportPeriodSet { period });
653 Ok(())
654 }
655
656 /// Set the expected time from the arrival of a validator set to the end of its era, in
657 /// milliseconds.
658 ///
659 /// It applies to the stored set too, whose arrival time is kept.
660 #[pallet::call_index(3)]
661 #[pallet::weight(T::WeightInfo::set_expected_era_duration())]
662 pub fn set_expected_era_duration(origin: OriginFor<T>, duration: u64) -> DispatchResult {
663 T::UpdateOrigin::ensure_origin(origin)?;
664 ensure!(duration > 0, Error::<T>::ZeroExpectedEraDuration);
665 ExpectedEraDuration::<T>::put(duration);
666 Self::deposit_event(Event::ExpectedEraDurationSet { duration });
667 Ok(())
668 }
669
670 /// Set the time before the expected end of an era at which the counts are reported, in
671 /// milliseconds.
672 ///
673 /// It applies to the stored set too, whose arrival time is kept.
674 #[pallet::call_index(4)]
675 #[pallet::weight(T::WeightInfo::set_report_margin())]
676 pub fn set_report_margin(origin: OriginFor<T>, margin: u64) -> DispatchResult {
677 T::UpdateOrigin::ensure_origin(origin)?;
678 ensure!(margin > 0, Error::<T>::ZeroReportMargin);
679 ensure!(margin <= T::MaxReportMargin::get(), Error::<T>::ReportMarginTooHigh);
680 ReportMargin::<T>::put(margin);
681 Self::deposit_event(Event::ReportMarginSet { margin });
682 Ok(())
683 }
684 }
685
686 impl<T: Config> Pallet<T> {
687 /// Store the validator set of `era` and its arrival time, and schedule the rotations that
688 /// bring it into force.
689 ///
690 /// An account listed more than once is kept once, and the set is checked against
691 /// [`Config::MaxValidators`] after that.
692 pub fn receive_validator_set(
693 era: EraIndex,
694 validators: impl IntoIterator<Item = T::AccountId>,
695 ) -> DispatchResult {
696 let validators =
697 BoundedBTreeSet::try_from(validators.into_iter().collect::<BTreeSet<_>>())
698 .map_err(|_| Error::<T>::TooManyValidators)?;
699 Self::do_receive_validator_set(era, validators)
700 }
701
702 pub(crate) fn do_receive_validator_set(
703 era: EraIndex,
704 validators: BoundedBTreeSet<T::AccountId, T::MaxValidators>,
705 ) -> DispatchResult {
706 ensure!(
707 ExternalValidatorSet::<T>::get().is_none_or(|stored| era > stored.era),
708 Error::<T>::StaleEra
709 );
710 let count = validators.len() as u32;
711 ExternalValidatorSet::<T>::put(EraValidatorSet { era, validators });
712 ExternalSetReceivedAt::<T>::put(T::UnixTime::now().as_millis().saturated_into::<u64>());
713 PendingRotation::<T>::put(RotationState::AwaitingQueue);
714 Self::deposit_event(Event::ValidatorSetReceived { era, count });
715 Ok(())
716 }
717
718 /// The relay chain storage keys this pallet reads from the relay chain state proof.
719 ///
720 /// A runtime returns them, next to the keys of other pallets, from
721 /// [`KeyToIncludeInRelayProof`](cumulus_primitives_core::KeyToIncludeInRelayProof).
722 pub fn relay_keys_to_prove() -> Vec<RelayStorageKey> {
723 vec![RelayStorageKey::Top(well_known_keys::ONE_EPOCH_AGO_RANDOMNESS.to_vec())]
724 }
725
726 /// The seed of a draw from the set of `era`, made of the genesis hash, the era and
727 /// [`EpochRandomness`], or a zero value when no randomness is cached.
728 pub(crate) fn draw_seed(era: EraIndex) -> [u8; 32] {
729 let randomness = EpochRandomness::<T>::get().unwrap_or_else(|| {
730 log::error!(
731 target: crate::LOG_TARGET,
732 "no relay chain epoch randomness is cached, drawing with a zero value"
733 );
734 [0; 32]
735 });
736 let genesis = frame_system::Pallet::<T>::block_hash(BlockNumberFor::<T>::zero());
737 BlakeTwo256::hash_of(&(b"validator-collators", genesis, era, randomness)).into()
738 }
739
740 /// Draw up to `cap` validators with registered keys from `set`, in drawn order.
741 ///
742 /// The whole set is shuffled before the key filter, so the order depends only on the seed
743 /// and the set.
744 fn draw_collators(
745 set: EraValidatorSet<T::AccountId, T::MaxValidators>,
746 cap: u32,
747 ) -> Vec<T::AccountId> {
748 let EraValidatorSet { era, validators } = set;
749 let mut order: Vec<_> = validators.into_iter().collect();
750 order.shuffle(&mut ChaCha20Rng::from_seed(Self::draw_seed(era)));
751 order
752 .into_iter()
753 .filter(T::ValidatorRegistration::is_registered)
754 .take(cap as usize)
755 .collect()
756 }
757
758 /// Weight of [`Self::report_blocks`] with `authors` entries read from [`AuthoredBlocks`].
759 ///
760 /// An entry of a validator in the stored set is handed to the reporter and removed, while
761 /// an entry of another author is only removed, which costs less. So the weight assumes as
762 /// many validators as the set holds, and the other authors beyond them.
763 pub(crate) fn report_weight(authors: u32) -> Weight {
764 let validators = authors.min(T::MaxValidators::get());
765 T::WeightInfo::report_blocks(validators, authors.saturating_sub(validators))
766 }
767
768 /// Hand the counted blocks of the stored validators to [`Config::BlockReporter`].
769 ///
770 /// Hands the counts of every author in [`ExternalValidatorSet`] to the reporter in one
771 /// call, and removes the counts of the other authors. The filter is the latest set, so
772 /// once a new set arrives, the counts of a [`DrawnCollators`] validator that is not in it
773 /// are dropped. The counts handed over are removed only if the reporter accepts them, and
774 /// the reporter's storage changes are rolled back if it rejects them. Without a stored
775 /// set every count is removed.
776 ///
777 /// `authors` is the number of entries in [`AuthoredBlocks`], which the caller reads to
778 /// weigh the report with [`Self::report_weight`] before making it. A rejected report
779 /// removes fewer counts than an accepted one, which is the weighed case.
780 pub(crate) fn report_blocks(authors: u32) {
781 if authors == 0 {
782 return;
783 }
784
785 let validators =
786 ExternalValidatorSet::<T>::get().map(|set| set.validators).unwrap_or_default();
787
788 // read all authored-blocks, and partition them in those that we send and those we may
789 // drop.
790 let (to_send, others): (Vec<_>, Vec<_>) = AuthoredBlocks::<T>::iter()
791 .take(T::MaxEntriesPerReport::get() as usize)
792 .partition(|(who, _)| validators.contains(who));
793 let (kept, dropped) = (to_send.len() as u32, others.len() as u32);
794
795 // We definitely want to delete these ones.
796 others.iter().for_each(|(who, _)| AuthoredBlocks::<T>::remove(who));
797
798 // No message is sent for a report with no entries.
799 let result = with_storage_layer(|| match to_send.is_empty() {
800 true => Ok(()),
801 false => T::BlockReporter::report(&to_send)
802 .map_err(|()| DispatchError::Other("the reporter rejected the counts")),
803 });
804
805 let event = match result {
806 Ok(()) => {
807 // we managed to send, delete the sent ones as well.
808 to_send.iter().for_each(|(who, _)| AuthoredBlocks::<T>::remove(who));
809 Event::BlocksReported { authors, reported: kept }
810 },
811 Err(_) => {
812 // we failed to send, we keep the ones that were authors now, having already
813 // dropped the rest.
814 log::warn!(
815 target: crate::LOG_TARGET,
816 "the reporter rejected the counts of {kept} authors, keeping them and \
817 dropping those of {dropped} authors outside the stored set"
818 );
819 Event::BlocksReportFailed { kept, dropped }
820 },
821 };
822 Self::deposit_event(event);
823 }
824
825 /// Check the pallet invariants.
826 #[cfg(any(test, feature = "try-runtime"))]
827 pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
828 // `a` implies `b`: fails only if `a` holds and `b` does not.
829 let implies = |a: bool, b: bool| !a || b;
830
831 // ExternalValidatorSet related
832 ensure!(
833 implies(
834 PendingRotation::<T>::get() != RotationState::Idle,
835 ExternalValidatorSet::<T>::exists()
836 ),
837 "a rotation is pending without a stored validator set"
838 );
839 ensure!(
840 ExternalValidatorSet::<T>::exists() == ExternalValidatorSet::<T>::get().is_some(),
841 "the stored validator set does not decode, it may exceed `MaxValidators`"
842 );
843
844 // DrawnCollators related
845 ensure!(
846 implies(DrawnCollators::<T>::exists(), ExternalValidatorSet::<T>::exists()),
847 "drawn collators are stored without a validator set"
848 );
849 ensure!(
850 DrawnCollators::<T>::exists() == DrawnCollators::<T>::get().is_some(),
851 "the drawn collators do not decode"
852 );
853 ensure!(
854 AuthoredBlocks::<T>::iter_values().all(|blocks| blocks > 0),
855 "an author is counted with zero blocks"
856 );
857 ensure!(ExpectedEraDuration::<T>::get() > 0, "the expected era duration is zero");
858 ensure!(ReportMargin::<T>::get() > 0, "the report margin is zero");
859
860 if PendingRotation::<T>::get() == RotationState::AwaitingQueue {
861 // Until the next rotation draws, the drawn collators still belong to the previous
862 // set or cap: of an older era after a new set, possibly by more than one era, or of
863 // the same era after a cap change. Only their era is checked.
864 if let (Some(set), Some(drawn)) =
865 (ExternalValidatorSet::<T>::get(), DrawnCollators::<T>::get())
866 {
867 ensure!(
868 drawn.era <= set.era,
869 "the drawn collators belong to a newer era than the stored set"
870 );
871 }
872 return Ok(());
873 }
874
875 // Keys can change between rotations, so the key filter of the last rotation is not
876 // checked.
877 let Some(set) = ExternalValidatorSet::<T>::get() else { return Ok(()) };
878 let drawn = DrawnCollators::<T>::get().ok_or("no collators are drawn for the set")?;
879 ensure!(drawn.era == set.era, "the drawn collators belong to another era");
880 let mut seen = BTreeSet::new();
881 ensure!(
882 drawn.collators.iter().all(|v| seen.insert(v)),
883 "the drawn collators contain duplicates"
884 );
885 ensure!(
886 drawn.collators.iter().all(|v| set.validators.contains(v)),
887 "a drawn collator is not in the stored validator set"
888 );
889 ensure!(
890 drawn.collators.len() <= MaxCollators::<T>::get().limit() as usize,
891 "more collators are drawn than the cap allows"
892 );
893 // With the pallet wired as `OnSystemEvent`, `on_relay_state_proof` caches a value in
894 // every block's inherent and the cache is never removed. So this holds for every draw
895 // after the first block that runs the pallet, and flags a runtime without that wiring.
896 ensure!(
897 EpochRandomness::<T>::exists(),
898 "collators are drawn without a cached relay chain epoch randomness"
899 );
900 Ok(())
901 }
902
903 /// The stored set, or `None` without one. A stored set that does not decode is `None` too,
904 /// and is logged and reported with [`UnexpectedKind::StoredSetUndecodable`].
905 fn external_validator_set() -> Option<EraValidatorSet<T::AccountId, T::MaxValidators>> {
906 if let Some(external_set) = ExternalValidatorSet::<T>::get() {
907 return Some(external_set);
908 } else if ExternalValidatorSet::<T>::exists() {
909 log::error!(
910 target: crate::LOG_TARGET,
911 "the stored external validator set does not decode"
912 );
913 Self::deposit_event(Event::Unexpected(UnexpectedKind::StoredSetUndecodable));
914 }
915 None
916 }
917 }
918
919 impl<T: Config> SessionManager<T::AccountId> for Pallet<T> {
920 fn new_session(_: SessionIndex) -> Option<Vec<T::AccountId>> {
921 // Advance the forced rotations. `AwaitingQueue` means a new external set or a new cap,
922 // so we draw again.
923 let new_external = match PendingRotation::<T>::get() {
924 RotationState::AwaitingQueue => {
925 PendingRotation::<T>::put(RotationState::AwaitingEnactment);
926 true
927 },
928 RotationState::AwaitingEnactment => {
929 PendingRotation::<T>::kill();
930 false
931 },
932 RotationState::Idle => false,
933 };
934
935 let Some(external_set) = Self::external_validator_set() else {
936 // Nothing is returned, so nothing is recorded. Without a stored set there is
937 // nothing to remove, but a set that no longer decodes leaves its collators behind.
938 DrawnCollators::<T>::kill();
939 Self::deposit_event(Event::NothingToDraw);
940 return None;
941 };
942 let (era, external_len) = (external_set.era, external_set.validators.len() as u32);
943
944 // Drawn and filtered at the rotation, which pallet-session weighs as the whole block,
945 // since the key reads may not fit the weight of the message or report that delivers
946 // the set.
947 let collators: Vec<_> = match new_external {
948 // a new set or cap: draw again, from the validators with keys.
949 true => Self::draw_collators(external_set, MaxCollators::<T>::get().limit()),
950 // nothing new: the last draw, without those that removed their keys since.
951 false => match DrawnCollators::<T>::get() {
952 Some(prev) => prev
953 .collators
954 .into_iter()
955 .filter(T::ValidatorRegistration::is_registered)
956 .collect(),
957 None => {
958 Self::deposit_event(Event::Unexpected(UnexpectedKind::NoPreviousDrawSet));
959 return None;
960 },
961 },
962 };
963 // At most the length of the set, which is bounded by `MaxValidators`.
964 let collators = BoundedVec::truncate_from(collators);
965
966 Self::deposit_event(Event::CollatorsDrawn {
967 era,
968 external_len,
969 drawn_len: collators.len() as u32,
970 new_external,
971 });
972 DrawnCollators::<T>::put(EraCollators { era, collators: collators.clone() });
973 Some(collators.into_inner())
974 }
975
976 fn start_session(_: SessionIndex) {}
977
978 fn end_session(_: SessionIndex) {}
979 }
980
981 impl<T: Config> ShouldEndSession<BlockNumberFor<T>> for Pallet<T> {
982 fn should_end_session(now: BlockNumberFor<T>) -> bool {
983 PendingRotation::<T>::get() != RotationState::Idle ||
984 T::PeriodicSession::should_end_session(now)
985 }
986 }
987
988 impl<T: Config> pallet_authorship::EventHandler<T::AccountId, BlockNumberFor<T>> for Pallet<T> {
989 /// Counts the block for `author` in [`AuthoredBlocks`].
990 fn note_author(author: T::AccountId) {
991 frame_system::Pallet::<T>::register_extra_weight_unchecked(
992 T::WeightInfo::note_author(),
993 DispatchClass::Mandatory,
994 );
995 AuthoredBlocks::<T>::mutate(author, |blocks| blocks.saturating_inc());
996 }
997 }
998
999 impl<T: Config> OnSystemEvent for Pallet<T> {
1000 fn on_validation_data(_: &PersistedValidationData) {}
1001
1002 fn on_validation_code_applied() {}
1003
1004 /// Caches the relay chain randomness of one epoch ago in [`EpochRandomness`].
1005 ///
1006 /// A proof that shows the key absent caches a zero value. A proof that lacks the trie nodes
1007 /// of the key, or holds a value that does not decode, panics and so makes the block
1008 /// invalid.
1009 fn on_relay_state_proof(relay_state_proof: &RelayChainStateProof) -> Weight {
1010 let randomness = match relay_state_proof
1011 .read_entry::<[u8; 32]>(well_known_keys::ONE_EPOCH_AGO_RANDOMNESS, None)
1012 {
1013 Ok(randomness) => randomness,
1014 // No randomness on the relay chain, as before its first epoch change, is cached as
1015 // the zero value a draw without randomness uses.
1016 Err(RelayProofError::ReadEntry(ReadEntryErr::Absent)) => {
1017 log::debug!(
1018 target: crate::LOG_TARGET,
1019 "the relay chain state proof shows no epoch randomness, caching a zero value"
1020 );
1021 [0; 32]
1022 },
1023 Err(RelayProofError::ReadEntry(
1024 error @ (ReadEntryErr::Proof | ReadEntryErr::Decode),
1025 )) => panic!(
1026 "Invalid relay chain epoch randomness in the relay chain state proof: {error:?}"
1027 ),
1028 // `read_entry` returns only `ReadEntry` errors.
1029 Err(error) => panic!("Invalid relay chain state proof: {error:?}"),
1030 };
1031 if EpochRandomness::<T>::get() != Some(randomness) {
1032 EpochRandomness::<T>::put(randomness);
1033 }
1034 T::WeightInfo::on_relay_state_proof()
1035 }
1036 }
1037}