jam-types 0.1.29

JAM protocol datatypes for interoperation between node internals, services and authorizers
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
#[allow(unused_imports)]
use super::Authorizer;
use crate::{FixedVec, chain_params, opaque};
use bounded_collections::{BoundedVec, Get};
use codec::{Decode, Encode, MaxEncodedLen};
use core::sync::atomic::Ordering::Relaxed;

/// Version of the Gray Paper implemented by this and dependent crates.
pub const GP_VERSION: &str = "0.8.0";

/// Beginning of the Jam "Common Era" (1200 UTC on January 1, 2025),
/// as seconds after the Unix epoch, excluding leap seconds.
pub const JAM_COMMON_ERA: u64 = 1_735_732_800;

/// Length of a transfer memo in bytes.
pub const MEMO_LEN: usize = 128;

/// Maximum length of the preimage in the encoded form.
#[doc(hidden)]
// TODO @ivan This is temporary value. Replace with the one from the GP when it's updated.
pub const MAX_PREIMAGE_LEN: usize = 32 * 1024 * 1024;

/// Maximum length of the preimage blob.
///
/// Equals `MAX_PREIMAGE_LEN` minus the overhead.
// TODO @ivan Unhide when the GP is updated.
#[doc(hidden)]
pub const MAX_PREIMAGE_BLOB_LEN: usize = MAX_PREIMAGE_LEN - 8;

/// PolkaVM page size in bytes.
pub const PAGE_SIZE: u32 = 4096;

/// The maximum number of levels in the implicit tree derived from the segment hashes in a
/// proof-page.
pub const SUFFIX_SKIP_LEN: usize = 6;

/// The maximum number of segments whose justification can be included in a single segment-sized
/// proof-page. Basically just the highest power of 2 which when multiplied by 32 (the size of a
/// hash) leaves enough room from 4104 (the size of a segment) to fit a partial Merkle proof of
/// 6 branches (6 * 32 = 192) plus the overhead for storing the actual number of hashes (should be
/// one byte for `PROVEN_PER_SEGMENT < 128`). It turns out that this is 2^6 = 64.
///
/// See `max_prefix_proof_len` for the actual formula.
pub const PROVEN_PER_SEGMENT: usize = 1 << SUFFIX_SKIP_LEN;

/// Fixed number of octets a storage item contributes to a service's footprint, over and above the
/// size of its key and value (GP: a 2-byte tag plus the 32-byte key hash).
pub const FOOTPRINT_STORAGE_OVERHEAD: u64 = 34;

/// Fixed number of octets a preimage lookup entry contributes to a service's footprint, over and
/// above the size of the preimage (GP account footprint formula).
pub const FOOTPRINT_PREIMAGE_OVERHEAD: u64 = 81;

/// Index for an attempt at producing a ticket for the right to produce a block.
pub type TicketAttempt = u8;

const DEFAULT_PARAMS: ProtocolParameters = ProtocolParameters::full();

chain_params! {
	/// Maximum number of validators in the JAM.
	pub fn max_val_count() -> ValIndex {
		(core_count() as usize * VALS_PER_CORE) as ValIndex
	}
	pub struct MaxValCount; impl Get<_> for _ {}

	/// Number of authorizations in a queue allocated to a core.
	static AUTH_QUEUE_LEN: _ = _(DEFAULT_PARAMS.auth_queue_len as _);
	pub fn auth_queue_len() -> usize;
	pub struct AuthQueueLen; impl Get<_> for _ {}

	/// Minimum period in blocks between going from becoming `Available` to `Zombie`, and then
	/// again from `Zombie` to non-existent.
	///
	/// This ensures firstly that any data added and referenced in a Work Report's lookup anchor
	/// block will remain on-chain right up until the latest possible time a dispute might
	/// conclude. Secondly, it ensure that we only need to record one "flip-flop" of the data's
	/// availability in order to be able to determine whether it's available or not at any block
	/// within this period.
	static MIN_TURNAROUND_PERIOD: _ = _(DEFAULT_PARAMS.min_turnaround_period);
	pub fn min_turnaround_period() -> Slot;

	/// Maximum number of Work Items in a Work Package.
	static MAX_WORK_ITEMS: _ = _(DEFAULT_PARAMS.max_work_items as _);
	pub fn max_work_items() -> usize;
	pub struct MaxWorkItems; impl Get<_> for _ {}

	/// Maximum number of imports in a Work Package.
	static MAX_IMPORTS: _ = _(DEFAULT_PARAMS.max_imports);
	pub fn max_imports() -> u32;
	pub struct MaxImports; impl Get<_> for _ {}

	/// Maximum number of exports in a Work Package.
	static MAX_EXPORTS: _ = _(DEFAULT_PARAMS.max_exports);
	pub fn max_exports() -> u32;

	/// Maximum number of extrinsics in a Work Package.
	static MAX_EXTRINSICS: _ = _(DEFAULT_PARAMS.max_extrinsics as _);
	pub fn max_extrinsics() -> u32;
	pub struct MaxExtrinsics; impl Get<_> for _ {}

	/// Maximum number of dependencies (total of prerequisites and SR lookup entries).
	static MAX_DEPENDENCIES: _ = _(DEFAULT_PARAMS.max_dependencies as _);
	pub fn max_dependencies() -> usize;
	pub struct MaxDependencies; impl Get<_> for _ {}

	/// Maximum total size of the authorization token, the authorizer config, the work-item
	/// payloads, the extrinsic data and the imports of a Work Package. Each import counts
	/// as one segment plus its maximum justification.
	static MAX_INPUT: _ = _(DEFAULT_PARAMS.max_input);
	pub fn max_input() -> u32;
	pub struct MaxInput; impl Get<_> for _ {}

	/// Number of bytes in a segment. This is fixed.
	pub const SEGMENT_LEN: _ = 4104;
	pub fn segment_len() -> usize;
	pub struct SegmentLen; impl Get<_> for _ {}

	/// Number of seconds in a time slot.
	static SLOT_PERIOD_SEC : _ = _(DEFAULT_PARAMS.slot_period_sec as _);
	pub fn slot_period_sec() -> u64;

	/// The rotation period, defined in number of slots.
	static ROTATION_PERIOD: _ = _(DEFAULT_PARAMS.rotation_period as _);
	pub fn rotation_period() -> Slot;

	/// The epoch period, defined in number of slots.
	static EPOCH_PERIOD: _ = _(DEFAULT_PARAMS.epoch_period);
	pub fn epoch_period() -> Slot;
	pub struct EpochPeriod; impl Get<_> for _ {}

	/// The length of the contest, defined in number of slots.
	static EPOCH_TAIL_START: _ = _(DEFAULT_PARAMS.epoch_tail_start);
	pub fn epoch_tail_start() -> Slot;

	/// Max tickets allowed to be embedded in each block extrinsic.
	static MAX_TICKETS_PER_BLOCK: _ = _(DEFAULT_PARAMS.max_tickets_per_block as _);
	pub fn max_tickets_per_block() -> usize;
	pub struct MaxTicketsPerBlock; impl Get<_> for _ {}

	static DEPOSIT_PER_ACCOUNT: _ = _(DEFAULT_PARAMS.deposit_per_account);
	pub fn deposit_per_account() -> Balance;

	static DEPOSIT_PER_ITEM: _ = _(DEFAULT_PARAMS.deposit_per_item);
	pub fn deposit_per_item() -> Balance;

	static DEPOSIT_PER_BYTE: _ = _(DEFAULT_PARAMS.deposit_per_byte);
	pub fn deposit_per_byte() -> Balance;

	/// The maximum gas which may be used in a single block. At present this is just the product of
	/// the maximum gas per work-report and the number of cores. In the future it should probably be
	/// more to account for the possibility of always-accumulate services.
	static BLOCK_GAS_LIMIT: _ = _(DEFAULT_PARAMS.block_gas_limit);
	pub fn block_gas_limit() -> UnsignedGas;

	/// Maximum gas which may be used to Authorize a single work-package.
	static MAX_IS_AUTHORIZED_GAS: _ = _(DEFAULT_PARAMS.max_is_authorized_gas);
	pub fn max_is_authorized_gas() -> UnsignedGas;

	/// Maximum gas which may be used to Refine a single work-report.
	static MAX_REFINE_GAS: _ = _(DEFAULT_PARAMS.max_refine_gas);
	pub fn max_refine_gas() -> UnsignedGas;

	/// Maximum gas which may be used to Accumulate a single work-report.
	static MAX_ACCUMULATE_GAS: _ = _(DEFAULT_PARAMS.max_accumulate_gas);
	pub fn max_accumulate_gas() -> UnsignedGas;

	static MAX_SERVICE_CODE_SIZE: _ = _(DEFAULT_PARAMS.max_service_code_size as _);
	pub fn max_service_code_size() -> usize;

	static MAX_AUTHORIZER_CODE_SIZE: _ = _(DEFAULT_PARAMS.max_authorizer_code_size as _);
	pub fn max_authorizer_code_size() -> usize;

	/// The number of blocks which are kept in the recent block cache. We use a `u8` to index into
	/// this and therefore it may be no larger than 255.
	static RECENT_BLOCK_COUNT: _ = _(DEFAULT_PARAMS.recent_block_count as _);
	pub fn recent_block_count() -> Slot;
	pub struct RecentBlockCount; impl Get<_> for _ {}

	/// The number of validators on each core.
	pub const VALS_PER_CORE: _ = 3;
	pub fn _vals_per_core() -> usize;
	pub struct _ValsPerCore; impl Get<_> for _ {}

	/// Number of cores in the JAM, including inactive cores.
	static CORE_COUNT: _ = _(DEFAULT_PARAMS.core_count);
	pub fn core_count() -> CoreIndex;
	pub struct CoreCount; impl Get<_> for _ {}

	/// Maximum number of DA segments that a Work Package can produce.
	pub fn max_export_segments() -> u32 {
		max_exports() + max_exports().div_ceil(PROVEN_PER_SEGMENT as u32)
	}
	pub struct MaxExportSegments; impl Get<_> for _ {}

	/// Maximum number of DA segments that a Work Package can require as imports. This is twice the
	/// maximum number of imports because each import may require a proof segment.
	pub fn max_import_segments() -> u32 { max_imports() * 2 }
	pub struct MaxImportSegments; impl Get<_> for _ {}

	/// The period in timeslots after which reported but unavailable work may be replaced.
	static AVAILABILITY_TIMEOUT: _ = _(DEFAULT_PARAMS.availability_timeout as _);
	pub fn availability_timeout() -> Slot;

	/// Number of items in the authorization window.
	static AUTH_WINDOW: _ = _(DEFAULT_PARAMS.auth_window as _);
	pub fn auth_window() -> usize;
	pub struct AuthWindow; impl Get<_> for _ {}

	/// Maximum age, in blocks, that the lookup anchor may be, taken from the regular anchor.
	static MAX_LOOKUP_ANCHOR_AGE: _ = _(DEFAULT_PARAMS.max_lookup_anchor_age);
	pub fn max_lookup_anchor_age() -> Slot;

	/// The maximum total size of all unbounded blobs in a work-report.
	/// Maximum age, in blocks, that the lookup anchor may be, taken from the regular anchor.
	static MAX_REPORT_ELECTIVE_DATA: _ = _(DEFAULT_PARAMS.max_report_elective_data);
	pub fn max_report_elective_data() -> u32;
	pub struct MaxReportElectiveData; impl Get<_> for _ {}
}

/// Whether `count` is an allowed validator-set size: a multiple of 3 in the
/// inclusive range `[6, 3·C]`.
pub fn is_valid_val_count(count: ValIndex) -> bool {
	count >= MIN_VAL_COUNT &&
		count <= max_val_count() &&
		(count as usize).is_multiple_of(VALS_PER_CORE)
}

/// Smallest allowed validator-set size.
pub const MIN_VAL_COUNT: ValIndex = 2 * VALS_PER_CORE as ValIndex;

/// Largest allowed core count: caps the validator set (`3·C`) at 1023, the bound assumed
/// by the Bandersnatch ring and by the erasure-code rate analysis.
pub const MAX_CORE_COUNT: CoreIndex = 341;

/// Largest allowed epoch period: keeps [`tickets_per_validator`] within `TicketAttempt` at
/// the smallest set size.
///
/// The allowance `⌈2E / v⌉` peaks at `v = MIN_VAL_COUNT` and fits `T=TicketAttempt::MAX`
/// only if `2E <= T * v`, that is `E <= T * v /2`. Beyond that the cast wraps silently.
pub const MAX_EPOCH_PERIOD: Slot = TicketAttempt::MAX as Slot * MIN_VAL_COUNT as Slot / 2;

/// Maximum number of tickets which each validator may create in an epoch, for a
/// non-empty pending validator set of size `val_count`.
///
/// The allowance grows as the validator set shrinks so the ticket accumulator can still
/// be saturated.
///
/// Influences the anonymity of block producers. As all published tickets have a public
/// attempt number less than this, if two tickets share an attempt number then they must
/// belong to two different validators, which reduces anonymity late as we approach the
/// epoch tail.
pub fn tickets_per_validator(val_count: ValIndex) -> TicketAttempt {
	((2 * epoch_period()).div_ceil(val_count as Slot)) as TicketAttempt
}

/// Erasure-coding recovery threshold `D(v)` for a validator set of size `val_count`:
/// any `D(v)` of the `v` erasure-coded chunks reconstruct the data.
///
/// The ideal rate (`D = v/3 + 1`) is lowered when needed so that pieces divide segments
/// without padding; it is ideal for the recommended set sizes `{6, 9, 15, 24, …, 1023}`.
pub const fn erasure_recovery_count(val_count: usize) -> usize {
	let mut recovery_count = val_count / VALS_PER_CORE + 1;
	// `SEGMENT_LEN` is even, so the loop always terminates at `d = 1`.
	while !SEGMENT_LEN.is_multiple_of(POINT_LEN * recovery_count) {
		recovery_count -= 1;
	}
	recovery_count
}

/// Number of bytes in a basic EC piece for a validator set of size `val_count`.
pub fn basic_piece_len(val_count: usize) -> usize {
	erasure_recovery_count(val_count) * POINT_LEN
}

/// Number of pieces in a segment for a validator set of size `val_count`.
pub fn pieces_per_segment(val_count: usize) -> usize {
	SEGMENT_LEN / basic_piece_len(val_count)
}

/// Number of bytes in a segment slice, the per-validator share of one segment, for a
/// validator set of size `val_count`.
pub fn segment_slice_len(val_count: usize) -> usize {
	SEGMENT_LEN / erasure_recovery_count(val_count)
}

/// Largest possible segment-slice length.
pub const MAX_SEGMENT_SLICE_LEN: usize =
	SEGMENT_LEN / erasure_recovery_count(MIN_VAL_COUNT as usize);
pub struct MaxSegmentSliceLen;
impl Get<u32> for MaxSegmentSliceLen {
	fn get() -> u32 {
		MAX_SEGMENT_SLICE_LEN as u32
	}
}

/// Baseline parameters for the JAM protocol.
#[derive(Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, MaxEncodedLen)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ProtocolParameters {
	/// (Bi) The additional deposit required for each preimage or storage item in an account.
	pub deposit_per_item: Balance,
	/// (Bl) The additional deposit required for each byte of each storage item in an account and
	/// preimage of an account.
	pub deposit_per_byte: Balance,
	/// (Bs) The base deposit required to retain an account.
	pub deposit_per_account: Balance,
	/// (C) Number of JAM cores.
	pub core_count: CoreIndex,
	/// (D) The period in timeslots after which an unreferenced preimage may be expunged.
	pub min_turnaround_period: Slot,
	/// (E) The epoch period, defined in number of slots.
	pub epoch_period: Slot,
	/// (Ga) Maximum gas which may be used to Accumulate a single work-report.
	pub max_accumulate_gas: UnsignedGas,
	/// (Gi) Maximum gas which may be used to Authorize a single work-package.
	pub max_is_authorized_gas: UnsignedGas,
	/// (Gr) Maximum gas which may be used to Refine a single work-report.
	pub max_refine_gas: UnsignedGas,
	/// (Gt) Maximum gas which can be processed in a single block.
	pub block_gas_limit: UnsignedGas,
	/// (H) The number of blocks which are kept in the recent block cache.
	pub recent_block_count: u16,
	/// (I) Maximum number of Work Items in a Work Package.
	pub max_work_items: u16,
	/// (J) Maximum number of dependencies (total of prerequisites and SR lookup entries).
	pub max_dependencies: u16,
	/// (K) Max tickets allowed to be embedded in each block extrinsic.
	pub max_tickets_per_block: u16,
	/// (L) Maximum age, in blocks, that the lookup anchor may be, taken from the regular anchor.
	pub max_lookup_anchor_age: Slot,
	/// (O) Number of items in the authorization window.
	pub auth_window: u16,
	/// (P) The period for each JAM time slot, defined in seconds.
	pub slot_period_sec: u16,
	/// (Q) Number of authorizations in a queue allocated to a core.
	pub auth_queue_len: u16,
	/// (R) The rotation period, defined in number of slots.
	pub rotation_period: u16,
	/// (T) Maximum number of extrinsics in a Work Package.
	pub max_extrinsics: u16,
	/// (U) The period in timeslots after which reported but unavailable work may be replaced.
	pub availability_timeout: u16,
	/// (Wa) The maximum size of authorizer code (used by Is-Authorized procedure).
	pub max_authorizer_code_size: u32,
	/// (Wb) Maximum size of a Work Package together with all extrinsic data and imported segments.
	pub max_input: u32,
	/// (Wc) The maximum size of service code (used by Refine/Accumulate/OnTransfer procedures).
	pub max_service_code_size: u32,
	/// (Wm) Maximum number of imports in a Work Package.
	pub max_imports: u32,
	/// (Wr) The maximum total size of all unbounded blobs in a work-report, in octets.
	pub max_report_elective_data: u32,
	/// (Wt) The size of a transfer memo in octets. The size of a transfer memo in octets.
	pub transfer_memo_size: u32,
	/// (Wx) Maximum number of exports in a Work Package.
	pub max_exports: u32,
	/// (Y) The length of the contest, defined in number of slots.
	pub epoch_tail_start: Slot,
}

impl ProtocolParameters {
	pub const fn full() -> Self {
		Self {
			core_count: 341,
			auth_queue_len: 80,
			min_turnaround_period: 19_200,
			max_work_items: 16,
			max_imports: 3072,
			max_exports: 3072,
			max_extrinsics: 128,
			max_dependencies: 8,
			max_input: 13_791_360,
			slot_period_sec: 6,
			epoch_period: 600,
			epoch_tail_start: 500,
			rotation_period: 10,
			block_gas_limit: 3_500_000_000,
			recent_block_count: 8,
			max_tickets_per_block: 16,
			deposit_per_account: 100,
			deposit_per_item: 10,
			deposit_per_byte: 1,
			max_is_authorized_gas: 50_000_000,
			max_refine_gas: 5_000_000_000,
			max_accumulate_gas: 10_000_000,
			max_service_code_size: 4_000_000,
			max_authorizer_code_size: 64_000,
			availability_timeout: 5,
			auth_window: 8,
			max_lookup_anchor_age: 24 * 600,
			max_report_elective_data: 48 * 1024,
			transfer_memo_size: 128,
		}
	}

	/// Roughly a quarter of the full spec: the parameters that `tiny` alters, scaled down to about
	/// a quarter of their full values. Large enough to resize the validator set over a wide range,
	/// small enough to cross epochs quickly.
	pub const fn large() -> Self {
		let mut params = Self::full();
		params.core_count = 85;
		params.epoch_period = 150;
		params.epoch_tail_start = 125;
		// Must divide the epoch; sits between tiny's 4 and full's 10.
		params.rotation_period = 5;
		params.block_gas_limit = 875_000_000;
		params.max_tickets_per_block = 4;
		params.max_refine_gas = 1_250_000_000;
		params.min_turnaround_period = 4_800;
		params.max_lookup_anchor_age = 3_600;
		params
	}

	pub const fn mini() -> Self {
		let mut params = Self::full();
		params.core_count = 26;
		params
	}

	pub const fn tiny() -> Self {
		let mut params = Self::full();
		params.core_count = 2;
		params.epoch_period = 12;
		params.epoch_tail_start = 10;
		params.rotation_period = 4;
		params.block_gas_limit = 20_000_000;
		params.max_tickets_per_block = 3;
		params.max_refine_gas = 1_000_000_000;
		// Remove unreferenced preimages after 32 slots.
		// The short retention period simplifies testing with test vectors and fuzzing.
		params.min_turnaround_period = 32;
		// Same reasoning as `min_turnaround_period`
		params.max_lookup_anchor_age = 24;
		params
	}

	/// Maximum validator-set size for this configuration.
	pub const fn max_val_count(&self) -> ValIndex {
		(self.core_count as usize * VALS_PER_CORE) as ValIndex
	}

	pub fn get() -> Self {
		Self {
			deposit_per_item: deposit_per_item(),
			deposit_per_byte: deposit_per_byte(),
			deposit_per_account: deposit_per_account(),
			core_count: core_count(),
			min_turnaround_period: min_turnaround_period(),
			epoch_period: epoch_period(),
			max_accumulate_gas: max_accumulate_gas(),
			max_is_authorized_gas: max_is_authorized_gas(),
			max_refine_gas: max_refine_gas(),
			block_gas_limit: block_gas_limit(),
			recent_block_count: recent_block_count() as _,
			max_work_items: max_work_items() as _,
			max_dependencies: max_dependencies() as _,
			max_tickets_per_block: max_tickets_per_block() as _,
			max_lookup_anchor_age: max_lookup_anchor_age(),
			auth_window: auth_window() as _,
			slot_period_sec: slot_period_sec() as _,
			auth_queue_len: auth_queue_len() as _,
			rotation_period: rotation_period() as _,
			max_extrinsics: max_extrinsics() as _,
			availability_timeout: availability_timeout() as _,
			max_authorizer_code_size: max_authorizer_code_size() as _,
			max_input: max_input(),
			max_service_code_size: max_service_code_size() as _,
			max_imports: max_imports() as _,
			max_report_elective_data: max_report_elective_data(),
			transfer_memo_size: MEMO_LEN as _,
			max_exports: max_exports(),
			epoch_tail_start: epoch_tail_start(),
		}
	}
	pub fn validate(&self) -> Result<(), &'static str> {
		if !self.epoch_period.is_multiple_of(self.rotation_period as Slot) {
			return Err("`rotation_period` does not divide into `epoch_period`")
		}
		if self.epoch_tail_start >= self.epoch_period {
			return Err("`epoch_tail_start` must be less than `epoch_period`")
		}
		if self.epoch_period > MAX_EPOCH_PERIOD {
			return Err("`epoch_period` may be no larger than `MAX_EPOCH_PERIOD` (765)")
		}
		if self.core_count < 2 {
			return Err("`core_count` must be at least 2, so the minimum validator set fits")
		}
		if self.core_count > MAX_CORE_COUNT {
			return Err("`core_count` may be no larger than `MAX_CORE_COUNT` (341)")
		}
		if self.transfer_memo_size != MEMO_LEN as u32 {
			return Err("`transfer_memo_size` must be equal tor `MEMO_LEN` (128)")
		}
		if recent_block_count() > 255 {
			return Err("`recent_block_count` may be no larger than `BlockIndex::MAX` (255)")
		}
		Ok(())
	}
	pub fn apply(self) -> Result<(), &'static str> {
		self.validate()?;
		DEPOSIT_PER_ITEM.store(self.deposit_per_item, Relaxed);
		DEPOSIT_PER_BYTE.store(self.deposit_per_byte, Relaxed);
		DEPOSIT_PER_ACCOUNT.store(self.deposit_per_account, Relaxed);
		MIN_TURNAROUND_PERIOD.store(self.min_turnaround_period, Relaxed);
		EPOCH_PERIOD.store(self.epoch_period, Relaxed);
		MAX_ACCUMULATE_GAS.store(self.max_accumulate_gas, Relaxed);
		MAX_IS_AUTHORIZED_GAS.store(self.max_is_authorized_gas, Relaxed);
		MAX_REFINE_GAS.store(self.max_refine_gas, Relaxed);
		BLOCK_GAS_LIMIT.store(self.block_gas_limit, Relaxed);
		RECENT_BLOCK_COUNT.store(self.recent_block_count as _, Relaxed);
		MAX_WORK_ITEMS.store(self.max_work_items as _, Relaxed);
		MAX_DEPENDENCIES.store(self.max_dependencies as _, Relaxed);
		MAX_TICKETS_PER_BLOCK.store(self.max_tickets_per_block as _, Relaxed);
		MAX_LOOKUP_ANCHOR_AGE.store(self.max_lookup_anchor_age as _, Relaxed);
		AUTH_WINDOW.store(self.auth_window as _, Relaxed);
		SLOT_PERIOD_SEC.store(self.slot_period_sec as _, Relaxed);
		AUTH_QUEUE_LEN.store(self.auth_queue_len as _, Relaxed);
		ROTATION_PERIOD.store(self.rotation_period as _, Relaxed);
		MAX_EXTRINSICS.store(self.max_extrinsics as _, Relaxed);
		AVAILABILITY_TIMEOUT.store(self.availability_timeout as _, Relaxed);
		CORE_COUNT.store(self.core_count, Relaxed);
		MAX_AUTHORIZER_CODE_SIZE.store(self.max_authorizer_code_size as _, Relaxed);
		MAX_INPUT.store(self.max_input, Relaxed);
		MAX_SERVICE_CODE_SIZE.store(self.max_service_code_size as _, Relaxed);
		MAX_IMPORTS.store(self.max_imports, Relaxed);
		MAX_REPORT_ELECTIVE_DATA.store(self.max_report_elective_data, Relaxed);
		MAX_EXPORTS.store(self.max_exports, Relaxed);
		EPOCH_TAIL_START.store(self.epoch_tail_start, Relaxed);
		Ok(())
	}
}

/// Number of bytes in an erasure-coding point.
pub const POINT_LEN: usize = 2;

/// The maximum number of validators `f` which may safely be faulty.
///
/// The total number of validators is `n = 3f + e` where `e in { 1, 2, 3 }`.
pub const fn byzantine_threshold(n: ValIndex) -> ValIndex {
	n.saturating_sub(1) / 3
}

/// The supermajority threshold of validators (`⌊2n/3⌋ + 1`) which represents a subset
/// guaranteed to have at least `f + 1` honest validators.
pub const fn supermajority_threshold(n: ValIndex) -> ValIndex {
	n - byzantine_threshold(n)
}

/// Max validators super-majority derived from the configured [`max_val_count`].
///
/// This is a codec/collection bound, not the protocol vote threshold: the exact
/// number of votes a verdict must carry is `supermajority_threshold(|V|)` where
/// `|V|` is the size of the validator set of the targeted epoch, which is checked
/// against the epoch's keyset by the STF.
#[doc(hidden)]
#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
pub struct MaxValSuperMajority;
impl Get<u32> for MaxValSuperMajority {
	fn get() -> u32 {
		supermajority_threshold(max_val_count()) as u32
	}
}

/// Type that represents a time slot of six seconds.
///
/// This can be either in a relative sense or as a period which has elapsed from the Polkadot
/// Common Era, beginning 1200 UTC, 1 January 2025.
pub type Slot = u32;
/// Type to represent the index of a validator.
pub type ValIndex = u16;
/// Type to represent the index of a compute core.
pub type CoreIndex = u16;
/// Type to represent the index of a service.
pub type ServiceId = u32;
/// Type to represent a balance.
pub type Balance = u64;
/// Type which is double the length of Balance, for non-overflowing multiplies.
pub type DoubleBalance = u128;
/// Type to represent some gas which may be below zero. This is used primarily for the `invoke`
/// hostcall API which must be able to return a negative gas amount in case of a gas overrun.
pub type SignedGas = i64;
/// Type to represent some gas which must be at least zero.
pub type UnsignedGas = u64;
/// Type which is double the length of Gas, for non-overflowing multiplies.
pub type DoubleGas = u128;

/// A basic 256-bit data value.
///
/// This should generally not be used directly in the rich data types, but instead one of the
/// rich opaque hash types to avoid accidental misuse and provide pretty-print facilities.
pub type Hash = [u8; 32];

opaque! {
	/// Hash of an encoded block header.
	pub struct HeaderHash(pub [u8; 32]);

	/// Hash of PVM program code.
	pub struct CodeHash(pub [u8; 32]);

	/// Hash of an encoded Work Package.
	pub struct WorkPackageHash(pub [u8; 32]);

	/// Hash of an encoded Work Report.
	pub struct WorkReportHash(pub [u8; 32]);

	/// Hash of a Work Item's [WorkPayload].
	pub struct PayloadHash(pub [u8; 32]);

	/// Hash of the JAM state root.
	pub struct StateRootHash(pub [u8; 32]);

	/// Hash of an MMR peak.
	pub struct MmrPeakHash(pub [u8; 32]);

	/// Hash of an accumulation tree root node.
	pub struct AccumulateRootHash(pub [u8; 32]);

	/// Hash of a piece of extrinsic data.
	pub struct ExtrinsicHash(pub [u8; 32]);

	/// Hash of an encoded [Authorizer] value.
	pub struct AuthorizerHash(pub [u8; 32]);

	/// Hash of a segment tree root node.
	pub struct SegmentTreeRoot(pub [u8; 32]);

	/// Hash of a [Segment] value.
	pub struct SegmentHash(pub [u8; 32]);

	/// Hash of a Merkle tree node.
	pub struct MerkleNodeHash(pub [u8; 32]);

	/// Non usage-specific hash.
	///
	/// This can be useful for pretty-printing [type@Hash] values.
	pub struct AnyHash(pub [u8; 32]);

	/// Transfer memo data, included with balance transfers between services.
	pub struct Memo(pub [u8; MEMO_LEN]);

	/// Data constituting the Authorization Token in a Work Package.
	pub struct Authorization(pub Vec<u8>);

	/// PVM Program code.
	pub struct Code(pub Vec<u8>);

	/// Payload data defining a Work Item.
	pub struct WorkPayload(pub Vec<u8>);

	/// Authorization parameter.
	pub struct AuthConfig(pub Vec<u8>);

	/// Non usage-specific data.
	///
	/// This can be useful for pretty-printing `Vec<u8>` values.
	pub struct AnyVec(pub Vec<u8>);

	/// Output data of Refinement operation, passed into Accumulation.
	pub struct WorkOutput(pub Vec<u8>);

	/// Output data of Is Authorized operation, passed into both Refinement and Accumulation.
	pub struct AuthTrace(pub Vec<u8>);

	/// Plain-old-data struct of the same length as an encoded Ed25519 public key.
	///
	/// This has no cryptographic functionality or dependencies.
	pub struct OpaqueEd25519Public(pub [u8; 32]);

	/// Plain-old-data struct of the same length as an encoded Bandersnatch public key.
	///
	/// This has no cryptographic functionality or dependencies.
	pub struct OpaqueBandersnatchPublic(pub [u8; 32]);

	/// Plain-old-data struct of the same length as an encoded BLS public key.
	///
	/// This has no cryptographic functionality or dependencies.
	pub struct OpaqueBlsPublic(pub [u8; 144]);

	/// Additional information on a validator, opaque to the actual usage.
	pub struct OpaqueValidatorMetadata(pub [u8; 128]);
}

#[cfg(feature = "bytes")]
opaque! {
	/// Non usage-specific data.
	///
	/// This can be useful for pretty-printing `Bytes` values.
	pub struct AnyBytes(pub Bytes);
}

/// A queue of [AuthorizerHash]s, each of which will be rotated into the authorizer pool for a core.
pub type AuthQueue = FixedVec<AuthorizerHash, AuthQueueLen>;

/// A segment of data.
pub type Segment = FixedVec<u8, SegmentLen>;
// TODO: ^^^ Measure performance penalty for this not being 4096.

impl Segment {
	pub fn as_array(&self) -> &[u8; SEGMENT_LEN] {
		self.as_slice().try_into().expect("Segment length is fixed")
	}
}

impl AsRef<[u8; SEGMENT_LEN]> for Segment {
	fn as_ref(&self) -> &[u8; SEGMENT_LEN] {
		self.as_array()
	}
}

pub trait ToAny {
	type Any;
	fn any(&self) -> Self::Any;
	fn into_any(self) -> Self::Any;
}

impl ToAny for [u8; 32] {
	type Any = AnyHash;
	fn any(&self) -> Self::Any {
		AnyHash(*self)
	}
	fn into_any(self) -> Self::Any {
		AnyHash(self)
	}
}

impl ToAny for alloc::vec::Vec<u8> {
	type Any = AnyVec;
	fn any(&self) -> Self::Any {
		AnyVec(self.clone())
	}
	fn into_any(self) -> Self::Any {
		AnyVec(self)
	}
}

impl ToAny for &[u8] {
	type Any = AnyVec;
	fn any(&self) -> Self::Any {
		AnyVec(self.to_vec())
	}
	fn into_any(self) -> Self::Any {
		AnyVec(self.to_vec())
	}
}

impl MaxEncodedLen for Authorization {
	fn max_encoded_len() -> usize {
		BoundedVec::<u8, MaxInput>::max_encoded_len()
	}
}

impl MaxEncodedLen for WorkPayload {
	fn max_encoded_len() -> usize {
		BoundedVec::<u8, MaxInput>::max_encoded_len()
	}
}

impl MaxEncodedLen for AuthConfig {
	fn max_encoded_len() -> usize {
		BoundedVec::<u8, MaxInput>::max_encoded_len()
	}
}

impl MaxEncodedLen for AuthTrace {
	fn max_encoded_len() -> usize {
		BoundedVec::<u8, MaxReportElectiveData>::max_encoded_len()
	}
}

impl AuthTrace {
	pub fn leak(self) -> &'static [u8] {
		self.0.leak()
	}
}

impl MaxEncodedLen for WorkOutput {
	fn max_encoded_len() -> usize {
		BoundedVec::<u8, MaxReportElectiveData>::max_encoded_len()
	}
}

impl WorkOutput {
	pub fn leak(self) -> &'static [u8] {
		self.0.leak()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	// The constant tuple exposed to services via the `fetch` host-call (case 0) must not
	// include the values GP #514 removed (V, N, WE, WP): they are no longer protocol
	// constants but derived from the validator-set size.
	#[test]
	fn protocol_parameters_fetch_encoding() {
		for params in [
			ProtocolParameters::full(),
			ProtocolParameters::large(),
			ProtocolParameters::mini(),
			ProtocolParameters::tiny(),
		] {
			// Every built-in spec must satisfy the parameter constraints.
			assert!(params.validate().is_ok(), "{params:?}");
			let encoded = params.encode();
			assert_eq!(encoded.len(), 7 * 8 + 11 * 4 + 11 * 2);
			let decoded = ProtocolParameters::decode(&mut &encoded[..]).unwrap();
			assert_eq!(decoded, params);
		}
	}

	// `D(v)` is defined as the largest `d <= v/3 + 1` such that `2d` divides the segment
	// size, so segments are always erasure-coded without padding. The rate is optimal
	// (`D(v) = v/3 + 1`) for the GP recommended set sizes.
	#[test]
	fn erasure_recovery_count_matches_gp() {
		assert_eq!(erasure_recovery_count(6), 3);
		assert_eq!(erasure_recovery_count(78), 27);
		assert_eq!(erasure_recovery_count(1023), 342);
		for count in (6..=1023).step_by(3) {
			let d = erasure_recovery_count(count);
			assert!(d <= count / VALS_PER_CORE + 1);
			assert!(SEGMENT_LEN.is_multiple_of(POINT_LEN * d), "v={count}");
		}
	}

	// `core_count` outside `[2, 341]` must be rejected: below 2 no allowed validator-set
	// size exists, above 341 the validator set would exceed 1023, the bound assumed by the
	// Bandersnatch ring and by the erasure-code rate analysis.
	#[test]
	fn core_count_bounds_enforced() {
		let mut params = ProtocolParameters::full();
		assert!(params.validate().is_ok());
		params.core_count = 1;
		assert!(params.validate().is_err());
		params.core_count = MAX_CORE_COUNT;
		assert!(params.validate().is_ok());
		params.core_count = MAX_CORE_COUNT + 1;
		assert!(params.validate().is_err());
	}

	// `⌈2E/|γP'|⌉` per-validator tickets: 2 with the full set, growing as the set shrinks
	// so the epoch's ticket accumulator can still be saturated at any allowed size.
	// Chain params default to the full spec here (E = 600, V = 1023).
	#[test]
	fn ticket_attempts_matches_gp() {
		assert_eq!(tickets_per_validator(max_val_count()), 2);
		assert_eq!(tickets_per_validator(MIN_VAL_COUNT), 200);
		for count in (MIN_VAL_COUNT as usize..=max_val_count() as usize).step_by(VALS_PER_CORE) {
			let attempts = tickets_per_validator(count as ValIndex) as usize;
			assert!(attempts * count >= 2 * epoch_period() as usize, "v={count}");
			assert!((attempts - 1) * count < 2 * epoch_period() as usize, "v={count}");
		}
	}
}