jam-std-common 0.1.26

Common datatypes and utilities for the JAM nodes and tooling
Documentation
use super::{hash_encoded, ValSignature};
use bounded_collections::Get;
use codec::{ConstEncodedLen, Decode, Encode, MaxEncodedLen};
use jam_types::{core_count, opaque, CoreIndex, FixedVec, HeaderHash};

pub fn bitfield_byte_count() -> usize {
	(core_count() + 7) as usize / 8
}
#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
pub struct BitfieldByteCount;
impl Get<u32> for BitfieldByteCount {
	fn get() -> u32 {
		bitfield_byte_count() as u32
	}
}

#[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, MaxEncodedLen)]
pub struct AvailabilityBitfield(FixedVec<u8, BitfieldByteCount>);

impl AvailabilityBitfield {
	pub fn new() -> Self {
		Self(FixedVec::default())
	}
	pub fn set(&mut self, i: CoreIndex) {
		self.0[i as usize / 8] |= 1 << (i % 8);
	}
	pub fn clear(&mut self, i: CoreIndex) {
		self.0[i as usize / 8] &= !(1 << (i % 8));
	}
	pub fn get(&self, i: CoreIndex) -> bool {
		self.0[i as usize / 8] & (1 << (i % 8)) != 0
	}

	pub fn is_all_unset(&self) -> bool {
		self.0.iter().all(|&b| b == 0)
	}
	pub fn count_ones(&self) -> u32 {
		self.0.iter().map(|&b| b.count_ones()).sum()
	}
}

impl ConstEncodedLen for AvailabilityBitfield {}

impl<T: std::borrow::Borrow<[CoreIndex]>> From<T> for AvailabilityBitfield {
	fn from(value: T) -> Self {
		let mut r = Self::new();
		for i in value.borrow() {
			r.set(*i);
		}
		r
	}
}

/// Multiple signatures are consolidated into a single Attestation in a space-efficient
/// manner using a `BitVec` to succinctly express which validators have attested.
#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq, MaxEncodedLen)]
pub struct AvailabilityStatement {
	/// The block to which this availability attestation corresponds.
	pub anchor: HeaderHash,
	/// The bitfield of whether any given core's reported package at `anchor` block is helped made
	/// available by this validator.
	pub bitfield: AvailabilityBitfield,
}

impl ConstEncodedLen for AvailabilityStatement {}

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

impl AvailabilityStatement {
	pub fn hash(&self) -> AvailabilityStatementHash {
		hash_encoded(self).into()
	}
}

/// Multiple signatures are combined with the statement and consolidated into a single Assurance.
#[derive(Clone, Encode, Decode, Debug, MaxEncodedLen)]
pub struct AvailabilityAssurance {
	/// The statement being attested.
	pub statement: AvailabilityStatement,
	/// A signature of the statement.
	pub signature: ValSignature,
}

impl ConstEncodedLen for AvailabilityAssurance {}

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