use crate::{Randomness, TicketBody, TicketId};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use codec::Encode;
use sp_consensus_slots::Slot;
pub use sp_core::bandersnatch::{
ring_vrf::{RingProver, RingVerifier, RingVerifierData, RingVrfSignature},
vrf::{VrfInput, VrfPreOutput, VrfSignData, VrfSignature},
};
pub const RING_VRF_DOMAIN_SIZE: u32 = 2048;
pub type RingContext = sp_core::bandersnatch::ring_vrf::RingContext<RING_VRF_DOMAIN_SIZE>;
fn vrf_input_from_data(
domain: &[u8],
data: impl IntoIterator<Item = impl AsRef<[u8]>>,
) -> VrfInput {
let buf = data.into_iter().fold(Vec::new(), |mut buf, item| {
let bytes = item.as_ref();
buf.extend_from_slice(bytes);
let len = u8::try_from(bytes.len()).expect("private function with well known inputs; qed");
buf.push(len);
buf
});
VrfInput::new(domain, buf)
}
pub fn slot_claim_input(randomness: &Randomness, slot: Slot, epoch: u64) -> VrfInput {
vrf_input_from_data(
b"sassafras-claim-v1.0",
[randomness.as_slice(), &slot.to_le_bytes(), &epoch.to_le_bytes()],
)
}
pub fn slot_claim_sign_data(randomness: &Randomness, slot: Slot, epoch: u64) -> VrfSignData {
let input = slot_claim_input(randomness, slot, epoch);
VrfSignData::new_unchecked(
b"sassafras-slot-claim-transcript-v1.0",
Option::<&[u8]>::None,
Some(input),
)
}
pub fn ticket_id_input(randomness: &Randomness, attempt: u32, epoch: u64) -> VrfInput {
vrf_input_from_data(
b"sassafras-ticket-v1.0",
[randomness.as_slice(), &attempt.to_le_bytes(), &epoch.to_le_bytes()],
)
}
pub fn revealed_key_input(randomness: &Randomness, attempt: u32, epoch: u64) -> VrfInput {
vrf_input_from_data(
b"sassafras-revealed-v1.0",
[randomness.as_slice(), &attempt.to_le_bytes(), &epoch.to_le_bytes()],
)
}
pub fn ticket_body_sign_data(ticket_body: &TicketBody, ticket_id_input: VrfInput) -> VrfSignData {
VrfSignData::new_unchecked(
b"sassafras-ticket-body-transcript-v1.0",
Some(ticket_body.encode().as_slice()),
Some(ticket_id_input),
)
}
pub fn make_ticket_id(input: &VrfInput, pre_output: &VrfPreOutput) -> TicketId {
let bytes = pre_output.make_bytes::<16>(b"ticket-id", input);
u128::from_le_bytes(bytes)
}
pub fn make_revealed_key_seed(input: &VrfInput, pre_output: &VrfPreOutput) -> [u8; 32] {
pre_output.make_bytes::<32>(b"revealed-seed", input)
}