pub mod criteria;
pub mod time;
pub mod v1 {
use sp_consensus_babe as babe_primitives;
pub use sp_consensus_babe::{
Randomness, Slot, VrfPreOutput, VrfProof, VrfSignature, VrfTranscript,
};
use codec::{Decode, Encode};
use polkadot_primitives::{
BlockNumber, CandidateHash, CandidateIndex, CoreIndex, GroupIndex, Hash, Header,
SessionIndex, ValidatorIndex, ValidatorSignature,
};
use sp_application_crypto::ByteArray;
pub type DelayTranche = u32;
pub const RELAY_VRF_STORY_CONTEXT: &[u8] = b"A&V RC-VRF";
pub const RELAY_VRF_MODULO_CONTEXT: &[u8] = b"A&V MOD";
pub const RELAY_VRF_DELAY_CONTEXT: &[u8] = b"A&V DELAY";
pub const ASSIGNED_CORE_CONTEXT: &[u8] = b"A&V ASSIGNED";
pub const CORE_RANDOMNESS_CONTEXT: &[u8] = b"A&V CORE";
pub const TRANCHE_RANDOMNESS_CONTEXT: &[u8] = b"A&V TRANCHE";
#[derive(Debug, Clone, Encode, Decode, PartialEq)]
pub struct RelayVRFStory(pub [u8; 32]);
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum AssignmentCertKind {
RelayVRFModulo {
sample: u32,
},
RelayVRFDelay {
core_index: CoreIndex,
},
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct AssignmentCert {
pub kind: AssignmentCertKind,
pub vrf: VrfSignature,
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct IndirectAssignmentCert {
pub block_hash: Hash,
pub validator: ValidatorIndex,
pub cert: AssignmentCert,
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct IndirectSignedApprovalVote {
pub block_hash: Hash,
pub candidate_index: CandidateIndex,
pub validator: ValidatorIndex,
pub signature: ValidatorSignature,
}
#[derive(Debug, Clone)]
pub struct BlockApprovalMeta {
pub hash: Hash,
pub number: BlockNumber,
pub parent_hash: Hash,
pub candidates: Vec<(CandidateHash, CoreIndex, GroupIndex)>,
pub slot: Slot,
pub session: SessionIndex,
pub vrf_story: RelayVRFStory,
}
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum ApprovalError {
#[error("Schnorrkel signature error")]
SchnorrkelSignature(schnorrkel::errors::SignatureError),
#[error("Authority index {0} out of bounds")]
AuthorityOutOfBounds(usize),
}
pub struct UnsafeVRFPreOutput {
vrf_pre_output: VrfPreOutput,
slot: Slot,
authority_index: u32,
}
impl UnsafeVRFPreOutput {
pub fn slot(&self) -> Slot {
self.slot
}
pub fn compute_randomness(
self,
authorities: &[(babe_primitives::AuthorityId, babe_primitives::BabeAuthorityWeight)],
randomness: &babe_primitives::Randomness,
epoch_index: u64,
) -> Result<RelayVRFStory, ApprovalError> {
let author = match authorities.get(self.authority_index as usize) {
None => return Err(ApprovalError::AuthorityOutOfBounds(self.authority_index as _)),
Some(x) => &x.0,
};
let pubkey = schnorrkel::PublicKey::from_bytes(author.as_slice())
.map_err(ApprovalError::SchnorrkelSignature)?;
let transcript =
sp_consensus_babe::make_vrf_transcript(randomness, self.slot, epoch_index);
let inout = self
.vrf_pre_output
.0
.attach_input_hash(&pubkey, transcript.0)
.map_err(ApprovalError::SchnorrkelSignature)?;
Ok(RelayVRFStory(inout.make_bytes(super::v1::RELAY_VRF_STORY_CONTEXT)))
}
}
pub fn babe_unsafe_vrf_info(header: &Header) -> Option<UnsafeVRFPreOutput> {
use babe_primitives::digests::CompatibleDigestItem;
for digest in &header.digest.logs {
if let Some(pre) = digest.as_babe_pre_digest() {
let slot = pre.slot();
let authority_index = pre.authority_index();
return pre.vrf_signature().map(|sig| UnsafeVRFPreOutput {
vrf_pre_output: sig.pre_output.clone(),
slot,
authority_index,
})
}
}
None
}
}
pub mod v2 {
use codec::{Decode, Encode};
pub use sp_consensus_babe::{
Randomness, Slot, VrfPreOutput, VrfProof, VrfSignature, VrfTranscript,
};
use std::ops::BitOr;
use bitvec::{prelude::Lsb0, vec::BitVec};
use polkadot_primitives::{
CandidateIndex, CoreIndex, Hash, ValidatorIndex, ValidatorSignature,
};
pub const CORE_RANDOMNESS_CONTEXT: &[u8] = b"A&V CORE v2";
pub const ASSIGNED_CORE_CONTEXT: &[u8] = b"A&V ASSIGNED v2";
pub const RELAY_VRF_MODULO_CONTEXT: &[u8] = b"A&V MOD v2";
#[derive(Clone, Debug, Encode, Decode, Hash, PartialEq, Eq)]
pub struct Bitfield<T>(BitVec<u8, bitvec::order::Lsb0>, std::marker::PhantomData<T>);
pub type CandidateBitfield = Bitfield<CandidateIndex>;
pub type CoreBitfield = Bitfield<CoreIndex>;
#[derive(Debug)]
pub enum BitfieldError {
NullAssignment,
}
#[cfg_attr(test, derive(PartialEq, Clone))]
pub struct BitIndex(pub usize);
pub trait AsBitIndex {
fn as_bit_index(&self) -> BitIndex;
}
impl<T> Bitfield<T> {
pub fn bit_at(&self, index: BitIndex) -> bool {
if self.0.len() <= index.0 {
false
} else {
self.0[index.0]
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn count_ones(&self) -> usize {
self.0.count_ones()
}
pub fn first_one(&self) -> Option<usize> {
self.0.first_one()
}
pub fn iter_ones(&self) -> bitvec::slice::IterOnes<u8, bitvec::order::Lsb0> {
self.0.iter_ones()
}
#[cfg(test)]
pub fn inner_mut(&mut self) -> &mut BitVec<u8, bitvec::order::Lsb0> {
&mut self.0
}
pub fn into_inner(self) -> BitVec<u8, bitvec::order::Lsb0> {
self.0
}
}
impl AsBitIndex for CandidateIndex {
fn as_bit_index(&self) -> BitIndex {
BitIndex(*self as usize)
}
}
impl AsBitIndex for CoreIndex {
fn as_bit_index(&self) -> BitIndex {
BitIndex(self.0 as usize)
}
}
impl AsBitIndex for usize {
fn as_bit_index(&self) -> BitIndex {
BitIndex(*self)
}
}
impl<T> From<T> for Bitfield<T>
where
T: AsBitIndex,
{
fn from(value: T) -> Self {
Self(
{
let mut bv = bitvec::bitvec![u8, Lsb0; 0; value.as_bit_index().0 + 1];
bv.set(value.as_bit_index().0, true);
bv
},
Default::default(),
)
}
}
impl<T> TryFrom<Vec<T>> for Bitfield<T>
where
T: Into<Bitfield<T>>,
{
type Error = BitfieldError;
fn try_from(mut value: Vec<T>) -> Result<Self, Self::Error> {
if value.is_empty() {
return Err(BitfieldError::NullAssignment)
}
let initial_bitfield =
value.pop().expect("Just checked above it's not empty; qed").into();
Ok(Self(
value.into_iter().fold(initial_bitfield.0, |initial_bitfield, element| {
let mut bitfield: Bitfield<T> = element.into();
bitfield
.0
.resize(std::cmp::max(initial_bitfield.len(), bitfield.0.len()), false);
bitfield.0.bitor(initial_bitfield)
}),
Default::default(),
))
}
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub enum AssignmentCertKindV2 {
#[codec(index = 0)]
RelayVRFModuloCompact {
core_bitfield: CoreBitfield,
},
#[codec(index = 1)]
RelayVRFDelay {
core_index: CoreIndex,
},
#[codec(index = 2)]
RelayVRFModulo {
sample: u32,
},
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct AssignmentCertV2 {
pub kind: AssignmentCertKindV2,
pub vrf: VrfSignature,
}
impl From<super::v1::AssignmentCert> for AssignmentCertV2 {
fn from(cert: super::v1::AssignmentCert) -> Self {
Self {
kind: match cert.kind {
super::v1::AssignmentCertKind::RelayVRFDelay { core_index } =>
AssignmentCertKindV2::RelayVRFDelay { core_index },
super::v1::AssignmentCertKind::RelayVRFModulo { sample } =>
AssignmentCertKindV2::RelayVRFModulo { sample },
},
vrf: cert.vrf,
}
}
}
#[derive(Debug)]
pub enum AssignmentConversionError {
CertificateNotSupported,
}
impl TryFrom<AssignmentCertV2> for super::v1::AssignmentCert {
type Error = AssignmentConversionError;
fn try_from(cert: AssignmentCertV2) -> Result<Self, AssignmentConversionError> {
Ok(Self {
kind: match cert.kind {
AssignmentCertKindV2::RelayVRFDelay { core_index } =>
super::v1::AssignmentCertKind::RelayVRFDelay { core_index },
AssignmentCertKindV2::RelayVRFModulo { sample } =>
super::v1::AssignmentCertKind::RelayVRFModulo { sample },
_ => return Err(AssignmentConversionError::CertificateNotSupported),
},
vrf: cert.vrf,
})
}
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct IndirectAssignmentCertV2 {
pub block_hash: Hash,
pub validator: ValidatorIndex,
pub cert: AssignmentCertV2,
}
impl From<super::v1::IndirectAssignmentCert> for IndirectAssignmentCertV2 {
fn from(indirect_cert: super::v1::IndirectAssignmentCert) -> Self {
Self {
block_hash: indirect_cert.block_hash,
validator: indirect_cert.validator,
cert: indirect_cert.cert.into(),
}
}
}
impl TryFrom<IndirectAssignmentCertV2> for super::v1::IndirectAssignmentCert {
type Error = AssignmentConversionError;
fn try_from(
indirect_cert: IndirectAssignmentCertV2,
) -> Result<Self, AssignmentConversionError> {
Ok(Self {
block_hash: indirect_cert.block_hash,
validator: indirect_cert.validator,
cert: indirect_cert.cert.try_into()?,
})
}
}
impl From<super::v1::IndirectSignedApprovalVote> for IndirectSignedApprovalVoteV2 {
fn from(value: super::v1::IndirectSignedApprovalVote) -> Self {
Self {
block_hash: value.block_hash,
validator: value.validator,
candidate_indices: value.candidate_index.into(),
signature: value.signature,
}
}
}
#[derive(Debug)]
pub enum ApprovalConversionError {
MoreThanOneCandidate(usize),
}
impl TryFrom<IndirectSignedApprovalVoteV2> for super::v1::IndirectSignedApprovalVote {
type Error = ApprovalConversionError;
fn try_from(value: IndirectSignedApprovalVoteV2) -> Result<Self, Self::Error> {
if value.candidate_indices.count_ones() != 1 {
return Err(ApprovalConversionError::MoreThanOneCandidate(
value.candidate_indices.count_ones(),
))
}
Ok(Self {
block_hash: value.block_hash,
validator: value.validator,
candidate_index: value.candidate_indices.first_one().expect("Qed we checked above")
as u32,
signature: value.signature,
})
}
}
#[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)]
pub struct IndirectSignedApprovalVoteV2 {
pub block_hash: Hash,
pub candidate_indices: CandidateBitfield,
pub validator: ValidatorIndex,
pub signature: ValidatorSignature,
}
}
#[cfg(test)]
mod test {
use super::v2::{BitIndex, Bitfield};
use polkadot_primitives::{CandidateIndex, CoreIndex};
#[test]
fn test_assignment_bitfield_from_vec() {
let candidate_indices = vec![1u32, 7, 3, 10, 45, 8, 200, 2];
let max_index = *candidate_indices.iter().max().unwrap();
let bitfield = Bitfield::try_from(candidate_indices.clone()).unwrap();
let candidate_indices =
candidate_indices.into_iter().map(|i| BitIndex(i as usize)).collect::<Vec<_>>();
for index in candidate_indices.clone() {
assert!(bitfield.bit_at(index));
}
for index in 0..max_index {
if candidate_indices.contains(&BitIndex(index as usize)) {
continue
}
assert!(!bitfield.bit_at(BitIndex(index as usize)));
}
}
#[test]
fn test_assignment_bitfield_invariant_msb() {
let core_indices = vec![CoreIndex(1), CoreIndex(3), CoreIndex(10), CoreIndex(20)];
let mut bitfield = Bitfield::try_from(core_indices.clone()).unwrap();
assert!(bitfield.inner_mut().pop().unwrap());
for i in 0..1024 {
assert!(Bitfield::try_from(CoreIndex(i)).unwrap().inner_mut().pop().unwrap());
assert!(Bitfield::try_from(i).unwrap().inner_mut().pop().unwrap());
}
}
#[test]
fn test_assignment_bitfield_basic() {
let bitfield = Bitfield::try_from(CoreIndex(0)).unwrap();
assert!(bitfield.bit_at(BitIndex(0)));
assert!(!bitfield.bit_at(BitIndex(1)));
assert_eq!(bitfield.len(), 1);
let mut bitfield = Bitfield::try_from(20 as CandidateIndex).unwrap();
assert!(bitfield.bit_at(BitIndex(20)));
assert_eq!(bitfield.inner_mut().count_ones(), 1);
assert_eq!(bitfield.len(), 21);
}
}