jam-std-common 0.1.26

Common datatypes and utilities for the JAM nodes and tooling
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
use crate::{
	AvailabilityStatement, Block, BoundedString, EpochIndex, ErasureRoot, PeerAddr, PeerDetails,
	PeerId, ReportGuarantee, TicketId, WorkReport,
};
use bounded_collections::{BoundedVec, ConstU32, TryCollect};
use codec::{Decode, Encode, MaxEncodedLen};
use jam_types::{
	CoreCount, CoreIndex, FixedVec, Hash, HeaderHash, ImportSpec, MaxDependencies,
	MaxImportSegments, MaxImports, MaxWorkItems, ProtocolParameters, SegmentTreeRoot, ServiceId,
	Slot, TicketAttempt, TicketsAttemptsNumber, UnsignedGas, ValIndex, WorkItem, WorkPackageHash,
	WorkReportHash, JAM_COMMON_ERA, VALS_PER_CORE,
};
use std::{
	ops::AddAssign,
	time::{Duration, SystemTime, UNIX_EPOCH},
};

/// Telemetry protocol version, should be incremented when the protocol changes.
pub const PROTOCOL_VERSION: u8 = 0;

pub type Reason = BoundedString<128>;

/// Microseconds since the beginning of the Jam "Common Era".
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode, MaxEncodedLen)]
pub struct Timestamp(pub u64);

impl Timestamp {
	pub fn now() -> Self {
		Self::from(SystemTime::now())
	}
}

impl std::fmt::Debug for Timestamp {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		self.0.fmt(f)
	}
}

impl From<SystemTime> for Timestamp {
	fn from(time: SystemTime) -> Self {
		let jam_ce = UNIX_EPOCH + Duration::from_secs(JAM_COMMON_ERA);
		let since_jam_ce = time.duration_since(jam_ce).unwrap_or(Duration::ZERO);
		Self(since_jam_ce.as_micros() as u64)
	}
}

impl From<Timestamp> for SystemTime {
	fn from(timestamp: Timestamp) -> Self {
		let jam_ce = UNIX_EPOCH + Duration::from_secs(JAM_COMMON_ERA);
		jam_ce + Duration::from_micros(timestamp.0)
	}
}

/// Each event sent over a connection is implicitly given an ID:
///
/// - The first event is given ID 0.
/// - The event immediately following an event E is given the ID of event E plus N, where N is the
///   number of dropped events if E is a "dropped" event, or 1 otherwise.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Encode, Decode, MaxEncodedLen)]
pub struct EventId(pub u64);

impl std::fmt::Debug for EventId {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		self.0.fmt(f)
	}
}

impl std::fmt::Display for EventId {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		self.0.fmt(f)
	}
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum ConnectionSide {
	Local = 0,
	Remote = 1,
}

pub type ShardIndex = u16;

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct BlockOutline {
	/// Size in bytes.
	pub size: u32,
	pub hash: HeaderHash,
	pub num_tickets: u32,
	pub num_preimages: u32,
	/// Total size of preimages in bytes.
	pub preimages_size: u32,
	pub num_guarantees: u32,
	pub num_assurances: u32,
	pub num_dispute_verdicts: u32,
}

impl From<(&Block, HeaderHash)> for BlockOutline {
	fn from((block, hash): (&Block, HeaderHash)) -> Self {
		Self {
			size: block.encoded_size() as u32,
			hash,
			num_tickets: block.extrinsic.tickets.len() as u32,
			num_preimages: block.extrinsic.preimages.len() as u32,
			preimages_size: block.extrinsic.preimages.iter().map(|p| p.blob.len() as u32).sum(),
			num_guarantees: block.extrinsic.guarantees.len() as u32,
			num_assurances: block.extrinsic.assurances.len() as u32,
			num_dispute_verdicts: block.extrinsic.disputes.verdicts.len() as u32,
		}
	}
}

impl From<&Block> for BlockOutline {
	fn from(block: &Block) -> Self {
		(block, block.header.hash()).into()
	}
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum BlockRequestDirection {
	AscendingExclusive = 0,
	DescendingInclusive = 1,
}

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct ExecCost {
	pub gas: UnsignedGas,
	/// Elapsed wall-clock time in nanoseconds.
	pub ns: u64,
}

impl AddAssign for ExecCost {
	fn add_assign(&mut self, rhs: Self) {
		self.gas += rhs.gas;
		self.ns += rhs.ns;
	}
}

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct IsAuthorizedCost {
	pub total: ExecCost,
	/// Time taken to load and compile the code, in nanoseconds.
	///
	/// Note that this is included in `total.ns`.
	pub load_ns: u64,
	/// Total cost of host calls.
	pub host_call: ExecCost,
}

impl AddAssign for IsAuthorizedCost {
	fn add_assign(&mut self, rhs: Self) {
		self.total += rhs.total;
		self.host_call += rhs.host_call;
	}
}

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct RefineHostCallCost {
	/// Total cost of `historical_lookup` calls.
	pub lookup: ExecCost,
	/// Total cost of `machine`/`expunge` calls.
	pub vm: ExecCost,
	/// Total cost of `peek`/`poke`/`pages` calls.
	pub mem: ExecCost,
	/// Total cost of `invoke` calls.
	pub invoke: ExecCost,
	/// Total cost of all other host calls.
	pub other: ExecCost,
}

impl AddAssign for RefineHostCallCost {
	fn add_assign(&mut self, rhs: Self) {
		self.lookup += rhs.lookup;
		self.vm += rhs.vm;
		self.mem += rhs.mem;
		self.invoke += rhs.invoke;
		self.other += rhs.other;
	}
}

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct RefineCost {
	pub total: ExecCost,
	/// Time taken to load and compile the code, in nanoseconds.
	///
	/// Note that this is included in `total.ns`.
	pub load_ns: u64,
	pub host_call: RefineHostCallCost,
}

impl AddAssign for RefineCost {
	fn add_assign(&mut self, rhs: Self) {
		self.total += rhs.total;
		self.host_call += rhs.host_call;
	}
}

pub type RefineCosts = BoundedVec<RefineCost, MaxWorkItems>;

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct AccumulateHostCallCost {
	/// Total cost of `read`/`write` calls.
	pub state: ExecCost,
	/// Total cost of `lookup` calls.
	pub lookup: ExecCost,
	/// Total cost of `query`/`solicit`/`forget`/`provide` calls.
	pub preimage: ExecCost,
	/// Total cost of `info`/`new`/`upgrade`/`eject` calls.
	pub service: ExecCost,
	/// Total cost of `transfer` calls.
	pub transfer: ExecCost,
	/// Total gas charged for transfer processing by destination services.
	pub transfer_dest_gas: UnsignedGas,
	/// Total cost of all other host calls.
	pub other: ExecCost,
}

impl AddAssign for AccumulateHostCallCost {
	fn add_assign(&mut self, rhs: Self) {
		self.state += rhs.state;
		self.lookup += rhs.lookup;
		self.preimage += rhs.preimage;
		self.service += rhs.service;
		self.transfer += rhs.transfer;
		self.transfer_dest_gas += rhs.transfer_dest_gas;
		self.other += rhs.other;
	}
}

#[derive(Clone, Debug, Default, Encode, Decode, MaxEncodedLen)]
pub struct AccumulateCost {
	/// Number of `accumulate` calls.
	pub num_calls: u32,
	/// Number of transfers processed.
	pub num_transfers: u32,
	/// Number of work items accumulated.
	pub num_items: u32,
	pub total: ExecCost,
	/// Time taken to load and compile the code, in nanoseconds.
	///
	/// Note that this is included in `total.ns`.
	pub load_ns: u64,
	pub host_call: AccumulateHostCallCost,
}

impl AddAssign for AccumulateCost {
	fn add_assign(&mut self, rhs: Self) {
		self.num_calls += rhs.num_calls;
		self.num_transfers += rhs.num_transfers;
		self.num_items += rhs.num_items;
		self.total += rhs.total;
		self.host_call += rhs.host_call;
	}
}

pub type AccumulateCosts = BoundedVec<(ServiceId, AccumulateCost), ConstU32<500>>;

/// Identifies a segment needed by a work-package.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportSegmentId {
	/// The segment with the given index in the overall list of imports.
	Import(u16),
	/// The proof page for the segment with the given index in the overall list of imports.
	ProofPage(u16),
}

impl ImportSegmentId {
	pub fn import(self) -> Option<u16> {
		match self {
			Self::Import(index) => Some(index),
			Self::ProofPage(_) => None,
		}
	}
}

impl Encode for ImportSegmentId {
	fn size_hint(&self) -> usize {
		2
	}

	fn encode_to<O: codec::Output + ?Sized>(&self, output: &mut O) {
		let index = match *self {
			Self::Import(index) => {
				debug_assert!(index < (1 << 15));
				index
			},
			Self::ProofPage(index) => {
				debug_assert!(index < (1 << 15));
				index + (1 << 15)
			},
		};
		index.encode_to(output);
	}
}

impl Decode for ImportSegmentId {
	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
		let index = u16::decode(input)?;
		if (index & (1 << 15)) == 0 {
			Ok(Self::Import(index))
		} else {
			Ok(Self::ProofPage(index & !(1 << 15)))
		}
	}

	fn encoded_fixed_size() -> Option<usize> {
		u16::encoded_fixed_size()
	}
}

impl MaxEncodedLen for ImportSegmentId {
	fn max_encoded_len() -> usize {
		u16::max_encoded_len()
	}
}

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct WorkItemOutline {
	pub service: ServiceId,
	pub payload_size: u32,
	pub refine_gas_limit: UnsignedGas,
	pub accumulate_gas_limit: UnsignedGas,
	/// Sum of extrinsic lengths.
	pub extrinsic_size: u32,
	pub imports: BoundedVec<ImportSpec, MaxImports>,
	pub num_exports: u16,
}

impl From<&WorkItem> for WorkItemOutline {
	fn from(item: &WorkItem) -> Self {
		Self {
			service: item.service,
			payload_size: item.payload.len() as u32,
			refine_gas_limit: item.refine_gas_limit,
			accumulate_gas_limit: item.accumulate_gas_limit,
			extrinsic_size: item.extrinsic_size(),
			imports: item.import_segments.clone(),
			num_exports: item.export_count,
		}
	}
}

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct WorkPackageOutline {
	/// Size in bytes, excluding extrinsic data.
	pub size: u32,
	pub hash: WorkPackageHash,
	pub anchor: HeaderHash,
	pub lookup_anchor_slot: Slot,
	pub prerequisites: BoundedVec<WorkPackageHash, MaxDependencies>,
	pub items: BoundedVec<WorkItemOutline, MaxWorkItems>,
}

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct WorkReportOutline {
	pub hash: WorkReportHash,
	/// Size of bundle in bytes.
	pub bundle_size: u32,
	pub erasure_root: ErasureRoot,
	pub exports_root: SegmentTreeRoot,
}

impl From<&WorkReport> for WorkReportOutline {
	fn from(report: &WorkReport) -> Self {
		Self {
			hash: report.hash(),
			bundle_size: report.package_spec.len,
			erasure_root: report.package_spec.erasure_root,
			exports_root: report.package_spec.exports_root,
		}
	}
}

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct GuaranteeOutline {
	pub report_hash: WorkReportHash,
	pub slot: Slot,
	pub guarantors: BoundedVec<ValIndex, ConstU32<{ VALS_PER_CORE as u32 }>>,
}

impl From<&ReportGuarantee> for GuaranteeOutline {
	fn from(guarantee: &ReportGuarantee) -> Self {
		Self {
			report_hash: guarantee.report.hash(),
			slot: guarantee.slot,
			guarantors: guarantee
				.signatures
				.iter()
				.map(|signature| signature.val_index)
				.try_collect()
				.expect("Output and input bounds are the same"),
		}
	}
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum GuaranteeDiscardReason {
	PackageReportedOnChain = 0,
	Superseded = 1,
	CannotReportOnChain = 2,
	TooMany = 3,
	Other = 4,
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum ReconstructionKind {
	/// A non-trivial reconstruction, involving at least some recovery shards.
	NonTrivial,
	/// A trivial reconstruction, using only original-data shards.
	Trivial,
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum AnnouncedPreimageForgetReason {
	ProvidedOnChain = 0,
	NotRequestedOnChain = 1,
	FailedToAcquire = 2,
	TooMany = 3,
	BadLength = 4,
	Other = 5,
}

#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen)]
pub enum PreimageDiscardReason {
	ProvidedOnChain = 0,
	NotRequestedOnChain = 1,
	TooMany = 2,
	Other = 3,
}

/// `NodeInfo` flag indicating that the node uses a PVM recompiler rather than an interpreter.
pub const NODE_USES_PVM_RECOMPILER: u32 = 1 << 0;

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct NodeInfo {
	/// Protocol parameters the node is using.
	pub params: ProtocolParameters,
	/// Genesis header hash.
	pub genesis: HeaderHash,
	/// Peer ID and external address of the node.
	pub details: PeerDetails,
	pub flags: u32,
	/// Name of the node implementation, eg "PolkaJam".
	pub impl_name: BoundedString<32>,
	/// Version of the node implementation, eg "1.0".
	pub impl_version: BoundedString<32>,
	/// Gray Paper version implemented by the node, eg "0.7.1".
	pub gp_version: BoundedString<16>,
	/// Freeform note with additional information about the node.
	pub note: BoundedString<512>,
}

macro_rules! event_struct {
	($(#[$attr:meta])* $name:ident { $($(#[$field_attr:meta])* $field_name:ident: $field_type:ty,)+ }) => {
		$(#[$attr])*
		#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
		pub struct $name {
			$($(#[$field_attr])* pub $field_name: $field_type,)+
		}
	};
}

macro_rules! events {
	($($(#[$attr:meta])* $name:ident = $discriminator:literal $fields:tt)+) => {
		pub mod event {
			use super::*;
			$(event_struct! { $(#[$attr])* $name $fields })+
		}

		#[repr(u8)]
		#[derive(Clone, Encode, Decode, MaxEncodedLen)]
		pub enum Event {
			$($name(event::$name) = $discriminator,)+
		}

		impl std::fmt::Debug for Event {
			fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
				match self {
					$(Self::$name(event) => event.fmt(f),)+
				}
			}
		}
	};
}

events! {
	Dropped = 0 {
		/// Timestamp of the last dropped event.
		last_timestamp: Timestamp,
		/// Number of dropped events.
		num: u64,
	}

	Status = 10 {
		/// Total number of peers.
		num_peers: u32,
		/// Number of validator peers.
		num_val_peers: u32,
		/// Number of peers with a block announcement stream open.
		num_sync_peers: u32,
		/// Number of guarantees in pool, by core.
		num_guarantees: FixedVec<u8, CoreCount>,
		/// Number of shards in availability store.
		num_shards: u32,
		/// Total size of shards in availability store, in bytes.
		shards_size: u64,
		/// Number of preimages in the pool, ready to be included in a block.
		num_preimages: u32,
		/// Total size of preimages in the pool, in bytes.
		preimages_size: u32,
	}

	BestBlockChanged = 11 {
		slot: Slot,
		hash: HeaderHash,
	}

	FinalizedBlockChanged = 12 {
		slot: Slot,
		hash: HeaderHash,
	}

	SyncStatusChanged = 13 {
		synced: bool,
	}

	ConnectionRefused = 20 {
		from: PeerAddr,
	}

	ConnectingIn = 21 {
		from: PeerAddr,
	}

	ConnectInFailed = 22 {
		connecting_id: EventId,
		reason: Reason,
	}

	ConnectedIn = 23 {
		connecting_id: EventId,
		peer_id: PeerId,
	}

	ConnectingOut = 24 {
		to: PeerDetails,
	}

	ConnectOutFailed = 25 {
		connecting_id: EventId,
		reason: Reason,
	}

	ConnectedOut = 26 {
		connecting_id: EventId,
	}

	Disconnected = 27 {
		peer: PeerId,
		/// Which side terminated the connection? May be `None` in case of eg timeout.
		terminator: Option<ConnectionSide>,
		reason: Reason,
	}

	PeerMisbehaved = 28 {
		peer: PeerId,
		reason: Reason,
	}

	Authoring = 40 {
		slot: Slot,
		parent: HeaderHash,
	}

	AuthoringFailed = 41 {
		authoring_id: EventId,
		reason: Reason,
	}

	Authored = 42 {
		authoring_id: EventId,
		outline: BlockOutline,
	}

	Importing = 43 {
		slot: Slot,
		outline: BlockOutline,
	}

	BlockVerificationFailed = 44 {
		importing_id: EventId,
		reason: Reason,
	}

	BlockVerified = 45 {
		importing_id: EventId,
	}

	BlockExecutionFailed = 46 {
		authoring_or_importing_id: EventId,
		reason: Reason,
	}

	BlockExecuted = 47 {
		authoring_or_importing_id: EventId,
		accumulate_costs: AccumulateCosts,
	}

	BlockAnnouncementStreamOpened = 60 {
		peer: PeerId,
		/// Which side opened the stream?
		opener: ConnectionSide,
	}

	BlockAnnouncementStreamClosed = 61 {
		peer: PeerId,
		/// Which side closed the stream?
		closer: ConnectionSide,
		reason: Reason,
	}

	BlockAnnounced = 62 {
		peer: PeerId,
		/// Which side announced the block?
		announcer: ConnectionSide,
		slot: Slot,
		hash: HeaderHash,
	}

	SendingBlockRequest = 63 {
		recipient: PeerId,
		hash: HeaderHash,
		direction: BlockRequestDirection,
		max_blocks: u32,
	}

	ReceivingBlockRequest = 64 {
		sender: PeerId,
	}

	BlockRequestFailed = 65 {
		/// ID of the corresponding `SendingBlockRequest` or `ReceivingBlockRequest` event.
		request_id: EventId,
		reason: Reason,
	}

	BlockRequestSent = 66 {
		/// ID of the corresponding `SendingBlockRequest`.
		request_id: EventId,
	}

	BlockRequestReceived = 67 {
		/// ID of the corresponding `ReceivingBlockRequest`.
		request_id: EventId,
		hash: HeaderHash,
		direction: BlockRequestDirection,
		max_blocks: u32,
	}

	BlockTransferred = 68 {
		/// ID of the corresponding `SendingBlockRequest` or `ReceivingBlockRequest` event.
		request_id: EventId,
		slot: Slot,
		outline: BlockOutline,
		/// Was this the last block for the request?
		last: bool,
	}

	GeneratingTickets = 80 {
		epoch: EpochIndex,
	}

	TicketGenerationFailed = 81 {
		/// ID of the corresponding `GeneratingTickets` event.
		generating_id: EventId,
		reason: Reason,
	}

	TicketsGenerated = 82 {
		/// ID of the corresponding `GeneratingTickets` event.
		generating_id: EventId,
		/// VRF outputs.
		ids: BoundedVec<TicketId, TicketsAttemptsNumber>,
	}

	TicketTransferFailed = 83 {
		peer: PeerId,
		/// Which side tried to send a ticket?
		sender: ConnectionSide,
		/// Was this a transfer from the proxy to a potential block author? If `false`, this was a
		/// transfer from the ticket creator to the proxy.
		from_proxy: bool,
		reason: Reason,
	}

	TicketTransferred = 84 {
		peer: PeerId,
		/// Which side sent a ticket?
		sender: ConnectionSide,
		/// Was this a transfer from the proxy to a potential block author? If `false`, this was a
		/// transfer from the ticket creator to the proxy.
		from_proxy: bool,
		/// The epoch the ticket is to be used in.
		epoch: EpochIndex,
		/// Ticket attempt number.
		attempt: TicketAttempt,
		/// VRF output.
		id: TicketId,
	}

	WorkPackageSubmission = 90 {
		builder: PeerId,
		bundle: bool,
	}

	WorkPackageBeingShared = 91 {
		primary: PeerId,
	}

	WorkPackageFailed = 92 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		reason: Reason,
	}

	DuplicateWorkPackage = 93 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		core: CoreIndex,
		hash: WorkPackageHash,
	}

	WorkPackageReceived = 94 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		core: CoreIndex,
		outline: WorkPackageOutline,
	}

	Authorized = 95 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		cost: IsAuthorizedCost,
	}

	ExtrinsicDataReceived = 96 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
	}

	ImportsReceived = 97 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
	}

	SharingWorkPackage = 98 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		secondary: PeerId,
	}

	WorkPackageSharingFailed = 99 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		secondary: PeerId,
		reason: Reason,
	}

	BundleSent = 100 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		secondary: PeerId,
	}

	Refined = 101 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		/// Cost of `refine` call for each work item.
		costs: RefineCosts,
	}

	WorkReportBuilt = 102 {
		/// ID of the corresponding `WorkPackageSubmission` or `WorkPackageBeingShared` event.
		submission_or_share_id: EventId,
		outline: WorkReportOutline,
	}

	WorkReportSignatureSent = 103 {
		/// ID of the corresponding `WorkPackageBeingShared` event.
		share_id: EventId,
	}

	WorkReportSignatureReceived = 104 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		secondary: PeerId,
	}

	GuaranteeBuilt = 105 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		outline: GuaranteeOutline,
	}

	SendingGuarantee = 106 {
		/// ID of the corresponding `GuaranteeBuilt` event.
		built_id: EventId,
		recipient: PeerId,
	}

	GuaranteeSendFailed = 107 {
		sending_id: EventId,
		reason: Reason,
	}

	GuaranteeSent = 108 {
		sending_id: EventId,
	}

	GuaranteesDistributed = 109 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
	}

	ReceivingGuarantee = 110 {
		sender: PeerId,
	}

	GuaranteeReceiveFailed = 111 {
		receiving_id: EventId,
		reason: Reason,
	}

	GuaranteeReceived = 112 {
		receiving_id: EventId,
		outline: GuaranteeOutline,
	}

	GuaranteeDiscarded = 113 {
		outline: GuaranteeOutline,
		reason: GuaranteeDiscardReason,
	}

	SendingShardRequest = 120 {
		guarantor: PeerId,
		erasure_root: ErasureRoot,
		shard: ShardIndex,
	}

	ReceivingShardRequest = 121 {
		assurer: PeerId,
	}

	ShardRequestFailed = 122 {
		/// ID of the corresponding `SendingShardRequest` or `ReceivingShardRequest` event.
		request_id: EventId,
		reason: Reason,
	}

	ShardRequestSent = 123 {
		/// ID of the corresponding `SendingShardRequest`.
		request_id: EventId,
	}

	ShardRequestReceived = 124 {
		/// ID of the corresponding `ReceivingShardRequest`.
		request_id: EventId,
		erasure_root: ErasureRoot,
		shard: ShardIndex,
	}

	ShardsTransferred = 125 {
		/// ID of the corresponding `SendingShardRequest` or `ReceivingShardRequest` event.
		request_id: EventId,
	}

	DistributingAssurance = 126 {
		statement: AvailabilityStatement,
	}

	AssuranceSendFailed = 127 {
		/// ID of the corresponding `DistributingAssurance` event.
		distributing_id: EventId,
		recipient: PeerId,
		reason: Reason,
	}

	AssuranceSent = 128 {
		/// ID of the corresponding `DistributingAssurance` event.
		distributing_id: EventId,
		recipient: PeerId,
	}

	AssuranceDistributed = 129 {
		/// ID of the corresponding `DistributingAssurance` event.
		distributing_id: EventId,
	}

	AssuranceReceiveFailed = 130 {
		sender: PeerId,
		reason: Reason,
	}

	AssuranceReceived = 131 {
		sender: PeerId,
		/// Assurance anchor.
		anchor: HeaderHash,
	}

	SendingBundleShardRequest = 140 {
		audit_id: EventId,
		assurer: PeerId,
		shard: ShardIndex,
	}

	ReceivingBundleShardRequest = 141 {
		auditor: PeerId,
	}

	BundleShardRequestFailed = 142 {
		/// ID of the corresponding `SendingBundleShardRequest` or `ReceivingBundleShardRequest`
		/// event.
		request_id: EventId,
		reason: Reason,
	}

	BundleShardRequestSent = 143 {
		/// ID of the corresponding `SendingBundleShardRequest`.
		request_id: EventId,
	}

	BundleShardRequestReceived = 144 {
		/// ID of the corresponding `ReceivingBundleShardRequest`.
		request_id: EventId,
		erasure_root: ErasureRoot,
		shard: ShardIndex,
	}

	BundleShardTransferred = 145 {
		/// ID of the corresponding `SendingBundleShardRequest` or `ReceivingBundleShardRequest`
		/// event.
		request_id: EventId,
	}

	ReconstructingBundle = 146 {
		audit_id: EventId,
		kind: ReconstructionKind,
	}

	BundleReconstructed = 147 {
		audit_id: EventId,
	}

	SendingBundleRequest = 148 {
		audit_id: EventId,
		guarantor: PeerId,
	}

	ReceivingBundleRequest = 149 {
		auditor: PeerId,
	}

	BundleRequestFailed = 150 {
		/// ID of the corresponding `SendingBundleRequest` or `ReceivingBundleRequest` event.
		request_id: EventId,
		reason: Reason,
	}

	BundleRequestSent = 151 {
		/// ID of the corresponding `SendingBundleRequest` event.
		request_id: EventId,
	}

	BundleRequestReceived = 152 {
		/// ID of the corresponding `ReceivingBundleRequest` event.
		request_id: EventId,
		erasure_root: ErasureRoot,
	}

	BundleTransferred = 153 {
		/// ID of the corresponding `SendingBundleRequest` or `ReceivingBundleRequest` event.
		request_id: EventId,
	}

	WorkPackageHashMapped = 160 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		work_package_hash: WorkPackageHash,
		segments_root: SegmentTreeRoot,
	}

	SegmentsRootMapped = 161 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		segments_root: SegmentTreeRoot,
		erasure_root: ErasureRoot,
	}

	SendingSegmentShardRequest = 162 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		assurer: PeerId,
		/// Are proofs of the segment shards being requested?
		proofs: bool,
		/// Segment shards being requested.
		shards: BoundedVec<(ImportSegmentId, ShardIndex), MaxImportSegments>,
	}

	ReceivingSegmentShardRequest = 163 {
		sender: PeerId,
		/// Have proofs of the segment shards been requested?
		proofs: bool,
	}

	SegmentShardRequestFailed = 164 {
		/// ID of the corresponding `SendingSegmentShardRequest` or `ReceivingSegmentShardRequest`
		/// event.
		request_id: EventId,
		reason: Reason,
	}

	SegmentShardRequestSent = 165 {
		/// ID of the corresponding `SendingSegmentShardRequest` event.
		request_id: EventId,
	}

	SegmentShardRequestReceived = 166 {
		/// ID of the corresponding `ReceivingSegmentShardRequest` event.
		request_id: EventId,
		/// Number of segment shards requested.
		num: u16,
	}

	SegmentShardsTransferred = 167 {
		/// ID of the corresponding `SendingSegmentShardRequest` or `ReceivingSegmentShardRequest`
		/// event.
		request_id: EventId,
	}

	ReconstructingSegments = 168 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		segments: BoundedVec<ImportSegmentId, MaxImportSegments>,
		kind: ReconstructionKind,
	}

	SegmentReconstructionFailed = 169 {
		/// ID of the corresponding `ReconstructingSegments` event.
		reconstructing_id: EventId,
		reason: Reason,
	}

	SegmentsReconstructed = 170 {
		/// ID of the corresponding `ReconstructingSegments` event.
		reconstructing_id: EventId,
	}

	SegmentVerificationFailed = 171 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		segments: BoundedVec<u16, MaxImports>,
		reason: Reason,
	}

	SegmentsVerified = 172 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		segments: BoundedVec<u16, MaxImports>,
	}

	SendingSegmentRequest = 173 {
		/// ID of the corresponding `WorkPackageSubmission` event.
		submission_id: EventId,
		prev_guarantor: PeerId,
		segments: BoundedVec<u16, MaxImportSegments>,
	}

	ReceivingSegmentRequest = 174 {
		guarantor: PeerId,
	}

	SegmentRequestFailed = 175 {
		/// ID of the corresponding `SendingSegmentRequest` or `ReceivingSegmentRequest` event.
		request_id: EventId,
		reason: Reason,
	}

	SegmentRequestSent = 176 {
		/// ID of the corresponding `SendingSegmentRequest` event.
		request_id: EventId,
	}

	SegmentRequestReceived = 177 {
		/// ID of the corresponding `ReceivingSegmentRequest` event.
		request_id: EventId,
		/// Number of segments requested.
		num: u16,
	}

	SegmentsTransferred = 178 {
		/// ID of the corresponding `SendingSegmentRequest` or `ReceivingSegmentRequest` event.
		request_id: EventId,
	}

	PreimageAnnouncementFailed = 190 {
		peer: PeerId,
		/// Which side tried to announce a preimage?
		announcer: ConnectionSide,
		reason: Reason,
	}

	PreimageAnnounced = 191 {
		peer: PeerId,
		/// Which side announced a preimage?
		announcer: ConnectionSide,
		/// ID of requesting service.
		service: ServiceId,
		hash: Hash,
		length: u32,
	}

	AnnouncedPreimageForgotten = 192 {
		service: ServiceId,
		hash: Hash,
		length: u32,
		reason: AnnouncedPreimageForgetReason,
	}

	SendingPreimageRequest = 193 {
		recipient: PeerId,
		hash: Hash,
	}

	ReceivingPreimageRequest = 194 {
		sender: PeerId,
	}

	PreimageRequestFailed = 195 {
		/// ID of the corresponding `SendingPreimageRequest` or `ReceivingPreimageRequest` event.
		request_id: EventId,
		reason: Reason,
	}

	PreimageRequestSent = 196 {
		/// ID of the corresponding `SendingPreimageRequest`.
		request_id: EventId,
	}

	PreimageRequestReceived = 197 {
		/// ID of the corresponding `ReceivingPreimageRequest`.
		request_id: EventId,
		hash: Hash,
	}

	PreimageTransferred = 198 {
		/// ID of the corresponding `SendingPreimageRequest` or `ReceivingPreimageRequest` event.
		request_id: EventId,
		length: u32,
	}

	PreimageDiscarded = 199 {
		hash: Hash,
		length: u32,
		reason: PreimageDiscardReason,
	}
}

impl Event {
	/// Returns the ID of the following event.
	///
	/// `id` should be the ID of this event.
	pub fn next_id(&self, id: EventId) -> EventId {
		let inc = match self {
			Self::Dropped(dropped) => dropped.num,
			_ => 1,
		};
		EventId(id.0 + inc)
	}
}

#[derive(Clone, Debug, Encode, Decode, MaxEncodedLen)]
pub struct TimestampedEvent {
	pub timestamp: Timestamp,
	pub event: Event,
}