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
//! # Author Noting Pallet
18
//!
19
//! This pallet notes the author of the different containerChains that have registered:
20
//!
21
//! The set of container chains is retrieved thanks to the GetContainerChains trait
22
//! For each containerChain, we inspect the Header stored in the relayChain as
23
//! a generic header. This is the first requirement for containerChains.
24
//!
25
//! The second requirement is that an Aura digest with the slot number for the containerChains
26
//! needs to exist
27
//!  
28
//! Using those two requirements we can select who the author was based on the collators assigned
29
//! to that containerChain, by simply assigning the slot position.
30

            
31
#![cfg_attr(not(feature = "std"), no_std)]
32

            
33
use {
34
    cumulus_pallet_parachain_system::RelaychainStateProvider,
35
    cumulus_primitives_core::{
36
        relay_chain::{BlakeTwo256, BlockNumber, HeadData},
37
        ParaId,
38
    },
39
    dp_core::well_known_keys::PARAS_HEADS_INDEX,
40
    frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*, Hashable},
41
    frame_system::pallet_prelude::*,
42
    nimbus_primitives::SlotBeacon,
43
    parity_scale_codec::{Decode, Encode},
44
    sp_consensus_aura::{inherents::InherentType, Slot, AURA_ENGINE_ID},
45
    sp_inherents::{InherentIdentifier, IsFatalError},
46
    sp_runtime::{traits::Header, DigestItem, DispatchResult},
47
    sp_std::borrow::Cow,
48
    sp_std::vec::Vec,
49
    tp_author_noting_inherent::INHERENT_IDENTIFIER,
50
    tp_traits::{
51
        AuthorNotingHook, AuthorNotingInfo, ContainerChainBlockInfo, ForSession, GenericStateProof,
52
        GenericStorageReader, GetContainerChainAuthor, GetContainerChainsWithCollators,
53
        LatestAuthorInfoFetcher, NativeStorageReader, ReadEntryErr,
54
    },
55
};
56

            
57
#[cfg(test)]
58
mod mock;
59

            
60
#[cfg(test)]
61
mod tests;
62
pub mod weights;
63
pub use weights::WeightInfo;
64

            
65
#[cfg(any(test, feature = "runtime-benchmarks"))]
66
mod benchmarks;
67
#[cfg(feature = "runtime-benchmarks")]
68
mod mock_proof;
69

            
70
pub use pallet::*;
71

            
72
28558
#[frame_support::pallet]
73
pub mod pallet {
74
    use super::*;
75

            
76
    #[pallet::config]
77
    pub trait Config: frame_system::Config {
78
        /// The overarching event type.
79
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
80

            
81
        type ContainerChains: GetContainerChainsWithCollators<Self::AccountId>;
82

            
83
        type SlotBeacon: SlotBeacon;
84

            
85
        type ContainerChainAuthor: GetContainerChainAuthor<Self::AccountId>;
86

            
87
        /// An entry-point for higher-level logic to react to containers chains authoring.
88
        ///
89
        /// Typically, this can be a hook to reward block authors.
90
        type AuthorNotingHook: AuthorNotingHook<Self::AccountId>;
91

            
92
        type RelayOrPara: RelayOrPara;
93

            
94
        /// Max length of para id list, should be the same value as in other pallets.
95
        #[pallet::constant]
96
        type MaxContainerChains: Get<u32>;
97

            
98
        /// Weight information for extrinsics in this pallet.
99
        type WeightInfo: WeightInfo;
100
    }
101

            
102
426
    #[pallet::error]
103
    pub enum Error<T> {
104
        /// The new value for a configuration parameter is invalid.
105
        FailedReading,
106
        FailedDecodingHeader,
107
        AuraDigestFirstItem,
108
        AsPreRuntimeError,
109
        NonDecodableSlot,
110
        AuthorNotFound,
111
        NonAuraDigest,
112
    }
113

            
114
2804
    #[pallet::pallet]
115
    pub struct Pallet<T>(PhantomData<T>);
116

            
117
46903
    #[pallet::hooks]
118
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
119
23445
        fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
120
23445
            let mut weight = Weight::zero();
121
23445

            
122
23445
            // We clear this storage item to make sure its always included
123
23445
            DidSetContainerAuthorData::<T>::kill();
124
23445

            
125
23445
            weight.saturating_accrue(T::DbWeight::get().writes(1));
126
23445

            
127
23445
            // The read onfinalizes
128
23445
            weight.saturating_accrue(T::DbWeight::get().reads(1));
129
23445

            
130
23445
            weight
131
23445
        }
132

            
133
23441
        fn on_finalize(_: BlockNumberFor<T>) {
134
23441
            assert!(
135
23441
                <DidSetContainerAuthorData<T>>::exists(),
136
1
                "Container chain author data needs to be present in every block!"
137
            );
138
23440
        }
139
    }
140

            
141
147430
    #[pallet::call]
142
    impl<T: Config> Pallet<T> {
143
        #[pallet::call_index(0)]
144
        #[pallet::weight((T::WeightInfo::set_latest_author_data(T::MaxContainerChains::get()), DispatchClass::Mandatory))]
145
        pub fn set_latest_author_data(
146
            origin: OriginFor<T>,
147
            data: InherentDataOf<T>,
148
23482
        ) -> DispatchResultWithPostInfo {
149
23482
            ensure_none(origin)?;
150

            
151
23482
            assert!(
152
23482
                !<DidSetContainerAuthorData<T>>::exists(),
153
1
                "DidSetContainerAuthorData must be updated only once in a block",
154
            );
155

            
156
23481
            let container_chains_to_check: Vec<_> =
157
23481
                T::ContainerChains::container_chains_with_collators(ForSession::Current)
158
23481
                    .into_iter()
159
43971
                    .filter_map(|(para_id, collators)| (!collators.is_empty()).then_some(para_id))
160
23481
                    .collect();
161
23481
            let mut total_weight =
162
23481
                T::WeightInfo::set_latest_author_data(container_chains_to_check.len() as u32);
163
23481

            
164
23481
            // We do this first to make sure we don't do 2 reads (parachains and relay state)
165
23481
            // when we have no containers registered
166
23481
            // Essentially one can pass an empty proof if no container-chains are registered
167
23481
            if !container_chains_to_check.is_empty() {
168
22447
                let storage_reader = T::RelayOrPara::create_storage_reader(data);
169
22447

            
170
22447
                let parent_tanssi_slot = u64::from(T::SlotBeacon::slot()).into();
171
22447
                let mut infos = Vec::with_capacity(container_chains_to_check.len());
172

            
173
45948
                for para_id in container_chains_to_check {
174
23505
                    match Self::fetch_block_info_from_proof(
175
23505
                        &storage_reader,
176
23505
                        para_id,
177
23505
                        parent_tanssi_slot,
178
23505
                    ) {
179
23066
                        Ok(block_info) => {
180
23066
                            LatestAuthor::<T>::mutate(
181
23066
                                para_id,
182
23066
                                |maybe_old_block_info: &mut Option<
183
                                    ContainerChainBlockInfo<T::AccountId>,
184
23066
                                >| {
185
23066
                                    // No block number is the same as the last block number being 0:
186
23066
                                    // the first block created by collators is block number 1.
187
23066
                                    let old_block_number = maybe_old_block_info
188
23066
                                        .as_ref()
189
23066
                                        .map(|old_block_info| old_block_info.block_number)
190
23066
                                        .unwrap_or(0);
191
23066
                                    // We only reward author if the block increases
192
23066
                                    // If there is no previous block, we should reward the author of the first block
193
23066
                                    if block_info.block_number > old_block_number {
194
22568
                                        let bi = block_info.clone();
195
22568
                                        let info = AuthorNotingInfo {
196
22568
                                            author: block_info.author,
197
22568
                                            block_number: block_info.block_number,
198
22568
                                            para_id,
199
22568
                                        };
200
22568
                                        infos.push(info);
201
22568
                                        *maybe_old_block_info = Some(bi);
202
22568
                                    }
203
23066
                                },
204
23066
                            );
205
23066
                        }
206
439
                        Err(e) => log::warn!(
207
426
                            "Author-noting error {:?} found in para {:?}",
208
426
                            e,
209
426
                            u32::from(para_id)
210
                        ),
211
                    }
212
                }
213

            
214
22443
                total_weight
215
22443
                    .saturating_accrue(T::AuthorNotingHook::on_container_authors_noted(&infos));
216
1034
            }
217

            
218
            // We correctly set the data
219
23477
            DidSetContainerAuthorData::<T>::put(true);
220
23477

            
221
23477
            Ok(PostDispatchInfo {
222
23477
                actual_weight: Some(total_weight),
223
23477
                pays_fee: Pays::No,
224
23477
            })
225
        }
226

            
227
        #[pallet::call_index(1)]
228
        #[pallet::weight(T::WeightInfo::set_author())]
229
        pub fn set_author(
230
            origin: OriginFor<T>,
231
            para_id: ParaId,
232
            block_number: BlockNumber,
233
            author: T::AccountId,
234
            latest_slot_number: Slot,
235
27
        ) -> DispatchResult {
236
27
            ensure_root(origin)?;
237
23
            LatestAuthor::<T>::insert(
238
23
                para_id,
239
23
                ContainerChainBlockInfo {
240
23
                    block_number,
241
23
                    author: author.clone(),
242
23
                    latest_slot_number,
243
23
                },
244
23
            );
245
23
            Self::deposit_event(Event::LatestAuthorChanged {
246
23
                para_id,
247
23
                block_number,
248
23
                new_author: author,
249
23
                latest_slot_number,
250
23
            });
251
23
            Ok(())
252
        }
253

            
254
        #[pallet::call_index(2)]
255
        #[pallet::weight(T::WeightInfo::kill_author_data())]
256
103
        pub fn kill_author_data(origin: OriginFor<T>, para_id: ParaId) -> DispatchResult {
257
103
            ensure_root(origin)?;
258
99
            LatestAuthor::<T>::remove(para_id);
259
99
            Self::deposit_event(Event::RemovedAuthorData { para_id });
260
99
            Ok(())
261
        }
262
    }
263

            
264
618
    #[pallet::event]
265
122
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
266
    pub enum Event<T: Config> {
267
1
        /// Latest author changed
268
        LatestAuthorChanged {
269
            para_id: ParaId,
270
            block_number: BlockNumber,
271
            new_author: T::AccountId,
272
            latest_slot_number: Slot,
273
        },
274
1
        /// Removed author data
275
        RemovedAuthorData { para_id: ParaId },
276
    }
277

            
278
23873
    #[pallet::storage]
279
    pub(super) type LatestAuthor<T: Config> =
280
        StorageMap<_, Blake2_128Concat, ParaId, ContainerChainBlockInfo<T::AccountId>, OptionQuery>;
281

            
282
    /// Was the containerAuthorData set?
283
188310
    #[pallet::storage]
284
    pub(super) type DidSetContainerAuthorData<T: Config> = StorageValue<_, bool, ValueQuery>;
285

            
286
    #[pallet::inherent]
287
    impl<T: Config> ProvideInherent for Pallet<T> {
288
        type Call = Call<T>;
289
        type Error = InherentError;
290
        // TODO, what should we put here
291
        const INHERENT_IDENTIFIER: InherentIdentifier =
292
            tp_author_noting_inherent::INHERENT_IDENTIFIER;
293

            
294
        fn is_inherent_required(_: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
295
            // Return Ok(Some(_)) unconditionally because this inherent is required in every block
296
            Ok(Some(InherentError::Other(Cow::from(
297
                "Pallet Author Noting Inherent required",
298
            ))))
299
        }
300

            
301
23446
        fn create_inherent(data: &InherentData) -> Option<Self::Call> {
302
23446
            let data = T::RelayOrPara::create_inherent_arg(data);
303
23446

            
304
23446
            Some(Call::set_latest_author_data { data })
305
23446
        }
306

            
307
23430
        fn is_inherent(call: &Self::Call) -> bool {
308
23430
            matches!(call, Call::set_latest_author_data { .. })
309
23430
        }
310
    }
311
}
312

            
313
impl<T: Config> Pallet<T> {
314
    /// Fetch author and block number from a proof of header
315
23504
    fn fetch_block_info_from_proof<S: GenericStorageReader>(
316
23504
        relay_state_proof: &S,
317
23504
        para_id: ParaId,
318
23504
        tanssi_slot: Slot,
319
23504
    ) -> Result<ContainerChainBlockInfo<T::AccountId>, Error<T>> {
320
23504
        let bytes = para_id.twox_64_concat();
321
23504
        // CONCAT
322
23504
        let key = [PARAS_HEADS_INDEX, bytes.as_slice()].concat();
323
        // We might encounter empty vecs
324
        // We only note if we can decode
325
        // In this process several errors can occur, but we will only log if such errors happen
326
        // We first take the HeadData
327
        // If the readError was that the key was not provided (identified by the Proof error),
328
        // then panic
329
23504
        let head_data = relay_state_proof
330
23504
            .read_entry::<HeadData>(key.as_slice(), None)
331
23504
            .map_err(|e| match e {
332
3
                ReadEntryErr::Proof => panic!("Invalid proof provided for para head key"),
333
428
                _ => Error::<T>::FailedReading,
334
23504
            })?;
335

            
336
        // We later take the Header decoded
337
23076
        let author_header = sp_runtime::generic::Header::<BlockNumber, BlakeTwo256>::decode(
338
23076
            &mut head_data.0.as_slice(),
339
23076
        )
340
23076
        .map_err(|_| Error::<T>::FailedDecodingHeader)?;
341

            
342
        // Return author from first aura log.
343
        // If there are no aura logs, it iterates over all the logs, then returns the error from the first element.
344
        // This is because it is hard to return a `Vec<Error<T>>`.
345
23071
        let mut first_error = None;
346
23071
        for aura_digest in author_header.digest().logs() {
347
23069
            match Self::author_from_log(aura_digest, para_id, &author_header, tanssi_slot) {
348
23066
                Ok(x) => return Ok(x),
349
3
                Err(e) => {
350
3
                    if first_error.is_none() {
351
3
                        first_error = Some(e);
352
3
                    }
353
                }
354
            }
355
        }
356

            
357
2
        Err(first_error.unwrap_or(Error::<T>::AuraDigestFirstItem))
358
23501
    }
359

            
360
    /// Get block author from aura digest
361
23069
    fn author_from_log(
362
23069
        aura_digest: &DigestItem,
363
23069
        para_id: ParaId,
364
23069
        author_header: &sp_runtime::generic::Header<BlockNumber, BlakeTwo256>,
365
23069
        tanssi_slot: Slot,
366
23069
    ) -> Result<ContainerChainBlockInfo<T::AccountId>, Error<T>> {
367
        // We decode the digest as pre-runtime digest
368
23069
        let (id, mut data) = aura_digest
369
23069
            .as_pre_runtime()
370
23069
            .ok_or(Error::<T>::AsPreRuntimeError)?;
371

            
372
        // Match against the Aura digest
373
23069
        if id == AURA_ENGINE_ID {
374
            // DecodeSlot
375
23067
            let slot = InherentType::decode(&mut data).map_err(|_| Error::<T>::NonDecodableSlot)?;
376

            
377
            // Fetch Author
378
23066
            let author = T::ContainerChainAuthor::author_for_slot(slot, para_id)
379
23066
                .ok_or(Error::<T>::AuthorNotFound)?;
380

            
381
23066
            Ok(ContainerChainBlockInfo {
382
23066
                block_number: author_header.number,
383
23066
                author,
384
23066
                // We store the slot number of the current tanssi block to have a time-based notion
385
23066
                // of when the last block of a container chain was included.
386
23066
                // Note that this is not the slot of the container chain block, and it does not
387
23066
                // indicate when that block was created, but when it was included in tanssi.
388
23066
                latest_slot_number: tanssi_slot,
389
23066
            })
390
        } else {
391
2
            Err(Error::<T>::NonAuraDigest)
392
        }
393
23069
    }
394

            
395
43
    pub fn latest_author(para_id: ParaId) -> Option<ContainerChainBlockInfo<T::AccountId>> {
396
43
        LatestAuthor::<T>::get(para_id)
397
43
    }
398
}
399

            
400
#[derive(Encode)]
401
#[cfg_attr(feature = "std", derive(Debug, Decode))]
402
pub enum InherentError {
403
    Other(Cow<'static, str>),
404
}
405

            
406
impl IsFatalError for InherentError {
407
    fn is_fatal_error(&self) -> bool {
408
        match *self {
409
            InherentError::Other(_) => true,
410
        }
411
    }
412
}
413

            
414
impl InherentError {
415
    /// Try to create an instance ouf of the given identifier and data.
416
    #[cfg(feature = "std")]
417
    pub fn try_from(id: &InherentIdentifier, data: &[u8]) -> Option<Self> {
418
        if id == &INHERENT_IDENTIFIER {
419
            <InherentError as parity_scale_codec::Decode>::decode(&mut &data[..]).ok()
420
        } else {
421
            None
422
        }
423
    }
424
}
425

            
426
impl<T: Config> LatestAuthorInfoFetcher<T::AccountId> for Pallet<T> {
427
24
    fn get_latest_author_info(para_id: ParaId) -> Option<ContainerChainBlockInfo<T::AccountId>> {
428
24
        LatestAuthor::<T>::get(para_id)
429
24
    }
430
}
431

            
432
/// This pallet has slightly different behavior when used in a parachain vs when used in a relay chain
433
/// (solochain). The main difference is:
434
/// In relay mode, we don't need a storage proof, so the inherent doesn't need any input argument,
435
/// and instead of reading from a storage proof we read from storage directly.
436
pub trait RelayOrPara {
437
    type InherentArg: TypeInfo + Clone + PartialEq + Encode + Decode + core::fmt::Debug;
438
    type GenericStorageReader: GenericStorageReader;
439

            
440
    fn create_inherent_arg(data: &InherentData) -> Self::InherentArg;
441
    fn create_storage_reader(data: Self::InherentArg) -> Self::GenericStorageReader;
442

            
443
    #[cfg(feature = "runtime-benchmarks")]
444
    fn set_current_relay_chain_state(state: cumulus_pallet_parachain_system::RelayChainState);
445
}
446

            
447
pub type InherentDataOf<T> = <<T as Config>::RelayOrPara as RelayOrPara>::InherentArg;
448

            
449
pub struct RelayMode;
450
pub struct ParaMode<RCSP: RelaychainStateProvider>(PhantomData<RCSP>);
451

            
452
impl RelayOrPara for RelayMode {
453
    type InherentArg = ();
454
    type GenericStorageReader = NativeStorageReader;
455

            
456
    fn create_inherent_arg(_data: &InherentData) -> Self::InherentArg {
457
        // This ignores the inherent data entirely, so it is compatible with clients that don't add our inherent
458
    }
459

            
460
272
    fn create_storage_reader(_data: Self::InherentArg) -> Self::GenericStorageReader {
461
272
        NativeStorageReader
462
272
    }
463

            
464
    #[cfg(feature = "runtime-benchmarks")]
465
    fn set_current_relay_chain_state(_state: cumulus_pallet_parachain_system::RelayChainState) {}
466
}
467

            
468
impl<RCSP: RelaychainStateProvider> RelayOrPara for ParaMode<RCSP> {
469
    type InherentArg = tp_author_noting_inherent::OwnParachainInherentData;
470
    type GenericStorageReader = GenericStateProof<cumulus_primitives_core::relay_chain::Block>;
471

            
472
23446
    fn create_inherent_arg(data: &InherentData) -> Self::InherentArg {
473
23446
        data.get_data(&INHERENT_IDENTIFIER)
474
23446
            .ok()
475
23446
            .flatten()
476
23446
            .expect("there is not data to be posted; qed")
477
23446
    }
478

            
479
22430
    fn create_storage_reader(data: Self::InherentArg) -> Self::GenericStorageReader {
480
22430
        let tp_author_noting_inherent::OwnParachainInherentData {
481
22430
            relay_storage_proof,
482
22430
        } = data;
483
22430

            
484
22430
        let relay_chain_state = RCSP::current_relay_chain_state();
485
22430
        let relay_storage_root = relay_chain_state.state_root;
486
22430

            
487
22430
        GenericStateProof::new(relay_storage_root, relay_storage_proof)
488
22430
            .expect("Invalid relay chain state proof")
489
22430
    }
490

            
491
    #[cfg(feature = "runtime-benchmarks")]
492
    fn set_current_relay_chain_state(state: cumulus_pallet_parachain_system::RelayChainState) {
493
        RCSP::set_current_relay_chain_state(state)
494
    }
495
}