referrerpolicy=no-referrer-when-downgrade

sp_consensus_sassafras/
vrf.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Utilities related to VRF input, pre-output and signatures.
19
20use crate::{Randomness, TicketBody, TicketId};
21#[cfg(not(feature = "std"))]
22use alloc::vec::Vec;
23use codec::Encode;
24use sp_consensus_slots::Slot;
25
26pub use sp_core::bandersnatch::{
27	ring_vrf::{RingProver, RingVerifier, RingVerifierKey, RingVrfSignature},
28	vrf::{VrfInput, VrfPreOutput, VrfSignData, VrfSignature},
29};
30
31/// Ring size (aka authorities count) for Sassafras consensus.
32pub const RING_SIZE: usize = 1024;
33
34/// Bandersnatch VRF [`RingContext`] specialization for Sassafras using [`RING_SIZE`].
35pub type RingContext = sp_core::bandersnatch::ring_vrf::RingContext<RING_SIZE>;
36
37/// Input for slot claim
38pub fn slot_claim_input(randomness: &Randomness, slot: Slot, epoch: u64) -> VrfInput {
39	let v = [b"sassafras-ticket", randomness.as_slice(), &slot.to_le_bytes(), &epoch.to_le_bytes()]
40		.concat();
41	VrfInput::new(&v[..])
42}
43
44/// Signing-data to claim slot ownership during block production.
45pub fn slot_claim_sign_data(randomness: &Randomness, slot: Slot, epoch: u64) -> VrfSignData {
46	let v = [b"sassafras-ticket", randomness.as_slice(), &slot.to_le_bytes(), &epoch.to_le_bytes()]
47		.concat();
48	VrfSignData::new(&v[..], &[])
49}
50
51/// VRF input to generate the ticket id.
52pub fn ticket_id_input(randomness: &Randomness, attempt: u32, epoch: u64) -> VrfInput {
53	let v =
54		[b"sassafras-ticket", randomness.as_slice(), &attempt.to_le_bytes(), &epoch.to_le_bytes()]
55			.concat();
56	VrfInput::new(&v[..])
57}
58
59/// Data to be signed via ring-vrf.
60pub fn ticket_body_sign_data(ticket_body: &TicketBody, ticket_id_input: VrfInput) -> VrfSignData {
61	VrfSignData { vrf_input: ticket_id_input, aux_data: ticket_body.encode() }
62}
63
64/// Make ticket-id from the given VRF pre-output.
65///
66/// Pre-output should have been obtained from the input directly using the vrf
67/// secret key or from the vrf signature pre-output.
68pub fn make_ticket_id(preout: &VrfPreOutput) -> TicketId {
69	let bytes: [u8; 16] = preout.make_bytes()[..16].try_into().unwrap();
70	u128::from_le_bytes(bytes)
71}