pallet_people/types.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//! Types for Proof-of-Personhood system.
19
20#![allow(clippy::result_unit_err)]
21
22use super::*;
23use frame_support::{pallet_prelude::*, DefaultNoBound};
24
25pub type RevisionIndex = u32;
26pub type PageIndex = u32;
27pub type KeyCount = u64;
28
29pub type MemberOf<T> = <<T as Config>::Crypto as GenerateVerifiable>::Member;
30pub type MembersOf<T> = <<T as Config>::Crypto as GenerateVerifiable>::Members;
31pub type IntermediateOf<T> = <<T as Config>::Crypto as GenerateVerifiable>::Intermediate;
32pub type SecretOf<T> = <<T as Config>::Crypto as GenerateVerifiable>::Secret;
33pub type SignatureOf<T> = <<T as Config>::Crypto as GenerateVerifiable>::Signature;
34pub type ChunksOf<T> = BoundedVec<
35 <<T as Config>::Crypto as GenerateVerifiable>::StaticChunk,
36 <T as Config>::ChunkPageSize,
37>;
38
39/// The overarching state of all people rings regarding the actions that are currently allowed to be
40/// performed on them.
41#[derive(
42 Clone,
43 PartialEq,
44 Eq,
45 Debug,
46 Default,
47 Encode,
48 Decode,
49 MaxEncodedLen,
50 TypeInfo,
51 DecodeWithMemTracking,
52)]
53pub enum RingMembersState {
54 /// The rings can accept new people sequentially if the maximum capacity has not been reached
55 /// yet. Ring building is permitted in this state by building the ring roots on top of
56 /// previously computed roots. In case a ring suffered mutations that invalidated a previous
57 /// ring root through the removal of an included member, the existing ring root will be removed
58 /// and ring building will start from scratch.
59 #[default]
60 AppendOnly,
61 /// A semaphore counting the number of entities making changes to the ring members list which
62 /// require the entire ring to be rebuilt. Whenever a DIM would want to suspend
63 /// people, it would first need to increment this counter and then start submitting the
64 /// suspended indices. After all indices are registered, the counter is decremented. Ring
65 /// merges are allowed only when no entity is allowed to suspend keys and the counter is 0.
66 Mutating(u8),
67 /// After mutations to the member set, any pending key migrations are enacted before the new
68 /// ring roots will be built in order to reflect the latest changes in state.
69 KeyMigration,
70}
71
72impl RingMembersState {
73 /// Returns whether the state allows only incremental additions to rings and their roots.
74 pub fn append_only(&self) -> bool {
75 matches!(self, Self::AppendOnly)
76 }
77
78 /// Returns whether the state allows mutating the member set of rings.
79 pub fn mutating(&self) -> bool {
80 matches!(self, Self::Mutating(_))
81 }
82
83 /// Returns whether the state allows the pending key migrations to be enacted.
84 pub fn key_migration(&self) -> bool {
85 matches!(self, Self::KeyMigration)
86 }
87
88 /// Move to a mutation state.
89 pub fn start_mutation_session(self) -> Result<Self, ()> {
90 match self {
91 Self::AppendOnly => Ok(Self::Mutating(1)),
92 Self::Mutating(n) => Ok(Self::Mutating(n.checked_add(1).ok_or(())?)),
93 Self::KeyMigration => Err(()),
94 }
95 }
96
97 /// Move out of a mutation state.
98 pub fn end_mutation_session(self) -> Result<Self, ()> {
99 match self {
100 Self::AppendOnly => Err(()),
101 Self::Mutating(1) => Ok(Self::KeyMigration),
102 Self::Mutating(n) => Ok(Self::Mutating(n.saturating_sub(1))),
103 Self::KeyMigration => Err(()),
104 }
105 }
106
107 /// Move out of a key migration state.
108 pub fn end_key_migration(self) -> Result<Self, ()> {
109 match self {
110 Self::KeyMigration => Ok(Self::AppendOnly),
111 _ => Err(()),
112 }
113 }
114}
115
116/// A contextual alias [`ContextualAlias`] used in a specific ring revision.
117///
118/// The revision can be used to tell in the future if an alias may have been suspended.
119/// For instance, if a person is suspended, then ring will get revised, the revised alias with the
120/// old revision shows that the alias may not be owned by a valid person anymore.
121#[derive(
122 Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking,
123)]
124pub struct RevisedContextualAlias {
125 pub revision: RevisionIndex,
126 pub ring: RingIndex,
127 pub ca: ContextualAlias,
128}
129
130/// An alias [`Alias`] used in a specific ring revision.
131///
132/// The revision can be used to tell in the future if an alias may have been suspended.
133/// For instance, if a person is suspended, then ring will get revised, the revised alias with the
134/// old revision shows that the alias may not be owned by a valid person anymore.
135#[derive(Clone, PartialEq, Eq, Debug, Encode, Decode, MaxEncodedLen, TypeInfo)]
136pub struct RevisedAlias {
137 pub revision: RevisionIndex,
138 pub ring: RingIndex,
139 pub alias: Alias,
140}
141
142#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
143#[scale_info(skip_type_params(T))]
144pub struct RingRoot<T: Config> {
145 /// The ring root for the current ring.
146 pub root: MembersOf<T>,
147 /// The revision index of the ring.
148 pub revision: RevisionIndex,
149 /// An intermediate value if the ring is not full.
150 pub intermediate: IntermediateOf<T>,
151}
152
153#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, DefaultNoBound)]
154#[scale_info(skip_type_params(T))]
155/// Information about the current key inclusion status in a ring.
156pub struct RingStatus {
157 /// The number of keys in the ring.
158 pub total: u32,
159 /// The number of keys that have already been baked in.
160 pub included: u32,
161}
162
163/// The state of a person's key within the pallet along with its position in relevant structures.
164///
165/// Differentiates between individuals included in a ring, those being onboarded and the suspended
166/// ones. For those already included, provides ring index and position in it. For those being
167/// onboarded, provides queue page index and position in the queue.
168#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
169pub enum RingPosition {
170 /// Coordinates within the onboarding queue for a person that doesn't belong to a ring yet.
171 Onboarding { queue_page: PageIndex },
172 /// Coordinates within the rings for a person that was registered.
173 Included { ring_index: RingIndex, ring_position: u32, scheduled_for_removal: bool },
174 /// The person is suspended and isn't part of any ring or onboarding queue page.
175 Suspended,
176}
177
178impl RingPosition {
179 /// Returns whether the person is suspended and has no position.
180 pub fn suspended(&self) -> bool {
181 matches!(self, Self::Suspended)
182 }
183
184 /// Returns whether the person is included in a ring and is scheduled for removal.
185 pub fn scheduled_for_removal(&self) -> bool {
186 match &self {
187 Self::Included { scheduled_for_removal, .. } => *scheduled_for_removal,
188 _ => false,
189 }
190 }
191
192 /// Returns the index of the ring if this person is included.
193 pub fn ring_index(&self) -> Option<RingIndex> {
194 match &self {
195 Self::Included { ring_index, .. } => Some(*ring_index),
196 _ => None,
197 }
198 }
199}
200
201/// Record of personhood.
202#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
203pub struct PersonRecord<Member, AccountId> {
204 // The key used for the person.
205 pub key: Member,
206 // The position identifier of the key.
207 pub position: RingPosition,
208 /// An optional privileged account that can send transaction on the behalf of the person.
209 pub account: Option<AccountId>,
210}
211
212/// Describes the action to take after checking the first two pages of the onboarding queue for a
213/// potential merge.
214#[derive(PartialEq, Eq, Clone, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
215#[scale_info(skip_type_params(T))]
216pub(crate) enum QueueMergeAction<T: Config> {
217 Merge {
218 initial_head: PageIndex,
219 new_head: PageIndex,
220 first_key_page: BoundedVec<MemberOf<T>, T::OnboardingQueuePageSize>,
221 second_key_page: BoundedVec<MemberOf<T>, T::OnboardingQueuePageSize>,
222 },
223 NoAction,
224}