referrerpolicy=no-referrer-when-downgrade

pallet_session/historical/
onchain.rs

1// This file is part of Substrate.
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
18//! On-chain logic to store a validator-set for deferred validation using an off-chain worker.
19
20use alloc::vec::Vec;
21use codec::Encode;
22use sp_runtime::traits::Convert;
23
24use super::{shared, Config as HistoricalConfig};
25use crate::{Config as SessionConfig, Pallet as SessionModule, SessionIndex};
26
27/// Store the validator-set associated to the `session_index` to the off-chain database.
28///
29/// Further processing is then done [`off-chain side`](super::offchain).
30///
31/// **Must** be called from on-chain, i.e. a call that originates from
32/// `on_initialize(..)` or `on_finalization(..)`.
33/// **Must** be called during the session, which validator-set is to be stored for further
34/// off-chain processing. Otherwise the `FullIdentification` might not be available.
35pub fn store_session_validator_set_to_offchain<T: HistoricalConfig + SessionConfig>(
36	session_index: SessionIndex,
37) {
38	let encoded_validator_list = <SessionModule<T>>::validators()
39		.into_iter()
40		.filter_map(|validator_id: <T as SessionConfig>::ValidatorId| {
41			let full_identification =
42				<<T as HistoricalConfig>::FullIdentificationOf>::convert(validator_id.clone());
43			full_identification.map(|full_identification| (validator_id, full_identification))
44		})
45		.collect::<Vec<_>>();
46
47	encoded_validator_list.using_encoded(|encoded_validator_list| {
48		let derived_key = shared::derive_key(shared::PREFIX, session_index);
49		sp_io::offchain_index::set(derived_key.as_slice(), encoded_validator_list);
50	});
51}
52
53/// Store the validator set associated to the _current_ session index to the off-chain database.
54///
55/// See [`store_session_validator_set_to_offchain`]
56/// for further information and restrictions.
57pub fn store_current_session_validator_set_to_offchain<T: HistoricalConfig + SessionConfig>() {
58	store_session_validator_set_to_offchain::<T>(<SessionModule<T>>::current_index());
59}