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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
dispatch,
traits::{Defensive, FindAuthor, Get, VerifySeal},
BoundedSlice, BoundedVec,
};
use sp_authorship::{InherentError, UnclesInherentData, INHERENT_IDENTIFIER};
use sp_runtime::traits::{Header as HeaderT, One, Saturating, UniqueSaturatedInto};
use sp_std::{collections::btree_set::BTreeSet, prelude::*, result};
const MAX_UNCLES: usize = 10;
struct MaxUncleEntryItems<T>(core::marker::PhantomData<T>);
impl<T: Config> Get<u32> for MaxUncleEntryItems<T> {
fn get() -> u32 {
let max_generations: u32 = T::UncleGenerations::get().unique_saturated_into();
(MAX_UNCLES as u32 + 1) * (max_generations + 1)
}
}
pub use pallet::*;
#[impl_trait_for_tuples::impl_for_tuples(30)]
pub trait EventHandler<Author, BlockNumber> {
fn note_author(author: Author);
fn note_uncle(author: Author, age: BlockNumber);
}
pub trait FilterUncle<Header, Author> {
type Accumulator: Default;
fn filter_uncle(
header: &Header,
acc: &mut Self::Accumulator,
) -> Result<Option<Author>, &'static str>;
}
impl<H, A> FilterUncle<H, A> for () {
type Accumulator = ();
fn filter_uncle(_: &H, _acc: &mut Self::Accumulator) -> Result<Option<A>, &'static str> {
Ok(None)
}
}
pub struct SealVerify<T>(sp_std::marker::PhantomData<T>);
impl<Header, Author, T: VerifySeal<Header, Author>> FilterUncle<Header, Author> for SealVerify<T> {
type Accumulator = ();
fn filter_uncle(header: &Header, _acc: &mut ()) -> Result<Option<Author>, &'static str> {
T::verify_seal(header)
}
}
pub struct OnePerAuthorPerHeight<T, N>(sp_std::marker::PhantomData<(T, N)>);
impl<Header, Author, T> FilterUncle<Header, Author> for OnePerAuthorPerHeight<T, Header::Number>
where
Header: HeaderT + PartialEq,
Header::Number: Ord,
Author: Clone + PartialEq + Ord,
T: VerifySeal<Header, Author>,
{
type Accumulator = BTreeSet<(Header::Number, Author)>;
fn filter_uncle(
header: &Header,
acc: &mut Self::Accumulator,
) -> Result<Option<Author>, &'static str> {
let author = T::verify_seal(header)?;
let number = header.number();
if let Some(ref author) = author {
if !acc.insert((*number, author.clone())) {
return Err("more than one uncle per number per author included")
}
}
Ok(author)
}
}
#[derive(Encode, Decode, sp_runtime::RuntimeDebug, scale_info::TypeInfo, MaxEncodedLen)]
#[cfg_attr(any(feature = "std", test), derive(PartialEq))]
enum UncleEntryItem<BlockNumber, Hash, Author> {
InclusionHeight(BlockNumber),
Uncle(Hash, Option<Author>),
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config {
type FindAuthor: FindAuthor<Self::AccountId>;
#[pallet::constant]
type UncleGenerations: Get<Self::BlockNumber>;
type FilterUncle: FilterUncle<Self::Header, Self::AccountId>;
type EventHandler: EventHandler<Self::AccountId, Self::BlockNumber>;
}
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(now: T::BlockNumber) -> Weight {
let uncle_generations = T::UncleGenerations::get();
if uncle_generations <= now {
let minimum_height = now - uncle_generations;
Self::prune_old_uncles(minimum_height)
}
<DidSetUncles<T>>::put(false);
if let Some(author) = Self::author() {
T::EventHandler::note_author(author);
}
Weight::zero()
}
fn on_finalize(_: T::BlockNumber) {
<Author<T>>::kill();
<DidSetUncles<T>>::kill();
}
}
#[pallet::storage]
pub(super) type Uncles<T: Config> = StorageValue<
_,
BoundedVec<UncleEntryItem<T::BlockNumber, T::Hash, T::AccountId>, MaxUncleEntryItems<T>>,
ValueQuery,
>;
#[pallet::storage]
pub(super) type Author<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;
#[pallet::storage]
pub(super) type DidSetUncles<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::error]
pub enum Error<T> {
InvalidUncleParent,
UnclesAlreadySet,
TooManyUncles,
GenesisUncle,
TooHighUncle,
UncleAlreadyIncluded,
OldUncle,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight((0, DispatchClass::Mandatory))]
pub fn set_uncles(origin: OriginFor<T>, new_uncles: Vec<T::Header>) -> DispatchResult {
ensure_none(origin)?;
ensure!(new_uncles.len() <= MAX_UNCLES, Error::<T>::TooManyUncles);
if <DidSetUncles<T>>::get() {
return Err(Error::<T>::UnclesAlreadySet.into())
}
<DidSetUncles<T>>::put(true);
Self::verify_and_import_uncles(new_uncles)
}
}
#[pallet::inherent]
impl<T: Config> ProvideInherent for Pallet<T> {
type Call = Call<T>;
type Error = InherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(data: &InherentData) -> Option<Self::Call> {
let uncles = data.uncles().unwrap_or_default();
let mut new_uncles = Vec::new();
if !uncles.is_empty() {
let prev_uncles = <Uncles<T>>::get();
let mut existing_hashes: Vec<_> = prev_uncles
.into_iter()
.filter_map(|entry| match entry {
UncleEntryItem::InclusionHeight(_) => None,
UncleEntryItem::Uncle(h, _) => Some(h),
})
.collect();
let mut acc: <T::FilterUncle as FilterUncle<_, _>>::Accumulator =
Default::default();
for uncle in uncles {
match Self::verify_uncle(&uncle, &existing_hashes, &mut acc) {
Ok(_) => {
let hash = uncle.hash();
new_uncles.push(uncle);
existing_hashes.push(hash);
if new_uncles.len() == MAX_UNCLES {
break
}
},
Err(_) => {
},
}
}
}
if new_uncles.is_empty() {
None
} else {
Some(Call::set_uncles { new_uncles })
}
}
fn check_inherent(
call: &Self::Call,
_data: &InherentData,
) -> result::Result<(), Self::Error> {
match call {
Call::set_uncles { ref new_uncles } if new_uncles.len() > MAX_UNCLES =>
Err(InherentError::Uncles(Error::<T>::TooManyUncles.as_str().into())),
_ => Ok(()),
}
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Call::set_uncles { .. })
}
}
}
impl<T: Config> Pallet<T> {
pub fn author() -> Option<T::AccountId> {
if let Some(author) = <Author<T>>::get() {
return Some(author)
}
let digest = <frame_system::Pallet<T>>::digest();
let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());
T::FindAuthor::find_author(pre_runtime_digests).map(|a| {
<Author<T>>::put(&a);
a
})
}
fn verify_and_import_uncles(new_uncles: Vec<T::Header>) -> dispatch::DispatchResult {
let now = <frame_system::Pallet<T>>::block_number();
let mut uncles = <Uncles<T>>::get();
uncles
.try_push(UncleEntryItem::InclusionHeight(now))
.defensive_proof("the list of uncles accepted per generation is bounded, and the number of generations is bounded, so pushing a new element will always succeed")
.map_err(|_| Error::<T>::TooManyUncles)?;
let mut acc: <T::FilterUncle as FilterUncle<_, _>>::Accumulator = Default::default();
for uncle in new_uncles {
let prev_uncles = uncles.iter().filter_map(|entry| match entry {
UncleEntryItem::InclusionHeight(_) => None,
UncleEntryItem::Uncle(h, _) => Some(h),
});
let maybe_author = Self::verify_uncle(&uncle, prev_uncles, &mut acc)?;
let hash = uncle.hash();
if let Some(author) = maybe_author.clone() {
T::EventHandler::note_uncle(author, now - *uncle.number());
}
uncles.try_push(UncleEntryItem::Uncle(hash, maybe_author))
.defensive_proof("the list of uncles accepted per generation is bounded, and the number of generations is bounded, so pushing a new element will always succeed")
.map_err(|_| Error::<T>::TooManyUncles)?;
}
<Uncles<T>>::put(&uncles);
Ok(())
}
fn verify_uncle<'a, I: IntoIterator<Item = &'a T::Hash>>(
uncle: &T::Header,
existing_uncles: I,
accumulator: &mut <T::FilterUncle as FilterUncle<T::Header, T::AccountId>>::Accumulator,
) -> Result<Option<T::AccountId>, dispatch::DispatchError> {
let now = <frame_system::Pallet<T>>::block_number();
let (minimum_height, maximum_height) = {
let uncle_generations = T::UncleGenerations::get();
let min = now.saturating_sub(uncle_generations);
(min, now)
};
let hash = uncle.hash();
if uncle.number() < &One::one() {
return Err(Error::<T>::GenesisUncle.into())
}
if uncle.number() > &maximum_height {
return Err(Error::<T>::TooHighUncle.into())
}
{
let parent_number = *uncle.number() - One::one();
let parent_hash = <frame_system::Pallet<T>>::block_hash(&parent_number);
if &parent_hash != uncle.parent_hash() {
return Err(Error::<T>::InvalidUncleParent.into())
}
}
if uncle.number() < &minimum_height {
return Err(Error::<T>::OldUncle.into())
}
let duplicate = existing_uncles.into_iter().any(|h| *h == hash);
let in_chain = <frame_system::Pallet<T>>::block_hash(uncle.number()) == hash;
if duplicate || in_chain {
return Err(Error::<T>::UncleAlreadyIncluded.into())
}
T::FilterUncle::filter_uncle(uncle, accumulator).map_err(Into::into)
}
fn prune_old_uncles(minimum_height: T::BlockNumber) {
let uncles = <Uncles<T>>::get();
let prune_entries = uncles.iter().take_while(|item| match item {
UncleEntryItem::Uncle(_, _) => true,
UncleEntryItem::InclusionHeight(height) => height < &minimum_height,
});
let prune_index = prune_entries.count();
let pruned_uncles =
<BoundedSlice<'_, _, MaxUncleEntryItems<T>>>::try_from(&uncles[prune_index..])
.expect("after pruning we can't end up with more uncles than we started with");
<Uncles<T>>::put(pruned_uncles);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate as pallet_authorship;
use frame_support::{
parameter_types,
traits::{ConstU32, ConstU64, OnFinalize, OnInitialize},
ConsensusEngineId,
};
use sp_core::H256;
use sp_runtime::{
generic::DigestItem,
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
};
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
frame_support::construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Authorship: pallet_authorship::{Pallet, Call, Storage, Inherent},
}
);
parameter_types! {
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(frame_support::weights::Weight::from_ref_time(1024));
}
impl frame_system::Config for Test {
type BaseCallFilter = frame_support::traits::Everything;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Call = Call;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = Event;
type BlockHashCount = ConstU64<250>;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
}
impl pallet::Config for Test {
type FindAuthor = AuthorGiven;
type UncleGenerations = ConstU64<5>;
type FilterUncle = SealVerify<VerifyBlock>;
type EventHandler = ();
}
const TEST_ID: ConsensusEngineId = [1, 2, 3, 4];
pub struct AuthorGiven;
impl FindAuthor<u64> for AuthorGiven {
fn find_author<'a, I>(digests: I) -> Option<u64>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
for (id, mut data) in digests {
if id == TEST_ID {
return u64::decode(&mut data).ok()
}
}
None
}
}
pub struct VerifyBlock;
impl VerifySeal<Header, u64> for VerifyBlock {
fn verify_seal(header: &Header) -> Result<Option<u64>, &'static str> {
let pre_runtime_digests = header.digest.logs.iter().filter_map(|d| d.as_pre_runtime());
let seals = header.digest.logs.iter().filter_map(|d| d.as_seal());
let author =
AuthorGiven::find_author(pre_runtime_digests).ok_or_else(|| "no author")?;
for (id, mut seal) in seals {
if id == TEST_ID {
match u64::decode(&mut seal) {
Err(_) => return Err("wrong seal"),
Ok(a) => {
if a != author {
return Err("wrong author in seal")
}
break
},
}
}
}
Ok(Some(author))
}
}
fn seal_header(mut header: Header, author: u64) -> Header {
{
let digest = header.digest_mut();
digest.logs.push(DigestItem::PreRuntime(TEST_ID, author.encode()));
digest.logs.push(DigestItem::Seal(TEST_ID, author.encode()));
}
header
}
fn create_header(number: u64, parent_hash: H256, state_root: H256) -> Header {
Header::new(number, Default::default(), state_root, parent_hash, Default::default())
}
fn new_test_ext() -> sp_io::TestExternalities {
let t = frame_system::GenesisConfig::default().build_storage::<Test>().unwrap();
t.into()
}
#[test]
fn prune_old_uncles_works() {
use UncleEntryItem::*;
new_test_ext().execute_with(|| {
let hash = Default::default();
let author = Default::default();
let uncles = vec![
InclusionHeight(1u64),
Uncle(hash, Some(author)),
Uncle(hash, None),
Uncle(hash, None),
InclusionHeight(2u64),
Uncle(hash, None),
InclusionHeight(3u64),
Uncle(hash, None),
];
let uncles = BoundedVec::try_from(uncles).unwrap();
<Authorship as Store>::Uncles::put(uncles);
Authorship::prune_old_uncles(3);
let uncles = <Authorship as Store>::Uncles::get();
assert_eq!(uncles, vec![InclusionHeight(3u64), Uncle(hash, None)]);
})
}
#[test]
fn rejects_bad_uncles() {
new_test_ext().execute_with(|| {
let author_a = 69;
struct CanonChain {
inner: Vec<Header>,
}
impl CanonChain {
fn best_hash(&self) -> H256 {
self.inner.last().unwrap().hash()
}
fn canon_hash(&self, index: usize) -> H256 {
self.inner[index].hash()
}
fn header(&self, index: usize) -> &Header {
&self.inner[index]
}
fn push(&mut self, header: Header) {
self.inner.push(header)
}
}
let mut canon_chain = CanonChain {
inner: vec![seal_header(
create_header(0, Default::default(), Default::default()),
999,
)],
};
let initialize_block = |number, hash: H256| {
System::reset_events();
System::initialize(&number, &hash, &Default::default())
};
for number in 1..8 {
initialize_block(number, canon_chain.best_hash());
let header = seal_header(System::finalize(), author_a);
canon_chain.push(header);
}
initialize_block(8, canon_chain.best_hash());
{
let uncle_a = seal_header(
create_header(3, canon_chain.canon_hash(2), [1; 32].into()),
author_a,
);
assert_eq!(
Authorship::verify_and_import_uncles(vec![uncle_a.clone(), uncle_a.clone()]),
Err(Error::<Test>::UncleAlreadyIncluded.into()),
);
}
{
let uncle_a = seal_header(
create_header(3, canon_chain.canon_hash(2), [1; 32].into()),
author_a,
);
assert!(Authorship::verify_and_import_uncles(vec![uncle_a.clone()]).is_ok());
assert_eq!(
Authorship::verify_and_import_uncles(vec![uncle_a.clone()]),
Err(Error::<Test>::UncleAlreadyIncluded.into()),
);
}
{
let uncle_clone = canon_chain.header(5).clone();
assert_eq!(
Authorship::verify_and_import_uncles(vec![uncle_clone]),
Err(Error::<Test>::UncleAlreadyIncluded.into()),
);
}
{
let unsealed = create_header(3, canon_chain.canon_hash(2), [2; 32].into());
assert_eq!(
Authorship::verify_and_import_uncles(vec![unsealed]),
Err("no author".into()),
);
}
{
assert_eq!(System::block_number(), 8);
let gen_2 = seal_header(
create_header(2, canon_chain.canon_hash(1), [3; 32].into()),
author_a,
);
assert_eq!(
Authorship::verify_and_import_uncles(vec![gen_2]),
Err(Error::<Test>::OldUncle.into()),
);
}
{
let other_8 = seal_header(
create_header(8, canon_chain.canon_hash(7), [1; 32].into()),
author_a,
);
assert!(Authorship::verify_and_import_uncles(vec![other_8]).is_ok());
}
});
}
#[test]
fn maximum_bound() {
new_test_ext().execute_with(|| {
let mut max_item_count = 0;
let mut author_counter = 0;
let mut current_depth = 1;
let mut parent_hash: H256 = [1; 32].into();
let mut uncles = vec![];
for _ in 0..<<Test as Config>::UncleGenerations as Get<u64>>::get() + 3 {
let new_uncles: Vec<_> = (0..MAX_UNCLES)
.map(|_| {
System::reset_events();
System::initialize(¤t_depth, &parent_hash, &Default::default());
author_counter += 1;
seal_header(System::finalize(), author_counter)
})
.collect();
author_counter += 1;
System::reset_events();
System::initialize(¤t_depth, &parent_hash, &Default::default());
Authorship::on_initialize(current_depth);
Authorship::set_uncles(Origin::none(), uncles).unwrap();
Authorship::on_finalize(current_depth);
max_item_count =
std::cmp::max(max_item_count, <Authorship as Store>::Uncles::get().len());
let new_parent = seal_header(System::finalize(), author_counter);
parent_hash = new_parent.hash();
uncles = new_uncles;
current_depth += 1;
}
assert_eq!(max_item_count, MaxUncleEntryItems::<Test>::get() as usize);
});
}
#[test]
fn sets_author_lazily() {
new_test_ext().execute_with(|| {
let author = 42;
let mut header =
seal_header(create_header(1, Default::default(), [1; 32].into()), author);
header.digest_mut().pop(); System::reset_events();
System::initialize(&1, &Default::default(), header.digest());
assert_eq!(Authorship::author(), Some(author));
});
}
#[test]
fn one_uncle_per_author_per_number() {
type Filter = OnePerAuthorPerHeight<VerifyBlock, u64>;
let author_a = 42;
let author_b = 43;
let mut acc: <Filter as FilterUncle<Header, u64>>::Accumulator = Default::default();
let header_a1 = seal_header(create_header(1, Default::default(), [1; 32].into()), author_a);
let header_b1 = seal_header(create_header(1, Default::default(), [1; 32].into()), author_b);
let header_a2_1 =
seal_header(create_header(2, Default::default(), [1; 32].into()), author_a);
let header_a2_2 =
seal_header(create_header(2, Default::default(), [2; 32].into()), author_a);
let mut check_filter = move |uncle| Filter::filter_uncle(uncle, &mut acc);
assert_eq!(check_filter(&header_a1), Ok(Some(author_a)));
assert_eq!(check_filter(&header_b1), Ok(Some(author_b)));
assert_eq!(check_filter(&header_a2_1), Ok(Some(author_a)));
assert!(check_filter(&header_a2_2).is_err());
}
}