jam-std-common 0.1.29

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
use crate::{
	Entropy, Mmr, ReportGuarantee, ValKeysets, WorkReport,
	bandersnatch::ring_vrf::RingCommitment,
	hash_raw_concat,
	safrole::{EpochTicketsAccumulator, TicketsOrKeys},
};
use bounded_collections::ConstU32;
use codec::{Decode, Encode};
use jam_types::{
	AuthQueue, AuthWindow, AuthorizerHash, Balance, BoundedVec, CodeHash, CoreCount, EpochPeriod,
	FOOTPRINT_PREIMAGE_OVERHEAD, FOOTPRINT_STORAGE_OVERHEAD, FixedVec, Hash, HeaderHash,
	MmrPeakHash, RecentBlockCount, SegmentTreeRoot, ServiceId, ServiceInfo, Slot, StateRootHash,
	UnsignedGas, VecMap, VecSet, WorkPackageHash, WorkReportHash, deposit_per_account,
	deposit_per_byte, deposit_per_item, opaque,
};

opaque! {
	pub struct StorageKey(pub [u8; 31]);
}

#[derive(Debug, Encode, Decode, Copy, Clone, Eq, PartialEq)]
pub enum SystemKey {
	Reserved0 = 0,
	AuthPools = 1,
	AuthQueues = 2,
	RecentBlocks = 3,
	Safrole = 4,
	Disputes = 5,
	Entropy = 6,
	Designates = 7,
	Validators = 8,
	PrevValidators = 9,
	Availability = 10,
	CurrentTime = 11,
	Privileges = 12,
	Statistics = 13,
	ReadyQueue = 14,
	Accumulated = 15,
	AccumulationOutput = 16,
}

impl From<SystemKey> for StorageKey {
	fn from(value: SystemKey) -> Self {
		let k = value.encode();
		let mut r = [0; StorageKey::LEN];
		r[..k.len()].copy_from_slice(&k[..]);
		r.into()
	}
}

impl IntoStorageKey for SystemKey {}

impl IntoStorageKey for StorageKey {}

#[derive(Clone)]
pub enum ServiceKey<'a> {
	Info { id: ServiceId },
	Value { id: ServiceId, key: &'a [u8] },
	Request { id: ServiceId, len: u32, hash: [u8; 32] },
	Preimage { id: ServiceId, hash: [u8; 32] },
}

pub trait IntoStorageKey: Into<StorageKey> {
	fn service_id(&self) -> Option<ServiceId> {
		None
	}
}

impl IntoStorageKey for ServiceKey<'_> {
	fn service_id(&self) -> Option<ServiceId> {
		Some(match self {
			Self::Info { id, .. } |
			Self::Value { id, .. } |
			Self::Request { id, .. } |
			Self::Preimage { id, .. } => *id,
		})
	}
}

impl<'a> From<ServiceKey<'a>> for StorageKey {
	fn from(k: ServiceKey<'a>) -> Self {
		use ServiceKey::*;
		let id = match k {
			Info { id } | Value { id, .. } | Request { id, .. } | Preimage { id, .. } => id,
		}
		.to_le_bytes();
		let mut r = [0; StorageKey::LEN];
		let hash = match k {
			Info { .. } => {
				r[0] = 255;
				r[1] = id[0];
				r[3] = id[1];
				r[5] = id[2];
				r[7] = id[3];
				return r.into();
			},
			Value { key, .. } => hash_raw_concat([&[0xff, 0xff, 0xff, 0xff], key]),
			Preimage { hash, .. } => hash_raw_concat([&[0xfe, 0xff, 0xff, 0xff], &hash[..]]),
			Request { len, hash, .. } => hash_raw_concat([&len.to_le_bytes(), &hash[..]]),
		};
		r[..8].copy_from_slice(&[id[0], hash[0], id[1], hash[1], id[2], hash[2], id[3], hash[3]]);
		r[8..].copy_from_slice(&hash[4..27]);
		r.into()
	}
}

/// If `key` is a [`ServiceKey::Info`] state key, extract the service id.
///
/// This is the inverse of the `Info` arm of the [`StorageKey`] construction above.
pub fn service_id_from_info_key(key: &[u8]) -> Option<ServiceId> {
	if key.len() == StorageKey::LEN &&
		key[0] == 255 &&
		key[2] == 0 &&
		key[4] == 0 &&
		key[6] == 0 &&
		key[8..] == [0; 23]
	{
		Some(ServiceId::from_le_bytes([key[1], key[3], key[5], key[7]]))
	} else {
		None
	}
}

/// Current service struct version.
const SERVICE_VERSION: u8 = 0;

#[derive(Debug, Clone)]
pub struct Service {
	/// The hash of the code of the service.
	pub code_hash: CodeHash,
	/// The existing balance of the service.
	pub balance: Balance,
	/// The minimum amount of gas which must be provided to this service's `accumulate` for each
	/// work item it must process.
	pub min_item_gas: UnsignedGas,
	/// The minimum amount of gas which must be provided to this service's `accumulate` for each
	/// incoming transfer it must process.
	pub min_memo_gas: UnsignedGas,
	/// The total number of bytes used for data electively held for this service on-chain.
	pub bytes: u64,
	/// Offset of storage footprint only above which a minimum deposit is needed.
	pub deposit_offset: Balance,
	/// The total number of items of data electively held for this service on-chain.
	pub items: u32,
	/// Creation time slot.
	pub creation_slot: Slot,
	/// Most recent accumulation time slot.
	pub last_accumulation_slot: Slot,
	/// Parent service identifier.
	pub parent_service: ServiceId,
}

impl From<Service> for ServiceInfo {
	fn from(service: Service) -> Self {
		ServiceInfo {
			code_hash: service.code_hash,
			balance: service.balance,
			min_item_gas: service.min_item_gas,
			min_memo_gas: service.min_memo_gas,
			bytes: service.bytes,
			items: service.items,
			threshold: service.threshold(),
			deposit_offset: service.deposit_offset,
			creation_slot: service.creation_slot,
			last_accumulation_slot: service.last_accumulation_slot,
			parent_service: service.parent_service,
		}
	}
}

impl Encode for Service {
	fn encode_to<T: codec::Output + ?Sized>(&self, dest: &mut T) {
		dest.push_byte(SERVICE_VERSION);
		self.code_hash.encode_to(dest);
		self.balance.encode_to(dest);
		self.min_item_gas.encode_to(dest);
		self.min_memo_gas.encode_to(dest);
		self.bytes.encode_to(dest);
		self.deposit_offset.encode_to(dest);
		self.items.encode_to(dest);
		self.creation_slot.encode_to(dest);
		self.last_accumulation_slot.encode_to(dest);
		self.parent_service.encode_to(dest);
	}
}

impl Decode for Service {
	fn decode<I: codec::Input>(input: &mut I) -> Result<Self, codec::Error> {
		if u8::decode(input)? != SERVICE_VERSION {
			return Err("Invalid service version".into())
		}
		Ok(Self {
			code_hash: CodeHash::decode(input)?,
			balance: Balance::decode(input)?,
			min_item_gas: UnsignedGas::decode(input)?,
			min_memo_gas: UnsignedGas::decode(input)?,
			bytes: u64::decode(input)?,
			deposit_offset: Balance::decode(input)?,
			items: u32::decode(input)?,
			creation_slot: Slot::decode(input)?,
			last_accumulation_slot: Slot::decode(input)?,
			parent_service: ServiceId::decode(input)?,
		})
	}
}

impl Service {
	pub fn threshold(&self) -> Balance {
		Self::deposit_required(self.items, self.bytes, self.deposit_offset)
	}
	pub fn free(&self) -> Balance {
		self.balance.saturating_sub(self.threshold())
	}
	pub fn deposit_required(items: u32, bytes: u64, deposit_offset: Balance) -> Balance {
		let base_deposit =
			items as u64 * deposit_per_item() + bytes * deposit_per_byte() + deposit_per_account();
		base_deposit.saturating_sub(deposit_offset)
	}
}

/// One electively held item of a service's footprint, for deposit accounting.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FootprintItem {
	/// No footprint.
	None,
	/// A storage entry, key plus value length.
	Storage(u64),
	/// A preimage, its length.
	Lookup(u32),
}

impl From<Option<FootprintItem>> for FootprintItem {
	fn from(item: Option<FootprintItem>) -> Self {
		item.unwrap_or(Self::None)
	}
}

impl FootprintItem {
	/// The (items, bytes) footprint this entry contributes to a service's deposit.
	pub fn implication(&self) -> (u32, u64) {
		match self {
			Self::None => (0, 0),
			Self::Storage(size) => (1, *size + FOOTPRINT_STORAGE_OVERHEAD),
			Self::Lookup(len) => (2, *len as u64 + FOOTPRINT_PREIMAGE_OVERHEAD),
		}
	}
}

/// Safrole consensus state.
#[derive(Encode, Decode, Debug, Clone)]
pub struct SafroleState {
	/// Next epoch validator keys (gamma_k).
	pub waiting_validators: ValKeysets,
	/// Next epoch ring keys commitment (gamma_z).
	pub ring_commitment: RingCommitment,
	/// Tickets or keys used to claim the current epoch's slots (gamma_s).
	pub tickets_or_keys: TicketsOrKeys,
	/// Next epoch tickets accumulator (gamma_a).
	pub ticket_accumulator: EpochTicketsAccumulator,
}

pub type AuthPool = BoundedVec<AuthorizerHash, AuthWindow>;
pub type AuthPools = FixedVec<AuthPool, CoreCount>;
pub type AuthQueues = FixedVec<AuthQueue, CoreCount>;

#[derive(Debug, Encode, Decode, Eq, PartialEq, Clone)]
pub struct AvailabilityAssignment {
	/// Work report guarantee.
	pub guarantee: ReportGuarantee,
	/// Slot at which the guarantee was registered on-chain. Unlike `guarantee.slot`, this is the
	/// reference point for the availability timeout.
	pub registered_slot: Slot,
}

impl AvailabilityAssignment {
	/// The guaranteed work report.
	pub fn report(&self) -> &WorkReport {
		&self.guarantee.report
	}
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct Privileges {
	/// The service index with the ability to alter the privileges as well as bestow services with
	/// storage deposit credits.
	pub bless: ServiceId,
	/// The service indices with the ability to assign authorizors to cores.
	pub assign: FixedVec<ServiceId, CoreCount>,
	/// The service index with the ability to set the staging validator keys.
	pub designate: ServiceId,
	/// The service index with the ability to register service ids in the protected range.
	pub register: ServiceId,
	/// The services which always accumulate, together with their free gas.
	pub always_acc: VecMap<ServiceId, UnsignedGas>,
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct Disputes {
	/// The allow-set of work-reports, these are known to be good.
	pub good: VecSet<WorkReportHash>,
	/// The corrupt-set of work-reports, these are known to be bad.
	pub bad: VecSet<WorkReportHash>,
	/// The ban-set of work-reports, these have been determined of uncertain validity.
	pub wonky: VecSet<WorkReportHash>,
	/// The offenders' Ed25519 keys, these are known to have incorrectly judged a work-report's
	/// validity.
	pub offenders: VecSet<super::ed25519::Public>,
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct ValActivityRecord {
	// The number of blocks produced by the validator.
	pub blocks: u32,
	// The number of tickets introduced by the validator.
	pub tickets: u32,
	// The number of preimages introduced by the validator.
	pub preimages: u32,
	// The total number of octets across all preimages introduced by the validator.
	pub preimages_size: u32,
	// The number of reports guaranteed by the validator.
	pub guarantees: u32,
	// The number of availability assurances made by the validator.
	pub assurances: u32,
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct ServiceActivityRecord {
	/// Number of preimages provided to this service.
	#[codec(compact)]
	pub provided_count: u16,
	/// Total size of preimages provided to this service.
	#[codec(compact)]
	pub provided_size: u32,
	/// Number of work-items refined by service for reported work.
	#[codec(compact)]
	pub refinement_count: u32,
	/// Amount of gas used for refinement by service for reported work.
	#[codec(compact)]
	pub refinement_gas_used: UnsignedGas,
	/// Number of segments imported from the DL by service for reported work.
	#[codec(compact)]
	pub imports: u32,
	/// Total number of extrinsics used by service for reported work.
	#[codec(compact)]
	pub extrinsic_count: u32,
	/// Total size of extrinsics used by service for reported work.
	#[codec(compact)]
	pub extrinsic_size: u32,
	/// Number of segments exported into the DL by service for reported work.
	#[codec(compact)]
	pub exports: u32,
	/// Number of work-items accumulated by service.
	#[codec(compact)]
	pub accumulate_count: u32,
	/// Number of transfers processed by service during accumulation.
	#[codec(compact)]
	pub accumulate_transfer_count: u32,
	/// Amount of gas used for accumulation by service.
	#[codec(compact)]
	pub accumulate_gas_used: UnsignedGas,
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct CoreActivityRecord {
	// Assurances coming in from general validators (but ultimately provided by guarantors)
	/// Amount of bytes which are placed into either Audits or Segments DA.
	/// This includes the work-bundle (including all extrinsics and imports) as well as all
	/// (exported) segments.
	#[codec(compact)]
	pub da_load: u32,
	/// Number of validators which formed super-majority for assurance.
	#[codec(compact)]
	pub popularity: u16,
	/// Number of segments imported from DA made by core for reported work.
	#[codec(compact)]
	pub imports: u16,
	/// Total number of extrinsics used by core for reported work.
	#[codec(compact)]
	pub extrinsic_count: u16,
	/// Total size of extrinsics used by core for reported work.
	#[codec(compact)]
	pub extrinsic_size: u32,
	/// Number of segments exported into DA made by core for reported work.
	#[codec(compact)]
	pub exports: u16,
	/// The work-bundle size. This is the size of data being placed into Audits DA by the core.
	#[codec(compact)]
	pub bundle_size: u32,
	// Reports coming in from guarantors
	/// Total gas consumed by core for reported work. Includes all refinement and authorizations.
	#[codec(compact)]
	pub gas_used: UnsignedGas,
}

pub type ValidatorsStats = BoundedVec<ValActivityRecord, jam_types::MaxValCount>;
pub type CoresStats = FixedVec<CoreActivityRecord, CoreCount>;
pub type ServicesStats = VecMap<ServiceId, ServiceActivityRecord>;

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct Statistics {
	pub vals_curr: ValidatorsStats,
	pub vals_last: ValidatorsStats,
	pub cores: CoresStats,
	pub services: ServicesStats,
}

impl Statistics {
	/// Reset the two accumulators.
	pub fn reset(&mut self) {
		self.cores = Default::default();
		self.services = Default::default();
	}
}

/// Entries relative to epoch `N`
/// `[0]`: epoch `N` entropy accumulator. Updated on each block with fresh entropy.
/// `[i]`, for 1 ≤ i ≤ 3: accumulator snapshot at the begin of epoch  `N-i+1`.
/// If `N-i+1 < 0` then the corresponding entry is set to some fixed default value.
pub type EntropyBuffer = FixedVec<Entropy, ConstU32<4>>;

/// Block information.
#[derive(Debug, Encode, Decode, Eq, PartialEq, Clone)]
pub struct BlockInfo {
	/// Header hash.
	pub hash: HeaderHash,
	/// Accumulation MMR root.
	pub beefy_root: MmrPeakHash,
	/// Posterior state root.
	pub state_root: StateRootHash,
	/// Block slot.
	pub slot: Slot,
	/// Hash of each work report made into the block which is no more than the
	/// number of cores.
	pub reported: VecMap<WorkPackageHash, SegmentTreeRoot>,
}

/// Recent blocks history
pub type RecentBlocksHistory = BoundedVec<BlockInfo, RecentBlockCount>;

/// Imported blocks information
#[derive(Clone, Encode, Decode, Default, Debug)]
pub struct RecentBlocks {
	pub history: RecentBlocksHistory,
	pub mmr: Mmr,
}

pub type AvailabilityAssignments = FixedVec<Option<AvailabilityAssignment>, CoreCount>;

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq)]
pub struct ReadyRecord {
	pub report: WorkReport,
	pub deps: VecSet<WorkPackageHash>,
}
pub type ReadyQueue = FixedVec<Vec<ReadyRecord>, EpochPeriod>;
pub type Accumulated = FixedVec<Vec<WorkPackageHash>, EpochPeriod>;

pub type AccumulationOutput = Vec<(ServiceId, Hash)>;