jam-std-common 0.1.16

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
use super::{Extrinsic, Header};
use core::fmt;
use jam_types::{
	chain_params, max_exports, max_imports, max_input, opaque, val_count, Balance, CoreIndex,
	FixedVec, SegmentSliceLen, Slot, UnsignedGas, ValIndex,
};
use scale::{Decode, Encode};
use std::{sync::atomic::Ordering::Relaxed, time::Duration};

/// Length of a timeslot in nanoseconds.
pub const SLOT_PERIOD_IN_NS: u64 = 6_000_000_000;

/// Length of a timeslot.
pub const SLOT_PERIOD: Duration = Duration::from_nanos(SLOT_PERIOD_IN_NS);

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

#[cfg(feature = "tiny")]
mod defaults {
	use super::{Slot, TicketAttempt};
	pub(super) const EPOCH_PERIOD: Slot = 12;
	pub(super) const ROTATION_PERIOD: Slot = 4;
	pub(super) const MAX_TICKETS_PER_BLOCK: usize = 3;
	pub(super) const TICKETS_ATTEMPTS_NUMBER: TicketAttempt = 3;
}
#[cfg(not(feature = "tiny"))]
mod defaults {
	use super::{Slot, TicketAttempt};
	pub(super) const EPOCH_PERIOD: Slot = 600;
	pub(super) const ROTATION_PERIOD: Slot = 10;
	pub(super) const MAX_TICKETS_PER_BLOCK: usize = 16;
	pub(super) const TICKETS_ATTEMPTS_NUMBER: TicketAttempt = 2;
}

chain_params! {
	/// The rotation period, defined in number of slots.
	static ROTATION_PERIOD: _ = _(defaults::ROTATION_PERIOD);
	pub fn rotation_period() -> Slot;
	pub struct RotationPeriod; impl Get<_> for _ {}

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

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

	/// Maximum number of tickets which each validator may create.
	///
	/// Influences the anonymity of block producers. As all published tickets have a public
	/// attempt number less than `attempts_number` 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.
	static TICKETS_ATTEMPTS_NUMBER: _ = _(defaults::TICKETS_ATTEMPTS_NUMBER);
	pub fn tickets_attempts_number() -> TicketAttempt;

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

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

	static DEPOSIT_PER_BYTE: _ = _(1);
	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: _ = _(3_500_000_000);
	pub fn block_gas_limit() -> UnsignedGas;

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

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

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

	static MAX_REFINE_CODE_SIZE: _ = _(10 * 1024 * 1024);
	pub fn max_refine_code_size() -> usize;

	static MAX_IS_AUTHORIZED_CODE_SIZE: _ = _(64 * 1024);
	pub fn max_is_authorized_code_size() -> usize;

	static MAX_REFINE_MEMORY: _ = _(1024 * 1024 * 1024);
	pub fn max_refine_memory() -> usize;

	static MAX_IS_AUTHORIZED_MEMORY: _ = _(256 * 1024);
	pub fn max_is_authorized_memory() -> 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: _ = _(8);
	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.
	pub fn core_count() -> CoreIndex {
		(val_count() as usize / VALS_PER_CORE) as 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: _ = _(5);
	pub fn availability_timeout() -> Slot;

	/// Number of items in the authorization window.
	static AUTH_WINDOW: _ = _(8);
	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: _ = _(24 * 600);
	pub fn max_lookup_anchor_age() -> Slot;
}

/// The conservative maximum size of a Work Package Bundle. This is basically `MAX_INPUT` plus sone
/// extra for the import proofs.
pub fn max_bundle_size() -> usize {
	max_input() as usize + 1024 * 1024
}

/// Parameters for the JAM protocol.
#[derive(
	Copy, Clone, Eq, PartialEq, Debug, Encode, Decode, serde::Serialize, serde::Deserialize,
)]
pub struct Parameters {
	/// Total number of validators. Must by divisible by guarantor group size (3).
	pub val_count: ValIndex,
	/// Number of octets in a basic piece. Must be even and divide into segment length (4,104).
	pub basic_piece_len: u32,
	/// Number of authorizations in a queue allocated to a core.
	pub auth_queue_len: u32,
	/// Minimum period in blocks between going from becoming `Available` to `Zombie`, and then
	/// again from `Zombie` to non-existent.
	pub min_turnaround_period: Slot,
	/// Maximum number of Work Items in a Work Package.
	pub max_work_items: u32,
	/// Maximum number of imports in a Work Package.
	pub max_imports: u32,
	/// Maximum number of exports in a Work Package.
	pub max_exports: u32,
	/// Maximum number of extrinsics in a Work Package.
	pub max_extrinsics: u32,
	/// Maximum number of dependencies (total of prerequisites and SR lookup entries).
	pub max_dependencies: u32,
	/// Maximum size of a Work Package together with all extrinsic data and imported segments.
	pub max_input: u32,

	/// The epoch period, defined in number of slots.
	pub epoch_period: Slot,
	/// The rotation period, defined in number of slots.
	pub rotation_period: Slot,
	/// Maximum gas which can be processed in a single block.
	pub block_gas_limit: UnsignedGas,
	/// The number of blocks which are kept in the recent block cache.
	pub recent_block_count: Slot,
	/// Max tickets allowed to be embedded in each block extrinsic.
	pub max_tickets_per_block: u32,
	/// The number of distinct tickets which may be created and submitted by each validator on each
	/// epoch.
	pub tickets_attempts_number: TicketAttempt,
	/// The base deposit required to retain an account.
	pub deposit_per_account: Balance,
	/// The additional deposit required for each preimage or storage item in an account.
	pub deposit_per_item: Balance,
	/// The additional deposit required for each byte of each storage item in an account and
	/// preimage of an account.
	pub deposit_per_byte: Balance,
	/// Maximum gas which may be used to Authorize a single work-package.
	pub max_is_authorized_gas: UnsignedGas,
	/// Maximum gas which may be used to Refine a single work-report.
	pub max_refine_gas: UnsignedGas,
	/// Maximum gas which may be used to Accumulate a single work-report.
	pub max_accumulate_gas: UnsignedGas,
	/// The maximum size of Refine/Accumulate code.
	pub max_refine_code_size: u32,
	/// The maximum size of Is-Authorized code.
	pub max_is_authorized_code_size: u32,
	/// The maximum amount of RAM which may be used by Refine/Accumulate code.
	pub max_refine_memory: u32,
	/// The maximum amount of RAM which may be used by IsAuthorized code.
	pub max_is_authorized_memory: u32,
	/// The period in timeslots after which reported but unavailable work may be replaced.
	pub availability_timeout: Slot,
	/// Number of items in the authorization window.
	pub auth_window: u32,
	/// Maximum age, in blocks, that the lookup anchor may be, taken from the regular anchor.
	pub max_lookup_anchor_age: Slot,
}
impl fmt::Display for Parameters {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"\n\
			val_count: {}\n\
			basic_piece_len: {}\n\
			auth_queue_len: {}\n\
			min_turnaround_period: {}\n\
			max_work_items: {}\n\
			max_imports: {}\n\
			max_exports: {}\n\
			max_extrinsics: {}\n\
			max_dependencies: {}\n\
			max_input: {}\n\
			epoch_period: {}\n\
			rotation_period: {}\n\
			block_gas_limit: {}\n\
			recent_block_count: {}\n\
			max_tickets_per_block: {}\n\
			tickets_attempts_number: {}\n\
			deposit_per_account: {}\n\
			deposit_per_item: {}\n\
			deposit_per_byte: {}\n\
			max_is_authorized_gas: {}\n\
			max_refine_gas: {}\n\
			max_accumulate_gas: {}\n\
			max_refine_code_size: {}\n\
			max_is_authorized_code_size: {}\n\
			max_refine_memory: {}\n\
			max_is_authorized_memory: {}\n\
			availability_timeout: {}\n\
			auth_window: {}\n\
			max_lookup_anchor_age: {}\n\
			",
			self.val_count,
			self.basic_piece_len,
			self.auth_queue_len,
			self.min_turnaround_period,
			self.max_work_items,
			self.max_imports,
			self.max_exports,
			self.max_extrinsics,
			self.max_dependencies,
			self.max_input,
			self.epoch_period,
			self.rotation_period,
			self.block_gas_limit,
			self.recent_block_count,
			self.max_tickets_per_block,
			self.tickets_attempts_number,
			self.deposit_per_account,
			self.deposit_per_item,
			self.deposit_per_byte,
			self.max_is_authorized_gas,
			self.max_refine_gas,
			self.max_accumulate_gas,
			self.max_refine_code_size,
			self.max_is_authorized_code_size,
			self.max_refine_memory,
			self.max_is_authorized_memory,
			self.availability_timeout,
			self.auth_window,
			self.max_lookup_anchor_age,
		)
	}
}

impl Parameters {
	pub fn tiny() -> Self {
		Self {
			val_count: 6,
			basic_piece_len: 4,
			auth_queue_len: 80,
			min_turnaround_period: 28_800,
			max_work_items: 16,
			max_imports: 3072,
			max_exports: 3072,
			max_extrinsics: 128,
			max_dependencies: 8,
			max_input: 12 * 1024 * 1024,
			epoch_period: 12,
			rotation_period: 4,
			block_gas_limit: 20_000_000,
			recent_block_count: 8,
			max_tickets_per_block: 3,
			tickets_attempts_number: 3,
			deposit_per_account: 100,
			deposit_per_item: 10,
			deposit_per_byte: 1,
			max_is_authorized_gas: 50_000_000,
			max_refine_gas: 1_600_000_000,
			max_accumulate_gas: 10_000_000,
			max_refine_code_size: 10 * 1024 * 1024,
			max_is_authorized_code_size: 64 * 1024,
			max_refine_memory: 1024 * 1024 * 1024,
			max_is_authorized_memory: 256 * 1024,
			availability_timeout: 5,
			auth_window: 8,
			max_lookup_anchor_age: 24 * 600,
		}
	}
	pub fn full() -> Self {
		Self {
			val_count: 1023,
			basic_piece_len: 684,
			auth_queue_len: 80,
			min_turnaround_period: 28_800,
			max_work_items: 16,
			max_imports: 3072,
			max_exports: 3072,
			max_extrinsics: 128,
			max_dependencies: 8,
			max_input: 12 * 1024 * 1024,
			epoch_period: 600,
			rotation_period: 10,
			block_gas_limit: 3_500_000_000,
			recent_block_count: 8,
			max_tickets_per_block: 16,
			tickets_attempts_number: 2,
			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_refine_code_size: 10 * 1024 * 1024,
			max_is_authorized_code_size: 64 * 1024,
			max_refine_memory: 1024 * 1024 * 1024,
			max_is_authorized_memory: 256 * 1024,
			availability_timeout: 5,
			auth_window: 8,
			max_lookup_anchor_age: 24 * 600,
		}
	}
	pub fn get() -> Self {
		let jam_types::Parameters {
			val_count,
			basic_piece_len,
			auth_queue_len,
			min_turnaround_period,
			max_work_items,
			max_imports,
			max_exports,
			max_extrinsics,
			max_dependencies,
			max_input,
		} = jam_types::Parameters::get();
		Self {
			val_count,
			basic_piece_len,
			auth_queue_len,
			min_turnaround_period,
			max_work_items,
			max_imports,
			max_exports,
			max_extrinsics,
			max_dependencies,
			max_input,
			epoch_period: EPOCH_PERIOD.load(Relaxed),
			rotation_period: ROTATION_PERIOD.load(Relaxed),
			block_gas_limit: BLOCK_GAS_LIMIT.load(Relaxed),
			recent_block_count: RECENT_BLOCK_COUNT.load(Relaxed),
			max_tickets_per_block: MAX_TICKETS_PER_BLOCK.load(Relaxed) as _,
			tickets_attempts_number: TICKETS_ATTEMPTS_NUMBER.load(Relaxed),
			deposit_per_account: DEPOSIT_PER_ACCOUNT.load(Relaxed),
			deposit_per_item: DEPOSIT_PER_ITEM.load(Relaxed),
			deposit_per_byte: DEPOSIT_PER_BYTE.load(Relaxed),
			max_is_authorized_gas: MAX_IS_AUTHORIZED_GAS.load(Relaxed),
			max_refine_gas: MAX_REFINE_GAS.load(Relaxed),
			max_accumulate_gas: MAX_ACCUMULATE_GAS.load(Relaxed),
			max_refine_code_size: MAX_REFINE_CODE_SIZE.load(Relaxed) as _,
			max_is_authorized_code_size: MAX_IS_AUTHORIZED_CODE_SIZE.load(Relaxed) as _,
			max_refine_memory: MAX_REFINE_MEMORY.load(Relaxed) as _,
			max_is_authorized_memory: MAX_IS_AUTHORIZED_MEMORY.load(Relaxed) as _,
			availability_timeout: AVAILABILITY_TIMEOUT.load(Relaxed),
			auth_window: AUTH_WINDOW.load(Relaxed) as _,
			max_lookup_anchor_age: MAX_LOOKUP_ANCHOR_AGE.load(Relaxed),
		}
	}
	pub fn validate(self) -> Result<jam_types::Parameters, &'static str> {
		let r = jam_types::Parameters {
			val_count: self.val_count,
			basic_piece_len: self.basic_piece_len,
			auth_queue_len: self.auth_queue_len,
			min_turnaround_period: self.min_turnaround_period,
			max_work_items: self.max_work_items,
			max_imports: self.max_imports,
			max_exports: self.max_exports,
			max_extrinsics: self.max_extrinsics,
			max_dependencies: self.max_dependencies,
			max_input: self.max_input,
		};
		r.validate()?;
		if self.epoch_period % self.rotation_period != 0 {
			return Err("`rotation_period` does not divide into `epoch_period`")
		}
		if self.val_count as usize % VALS_PER_CORE != 0 {
			return Err("`val_count` does not divide by `VALS_PER_CORE` (3)")
		}
		if recent_block_count() > 255 {
			return Err("`recent_block_count` may be no larger than `BlockIndex::MAX` (255)")
		}
		Ok(r)
	}
	pub fn apply(self) -> Result<(), &'static str> {
		let base = self.validate()?;
		base.apply()?;
		EPOCH_PERIOD.store(self.epoch_period, Relaxed);
		ROTATION_PERIOD.store(self.rotation_period, Relaxed);
		BLOCK_GAS_LIMIT.store(self.block_gas_limit, Relaxed);
		RECENT_BLOCK_COUNT.store(self.recent_block_count, Relaxed);
		MAX_TICKETS_PER_BLOCK.store(self.max_tickets_per_block as _, Relaxed);
		TICKETS_ATTEMPTS_NUMBER.store(self.tickets_attempts_number, Relaxed);
		DEPOSIT_PER_ACCOUNT.store(self.deposit_per_account, Relaxed);
		DEPOSIT_PER_ITEM.store(self.deposit_per_item, Relaxed);
		DEPOSIT_PER_BYTE.store(self.deposit_per_byte, Relaxed);
		MAX_IS_AUTHORIZED_GAS.store(self.max_is_authorized_gas, Relaxed);
		MAX_REFINE_GAS.store(self.max_refine_gas, Relaxed);
		MAX_ACCUMULATE_GAS.store(self.max_accumulate_gas, Relaxed);
		MAX_REFINE_CODE_SIZE.store(self.max_refine_code_size as _, Relaxed);
		MAX_IS_AUTHORIZED_CODE_SIZE.store(self.max_is_authorized_code_size as _, Relaxed);
		MAX_REFINE_MEMORY.store(self.max_refine_memory as _, Relaxed);
		MAX_IS_AUTHORIZED_MEMORY.store(self.max_is_authorized_memory as _, Relaxed);
		RECENT_BLOCK_COUNT.store(self.recent_block_count, Relaxed);
		AVAILABILITY_TIMEOUT.store(self.availability_timeout, Relaxed);
		AUTH_WINDOW.store(self.auth_window as _, Relaxed);
		MAX_LOOKUP_ANCHOR_AGE.store(self.max_lookup_anchor_age, Relaxed);
		Ok(())
	}
}

/// Maximum basic size of a Work Package that we accept.
pub const SANE_MAX_PACKAGE_SIZE: usize = 100 * 1024;

/// Maximum total output blobs which can be in a Work Report. The maximum encoded size of a Work
/// Report is this together with the portions which are constant or based on the (very limited)
/// number of Work Items.
pub const MAX_REPORT_ELECTIVE_DATA: usize = 48 * 1024;

/// The min. no. of signatures required for a guarantee to be valid.
///
/// Equals 2/3 of guarantors assigned to a core.
pub const GUARANTEE_MIN_SIGNATURES: usize = (VALS_PER_CORE * 2).div_ceil(3);

// Entropy required by some protocol's operations.
opaque! { pub struct Entropy(pub [u8; 32]); }

#[derive(Clone, Encode, Decode, Debug)]
pub struct Block {
	pub header: Header,
	pub extrinsic: Extrinsic,
}

/// The maximum number of levels in the implicit tree derived from the segment hashes in a
/// proof-page.
//pub const SUFFIX_SKIP_LEN: usize = (SEGMENT_LEN / 2 / 32).trailing_zeros() as usize;
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;

pub type SegmentSlice = FixedVec<u8, SegmentSliceLen>;

/// Type to represent the index of a tranche.
pub type TrancheIndex = u8;