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
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_std::prelude::*;
use crate::{
codec::{Decode, Encode, Error, Input},
scale_info::{
build::{Fields, Variants},
Path, Type, TypeInfo,
},
ConsensusEngineId,
};
use sp_core::RuntimeDebug;
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, parity_util_mem::MallocSizeOf))]
pub struct Digest {
pub logs: Vec<DigestItem>,
}
impl Default for Digest {
fn default() -> Self {
Self { logs: Vec::new() }
}
}
impl Digest {
pub fn logs(&self) -> &[DigestItem] {
&self.logs
}
pub fn push(&mut self, item: DigestItem) {
self.logs.push(item);
}
pub fn pop(&mut self) -> Option<DigestItem> {
self.logs.pop()
}
pub fn log<T: ?Sized, F: Fn(&DigestItem) -> Option<&T>>(&self, predicate: F) -> Option<&T> {
self.logs().iter().find_map(predicate)
}
pub fn convert_first<T, F: Fn(&DigestItem) -> Option<T>>(&self, predicate: F) -> Option<T> {
self.logs().iter().find_map(predicate)
}
}
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(parity_util_mem::MallocSizeOf))]
pub enum DigestItem {
PreRuntime(ConsensusEngineId, Vec<u8>),
Consensus(ConsensusEngineId, Vec<u8>),
Seal(ConsensusEngineId, Vec<u8>),
Other(Vec<u8>),
RuntimeEnvironmentUpdated,
}
#[cfg(feature = "std")]
impl serde::Serialize for DigestItem {
fn serialize<S>(&self, seq: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.using_encoded(|bytes| sp_core::bytes::serialize(bytes, seq))
}
}
#[cfg(feature = "std")]
impl<'a> serde::Deserialize<'a> for DigestItem {
fn deserialize<D>(de: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'a>,
{
let r = sp_core::bytes::deserialize(de)?;
Decode::decode(&mut &r[..])
.map_err(|e| serde::de::Error::custom(format!("Decode error: {}", e)))
}
}
impl TypeInfo for DigestItem {
type Identity = Self;
fn type_info() -> Type {
Type::builder().path(Path::new("DigestItem", module_path!())).variant(
Variants::new()
.variant("PreRuntime", |v| {
v.index(DigestItemType::PreRuntime as u8).fields(
Fields::unnamed()
.field(|f| f.ty::<ConsensusEngineId>().type_name("ConsensusEngineId"))
.field(|f| f.ty::<Vec<u8>>().type_name("Vec<u8>")),
)
})
.variant("Consensus", |v| {
v.index(DigestItemType::Consensus as u8).fields(
Fields::unnamed()
.field(|f| f.ty::<ConsensusEngineId>().type_name("ConsensusEngineId"))
.field(|f| f.ty::<Vec<u8>>().type_name("Vec<u8>")),
)
})
.variant("Seal", |v| {
v.index(DigestItemType::Seal as u8).fields(
Fields::unnamed()
.field(|f| f.ty::<ConsensusEngineId>().type_name("ConsensusEngineId"))
.field(|f| f.ty::<Vec<u8>>().type_name("Vec<u8>")),
)
})
.variant("Other", |v| {
v.index(DigestItemType::Other as u8)
.fields(Fields::unnamed().field(|f| f.ty::<Vec<u8>>().type_name("Vec<u8>")))
})
.variant("RuntimeEnvironmentUpdated", |v| {
v.index(DigestItemType::RuntimeEnvironmentUpdated as u8).fields(Fields::unit())
}),
)
}
}
#[derive(PartialEq, Eq, Clone, RuntimeDebug)]
pub enum DigestItemRef<'a> {
PreRuntime(&'a ConsensusEngineId, &'a Vec<u8>),
Consensus(&'a ConsensusEngineId, &'a Vec<u8>),
Seal(&'a ConsensusEngineId, &'a Vec<u8>),
Other(&'a Vec<u8>),
RuntimeEnvironmentUpdated,
}
#[repr(u32)]
#[derive(Encode, Decode)]
pub enum DigestItemType {
Other = 0,
Consensus = 4,
Seal = 5,
PreRuntime = 6,
RuntimeEnvironmentUpdated = 8,
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum OpaqueDigestItemId<'a> {
PreRuntime(&'a ConsensusEngineId),
Consensus(&'a ConsensusEngineId),
Seal(&'a ConsensusEngineId),
Other,
}
impl DigestItem {
pub fn dref(&self) -> DigestItemRef {
match *self {
Self::PreRuntime(ref v, ref s) => DigestItemRef::PreRuntime(v, s),
Self::Consensus(ref v, ref s) => DigestItemRef::Consensus(v, s),
Self::Seal(ref v, ref s) => DigestItemRef::Seal(v, s),
Self::Other(ref v) => DigestItemRef::Other(v),
Self::RuntimeEnvironmentUpdated => DigestItemRef::RuntimeEnvironmentUpdated,
}
}
pub fn as_pre_runtime(&self) -> Option<(ConsensusEngineId, &[u8])> {
self.dref().as_pre_runtime()
}
pub fn as_consensus(&self) -> Option<(ConsensusEngineId, &[u8])> {
self.dref().as_consensus()
}
pub fn as_seal(&self) -> Option<(ConsensusEngineId, &[u8])> {
self.dref().as_seal()
}
pub fn as_other(&self) -> Option<&[u8]> {
self.dref().as_other()
}
pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&[u8]> {
self.dref().try_as_raw(id)
}
pub fn try_to<T: Decode>(&self, id: OpaqueDigestItemId) -> Option<T> {
self.dref().try_to::<T>(id)
}
pub fn seal_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
self.dref().seal_try_to(id)
}
pub fn consensus_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
self.dref().consensus_try_to(id)
}
pub fn pre_runtime_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
self.dref().pre_runtime_try_to(id)
}
}
impl Encode for DigestItem {
fn encode(&self) -> Vec<u8> {
self.dref().encode()
}
}
impl codec::EncodeLike for DigestItem {}
impl Decode for DigestItem {
#[allow(deprecated)]
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let item_type: DigestItemType = Decode::decode(input)?;
match item_type {
DigestItemType::PreRuntime => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::PreRuntime(vals.0, vals.1))
},
DigestItemType::Consensus => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::Consensus(vals.0, vals.1))
},
DigestItemType::Seal => {
let vals: (ConsensusEngineId, Vec<u8>) = Decode::decode(input)?;
Ok(Self::Seal(vals.0, vals.1))
},
DigestItemType::Other => Ok(Self::Other(Decode::decode(input)?)),
DigestItemType::RuntimeEnvironmentUpdated => Ok(Self::RuntimeEnvironmentUpdated),
}
}
}
impl<'a> DigestItemRef<'a> {
pub fn as_pre_runtime(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
match *self {
Self::PreRuntime(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
_ => None,
}
}
pub fn as_consensus(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
match *self {
Self::Consensus(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
_ => None,
}
}
pub fn as_seal(&self) -> Option<(ConsensusEngineId, &'a [u8])> {
match *self {
Self::Seal(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)),
_ => None,
}
}
pub fn as_other(&self) -> Option<&'a [u8]> {
match *self {
Self::Other(ref data) => Some(data),
_ => None,
}
}
pub fn try_as_raw(&self, id: OpaqueDigestItemId) -> Option<&'a [u8]> {
match (id, self) {
(OpaqueDigestItemId::Consensus(w), &Self::Consensus(v, s)) |
(OpaqueDigestItemId::Seal(w), &Self::Seal(v, s)) |
(OpaqueDigestItemId::PreRuntime(w), &Self::PreRuntime(v, s))
if v == w =>
Some(&s[..]),
(OpaqueDigestItemId::Other, &Self::Other(s)) => Some(&s[..]),
_ => None,
}
}
pub fn try_to<T: Decode>(&self, id: OpaqueDigestItemId) -> Option<T> {
self.try_as_raw(id).and_then(|mut x| Decode::decode(&mut x).ok())
}
pub fn seal_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::Seal(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
pub fn consensus_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::Consensus(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
pub fn pre_runtime_try_to<T: Decode>(&self, id: &ConsensusEngineId) -> Option<T> {
match self {
Self::PreRuntime(v, s) if *v == id => Decode::decode(&mut &s[..]).ok(),
_ => None,
}
}
}
impl<'a> Encode for DigestItemRef<'a> {
fn encode(&self) -> Vec<u8> {
let mut v = Vec::new();
match *self {
Self::Consensus(val, data) => {
DigestItemType::Consensus.encode_to(&mut v);
(val, data).encode_to(&mut v);
},
Self::Seal(val, sig) => {
DigestItemType::Seal.encode_to(&mut v);
(val, sig).encode_to(&mut v);
},
Self::PreRuntime(val, data) => {
DigestItemType::PreRuntime.encode_to(&mut v);
(val, data).encode_to(&mut v);
},
Self::Other(val) => {
DigestItemType::Other.encode_to(&mut v);
val.encode_to(&mut v);
},
Self::RuntimeEnvironmentUpdated => {
DigestItemType::RuntimeEnvironmentUpdated.encode_to(&mut v);
},
}
v
}
}
impl<'a> codec::EncodeLike for DigestItemRef<'a> {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_serialize_digest() {
let digest = Digest {
logs: vec![DigestItem::Other(vec![1, 2, 3]), DigestItem::Seal(*b"test", vec![1, 2, 3])],
};
assert_eq!(
serde_json::to_string(&digest).unwrap(),
r#"{"logs":["0x000c010203","0x05746573740c010203"]}"#
);
}
#[test]
fn digest_item_type_info() {
let type_info = DigestItem::type_info();
let variants = if let scale_info::TypeDef::Variant(variant) = type_info.type_def() {
variant.variants()
} else {
panic!("Should be a TypeDef::TypeDefVariant")
};
let check = |digest_item_type: DigestItemType| {
let (variant_name, digest_item) = match digest_item_type {
DigestItemType::Other => ("Other", DigestItem::Other(Default::default())),
DigestItemType::Consensus =>
("Consensus", DigestItem::Consensus(Default::default(), Default::default())),
DigestItemType::Seal =>
("Seal", DigestItem::Seal(Default::default(), Default::default())),
DigestItemType::PreRuntime =>
("PreRuntime", DigestItem::PreRuntime(Default::default(), Default::default())),
DigestItemType::RuntimeEnvironmentUpdated =>
("RuntimeEnvironmentUpdated", DigestItem::RuntimeEnvironmentUpdated),
};
let encoded = digest_item.encode();
let variant = variants
.iter()
.find(|v| v.name() == &variant_name)
.expect(&format!("Variant {} not found", variant_name));
assert_eq!(encoded[0], variant.index())
};
check(DigestItemType::Other);
check(DigestItemType::Consensus);
check(DigestItemType::Seal);
check(DigestItemType::PreRuntime);
check(DigestItemType::RuntimeEnvironmentUpdated);
}
}