1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
//! Invulnerables pallet.
18
//!
19
//! A pallet to manage invulnerable collators in a parachain.
20
//!
21
//! ## Terminology
22
//!
23
//! - Collator: A parachain block producer.
24
//! - Invulnerable: An account appointed by governance and guaranteed to be in the collator set.
25

            
26
#![cfg_attr(not(feature = "std"), no_std)]
27
extern crate alloc;
28

            
29
pub use pallet::*;
30
use {
31
    core::marker::PhantomData,
32
    sp_runtime::{traits::Convert, TokenError},
33
};
34

            
35
#[cfg(test)]
36
mod mock;
37

            
38
#[cfg(test)]
39
mod tests;
40

            
41
#[cfg(feature = "runtime-benchmarks")]
42
mod benchmarking;
43
pub mod weights;
44

            
45
8736
#[frame_support::pallet]
46
pub mod pallet {
47
    pub use crate::weights::WeightInfo;
48

            
49
    #[cfg(feature = "runtime-benchmarks")]
50
    use frame_support::traits::Currency;
51

            
52
    use {
53
        alloc::vec::Vec,
54
        frame_support::{
55
            pallet_prelude::*,
56
            traits::{EnsureOrigin, ValidatorRegistration},
57
            BoundedVec, DefaultNoBound,
58
        },
59
        frame_system::pallet_prelude::*,
60
        pallet_session::SessionManager,
61
        sp_runtime::traits::Convert,
62
        sp_staking::SessionIndex,
63
    };
64

            
65
    /// The current storage version.
66
    const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
67

            
68
    /// Configure the pallet by specifying the parameters and types on which it depends.
69
    #[pallet::config]
70
    pub trait Config: frame_system::Config {
71
        /// Overarching event type.
72
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
73

            
74
        /// Origin that can dictate updating parameters of this pallet.
75
        type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
76

            
77
        /// Maximum number of invulnerables.
78
        #[pallet::constant]
79
        type MaxInvulnerables: Get<u32>;
80

            
81
        /// A stable ID for a collator.
82
        type CollatorId: Member + Parameter + MaybeSerializeDeserialize + MaxEncodedLen + Ord;
83

            
84
        /// A conversion from account ID to collator ID.
85
        ///
86
        /// Its cost must be at most one storage read.
87
        type CollatorIdOf: Convert<Self::AccountId, Option<Self::CollatorId>>;
88

            
89
        /// Validate a user is registered
90
        type CollatorRegistration: ValidatorRegistration<Self::CollatorId>;
91

            
92
        /// The weight information of this pallet.
93
        type WeightInfo: WeightInfo;
94

            
95
        #[cfg(feature = "runtime-benchmarks")]
96
        type Currency: Currency<Self::AccountId>
97
            + frame_support::traits::fungible::Balanced<Self::AccountId>;
98
    }
99

            
100
69439
    #[pallet::pallet]
101
    #[pallet::storage_version(STORAGE_VERSION)]
102
    pub struct Pallet<T>(_);
103

            
104
    /// The invulnerable, permissioned collators.
105
124990
    #[pallet::storage]
106
    pub type Invulnerables<T: Config> =
107
        StorageValue<_, BoundedVec<T::CollatorId, T::MaxInvulnerables>, ValueQuery>;
108

            
109
    #[pallet::genesis_config]
110
    #[derive(DefaultNoBound)]
111
    pub struct GenesisConfig<T: Config> {
112
        pub invulnerables: Vec<T::CollatorId>,
113
    }
114

            
115
351
    #[pallet::genesis_build]
116
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
117
1132
        fn build(&self) {
118
1132
            let duplicate_invulnerables = self
119
1132
                .invulnerables
120
1132
                .iter()
121
1132
                .collect::<alloc::collections::btree_set::BTreeSet<_>>();
122
1132
            assert!(
123
1132
                duplicate_invulnerables.len() == self.invulnerables.len(),
124
                "duplicate invulnerables in genesis."
125
            );
126

            
127
1132
            let bounded_invulnerables =
128
1132
                BoundedVec::<_, T::MaxInvulnerables>::try_from(self.invulnerables.clone())
129
1132
                    .expect("genesis invulnerables are more than T::MaxInvulnerables");
130
1132

            
131
1132
            <Invulnerables<T>>::put(bounded_invulnerables);
132
1132
        }
133
    }
134

            
135
624
    #[pallet::event]
136
204
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
137
    pub enum Event<T: Config> {
138
        /// A new Invulnerable was added.
139
        InvulnerableAdded { account_id: T::AccountId },
140
        /// An Invulnerable was removed.
141
        InvulnerableRemoved { account_id: T::AccountId },
142
    }
143

            
144
624
    #[pallet::error]
145
    pub enum Error<T> {
146
        /// There are too many Invulnerables.
147
        TooManyInvulnerables,
148
        /// Account is already an Invulnerable.
149
        AlreadyInvulnerable,
150
        /// Account is not an Invulnerable.
151
        NotInvulnerable,
152
        /// Account does not have keys registered
153
        NoKeysRegistered,
154
        /// Unable to derive collator id from account id
155
        UnableToDeriveCollatorId,
156
    }
157

            
158
624
    #[pallet::call]
159
    impl<T: Config> Pallet<T> {
160
        /// Add a new account `who` to the list of `Invulnerables` collators.
161
        ///
162
        /// The origin for this call must be the `UpdateOrigin`.
163
        #[pallet::call_index(1)]
164
        #[pallet::weight(T::WeightInfo::add_invulnerable(
165
			T::MaxInvulnerables::get().saturating_sub(1),
166
		))]
167
        #[allow(clippy::useless_conversion)]
168
121
        pub fn add_invulnerable(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
169
121
            T::UpdateOrigin::ensure_origin(origin)?;
170
            // don't let one unprepared collator ruin things for everyone.
171
120
            let maybe_collator_id = T::CollatorIdOf::convert(who.clone())
172
120
                .filter(T::CollatorRegistration::is_registered);
173

            
174
120
            let collator_id = maybe_collator_id.ok_or(Error::<T>::NoKeysRegistered)?;
175

            
176
119
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
177
119
                if invulnerables.contains(&collator_id) {
178
13
                    Err(Error::<T>::AlreadyInvulnerable)?;
179
106
                }
180
106
                invulnerables
181
106
                    .try_push(collator_id.clone())
182
106
                    .map_err(|_| Error::<T>::TooManyInvulnerables)?;
183
105
                Ok(())
184
119
            })?;
185

            
186
105
            Self::deposit_event(Event::InvulnerableAdded { account_id: who });
187
105

            
188
105
            Ok(())
189
        }
190

            
191
        /// Remove an account `who` from the list of `Invulnerables` collators.
192
        ///
193
        /// The origin for this call must be the `UpdateOrigin`.
194
        #[pallet::call_index(2)]
195
        #[pallet::weight(T::WeightInfo::remove_invulnerable(T::MaxInvulnerables::get()))]
196
101
        pub fn remove_invulnerable(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
197
101
            T::UpdateOrigin::ensure_origin(origin)?;
198

            
199
100
            let collator_id = T::CollatorIdOf::convert(who.clone())
200
100
                .ok_or(Error::<T>::UnableToDeriveCollatorId)?;
201

            
202
100
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
203
100
                let pos = invulnerables
204
100
                    .iter()
205
121
                    .position(|x| x == &collator_id)
206
100
                    .ok_or(Error::<T>::NotInvulnerable)?;
207
99
                invulnerables.remove(pos);
208
99
                Ok(())
209
100
            })?;
210

            
211
99
            Self::deposit_event(Event::InvulnerableRemoved { account_id: who });
212
99
            Ok(())
213
        }
214
    }
215

            
216
    impl<T: Config> Pallet<T> {
217
5590
        pub fn invulnerables() -> BoundedVec<T::CollatorId, T::MaxInvulnerables> {
218
5590
            Invulnerables::<T>::get()
219
5590
        }
220
    }
221

            
222
    /// Play the role of the session manager.
223
    impl<T: Config> SessionManager<T::CollatorId> for Pallet<T> {
224
12
        fn new_session(index: SessionIndex) -> Option<Vec<T::CollatorId>> {
225
12
            log::info!(
226
                "assembling new invulnerable collators for new session {} at #{:?}",
227
                index,
228
                <frame_system::Pallet<T>>::block_number(),
229
            );
230

            
231
12
            let invulnerables = Self::invulnerables().to_vec();
232
12
            frame_system::Pallet::<T>::register_extra_weight_unchecked(
233
12
                T::WeightInfo::new_session(invulnerables.len() as u32),
234
12
                DispatchClass::Mandatory,
235
12
            );
236
12
            Some(invulnerables)
237
12
        }
238
6
        fn start_session(_: SessionIndex) {
239
6
            // we don't care.
240
6
        }
241
        fn end_session(_: SessionIndex) {
242
            // we don't care.
243
        }
244
    }
245
}
246

            
247
/// If the rewarded account is an Invulnerable, distribute the entire reward
248
/// amount to them. Otherwise use the `Fallback` distribution.
249
pub struct InvulnerableRewardDistribution<Runtime, Currency, Fallback>(
250
    PhantomData<(Runtime, Currency, Fallback)>,
251
);
252

            
253
use {frame_support::pallet_prelude::Weight, sp_runtime::traits::Get};
254

            
255
type CreditOf<Runtime, Currency> =
256
    frame_support::traits::fungible::Credit<<Runtime as frame_system::Config>::AccountId, Currency>;
257
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
258

            
259
impl<Runtime, Currency, Fallback>
260
    tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>
261
    for InvulnerableRewardDistribution<Runtime, Currency, Fallback>
262
where
263
    Runtime: frame_system::Config + Config,
264
    Fallback: tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>,
265
    Currency: frame_support::traits::fungible::Balanced<AccountIdOf<Runtime>>,
266
{
267
50182
    fn distribute_rewards(
268
50182
        rewarded: AccountIdOf<Runtime>,
269
50182
        amount: CreditOf<Runtime, Currency>,
270
50182
    ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
271
50182
        let mut total_weight = Weight::zero();
272
50182
        let collator_id = Runtime::CollatorIdOf::convert(rewarded.clone())
273
50182
            .ok_or(Error::<Runtime>::UnableToDeriveCollatorId)?;
274
        // weight to read invulnerables
275
50182
        total_weight.saturating_accrue(Runtime::DbWeight::get().reads(1));
276
50182
        if !Invulnerables::<Runtime>::get().contains(&collator_id) {
277
1115
            let post_info = Fallback::distribute_rewards(rewarded, amount)?;
278
1082
            if let Some(weight) = post_info.actual_weight {
279
1056
                total_weight.saturating_accrue(weight);
280
1082
            }
281
        } else {
282
49067
            Currency::resolve(&rewarded, amount).map_err(|_| TokenError::NotExpendable)?;
283
49067
            total_weight.saturating_accrue(Runtime::WeightInfo::reward_invulnerable(
284
49067
                Runtime::MaxInvulnerables::get(),
285
49067
            ))
286
        }
287
50149
        Ok(Some(total_weight).into())
288
50182
    }
289
}