1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # Aura Module
//!
//! - [`Config`]
//! - [`Pallet`]
//!
//! ## Overview
//!
//! The Aura module extends Aura consensus by managing offline reporting.
//!
//! ## Interface
//!
//! ### Public Functions
//!
//! - `slot_duration` - Determine the Aura slot-duration based on the Timestamp module
//!   configuration.
//!
//! ## Related Modules
//!
//! - [Timestamp](../pallet_timestamp/index.html): The Timestamp module is used in Aura to track
//! consensus rounds (via `slots`).

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

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
	traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler},
	BoundedSlice, BoundedVec, ConsensusEngineId, Parameter,
};
use sp_consensus_aura::{AuthorityIndex, ConsensusLog, Slot, AURA_ENGINE_ID};
use sp_runtime::{
	Percent,
	generic::DigestItem,
	traits::{IsMember, Member, SaturatedConversion, Saturating, Zero},
	RuntimeAppPublic,
};
use sp_std::prelude::*;

// pub mod migrations;
// mod mock;
// mod tests;

pub use pallet::*;

const LOG_TARGET: &str = "runtime::aura";

/// A slot duration provider which infers the slot duration from the
/// [`pallet_timestamp::Config::MinimumPeriod`] by multiplying it by two, to ensure
/// that authors have the majority of their slot to author within.
///
/// This was the default behavior of the Aura pallet and may be used for
/// backwards compatibility.
///
/// Note that this type is likely not useful without the `experimental`
/// feature.
pub struct MinimumPeriodTimesTwo<T>(sp_std::marker::PhantomData<T>);

impl<T: pallet_timestamp::Config> Get<T::Moment> for MinimumPeriodTimesTwo<T> {
	fn get() -> T::Moment {
		<T as pallet_timestamp::Config>::MinimumPeriod::get().saturating_mul(2u32.into())
	}
}

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::pallet_prelude::*;
	use frame_system::pallet_prelude::*;

	#[pallet::config]
	pub trait Config: pallet_timestamp::Config + frame_system::Config {

        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
		/// The identifier type for an authority.
		type AuthorityId: Member
			+ Parameter
			+ RuntimeAppPublic
			+ MaybeSerializeDeserialize
			+ MaxEncodedLen;
		/// The maximum number of authorities that the pallet can hold.
		type MaxAuthorities: Get<u32>;

		#[pallet::constant]
		type SessionPeriod: Get<u32>;

		#[pallet::constant]
		type MaxSplits: Get<u32>;

		/// A way to check whether a given validator is disabled and should not be authoring blocks.
		/// Blocks authored by a disabled validator will lead to a panic as part of this module's
		/// initialization.
		type DisabledValidators: DisabledValidators;

		/// Whether to allow block authors to create multiple blocks per slot.
		///
		/// If this is `true`, the pallet will allow slots to stay the same across sequential
		/// blocks. If this is `false`, the pallet will require that subsequent blocks always have
		/// higher slots than previous ones.
		///
		/// Regardless of the setting of this storage value, the pallet will always enforce the
		/// invariant that slots don't move backwards as the chain progresses.
		///
		/// The typical value for this should be 'false' unless this pallet is being augmented by
		/// another pallet which enforces some limitation on the number of blocks authors can create
		/// using the same slot.
		type AllowMultipleBlocksPerSlot: Get<bool>;

		/// The slot duration Aura should run with, expressed in milliseconds.
		/// The effective value of this type should not change while the chain is running.
		///
		/// For backwards compatibility either use [`MinimumPeriodTimesTwo`] or a const.
		///
		/// This associated type is only present when compiled with the `experimental`
		/// feature.
		#[cfg(feature = "experimental")]
		type SlotDuration: Get<<Self as pallet_timestamp::Config>::Moment>;
	}

	#[pallet::pallet]
	pub struct Pallet<T>(sp_std::marker::PhantomData<T>);

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config> {
		/// Validators set is changed
		DecisionRequired { round_at: u32 },
		DecisionAccepted { decisions: u32 }
	}

	#[pallet::error]
	pub enum Error<T> {
		InvalidAuthorSlotCount,
		IncorrectSlotAlloc,
		TooManyValidators,
		InvalidAuthorIndexes,
		UnknownValidators,
	}

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
		fn on_initialize(n: BlockNumberFor<T>) -> Weight {
			if let Some(new_slot) = Self::current_slot_from_digests() {
				let current_slot = CurrentSlot::<T>::get();

				if T::AllowMultipleBlocksPerSlot::get() {
					assert!(current_slot <= new_slot, "Slot must not decrease");
				} else {
					assert!(current_slot < new_slot, "Slot must increase");
				}

				CurrentSlot::<T>::put(new_slot);

				if let Some(n_authorities) = <Authorities<T>>::decode_len() {
					let authority_index = *new_slot % n_authorities as u64;
					if T::DisabledValidators::is_disabled(authority_index as u32) {
						panic!(
							"Validator with index {:?} is disabled and should not be attempting to author blocks.",
							authority_index,
						);
					}
				}

				let decisions = <TotalDecisions<T>>::get();

				if !decisions.is_zero() {
					let round_at = <RoundAt<T>>::get();
					let slots_each_round = <SlotsEachRound<T>>::get();
					let authors_each_round = <AuthorsEachRound<T>>::get();

					if !((n % T::SessionPeriod::get().into()).is_zero()) {
						if round_at < T::MaxSplits::get() {
							let current_round_slot = Percent::from_percent(slots_each_round[round_at as usize] as u8) * T::SessionPeriod::get();
							if <LastRoundAt<T>>::get().is_zero() {<LastRoundAt<T>>::put(n);}
							let current_round_block = <LastRoundAt<T>>::get().saturating_add(current_round_slot.into());

							if n == current_round_block {
								let range_to_start = if round_at > 0 {(authors_each_round[round_at as usize].checked_add(1).unwrap()) as usize} else {round_at as usize};
								let all_validators = <AllValidators<T>>::get();
								let range_to_inclusive = if round_at < T::MaxSplits::get().saturating_sub(1) {
									authors_each_round[(round_at+1) as usize] as usize
								}else{
									all_validators.len().saturating_sub(1)
								};
								let current_authorities = &all_validators[range_to_start..=range_to_inclusive];
								let bounded = <BoundedVec<_, T::MaxAuthorities>>::truncate_from(current_authorities.into());
								if current_authorities.len() > 1 {Self::change_authorities(bounded);}
								<RoundAt<T>>::put(round_at+1);
								<LastRoundAt<T>>::put(n);
							}
						}else{
							<RoundAt<T>>::put(0);
						}
					}
				}

				// TODO [#3398] Generate offence report for all authorities that skipped their
				// slots.

				T::DbWeight::get().reads_writes(2, 1)
			} else {
				T::DbWeight::get().reads(1)
			}
		}

		#[cfg(feature = "try-runtime")]
		fn try_state(_: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
			Self::do_try_state()
		}
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		#[pallet::call_index(0)]
		#[pallet::weight((T::DbWeight::get().reads_writes(1, 1), DispatchClass::Operational, Pays::No))]
		pub fn pass_decision(
			origin: OriginFor<T>,
			slots_each_round: Vec<u32>,
			authors_each_round: Vec<u32>,
			validators_categorized: Vec<T::AuthorityId>
		) -> DispatchResultWithPostInfo {
			ensure_root(origin)?;
			let all_validators_len =
			<AllValidators<T>>::decode_len().ok_or("Failed to decode validators length")?;
			frame_support::ensure!(
				slots_each_round.len() as u32 == T::MaxSplits::get() &&
				authors_each_round.len() == slots_each_round.len(),
				Error::<T>::InvalidAuthorSlotCount
			);
			let slot_sum: u32 = slots_each_round.iter().sum();
			frame_support::ensure!(slot_sum == 100, Error::<T>::IncorrectSlotAlloc);
			let cmp = Self::is_sorted_and_unique(&authors_each_round); //authors_each_round.iter().is_sorted();//is_sorted_and_unique
			let cmp2 = authors_each_round.iter().any(|&i| i >= (all_validators_len.saturating_sub(1)) as u32);
			frame_support::ensure!(cmp, Error::<T>::InvalidAuthorIndexes);
			frame_support::ensure!(!cmp2, Error::<T>::TooManyValidators);
			frame_support::ensure!(
				validators_categorized.len() == all_validators_len,
				Error::<T>::TooManyValidators
			);

			let current_validators = <AllValidators<T>>::get().into_inner();
			let diff: Vec<T::AuthorityId> = validators_categorized.iter()
				.filter(|item| !current_validators.contains(item)).cloned().collect();
			frame_support::ensure!(diff.len().is_zero(), Error::<T>::UnknownValidators);

			let slots = <BoundedVec<_, T::MaxSplits>>::try_from(slots_each_round)
				.expect("slots can not exceed T::MaxSplits");
			let authors = <BoundedVec<_, T::MaxSplits>>::try_from(authors_each_round)
				.expect("authors can not exceed T::MaxSplits");

			let validators = <BoundedVec<_, T::MaxAuthorities>>::truncate_from(validators_categorized);

			Self::change_decision(slots, authors, validators);

			Ok(().into())
		}
	}

	#[pallet::storage]
	#[pallet::getter(fn total_decision)]
	pub(super) type TotalDecisions<T: Config> =
		StorageValue<_, u32, ValueQuery>;

	#[pallet::storage]
	#[pallet::getter(fn last_round_at)]
	pub(super) type LastRoundAt<T: Config> =
		StorageValue<_, BlockNumberFor<T>, ValueQuery>;

	#[pallet::storage]
	pub(super) type RoundAt<T: Config> =
		StorageValue<_, u32, ValueQuery>;

	#[pallet::storage]
	pub(super) type SlotsEachRound<T: Config> =
		StorageValue<_, BoundedVec<u32, T::MaxSplits>, ValueQuery>;

	#[pallet::storage]
	pub(super) type AuthorsEachRound<T: Config> =
		StorageValue<_, BoundedVec<u32, T::MaxSplits>, ValueQuery>;

	/// The all authority set.
	#[pallet::storage]
	#[pallet::getter(fn all_validators)]
	pub(super) type AllValidators<T: Config> =
		StorageValue<_, BoundedVec<T::AuthorityId, T::MaxAuthorities>, ValueQuery>;

	/// The current authority set.
	#[pallet::storage]
	#[pallet::getter(fn authorities)]
	pub(super) type Authorities<T: Config> =
		StorageValue<_, BoundedVec<T::AuthorityId, T::MaxAuthorities>, ValueQuery>;

	/// The current slot of this block.
	///
	/// This will be set in `on_initialize`.
	#[pallet::storage]
	#[pallet::getter(fn current_slot)]
	pub(super) type CurrentSlot<T: Config> = StorageValue<_, Slot, ValueQuery>;

	#[pallet::genesis_config]
	#[derive(frame_support::DefaultNoBound)]
	pub struct GenesisConfig<T: Config> {
		pub authorities: Vec<T::AuthorityId>,
	}

	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
		fn build(&self) {
			Pallet::<T>::initialize_authorities(&self.authorities);
		}
	}
}

impl<T: Config> Pallet<T> {
	/// Change authorities.
	///
	/// The storage will be applied immediately.
	/// And aura consensus log will be appended to block's log.
	///
	/// This is a no-op if `new` is empty.
	pub fn change_authorities(new: BoundedVec<T::AuthorityId, T::MaxAuthorities>) {
		if new.is_empty() {
			log::warn!(target: LOG_TARGET, "Ignoring empty authority change.");

			return
		}

		<Authorities<T>>::put(&new);

		let log = DigestItem::Consensus(
			AURA_ENGINE_ID,
			ConsensusLog::AuthoritiesChange(new.into_inner()).encode(),
		);
		<frame_system::Pallet<T>>::deposit_log(log);
	}

	/// Change validators.
	///
	/// The storage will be applied immediately.
	/// Validators will be added as authorities in the next AiRound
	///
	/// This is a no-op if `new` is empty.
	pub fn change_validators(new: BoundedVec<T::AuthorityId, T::MaxAuthorities>) {
		if new.is_empty() {
			log::warn!(target: LOG_TARGET, "Ignoring empty validator change.");

			return
		}

		<AllValidators<T>>::put(&new);
		Self::deposit_event(Event::DecisionRequired{round_at: <RoundAt<T>>::get()});
	}

	pub fn change_decision(
		slots: BoundedVec<u32, T::MaxSplits>, 
		authors: BoundedVec<u32, T::MaxSplits>, 
		validators: BoundedVec<T::AuthorityId, T::MaxAuthorities>
	) {
		
		<SlotsEachRound<T>>::put(slots);
		<AuthorsEachRound<T>>::put(authors);
		<AllValidators<T>>::put(validators);

		let decisions = <TotalDecisions<T>>::get();
		<TotalDecisions<T>>::put(decisions.checked_add(1).unwrap());
		
		Self::deposit_event(Event::DecisionAccepted{decisions: <TotalDecisions<T>>::get()});
	}

	/// Initial authorities.
	///
	/// The storage will be applied immediately.
	///
	/// The authorities length must be equal or less than T::MaxAuthorities.
	pub fn initialize_authorities(authorities: &[T::AuthorityId]) {
		if !authorities.is_empty() {
			assert!(<Authorities<T>>::get().is_empty(), "Authorities are already initialized!");
			let bounded = <BoundedSlice<'_, _, T::MaxAuthorities>>::try_from(authorities)
				.expect("Initial authority set must be less than T::MaxAuthorities");
			<Authorities<T>>::put(bounded);
			<AllValidators<T>>::put(bounded);
			<RoundAt<T>>::put(0);
		}
	}

	/// Get the current slot from the pre-runtime digests.
	fn current_slot_from_digests() -> Option<Slot> {
		let digest = frame_system::Pallet::<T>::digest();
		let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
		for (id, mut data) in pre_runtime_digests {
			if id == AURA_ENGINE_ID {
				return Slot::decode(&mut data).ok()
			}
		}

		None
	}

	/// Determine the Aura slot-duration based on the Timestamp module configuration.
	pub fn slot_duration() -> T::Moment {
		#[cfg(feature = "experimental")]
		{
			T::SlotDuration::get()
		}

		#[cfg(not(feature = "experimental"))]
		{
			// we double the minimum block-period so each author can always propose within
			// the majority of its slot.
			<T as pallet_timestamp::Config>::MinimumPeriod::get().saturating_mul(2u32.into())
		}
	}

	/// Ensure the correctness of the state of this pallet.
	///
	/// This should be valid before or after each state transition of this pallet.
	///
	/// # Invariants
	///
	/// ## `CurrentSlot`
	///
	/// If we don't allow for multiple blocks per slot, then the current slot must be less than the
	/// maximal slot number. Otherwise, it can be arbitrary.
	///
	/// ## `Authorities`
	///
	/// * The authorities must be non-empty.
	/// * The current authority cannot be disabled.
	/// * The number of authorities must be less than or equal to `T::MaxAuthorities`. This however,
	///   is guarded by the type system.
	#[cfg(any(test, feature = "try-runtime"))]
	pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
		// We don't have any guarantee that we are already after `on_initialize` and thus we have to
		// check the current slot from the digest or take the last known slot.
		#[allow(clippy::redundant_closure)]
		let current_slot =
			Self::current_slot_from_digests().unwrap_or_else(|| CurrentSlot::<T>::get());

		// Check that the current slot is less than the maximal slot number, unless we allow for
		// multiple blocks per slot.
		if !T::AllowMultipleBlocksPerSlot::get() {
			frame_support::ensure!(
				current_slot < u64::MAX,
				"Current slot has reached maximum value and cannot be incremented further.",
			);
		}

		let authorities_len =
			<Authorities<T>>::decode_len().ok_or("Failed to decode authorities length")?;

		// Check that the authorities are non-empty.
		frame_support::ensure!(!authorities_len.is_zero(), "Authorities must be non-empty.");

		// Check that the current authority is not disabled.
		let authority_index = *current_slot % authorities_len as u64;
		frame_support::ensure!(
			!T::DisabledValidators::is_disabled(authority_index as u32),
			"Current validator is disabled and should not be attempting to author blocks.",
		);

		Ok(())
	}

	/// Check the list is sorted and has no duplicates.
	fn is_sorted_and_unique(authors: &[u32]) -> bool {
		authors.windows(2).all(|w| w[0] < w[1])
	}

}

impl<T: Config> sp_runtime::BoundToRuntimeAppPublic for Pallet<T> {
	type Public = T::AuthorityId;
}

impl<T: Config> OneSessionHandler<T::AccountId> for Pallet<T> {
	type Key = T::AuthorityId;

	fn on_genesis_session<'a, I: 'a>(validators: I)
	where
		I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
	{
		let authorities = validators.map(|(_, k)| k).collect::<Vec<_>>();
		Self::initialize_authorities(&authorities);
	}

	fn on_new_session<'a, I: 'a>(changed: bool, validators: I, _queued_validators: I)
	where
		I: Iterator<Item = (&'a T::AccountId, T::AuthorityId)>,
	{
		// instant changes
		if changed {
			let next_validators = validators.map(|(_, k)| k).collect::<Vec<_>>();
			let last_validators = Self::all_validators();
			if last_validators != next_validators {
				if next_validators.len() as u32 > T::MaxAuthorities::get() {
					log::warn!(
						target: LOG_TARGET,
						"next authorities list larger than {}, truncating",
						T::MaxAuthorities::get(),
					);
				}
				let bounded = <BoundedVec<_, T::MaxAuthorities>>::truncate_from(next_validators);
				Self::change_validators(bounded);
			}
		}
	}

	fn on_disabled(i: u32) {
		let log = DigestItem::Consensus(
			AURA_ENGINE_ID,
			ConsensusLog::<T::AuthorityId>::OnDisabled(i as AuthorityIndex).encode(),
		);

		<frame_system::Pallet<T>>::deposit_log(log);
	}
}

impl<T: Config> FindAuthor<u32> for Pallet<T> {
	fn find_author<'a, I>(digests: I) -> Option<u32>
	where
		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
	{
		for (id, mut data) in digests.into_iter() {
			if id == AURA_ENGINE_ID {
				let slot = Slot::decode(&mut data).ok()?;
				let author_index = *slot % Authorities::<T>::decode_len().unwrap() as u64;
				return Some(author_index as u32)
			}
		}

		None
	}
}

/// We can not implement `FindAuthor` twice, because the compiler does not know if
/// `u32 == T::AuthorityId` and thus, prevents us to implement the trait twice.
#[doc(hidden)]
pub struct FindAccountFromAuthorIndex<T, Inner>(sp_std::marker::PhantomData<(T, Inner)>);

impl<T: Config, Inner: FindAuthor<u32>> FindAuthor<T::AuthorityId>
	for FindAccountFromAuthorIndex<T, Inner>
{
	fn find_author<'a, I>(digests: I) -> Option<T::AuthorityId>
	where
		I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
	{
		let i = Inner::find_author(digests)?;

		let validators = <Pallet<T>>::authorities();
		validators.get(i as usize).cloned()
	}
}

/// Find the authority ID of the Aura authority who authored the current block.
pub type AuraAuthorId<T> = FindAccountFromAuthorIndex<T, Pallet<T>>;

impl<T: Config> IsMember<T::AuthorityId> for Pallet<T> {
	fn is_member(authority_id: &T::AuthorityId) -> bool {
		Self::authorities().iter().any(|id| id == authority_id)
	}
}

impl<T: Config> OnTimestampSet<T::Moment> for Pallet<T> {
	fn on_timestamp_set(moment: T::Moment) {
		let slot_duration = Self::slot_duration();
		assert!(!slot_duration.is_zero(), "Aura slot duration cannot be zero.");

		let timestamp_slot = moment / slot_duration;
		let timestamp_slot = Slot::from(timestamp_slot.saturated_into::<u64>());

		assert!(
			CurrentSlot::<T>::get() == timestamp_slot,
			"Timestamp slot must match `CurrentSlot`"
		);
	}
}