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
//! Substrate core types around sessions.
19

            
20
#![cfg_attr(not(feature = "std"), no_std)]
21

            
22
extern crate alloc;
23

            
24
use codec::{Decode, Encode};
25

            
26
#[cfg(feature = "std")]
27
use sp_api::ProvideRuntimeApi;
28
#[cfg(feature = "std")]
29
use sp_runtime::traits::Block as BlockT;
30

            
31
use alloc::vec::Vec;
32
use sp_core::RuntimeDebug;
33
use sp_staking::SessionIndex;
34

            
35
pub mod runtime_api;
36
pub use runtime_api::*;
37

            
38
/// Number of validators in a given session.
39
pub type ValidatorCount = u32;
40

            
41
/// Proof of membership of a specific key in a given session.
42
#[derive(Encode, Decode, Clone, Eq, PartialEq, Default, RuntimeDebug, scale_info::TypeInfo)]
43
pub struct MembershipProof {
44
	/// The session index on which the specific key is a member.
45
	pub session: SessionIndex,
46
	/// Trie nodes of a merkle proof of session membership.
47
	pub trie_nodes: Vec<Vec<u8>>,
48
	/// The validator count of the session on which the specific key is a member.
49
	pub validator_count: ValidatorCount,
50
}
51

            
52
/// A utility trait to get a session number. This is implemented for
53
/// `MembershipProof` below to fetch the session number the given session
54
/// membership proof is for. It is useful when we need to deal with key owner
55
/// proofs generically (i.e. just typing against the `KeyOwnerProofSystem`
56
/// trait) but still restrict their capabilities.
57
pub trait GetSessionNumber {
58
	fn session(&self) -> SessionIndex;
59
}
60

            
61
/// A utility trait to get the validator count of a given session. This is
62
/// implemented for `MembershipProof` below and fetches the number of validators
63
/// in the session the membership proof is for. It is useful when we need to
64
/// deal with key owner proofs generically (i.e. just typing against the
65
/// `KeyOwnerProofSystem` trait) but still restrict their capabilities.
66
pub trait GetValidatorCount {
67
	fn validator_count(&self) -> ValidatorCount;
68
}
69

            
70
impl GetSessionNumber for sp_core::Void {
71
	fn session(&self) -> SessionIndex {
72
		Default::default()
73
	}
74
}
75

            
76
impl GetValidatorCount for sp_core::Void {
77
	fn validator_count(&self) -> ValidatorCount {
78
		Default::default()
79
	}
80
}
81

            
82
impl GetSessionNumber for MembershipProof {
83
2034
	fn session(&self) -> SessionIndex {
84
2034
		self.session
85
2034
	}
86
}
87

            
88
impl GetValidatorCount for MembershipProof {
89
7704
	fn validator_count(&self) -> ValidatorCount {
90
7704
		self.validator_count
91
7704
	}
92
}
93

            
94
/// Generate the initial session keys with the given seeds, at the given block and store them in
95
/// the client's keystore.
96
#[cfg(feature = "std")]
97
pub fn generate_initial_session_keys<Block, T>(
98
	client: std::sync::Arc<T>,
99
	at: Block::Hash,
100
	seeds: Vec<String>,
101
	keystore: sp_keystore::KeystorePtr,
102
) -> Result<(), sp_api::ApiError>
103
where
104
	Block: BlockT,
105
	T: ProvideRuntimeApi<Block>,
106
	T::Api: SessionKeys<Block>,
107
{
108
	use sp_api::ApiExt;
109

            
110
	if seeds.is_empty() {
111
		return Ok(())
112
	}
113

            
114
	let mut runtime_api = client.runtime_api();
115

            
116
	runtime_api.register_extension(sp_keystore::KeystoreExt::from(keystore));
117

            
118
	for seed in seeds {
119
		runtime_api.generate_session_keys(at, Some(seed.as_bytes().to_vec()))?;
120
	}
121

            
122
	Ok(())
123
}