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
use crate::{
	deposit_per_account, deposit_per_byte, deposit_per_item, hash_encoded, hash_raw_concat,
	simple::AuthWindow, CoreCount, Entropy, EpochPeriod, Mmr, RecentBlockCount, WorkReport,
};
use bounded_collections::ConstU32;
use jam_types::{
	opaque, AuthQueue, AuthorizerHash, Balance, BoundedVec, CodeHash, FixedVec, HeaderHash,
	SegmentTreeRoot, ServiceId, ServiceInfo, Slot, StateRootHash, UnsignedGas, VecMap, VecSet,
	WorkPackageHash, WorkReportHash,
};
use scale::{Decode, Encode};

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

#[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,
}

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

impl IntoStorageKey for SystemKey {
	fn service_id(&self) -> Option<ServiceId> {
		None
	}
}

#[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>;
}

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; 32];
		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 { id, key } => {
				let mut hash = hash_raw_concat([&id.to_le_bytes()[..], key]);
				hash.copy_within(0..28, 4);
				hash[..4].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
				hash
			},
			Preimage { mut hash, .. } => {
				hash.copy_within(1..29, 4);
				hash[..4].copy_from_slice(&[0xfe, 0xff, 0xff, 0xff]);
				hash
			},
			Request { len, hash, .. } => {
				let mut hash = hash_encoded(&hash);
				hash.copy_within(2..30, 4);
				hash[..4].copy_from_slice(&len.to_le_bytes());
				hash
			},
		};
		r[8..].copy_from_slice(&hash[4..28]);
		r[..8].copy_from_slice(&[id[0], hash[0], id[1], hash[1], id[2], hash[2], id[3], hash[3]]);
		r.into()
	}
}

#[derive(Debug, Clone, Encode, Decode)]
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 `on_transfer` for each
	/// memo (i.e. transfer receipt) 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,
	/// The total number of items of data electively held for this service on-chain.
	pub items: u32,
}

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(),
		}
	}
}

impl Service {
	pub fn new(
		code_hash: CodeHash,
		code_len: impl Into<u32>,
		min_item_gas: UnsignedGas,
		min_memo_gas: UnsignedGas,
	) -> Self {
		let (items, bytes) = FootprintItem::Lookup(code_len.into()).implication();
		Self {
			code_hash,
			min_item_gas,
			min_memo_gas,
			balance: deposit_required(items, bytes),
			items,
			bytes,
		}
	}
	pub fn balance(&self) -> Balance {
		self.balance
	}
	pub fn lower_balance(&mut self, amount: Balance) -> Result<(), ()> {
		if self.free() < amount {
			return Err(())
		}
		self.balance = self.balance.checked_sub(amount).ok_or(())?;
		Ok(())
	}
	pub fn raise_balance(&mut self, amount: Balance) {
		self.balance = self.balance.saturating_add(amount);
	}
	pub fn prepare_change_state(
		&mut self,
		remove: FootprintItem,
		add: FootprintItem,
	) -> Result<(), ()> {
		let (aitems, abytes) = add.implication();
		let (sitems, sbytes) = remove.implication();
		let new_items = self.items.saturating_sub(sitems).saturating_add(aitems);
		let new_bytes = self.bytes.saturating_sub(sbytes).saturating_add(abytes);
		if self.balance < deposit_required(new_items, new_bytes) {
			return Err(())
		}
		self.items = new_items;
		self.bytes = new_bytes;
		Ok(())
	}
	pub fn prepare_insert_state(&mut self, add: FootprintItem) -> Result<(), ()> {
		self.prepare_change_state(FootprintItem::None, add)
	}
	pub fn prepare_remove_state(&mut self, remove: FootprintItem) {
		let (items, bytes) = remove.implication();
		self.items = self.items.saturating_sub(items);
		self.bytes = self.bytes.saturating_sub(bytes);
	}
	pub fn footprint_is_one_preimage(&self) -> Option<u64> {
		let (items, bytes) = FootprintItem::Lookup(0).implication();
		if self.items == items && self.bytes >= bytes {
			Some(self.bytes - bytes)
		} else {
			None
		}
	}

	pub fn threshold(&self) -> Balance {
		deposit_required(self.items, self.bytes)
	}
	pub fn free(&self) -> Balance {
		self.balance.saturating_sub(self.threshold())
	}
}

fn deposit_required(items: u32, bytes: u64) -> u64 {
	items as u64 * deposit_per_item() + bytes * deposit_per_byte() + deposit_per_account()
}

#[derive(Debug, Clone, Copy)]
pub enum FootprintItem {
	None,
	Storage(usize),
	Lookup(u32),
}
impl From<Option<FootprintItem>> for FootprintItem {
	fn from(i: Option<FootprintItem>) -> Self {
		i.unwrap_or(Self::None)
	}
}
impl FootprintItem {
	pub fn implication(&self) -> (u32, u64) {
		match self {
			Self::None => (0, 0),
			Self::Storage(s) => (1, *s as u64 + 32),
			Self::Lookup(s) => (2, *s as u64 + 81),
		}
	}
}

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

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

#[derive(Debug, Encode, Decode, Eq, PartialEq, Clone)]
pub struct AvailabilityAssignment {
	/// Work report.
	pub report: WorkReport,
	/// Timeslot when `report` has been reported.
	pub report_slot: Slot,
}

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct Privileges {
	/// The service index with the ability to alter the privileges.
	pub bless: ServiceId,
	/// The service index with the ability to assign authorizors to cores.
	pub assign: ServiceId,
	/// The service index with the ability to set the validator keys.
	pub designate: 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,
	/// Number of segments exported into the DL by service for reported work.
	#[codec(compact)]
	pub exports: u32,
	/// Total size of extrinsics used by service for reported work.
	#[codec(compact)]
	pub extrinsic_size: u32,
	/// Total number of extrinsics used by service for reported work.
	#[codec(compact)]
	pub extrinsic_count: u32,
	/// Number of work-items accumulated by service.
	#[codec(compact)]
	pub accumulate_count: u32,
	/// Amount of gas used for accumulation by service.
	#[codec(compact)]
	pub accumulate_gas_used: UnsignedGas,
	/// Number of transfers processed by service.
	#[codec(compact)]
	pub on_transfers_count: u32,
	/// Amount of gas used for processing transfers by service.
	#[codec(compact)]
	pub on_transfers_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,
	/// Number of segments exported into DA made by core for reported work.
	#[codec(compact)]
	pub exports: u16,
	/// Total size of extrinsics used by core for reported work.
	#[codec(compact)]
	pub extrinsic_size: u32,
	/// Total number of extrinsics used by core for reported work.
	#[codec(compact)]
	pub extrinsic_count: 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 CoresStats = FixedVec<CoreActivityRecord, CoreCount>;
pub type ServicesStats = VecMap<ServiceId, ServiceActivityRecord>;

#[derive(Clone, Encode, Decode, Debug, Eq, PartialEq, Default)]
pub struct Statistics {
	pub vals_current: FixedVec<ValActivityRecord, jam_types::ValCount>,
	pub vals_last: FixedVec<ValActivityRecord, jam_types::ValCount>,
	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>>;

pub type RecentBlocks = BoundedVec<BlockInfo, RecentBlockCount>;

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>;