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
#[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
    /// A convertor from collators id. Since this pallet does not have stash/controller, this is
69
    /// just identity.
70
    pub struct IdentityCollator;
71
    impl<T> sp_runtime::traits::Convert<T, Option<T>> for IdentityCollator {
72
16824
        fn convert(t: T) -> Option<T> {
73
16824
            Some(t)
74
16824
        }
75
    }
76

            
77
    /// Configure the pallet by specifying the parameters and types on which it depends.
78
    #[pallet::config]
79
    pub trait Config: frame_system::Config {
80
        /// Overarching event type.
81
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
82

            
83
        /// Origin that can dictate updating parameters of this pallet.
84
        type UpdateOrigin: EnsureOrigin<Self::RuntimeOrigin>;
85

            
86
        /// Maximum number of invulnerables.
87
        #[pallet::constant]
88
        type MaxInvulnerables: Get<u32>;
89

            
90
        /// A stable ID for a collator.
91
        type CollatorId: Member + Parameter + MaybeSerializeDeserialize + MaxEncodedLen + Ord;
92

            
93
        /// A conversion from account ID to collator ID.
94
        ///
95
        /// Its cost must be at most one storage read.
96
        type CollatorIdOf: Convert<Self::AccountId, Option<Self::CollatorId>>;
97

            
98
        /// Validate a user is registered
99
        type CollatorRegistration: ValidatorRegistration<Self::CollatorId>;
100

            
101
        /// The weight information of this pallet.
102
        type WeightInfo: WeightInfo;
103

            
104
        #[cfg(feature = "runtime-benchmarks")]
105
        type Currency: Currency<Self::AccountId>
106
            + frame_support::traits::fungible::Balanced<Self::AccountId>;
107
    }
108

            
109
13623
    #[pallet::pallet]
110
    #[pallet::storage_version(STORAGE_VERSION)]
111
    pub struct Pallet<T>(_);
112

            
113
    /// The invulnerable, permissioned collators. This list must be sorted.
114
46191
    #[pallet::storage]
115
    #[pallet::getter(fn invulnerables)]
116
    pub type Invulnerables<T: Config> =
117
        StorageValue<_, BoundedVec<T::CollatorId, T::MaxInvulnerables>, ValueQuery>;
118

            
119
    #[pallet::genesis_config]
120
    #[derive(DefaultNoBound)]
121
    pub struct GenesisConfig<T: Config> {
122
        pub invulnerables: Vec<T::CollatorId>,
123
    }
124

            
125
512
    #[pallet::genesis_build]
126
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
127
259
        fn build(&self) {
128
259
            let duplicate_invulnerables = self
129
259
                .invulnerables
130
259
                .iter()
131
259
                .collect::<sp_std::collections::btree_set::BTreeSet<_>>();
132
259
            assert!(
133
259
                duplicate_invulnerables.len() == self.invulnerables.len(),
134
                "duplicate invulnerables in genesis."
135
            );
136

            
137
259
            let bounded_invulnerables =
138
259
                BoundedVec::<_, T::MaxInvulnerables>::try_from(self.invulnerables.clone())
139
259
                    .expect("genesis invulnerables are more than T::MaxInvulnerables");
140
259

            
141
259
            <Invulnerables<T>>::put(bounded_invulnerables);
142
259
        }
143
    }
144

            
145
    #[pallet::event]
146
76
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
147
    pub enum Event<T: Config> {
148
        /// New Invulnerables were set.
149
        NewInvulnerables { invulnerables: Vec<T::CollatorId> },
150
3
        /// A new Invulnerable was added.
151
        InvulnerableAdded { account_id: T::AccountId },
152
1
        /// An Invulnerable was removed.
153
        InvulnerableRemoved { account_id: T::AccountId },
154
        /// An account was unable to be added to the Invulnerables because they did not have keys
155
        /// registered. Other Invulnerables may have been set.
156
        InvalidInvulnerableSkipped { account_id: T::AccountId },
157
    }
158

            
159
10
    #[pallet::error]
160
    pub enum Error<T> {
161
        /// There are too many Invulnerables.
162
        TooManyInvulnerables,
163
        /// Account is already an Invulnerable.
164
        AlreadyInvulnerable,
165
        /// Account is not an Invulnerable.
166
        NotInvulnerable,
167
        /// Account does not have keys registered
168
        NoKeysRegistered,
169
        /// Unable to derive collator id from account id
170
        UnableToDeriveCollatorId,
171
    }
172

            
173
130
    #[pallet::call]
174
    impl<T: Config> Pallet<T> {
175
        /// Add a new account `who` to the list of `Invulnerables` collators.
176
        ///
177
        /// The origin for this call must be the `UpdateOrigin`.
178
        #[pallet::call_index(1)]
179
        #[pallet::weight(T::WeightInfo::add_invulnerable(
180
			T::MaxInvulnerables::get().saturating_sub(1),
181
		))]
182
        pub fn add_invulnerable(
183
            origin: OriginFor<T>,
184
            who: T::AccountId,
185
51
        ) -> DispatchResultWithPostInfo {
186
51
            T::UpdateOrigin::ensure_origin(origin)?;
187
            // don't let one unprepared collator ruin things for everyone.
188
50
            let maybe_collator_id = T::CollatorIdOf::convert(who.clone())
189
50
                .filter(T::CollatorRegistration::is_registered);
190

            
191
50
            let collator_id = maybe_collator_id.ok_or(Error::<T>::NoKeysRegistered)?;
192

            
193
49
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
194
49
                if invulnerables.contains(&collator_id) {
195
3
                    Err(Error::<T>::AlreadyInvulnerable)?;
196
46
                }
197
46
                invulnerables
198
46
                    .try_push(collator_id.clone())
199
46
                    .map_err(|_| Error::<T>::TooManyInvulnerables)?;
200
45
                Ok(())
201
49
            })?;
202

            
203
45
            Self::deposit_event(Event::InvulnerableAdded { account_id: who });
204
45

            
205
45
            let weight_used = T::WeightInfo::add_invulnerable(
206
45
                Invulnerables::<T>::decode_len()
207
45
                    .unwrap_or_default()
208
45
                    .try_into()
209
45
                    .unwrap_or(T::MaxInvulnerables::get().saturating_sub(1)),
210
45
            );
211
45

            
212
45
            Ok(Some(weight_used).into())
213
        }
214

            
215
        /// Remove an account `who` from the list of `Invulnerables` collators. `Invulnerables` must
216
        /// be sorted.
217
        ///
218
        /// The origin for this call must be the `UpdateOrigin`.
219
        #[pallet::call_index(2)]
220
        #[pallet::weight(T::WeightInfo::remove_invulnerable(T::MaxInvulnerables::get()))]
221
33
        pub fn remove_invulnerable(origin: OriginFor<T>, who: T::AccountId) -> DispatchResult {
222
33
            T::UpdateOrigin::ensure_origin(origin)?;
223

            
224
32
            let collator_id = T::CollatorIdOf::convert(who.clone())
225
32
                .ok_or(Error::<T>::UnableToDeriveCollatorId)?;
226

            
227
32
            <Invulnerables<T>>::try_mutate(|invulnerables| -> DispatchResult {
228
32
                let pos = invulnerables
229
32
                    .iter()
230
37
                    .position(|x| x == &collator_id)
231
32
                    .ok_or(Error::<T>::NotInvulnerable)?;
232
31
                invulnerables.remove(pos);
233
31
                Ok(())
234
32
            })?;
235

            
236
31
            Self::deposit_event(Event::InvulnerableRemoved { account_id: who });
237
31
            Ok(())
238
        }
239
    }
240

            
241
    /// Play the role of the session manager.
242
    impl<T: Config> SessionManager<T::CollatorId> for Pallet<T> {
243
12
        fn new_session(index: SessionIndex) -> Option<Vec<T::CollatorId>> {
244
12
            log::info!(
245
                "assembling new invulnerable collators for new session {} at #{:?}",
246
                index,
247
                <frame_system::Pallet<T>>::block_number(),
248
            );
249

            
250
12
            let invulnerables = Self::invulnerables().to_vec();
251
12
            frame_system::Pallet::<T>::register_extra_weight_unchecked(
252
12
                T::WeightInfo::new_session(invulnerables.len() as u32),
253
12
                DispatchClass::Mandatory,
254
12
            );
255
12
            Some(invulnerables)
256
12
        }
257
6
        fn start_session(_: SessionIndex) {
258
6
            // we don't care.
259
6
        }
260
        fn end_session(_: SessionIndex) {
261
            // we don't care.
262
        }
263
    }
264
}
265

            
266
/// If the rewarded account is an Invulnerable, distribute the entire reward
267
/// amount to them. Otherwise use the `Fallback` distribution.
268
pub struct InvulnerableRewardDistribution<Runtime, Currency, Fallback>(
269
    PhantomData<(Runtime, Currency, Fallback)>,
270
);
271

            
272
use {frame_support::pallet_prelude::Weight, sp_runtime::traits::Get};
273

            
274
type CreditOf<Runtime, Currency> =
275
    frame_support::traits::fungible::Credit<<Runtime as frame_system::Config>::AccountId, Currency>;
276
pub type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
277

            
278
impl<Runtime, Currency, Fallback>
279
    tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>
280
    for InvulnerableRewardDistribution<Runtime, Currency, Fallback>
281
where
282
    Runtime: frame_system::Config + Config,
283
    Fallback: tp_traits::DistributeRewards<AccountIdOf<Runtime>, CreditOf<Runtime, Currency>>,
284
    Currency: frame_support::traits::fungible::Balanced<AccountIdOf<Runtime>>,
285
{
286
16681
    fn distribute_rewards(
287
16681
        rewarded: AccountIdOf<Runtime>,
288
16681
        amount: CreditOf<Runtime, Currency>,
289
16681
    ) -> frame_support::pallet_prelude::DispatchResultWithPostInfo {
290
16681
        let mut total_weight = Weight::zero();
291
16681
        let collator_id = Runtime::CollatorIdOf::convert(rewarded.clone())
292
16681
            .ok_or(Error::<Runtime>::UnableToDeriveCollatorId)?;
293
        // weight to read invulnerables
294
16681
        total_weight += Runtime::DbWeight::get().reads(1);
295
16681
        if !Invulnerables::<Runtime>::get().contains(&collator_id) {
296
397
            let post_info = Fallback::distribute_rewards(rewarded, amount)?;
297
364
            if let Some(weight) = post_info.actual_weight {
298
338
                total_weight += weight;
299
364
            }
300
        } else {
301
16284
            Currency::resolve(&rewarded, amount).map_err(|_| TokenError::NotExpendable)?;
302
16284
            total_weight +=
303
16284
                Runtime::WeightInfo::reward_invulnerable(Runtime::MaxInvulnerables::get())
304
        }
305
16648
        Ok(Some(total_weight).into())
306
16681
    }
307
}