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

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

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

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

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

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

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

            
51
    use {
52
        frame_support::{
53
            dispatch::DispatchResultWithPostInfo,
54
            pallet_prelude::*,
55
            traits::{EnsureOrigin, ValidatorRegistration},
56
            BoundedVec, DefaultNoBound,
57
        },
58
        frame_system::pallet_prelude::*,
59
        pallet_session::SessionManager,
60
        sp_runtime::traits::Convert,
61
        sp_staking::SessionIndex,
62
        sp_std::vec::Vec,
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
41959
    #[pallet::pallet]
101
    #[pallet::storage_version(STORAGE_VERSION)]
102
    pub struct Pallet<T>(_);
103

            
104
    /// The invulnerable, permissioned collators.
105
103264
    #[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
314
    #[pallet::genesis_build]
116
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
117
318
        fn build(&self) {
118
318
            let duplicate_invulnerables = self
119
318
                .invulnerables
120
318
                .iter()
121
318
                .collect::<sp_std::collections::btree_set::BTreeSet<_>>();
122
318
            assert!(
123
318
                duplicate_invulnerables.len() == self.invulnerables.len(),
124
                "duplicate invulnerables in genesis."
125
            );
126

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

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

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

            
144
28
    #[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
468
    #[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
        pub fn add_invulnerable(
168
            origin: OriginFor<T>,
169
            who: T::AccountId,
170
58
        ) -> DispatchResultWithPostInfo {
171
58
            T::UpdateOrigin::ensure_origin(origin)?;
172
            // don't let one unprepared collator ruin things for everyone.
173
57
            let maybe_collator_id = T::CollatorIdOf::convert(who.clone())
174
57
                .filter(T::CollatorRegistration::is_registered);
175

            
176
57
            let collator_id = maybe_collator_id.ok_or(Error::<T>::NoKeysRegistered)?;
177

            
178
56
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
179
56
                if invulnerables.contains(&collator_id) {
180
7
                    Err(Error::<T>::AlreadyInvulnerable)?;
181
49
                }
182
49
                invulnerables
183
49
                    .try_push(collator_id.clone())
184
49
                    .map_err(|_| Error::<T>::TooManyInvulnerables)?;
185
48
                Ok(())
186
56
            })?;
187

            
188
48
            Self::deposit_event(Event::InvulnerableAdded { account_id: who });
189
48

            
190
48
            let weight_used = T::WeightInfo::add_invulnerable(
191
48
                Invulnerables::<T>::decode_len()
192
48
                    .unwrap_or_default()
193
48
                    .try_into()
194
48
                    .unwrap_or(T::MaxInvulnerables::get().saturating_sub(1)),
195
48
            );
196
48

            
197
48
            Ok(Some(weight_used).into())
198
        }
199

            
200
        /// Remove an account `who` from the list of `Invulnerables` collators.
201
        ///
202
        /// The origin for this call must be the `UpdateOrigin`.
203
        #[pallet::call_index(2)]
204
        #[pallet::weight(T::WeightInfo::remove_invulnerable(T::MaxInvulnerables::get()))]
205
83
        pub fn remove_invulnerable(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
206
83
            T::UpdateOrigin::ensure_origin(origin)?;
207

            
208
82
            let collator_id = T::CollatorIdOf::convert(who.clone())
209
82
                .ok_or(Error::<T>::UnableToDeriveCollatorId)?;
210

            
211
82
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
212
82
                let pos = invulnerables
213
82
                    .iter()
214
87
                    .position(|x| x == &collator_id)
215
82
                    .ok_or(Error::<T>::NotInvulnerable)?;
216
81
                invulnerables.remove(pos);
217
81
                Ok(())
218
82
            })?;
219

            
220
81
            Self::deposit_event(Event::InvulnerableRemoved { account_id: who });
221
81
            Ok(())
222
        }
223
    }
224

            
225
    impl<T: Config> Pallet<T> {
226
3225
        pub fn invulnerables() -> BoundedVec<T::CollatorId, T::MaxInvulnerables> {
227
3225
            Invulnerables::<T>::get()
228
3225
        }
229
    }
230

            
231
    /// Play the role of the session manager.
232
    impl<T: Config> SessionManager<T::CollatorId> for Pallet<T> {
233
12
        fn new_session(index: SessionIndex) -> Option<Vec<T::CollatorId>> {
234
12
            log::info!(
235
                "assembling new invulnerable collators for new session {} at #{:?}",
236
                index,
237
                <frame_system::Pallet<T>>::block_number(),
238
            );
239

            
240
12
            let invulnerables = Self::invulnerables().to_vec();
241
12
            frame_system::Pallet::<T>::register_extra_weight_unchecked(
242
12
                T::WeightInfo::new_session(invulnerables.len() as u32),
243
12
                DispatchClass::Mandatory,
244
12
            );
245
12
            Some(invulnerables)
246
12
        }
247
6
        fn start_session(_: SessionIndex) {
248
6
            // we don't care.
249
6
        }
250
        fn end_session(_: SessionIndex) {
251
            // we don't care.
252
        }
253
    }
254
}
255

            
256
/// If the rewarded account is an Invulnerable, distribute the entire reward
257
/// amount to them. Otherwise use the `Fallback` distribution.
258
pub struct InvulnerableRewardDistribution<Runtime, Currency, Fallback>(
259
    PhantomData<(Runtime, Currency, Fallback)>,
260
);
261

            
262
use {frame_support::pallet_prelude::Weight, sp_runtime::traits::Get};
263

            
264
type CreditOf<Runtime, Currency> =
265
    frame_support::traits::fungible::Credit<<Runtime as frame_system::Config>::AccountId, Currency>;
266
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
267

            
268
impl<Runtime, Currency, Fallback>
269
    tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>
270
    for InvulnerableRewardDistribution<Runtime, Currency, Fallback>
271
where
272
    Runtime: frame_system::Config + Config,
273
    Fallback: tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>,
274
    Currency: frame_support::traits::fungible::Balanced<AccountIdOf<Runtime>>,
275
{
276
44483
    fn distribute_rewards(
277
44483
        rewarded: AccountIdOf<Runtime>,
278
44483
        amount: CreditOf<Runtime, Currency>,
279
44483
    ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
280
44483
        let mut total_weight = Weight::zero();
281
44483
        let collator_id = Runtime::CollatorIdOf::convert(rewarded.clone())
282
44483
            .ok_or(Error::<Runtime>::UnableToDeriveCollatorId)?;
283
        // weight to read invulnerables
284
44483
        total_weight += Runtime::DbWeight::get().reads(1);
285
44483
        if !Invulnerables::<Runtime>::get().contains(&collator_id) {
286
1061
            let post_info = Fallback::distribute_rewards(rewarded, amount)?;
287
1028
            if let Some(weight) = post_info.actual_weight {
288
1002
                total_weight += weight;
289
1028
            }
290
        } else {
291
43422
            Currency::resolve(&rewarded, amount).map_err(|_| TokenError::NotExpendable)?;
292
43422
            total_weight +=
293
43422
                Runtime::WeightInfo::reward_invulnerable(Runtime::MaxInvulnerables::get())
294
        }
295
44450
        Ok(Some(total_weight).into())
296
44483
    }
297
}