-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathheader.rs
1424 lines (1294 loc) · 54.5 KB
/
header.rs
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Smoldot
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! Parsing SCALE-encoded header.
//!
//! Each block of a chain is composed of two parts: its header, and its body.
//!
//! The header of a block consists in a list of hard coded fields such as the parent block's hash
//! or the block number, and a variable-sized list of log items.
//!
//! The standard format of a block header is the
//! [SCALE encoding](https://docs.substrate.io/v3/advanced/scale-codec). It is typically
//! under this encoding that block headers are for example transferred over the network or stored
//! in the database. Use the [`decode`] function in order to decompose a SCALE-encoded header
//! into a usable [`HeaderRef`].
//!
//! # Example
//!
//! ```
//! // Example encoded header.
//! let scale_encoded_header: &[u8] = &[
//! 246, 90, 76, 223, 195, 230, 202, 111, 120, 197, 6, 9, 90, 164, 170, 8, 194, 57, 184, 75,
//! 95, 67, 240, 169, 62, 244, 171, 95, 237, 85, 86, 1, 122, 169, 8, 0, 138, 149, 72, 185, 56,
//! 62, 30, 76, 117, 134, 123, 62, 4, 132, 23, 143, 200, 150, 171, 42, 63, 19, 173, 21, 89, 98,
//! 38, 175, 43, 132, 69, 75, 96, 168, 82, 108, 19, 182, 130, 230, 161, 43, 7, 225, 20, 229,
//! 92, 103, 57, 188, 151, 170, 16, 8, 126, 122, 98, 131, 121, 43, 181, 19, 180, 228, 8, 6, 66,
//! 65, 66, 69, 181, 1, 3, 1, 0, 0, 0, 250, 8, 207, 15, 0, 0, 0, 0, 86, 157, 105, 202, 151,
//! 254, 95, 169, 249, 150, 219, 194, 195, 143, 181, 39, 43, 87, 179, 157, 152, 191, 40, 255,
//! 23, 66, 18, 249, 93, 170, 58, 15, 178, 210, 130, 18, 66, 244, 232, 119, 74, 190, 92, 145,
//! 33, 192, 195, 176, 125, 217, 124, 33, 167, 97, 64, 63, 149, 200, 220, 191, 64, 134, 232, 9,
//! 3, 178, 186, 150, 130, 105, 25, 148, 218, 35, 208, 226, 112, 85, 184, 237, 23, 243, 86, 81,
//! 27, 127, 188, 223, 162, 244, 26, 77, 234, 116, 24, 11, 5, 66, 65, 66, 69, 1, 1, 112, 68,
//! 111, 83, 145, 78, 98, 96, 247, 64, 179, 237, 113, 175, 125, 177, 110, 39, 185, 55, 156,
//! 197, 177, 225, 226, 90, 238, 223, 115, 193, 185, 35, 67, 216, 98, 25, 55, 225, 224, 19, 43,
//! 255, 226, 125, 22, 160, 33, 182, 222, 213, 150, 40, 108, 108, 124, 254, 140, 228, 155, 29,
//! 250, 193, 65, 140,
//! ];
//!
//! // Decoding the header can panic if it is malformed. Do not unwrap if, for example, the
//! // header has been received from a remote!
//! // The second parameter is specific to each chain and corresponds to the number of bytes
//! // that are used to encode block numbers. This value is also necessary when calculating
//! // the hash of the header or encoding it.
//! let decoded_header = smoldot::header::decode(&scale_encoded_header, 4).unwrap();
//!
//! println!("Block hash: {:?}", decoded_header.hash(4));
//! println!("Header number: {}", decoded_header.number);
//! println!("Parent block hash: {:?}", decoded_header.parent_hash);
//! for item in decoded_header.digest.logs() {
//! println!("Digest item: {:?}", item);
//! }
//!
//! // Call `scale_encoding` to produce the header encoding.
//! let reencoded: Vec<u8> = decoded_header
//! .scale_encoding(4)
//! .fold(Vec::new(), |mut a, b| { a.extend_from_slice(b.as_ref()); a });
//! assert_eq!(reencoded, scale_encoded_header);
//! ```
// TODO: consider rewriting the encoding into a more legible style
use crate::{trie, util};
use alloc::{vec, vec::Vec};
use core::{fmt, iter, slice};
mod aura;
mod babe;
mod grandpa;
mod tests;
pub use aura::*;
pub use babe::*;
pub use grandpa::*;
/// Returns a hash of a SCALE-encoded header.
///
/// Does not verify the validity of the header.
pub fn hash_from_scale_encoded_header(header: impl AsRef<[u8]>) -> [u8; 32] {
hash_from_scale_encoded_header_vectored(iter::once(header))
}
/// Returns a hash of a SCALE-encoded header.
///
/// Must be passed a list of buffers, which, when concatenated, form the SCALE-encoded header.
///
/// Does not verify the validity of the header.
pub fn hash_from_scale_encoded_header_vectored(
header: impl Iterator<Item = impl AsRef<[u8]>>,
) -> [u8; 32] {
let mut hasher = blake2_rfc::blake2b::Blake2b::with_key(32, &[]);
for buf in header {
hasher.update(buf.as_ref());
}
let result = hasher.finalize();
debug_assert_eq!(result.as_bytes().len(), 32);
let mut out = [0; 32];
out.copy_from_slice(result.as_bytes());
out
}
/// Returns the value appropriate for [`Header::extrinsics_root`]. Must be passed the list of
/// transactions in that block.
pub fn extrinsics_root(transactions: &[impl AsRef<[u8]>]) -> [u8; 32] {
// The extrinsics root is always calculated with V0 of the trie.
trie::ordered_root(
trie::TrieEntryVersion::V0,
trie::HashFunction::Blake2,
transactions,
)
}
/// Attempt to decode the given SCALE-encoded header.
pub fn decode(scale_encoded: &[u8], block_number_bytes: usize) -> Result<HeaderRef, Error> {
let (header, remainder) = decode_partial(scale_encoded, block_number_bytes)?;
if !remainder.is_empty() {
return Err(Error::TooLong);
}
Ok(header)
}
/// Attempt to decode the given SCALE-encoded header.
///
/// Contrary to [`decode`], doesn't return an error if the slice is too long but returns the
/// remainder.
pub fn decode_partial(
mut scale_encoded: &[u8],
block_number_bytes: usize,
) -> Result<(HeaderRef, &[u8]), Error> {
if scale_encoded.len() < 32 + 1 {
return Err(Error::TooShort);
}
let parent_hash: &[u8; 32] = TryFrom::try_from(&scale_encoded[0..32]).unwrap();
scale_encoded = &scale_encoded[32..];
let (mut scale_encoded, number) =
crate::util::nom_scale_compact_u64::<nom::error::Error<&[u8]>>(scale_encoded)
.map_err(|_| Error::BlockNumberDecodeError)?;
if scale_encoded.len() < 32 + 32 + 1 {
return Err(Error::TooShort);
}
let state_root: &[u8; 32] = TryFrom::try_from(&scale_encoded[0..32]).unwrap();
scale_encoded = &scale_encoded[32..];
let extrinsics_root: &[u8; 32] = TryFrom::try_from(&scale_encoded[0..32]).unwrap();
scale_encoded = &scale_encoded[32..];
let (digest, remainder) = DigestRef::from_scale_bytes(scale_encoded, block_number_bytes)?;
let header = HeaderRef {
parent_hash,
number,
state_root,
extrinsics_root,
digest,
};
Ok((header, remainder))
}
/// Potential error when decoding a header.
#[derive(Debug, derive_more::Display, Clone)]
pub enum Error {
/// Header is not long enough.
TooShort,
/// Header is too long.
TooLong,
/// Error while decoding the block number.
BlockNumberDecodeError,
/// Error while decoding the digest length.
DigestLenDecodeError,
/// Error while decoding a digest log item length.
DigestItemLenDecodeError,
/// Error while decoding a digest item.
DigestItemDecodeError,
/// Digest log item with an unrecognized type.
#[display(fmt = "Digest log with an unrecognized type {_0}")]
UnknownDigestLogType(u8),
/// Found a seal that isn't the last item in the list.
SealIsntLastItem,
/// Bad length of an AURA seal.
BadAuraSealLength,
BadAuraConsensusRefType,
BadAuraAuthoritiesListLen,
/// There are multiple Aura pre-runtime digests in the block header.
MultipleAuraPreRuntimeDigests,
/// Bad length of a BABE seal.
BadBabeSealLength,
BadBabePreDigestRefType,
BadBabeConsensusRefType,
BadBabeNextConfigVersion,
/// There are multiple Babe pre-runtime digests in the block header.
MultipleBabePreRuntimeDigests,
/// There are multiple Babe epoch descriptor digests in the block header.
MultipleBabeEpochDescriptors,
/// There are multiple Babe configuration descriptor digests in the block header.
MultipleBabeConfigDescriptors,
/// There are multiple runtime environment updated digests in the block header.
MutipleRuntimeEnvironmentUpdated,
/// Found a Babe configuration change digest without an epoch change digest.
UnexpectedBabeConfigDescriptor,
GrandpaConsensusLogDecodeError,
/// Proof-of-work consensus algorithm is intentionally not supported for ideological reasons.
PowIdeologicallyNotSupported,
}
/// Header of a block, after decoding.
///
/// Note that the information in there are not guaranteed to be exact. The exactness of the
/// information depends on the context.
#[derive(Debug, Clone)]
pub struct HeaderRef<'a> {
/// Hash of the parent block stored in the header.
pub parent_hash: &'a [u8; 32],
/// Block number stored in the header.
pub number: u64,
/// The state trie Merkle root
pub state_root: &'a [u8; 32],
/// The Merkle root of the extrinsics.
///
/// You can use the [`extrinsics_root`] function to compute this value.
pub extrinsics_root: &'a [u8; 32],
/// List of auxiliary data appended to the block header.
pub digest: DigestRef<'a>,
}
impl<'a> HeaderRef<'a> {
/// Returns an iterator to list of buffers which, when concatenated, produces the SCALE
/// encoding of the header.
pub fn scale_encoding(
&self,
block_number_bytes: usize,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + 'a> + Clone + 'a {
self.scale_encoding_before_digest().map(either::Left).chain(
self.digest
.scale_encoding(block_number_bytes)
.map(either::Right),
)
}
/// Same as [`HeaderRef::scale_encoding`], but with an extra digest item added to the end of
/// the list.
///
/// > **Note**: Keep in mind that this can produce a potentially invalid header, for example
/// > if the digest contains duplicate items that shouldn't be duplicate.
pub fn scale_encoding_with_extra_digest_item(
&self,
block_number_bytes: usize,
extra_item: DigestItemRef<'a>,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + 'a> + Clone + 'a {
self.scale_encoding_before_digest().map(either::Left).chain(
self.digest
.scale_encoding_with_extra_item(block_number_bytes, extra_item)
.map(either::Right),
)
}
fn scale_encoding_before_digest(
&self,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + 'a> + Clone + 'a {
iter::once(either::Left(&self.parent_hash[..]))
.chain(iter::once(either::Right(util::encode_scale_compact_u64(
self.number,
))))
.chain(iter::once(either::Left(&self.state_root[..])))
.chain(iter::once(either::Left(&self.extrinsics_root[..])))
}
/// Equivalent to [`HeaderRef::scale_encoding`] but returns the data in a `Vec`.
pub fn scale_encoding_vec(&self, block_number_bytes: usize) -> Vec<u8> {
// We assume that an average header should be less than this size.
// At the time of writing of this comment, the average Westend/Polkadot/Kusama block
// header is 288 bytes, and the average parachain block is 186 bytes. Some blocks
// (the epoch transition blocks in particular) have a much larger header, but considering
// that they are the vast minority we don't care so much about that.
const CAP: usize = 1024;
self.scale_encoding(block_number_bytes)
.fold(Vec::with_capacity(CAP), |mut a, b| {
a.extend_from_slice(b.as_ref());
a
})
}
/// Builds the hash of the header.
pub fn hash(&self, block_number_bytes: usize) -> [u8; 32] {
hash_from_scale_encoded_header_vectored(self.scale_encoding(block_number_bytes))
}
}
impl<'a> From<&'a Header> for HeaderRef<'a> {
fn from(a: &'a Header) -> HeaderRef<'a> {
HeaderRef {
parent_hash: &a.parent_hash,
number: a.number,
state_root: &a.state_root,
extrinsics_root: &a.extrinsics_root,
digest: (&a.digest).into(),
}
}
}
/// Header of a block, after decoding.
///
/// Note that the information in there are not guaranteed to be exact. The exactness of the
/// information depends on the context.
#[derive(Debug, Clone)]
pub struct Header {
/// Hash of the parent block stored in the header.
pub parent_hash: [u8; 32],
/// Block number stored in the header.
pub number: u64,
/// The state trie Merkle root
pub state_root: [u8; 32],
/// The Merkle root of the extrinsics.
///
/// You can use the [`extrinsics_root`] function to compute this value.
pub extrinsics_root: [u8; 32],
/// List of auxiliary data appended to the block header.
pub digest: Digest,
}
impl Header {
/// Returns an iterator to list of buffers which, when concatenated, produces the SCALE
/// encoding of the header.
pub fn scale_encoding(
&'_ self,
block_number_bytes: usize,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + '_> + Clone + '_ {
HeaderRef::from(self).scale_encoding(block_number_bytes)
}
/// Equivalent to [`Header::scale_encoding`] but returns the data in a `Vec`.
pub fn scale_encoding_vec(&self, block_number_bytes: usize) -> Vec<u8> {
HeaderRef::from(self).scale_encoding_vec(block_number_bytes)
}
/// Builds the hash of the header.
pub fn hash(&self, block_number_bytes: usize) -> [u8; 32] {
HeaderRef::from(self).hash(block_number_bytes)
}
}
impl<'a> From<HeaderRef<'a>> for Header {
fn from(a: HeaderRef<'a>) -> Header {
Header {
parent_hash: *a.parent_hash,
number: a.number,
state_root: *a.state_root,
extrinsics_root: *a.extrinsics_root,
digest: a.digest.into(),
}
}
}
/// Generic header digest.
#[derive(Clone)]
pub struct DigestRef<'a> {
/// Actual source of digest items.
inner: DigestRefInner<'a>,
/// Index of the [`DigestItemRef::AuraSeal`] item, if any.
aura_seal_index: Option<usize>,
/// Index of the [`DigestItemRef::AuraPreDigest`] item, if any.
aura_predigest_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeSeal`] item, if any.
babe_seal_index: Option<usize>,
/// Index of the [`DigestItemRef::BabePreDigest`] item, if any.
babe_predigest_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeConsensus`] item containing a
/// [`BabeConsensusLogRef::NextEpochData`], if any.
babe_next_epoch_data_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeConsensus`] item containing a
/// [`BabeConsensusLogRef::NextConfigData`], if any.
babe_next_config_data_index: Option<usize>,
/// `true` if there is a [`DigestItemRef::RuntimeEnvironmentUpdated`] item.
has_runtime_environment_updated: bool,
}
#[derive(Clone)]
enum DigestRefInner<'a> {
/// Source of data is an undecoded slice of bytes.
Undecoded {
/// Number of log items in the header.
/// Must always match the actual number of items in [`DigestRefInner::Undecoded::digest`].
/// The validity must be verified before a [`DigestRef`] object is instantiated.
digest_logs_len: usize,
/// Encoded digest. Its validity must be verified before a [`DigestRef`] object is
/// instantiated.
digest: &'a [u8],
/// Number of bytes used to encode block numbers in headers.
block_number_bytes: usize,
},
Parsed(&'a [DigestItem]),
}
impl<'a> DigestRef<'a> {
/// Returns a digest with empty logs.
pub fn empty() -> DigestRef<'a> {
DigestRef {
inner: DigestRefInner::Parsed(&[]),
aura_seal_index: None,
aura_predigest_index: None,
babe_seal_index: None,
babe_predigest_index: None,
babe_next_epoch_data_index: None,
babe_next_config_data_index: None,
has_runtime_environment_updated: false,
}
}
/// Returns true if the list has any item that belong to the Aura consensus engine.
///
/// This function is `O(n)` over the number of log items.
pub fn has_any_aura(&self) -> bool {
self.logs().any(|l| l.is_aura())
}
/// Returns true if the list has any item that belong to the Babe consensus engine.
///
/// This function is `O(n)` over the number of log items.
pub fn has_any_babe(&self) -> bool {
self.logs().any(|l| l.is_babe())
}
/// Returns true if the list has any item that belong to the Grandpa finality engine.
///
/// This function is `O(n)` over the number of log items.
pub fn has_any_grandpa(&self) -> bool {
self.logs().any(|l| l.is_grandpa())
}
/// Returns the Aura seal digest item, if any.
pub fn aura_seal(&self) -> Option<&'a [u8; 64]> {
if let Some(aura_seal_index) = self.aura_seal_index {
if let DigestItemRef::AuraSeal(seal) = self.logs().nth(aura_seal_index).unwrap() {
Some(seal)
} else {
unreachable!()
}
} else {
None
}
}
/// Returns the Aura pre-runtime digest item, if any.
pub fn aura_pre_runtime(&self) -> Option<AuraPreDigest> {
if let Some(aura_predigest_index) = self.aura_predigest_index {
if let DigestItemRef::AuraPreDigest(item) =
self.logs().nth(aura_predigest_index).unwrap()
{
Some(item)
} else {
unreachable!()
}
} else {
None
}
}
/// Returns the Babe seal digest item, if any.
pub fn babe_seal(&self) -> Option<&'a [u8; 64]> {
if let Some(babe_seal_index) = self.babe_seal_index {
if let DigestItemRef::BabeSeal(seal) = self.logs().nth(babe_seal_index).unwrap() {
Some(seal)
} else {
unreachable!()
}
} else {
None
}
}
/// Returns the Babe pre-runtime digest item, if any.
pub fn babe_pre_runtime(&self) -> Option<BabePreDigestRef<'a>> {
if let Some(babe_predigest_index) = self.babe_predigest_index {
if let DigestItemRef::BabePreDigest(item) =
self.logs().nth(babe_predigest_index).unwrap()
{
Some(item)
} else {
unreachable!()
}
} else {
None
}
}
/// Returns the Babe epoch information stored in the header, if any.
///
/// It is guaranteed that a configuration change is present only if an epoch change is
/// present too.
pub fn babe_epoch_information(&self) -> Option<(BabeNextEpochRef<'a>, Option<BabeNextConfig>)> {
if let Some(babe_next_epoch_data_index) = self.babe_next_epoch_data_index {
if let DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextEpochData(epoch)) =
self.logs().nth(babe_next_epoch_data_index).unwrap()
{
if let Some(babe_next_config_data_index) = self.babe_next_config_data_index {
if let DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextConfigData(
config,
)) = self.logs().nth(babe_next_config_data_index).unwrap()
{
Some((epoch, Some(config)))
} else {
panic!()
}
} else {
Some((epoch, None))
}
} else {
unreachable!()
}
} else {
debug_assert!(self.babe_next_config_data_index.is_none());
None
}
}
/// Returns `true` if there is a [`DigestItemRef::RuntimeEnvironmentUpdated`] item.
pub fn has_runtime_environment_updated(&self) -> bool {
self.has_runtime_environment_updated
}
/// If the last element of the list is a seal, removes it from the [`DigestRef`].
pub fn pop_seal(&mut self) -> Option<Seal<'a>> {
let seal_pos = self.babe_seal_index.or(self.aura_seal_index)?;
match &mut self.inner {
DigestRefInner::Parsed(list) => {
debug_assert!(!list.is_empty());
debug_assert_eq!(seal_pos, list.len() - 1);
let item = &list[seal_pos];
*list = &list[..seal_pos];
match item {
DigestItem::AuraSeal(seal) => Some(Seal::Aura(seal)),
DigestItem::BabeSeal(seal) => Some(Seal::Babe(seal)),
_ => unreachable!(),
}
}
DigestRefInner::Undecoded {
digest,
digest_logs_len,
block_number_bytes,
} => {
debug_assert_eq!(seal_pos, *digest_logs_len - 1);
let mut iter = LogsIter {
inner: LogsIterInner::Undecoded {
pointer: digest,
remaining_len: *digest_logs_len,
block_number_bytes: *block_number_bytes,
},
};
for _ in 0..seal_pos {
let _item = iter.next();
debug_assert!(_item.is_some());
}
if let LogsIterInner::Undecoded {
pointer,
remaining_len,
..
} = iter.inner
{
*digest_logs_len -= 1;
*digest = &digest[..digest.len() - pointer.len()];
self.babe_seal_index = None;
debug_assert_eq!(remaining_len, 1);
} else {
unreachable!()
}
match iter.next() {
Some(DigestItemRef::AuraSeal(seal)) => Some(Seal::Aura(seal)),
Some(DigestItemRef::BabeSeal(seal)) => Some(Seal::Babe(seal)),
_ => unreachable!(),
}
}
}
}
/// Returns an iterator to the log items in this digest.
pub fn logs(&self) -> LogsIter<'a> {
LogsIter {
inner: match self.inner {
DigestRefInner::Parsed(list) => LogsIterInner::Decoded(list.iter()),
DigestRefInner::Undecoded {
digest,
digest_logs_len,
block_number_bytes,
} => LogsIterInner::Undecoded {
pointer: digest,
remaining_len: digest_logs_len,
block_number_bytes,
},
},
}
}
/// Returns an iterator to list of buffers which, when concatenated, produces the SCALE
/// encoding of the digest items.
pub fn scale_encoding(
&self,
block_number_bytes: usize,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + 'a> + Clone + 'a {
let encoded_len = util::encode_scale_compact_usize(self.logs().len());
iter::once(either::Left(encoded_len)).chain(
self.logs()
.flat_map(move |v| v.scale_encoding(block_number_bytes).map(either::Right)),
)
}
/// Same as [`DigestRef::scale_encoding`], but with an extra item added to the end of the list.
pub fn scale_encoding_with_extra_item(
&self,
block_number_bytes: usize,
extra_item: DigestItemRef<'a>,
) -> impl Iterator<Item = impl AsRef<[u8]> + Clone + 'a> + Clone + 'a {
// Given that `self.logs().len()` counts a number of items present in memory, and that
// these items have a non-zero size, it is not possible for this value to be equal to
// `usize::max_value()`, as that would mean that the entire memory is completely full
// of digest log items. Therefore, doing `+ 1` is also guaranteed to never overflow.
let new_len = self.logs().len() + 1;
let encoded_len = util::encode_scale_compact_usize(new_len);
iter::once(either::Left(encoded_len)).chain(
self.logs()
.chain(iter::once(extra_item))
.flat_map(move |v| v.scale_encoding(block_number_bytes).map(either::Right)),
)
}
/// Turns an already-decoded list of items into a [`DigestRef`].
///
/// Error can happen if the list of items is invalid, for example if it contains a seal at the
/// non-last position.
pub fn from_slice(slice: &'a [DigestItem]) -> Result<Self, Error> {
let mut aura_seal_index = None;
let mut aura_predigest_index = None;
let mut babe_seal_index = None;
let mut babe_predigest_index = None;
let mut babe_next_epoch_data_index = None;
let mut babe_next_config_data_index = None;
let mut has_runtime_environment_updated = false;
// Iterate through the log items to see if anything is wrong.
for (item_num, item) in slice.iter().enumerate() {
match item {
DigestItem::AuraPreDigest(_) if aura_predigest_index.is_none() => {
aura_predigest_index = Some(item_num);
}
DigestItem::AuraPreDigest(_) => return Err(Error::MultipleAuraPreRuntimeDigests),
DigestItem::AuraConsensus(_) => {}
DigestItem::BabePreDigest(_) if babe_predigest_index.is_none() => {
babe_predigest_index = Some(item_num);
}
DigestItem::BabePreDigest(_) => return Err(Error::MultipleBabePreRuntimeDigests),
DigestItem::BabeConsensus(BabeConsensusLog::NextEpochData(_))
if babe_next_epoch_data_index.is_none() =>
{
babe_next_epoch_data_index = Some(item_num);
}
DigestItem::BabeConsensus(BabeConsensusLog::NextEpochData(_)) => {
return Err(Error::MultipleBabeEpochDescriptors);
}
DigestItem::BabeConsensus(BabeConsensusLog::NextConfigData(_))
if babe_next_config_data_index.is_none() =>
{
babe_next_config_data_index = Some(item_num);
}
DigestItem::BabeConsensus(BabeConsensusLog::NextConfigData(_)) => {
return Err(Error::MultipleBabeConfigDescriptors);
}
DigestItem::BabeConsensus(BabeConsensusLog::OnDisabled(_)) => {}
DigestItem::GrandpaConsensus(_) => {}
DigestItem::AuraSeal(_) if item_num == slice.len() - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
aura_seal_index = Some(item_num);
}
DigestItem::AuraSeal(_) => return Err(Error::SealIsntLastItem),
DigestItem::BabeSeal(_) if item_num == slice.len() - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
babe_seal_index = Some(item_num);
}
DigestItem::RuntimeEnvironmentUpdated if has_runtime_environment_updated => {
return Err(Error::MutipleRuntimeEnvironmentUpdated);
}
DigestItem::RuntimeEnvironmentUpdated => {
has_runtime_environment_updated = true;
}
DigestItem::BabeSeal(_) => return Err(Error::SealIsntLastItem),
DigestItem::UnknownSeal { .. } if item_num == slice.len() - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
}
DigestItem::UnknownSeal { .. } => return Err(Error::SealIsntLastItem),
DigestItem::UnknownConsensus { .. }
| DigestItem::UnknownPreRuntime { .. }
| DigestItem::Other(..) => {}
}
}
if babe_next_config_data_index.is_some() && babe_next_epoch_data_index.is_none() {
return Err(Error::UnexpectedBabeConfigDescriptor);
}
Ok(DigestRef {
inner: DigestRefInner::Parsed(slice),
aura_seal_index,
aura_predigest_index,
babe_seal_index,
babe_predigest_index,
babe_next_epoch_data_index,
babe_next_config_data_index,
has_runtime_environment_updated,
})
}
/// Try to decode a list of digest items, from their SCALE encoding.
fn from_scale_bytes(
scale_encoded: &'a [u8],
block_number_bytes: usize,
) -> Result<(Self, &'a [u8]), Error> {
let (scale_encoded, digest_logs_len) =
crate::util::nom_scale_compact_usize::<nom::error::Error<&[u8]>>(scale_encoded)
.map_err(|_| Error::DigestItemLenDecodeError)?;
let mut aura_seal_index = None;
let mut aura_predigest_index = None;
let mut babe_seal_index = None;
let mut babe_predigest_index = None;
let mut babe_next_epoch_data_index = None;
let mut babe_next_config_data_index = None;
let mut has_runtime_environment_updated = false;
// Iterate through the log items to see if anything is wrong.
let mut next_digest = scale_encoded;
for item_num in 0..digest_logs_len {
let (item, next) = decode_item(next_digest, block_number_bytes)?;
next_digest = next;
match item {
DigestItemRef::AuraPreDigest(_) if aura_predigest_index.is_none() => {
aura_predigest_index = Some(item_num);
}
DigestItemRef::AuraPreDigest(_) => {
return Err(Error::MultipleAuraPreRuntimeDigests)
}
DigestItemRef::AuraConsensus(_) => {}
DigestItemRef::BabePreDigest(_) if babe_predigest_index.is_none() => {
babe_predigest_index = Some(item_num);
}
DigestItemRef::BabePreDigest(_) => {
return Err(Error::MultipleBabePreRuntimeDigests)
}
DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextEpochData(_))
if babe_next_epoch_data_index.is_none() =>
{
babe_next_epoch_data_index = Some(item_num);
}
DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextEpochData(_)) => {
return Err(Error::MultipleBabeEpochDescriptors);
}
DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextConfigData(_))
if babe_next_config_data_index.is_none() =>
{
babe_next_config_data_index = Some(item_num);
}
DigestItemRef::BabeConsensus(BabeConsensusLogRef::NextConfigData(_)) => {
return Err(Error::MultipleBabeConfigDescriptors);
}
DigestItemRef::BabeConsensus(BabeConsensusLogRef::OnDisabled(_)) => {}
DigestItemRef::GrandpaConsensus(_) => {}
DigestItemRef::AuraSeal(_) if item_num == digest_logs_len - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
aura_seal_index = Some(item_num);
}
DigestItemRef::AuraSeal(_) => return Err(Error::SealIsntLastItem),
DigestItemRef::BabeSeal(_) if item_num == digest_logs_len - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
babe_seal_index = Some(item_num);
}
DigestItemRef::RuntimeEnvironmentUpdated if has_runtime_environment_updated => {
return Err(Error::MutipleRuntimeEnvironmentUpdated);
}
DigestItemRef::RuntimeEnvironmentUpdated => {
has_runtime_environment_updated = true;
}
DigestItemRef::BabeSeal(_) => return Err(Error::SealIsntLastItem),
DigestItemRef::UnknownSeal { .. } if item_num == digest_logs_len - 1 => {
debug_assert!(aura_seal_index.is_none());
debug_assert!(babe_seal_index.is_none());
}
DigestItemRef::UnknownSeal { .. } => return Err(Error::SealIsntLastItem),
DigestItemRef::UnknownConsensus { .. }
| DigestItemRef::UnknownPreRuntime { .. }
| DigestItemRef::Other { .. } => {}
}
}
if babe_next_config_data_index.is_some() && babe_next_epoch_data_index.is_none() {
return Err(Error::UnexpectedBabeConfigDescriptor);
}
let out = DigestRef {
inner: DigestRefInner::Undecoded {
digest_logs_len,
digest: scale_encoded,
block_number_bytes,
},
aura_seal_index,
aura_predigest_index,
babe_seal_index,
babe_predigest_index,
babe_next_epoch_data_index,
babe_next_config_data_index,
has_runtime_environment_updated,
};
Ok((out, next_digest))
}
}
impl<'a> fmt::Debug for DigestRef<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.logs()).finish()
}
}
impl<'a> From<&'a Digest> for DigestRef<'a> {
fn from(digest: &'a Digest) -> DigestRef<'a> {
DigestRef {
inner: DigestRefInner::Parsed(&digest.list),
aura_seal_index: digest.aura_seal_index,
aura_predigest_index: digest.aura_predigest_index,
babe_seal_index: digest.babe_seal_index,
babe_predigest_index: digest.babe_predigest_index,
babe_next_epoch_data_index: digest.babe_next_epoch_data_index,
babe_next_config_data_index: digest.babe_next_config_data_index,
has_runtime_environment_updated: digest.has_runtime_environment_updated,
}
}
}
/// Seal popped using [`DigestRef::pop_seal`].
pub enum Seal<'a> {
Aura(&'a [u8; 64]),
Babe(&'a [u8; 64]),
}
/// Generic header digest.
#[derive(Clone)]
pub struct Digest {
/// Actual list of items.
list: Vec<DigestItem>,
/// Index of the [`DigestItemRef::AuraSeal`] item, if any.
aura_seal_index: Option<usize>,
/// Index of the [`DigestItemRef::AuraPreDigest`] item, if any.
aura_predigest_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeSeal`] item, if any.
babe_seal_index: Option<usize>,
/// Index of the [`DigestItemRef::BabePreDigest`] item, if any.
babe_predigest_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeConsensus`] item containing a
/// [`BabeConsensusLogRef::NextEpochData`], if any.
babe_next_epoch_data_index: Option<usize>,
/// Index of the [`DigestItemRef::BabeConsensus`] item containing a
/// [`BabeConsensusLogRef::NextConfigData`], if any.
babe_next_config_data_index: Option<usize>,
/// `true` if there is a [`DigestItemRef::RuntimeEnvironmentUpdated`] item.
has_runtime_environment_updated: bool,
}
impl Digest {
/// Returns an iterator to the log items in this digest.
pub fn logs(&self) -> LogsIter {
DigestRef::from(self).logs()
}
/// Returns the Aura seal digest item, if any.
pub fn aura_seal(&self) -> Option<&[u8; 64]> {
DigestRef::from(self).aura_seal()
}
/// Returns the Babe seal digest item, if any.
pub fn babe_seal(&self) -> Option<&[u8; 64]> {
DigestRef::from(self).babe_seal()
}
/// Returns the Babe pre-runtime digest item, if any.
pub fn babe_pre_runtime(&self) -> Option<BabePreDigestRef> {
DigestRef::from(self).babe_pre_runtime()
}
/// Returns the Babe epoch information stored in the header, if any.
///
/// It is guaranteed that a configuration change is present only if an epoch change is
/// present too.
pub fn babe_epoch_information(&self) -> Option<(BabeNextEpochRef, Option<BabeNextConfig>)> {
DigestRef::from(self).babe_epoch_information()
}
/// Returns `true` if there is a [`DigestItemRef::RuntimeEnvironmentUpdated`] item.
pub fn has_runtime_environment_updated(&self) -> bool {
self.has_runtime_environment_updated
}
}
impl fmt::Debug for Digest {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list()
.entries(self.list.iter().map(DigestItemRef::from))
.finish()
}
}
impl<'a> From<DigestRef<'a>> for Digest {
fn from(digest: DigestRef<'a>) -> Digest {
Digest {
list: digest.logs().map(Into::into).collect(),
aura_seal_index: digest.aura_seal_index,
aura_predigest_index: digest.aura_predigest_index,
babe_seal_index: digest.babe_seal_index,
babe_predigest_index: digest.babe_predigest_index,
babe_next_epoch_data_index: digest.babe_next_epoch_data_index,
babe_next_config_data_index: digest.babe_next_config_data_index,
has_runtime_environment_updated: digest.has_runtime_environment_updated,
}
}
}
/// Iterator towards the digest log items.
#[derive(Clone)]
pub struct LogsIter<'a> {
inner: LogsIterInner<'a>,
}
#[derive(Clone)]
enum LogsIterInner<'a> {
Decoded(slice::Iter<'a, DigestItem>),
Undecoded {
/// Encoded digest.
pointer: &'a [u8],
/// Number of log items remaining.
remaining_len: usize,
/// Number of bytes used to encode block numbers in the header.
block_number_bytes: usize,
},
}
impl<'a> Iterator for LogsIter<'a> {
type Item = DigestItemRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
match &mut self.inner {
LogsIterInner::Decoded(iter) => iter.next().map(Into::into),
LogsIterInner::Undecoded {
pointer,
remaining_len,
block_number_bytes,
} => {
if *remaining_len == 0 {
return None;
}
// Validity is guaranteed when the `DigestRef` is constructed.
let (item, new_pointer) = decode_item(pointer, *block_number_bytes).unwrap();
*pointer = new_pointer;
*remaining_len -= 1;
Some(item)
}
}
}