Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Sassafras primitives #14768

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ frame-support = { path = "frame/support" }

node-cli = { path = "bin/node/cli" }

# This list of dependencies is necessary to build sassafras primitives.
# `bandersnatch-experimental` is transitively passed between:
# sp-consensus-sassafras → sp-application-crypto → sp-io → sp-keystore
# Thus we end up having the bandersnatch functions "unlocked" in the `Keystore` trait.
# Follow that we require bandersnatch implementations in the client keystore as well.
sp-consensus-sassafras = { path = "primitives/consensus/sassafras", optional = true }
sc-keystore = { path = "client/keystore" }

# Feature to unlock "Sassafras" experimental crates
[features]
sassafras-experimental = [
"sp-consensus-sassafras",
"sc-keystore/bandersnatch-experimental",
]

# Exists here to be backwards compatible and to support `cargo run` in the workspace.
#
# Just uses the `node-cli` main binary. `node-cli` itself also again exposes the node as
Expand Down
50 changes: 50 additions & 0 deletions primitives/consensus/sassafras/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
[package]
name = "sp-consensus-sassafras"
version = "0.3.4-dev"
authors = ["Parity Technologies <[email protected]>"]
description = "Primitives for Sassafras consensus"
edition = "2021"
license = "Apache-2.0"
homepage = "https://substrate.io"
repository = "https://github.com/paritytech/substrate/"
documentation = "https://docs.rs/sp-consensus-sassafras"
readme = "README.md"
publish = false

[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]

[dependencies]
scale-codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false }
scale-info = { version = "2.5.0", default-features = false, features = ["derive"] }
serde = { version = "1.0.163", default-features = false, features = ["derive"], optional = true }
sp-api = { version = "4.0.0-dev", default-features = false, path = "../../api" }
sp-application-crypto = { version = "23.0.0", default-features = false, path = "../../application-crypto", features = ["bandersnatch-experimental"] }
sp-consensus-slots = { version = "0.10.0-dev", default-features = false, path = "../slots" }
sp-core = { version = "21.0.0", default-features = false, path = "../../core", features = ["bandersnatch-experimental"] }
sp-runtime = { version = "24.0.0", default-features = false, path = "../../runtime" }
sp-std = { version = "8.0.0", default-features = false, path = "../../std" }

[features]
default = ["std"]
std = [
"scale-codec/std",
"scale-info/std",
"serde/std",
"sp-api/std",
"sp-application-crypto/std",
"sp-consensus-slots/std",
"sp-core/std",
"sp-runtime/std",
"sp-std/std",
]

# Serde support without relying on std features.
serde = [
"dep:serde",
"scale-info/serde",
"sp-application-crypto/serde",
"sp-consensus-slots/serde",
"sp-core/serde",
"sp-runtime/serde",
]
12 changes: 12 additions & 0 deletions primitives/consensus/sassafras/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Primitives for SASSAFRAS.

# ⚠️ WARNING ⚠️

The crate interfaces and structures are highly experimental and may be subject
to significant changes.

Depends on upstream experimental feature: `bandersnatch-experimental`.

These structs were mostly extracted from the main SASSAFRAS protocol PR: https://github.com/paritytech/substrate/pull/11879.

Tracking issue: https://github.com/paritytech/substrate/issues/11515.
99 changes: 99 additions & 0 deletions primitives/consensus/sassafras/src/digests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Sassafras digests structures and helpers.

use crate::{
ticket::TicketClaim, AuthorityId, AuthorityIndex, AuthoritySignature, EpochConfiguration,
Randomness, Slot, VrfSignature, SASSAFRAS_ENGINE_ID,
};

use scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;

use sp_runtime::{DigestItem, RuntimeDebug};
use sp_std::vec::Vec;

/// Sassafras slot assignment pre-digest.
#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct PreDigest {
/// Authority index that claimed the slot.
pub authority_idx: AuthorityIndex,
/// Corresponding slot number.
pub slot: Slot,
/// Slot claim VRF signature.
pub vrf_signature: VrfSignature,
/// Ticket auxiliary information for claim check.
pub ticket_claim: Option<TicketClaim>,
}

/// Information about the next epoch.
///
/// This is broadcast in the first block of each epoch.
#[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
pub struct NextEpochDescriptor {
/// Authorities list.
pub authorities: Vec<AuthorityId>,
/// Epoch randomness.
pub randomness: Randomness,
/// Configurable parameters. If not present previous epoch parameters are used.
pub config: Option<EpochConfiguration>,
}

/// Consensus log item.
#[derive(Decode, Encode, Clone, PartialEq, Eq)]
pub enum ConsensusLog {
/// Provides information about the next epoch parameters.
#[codec(index = 1)]
NextEpochData(NextEpochDescriptor),
/// Disable the authority with given index.
#[codec(index = 2)]
OnDisabled(AuthorityIndex),
}

/// A digest item which is usable by Sassafras.
pub trait CompatibleDigestItem {
/// Construct a digest item which contains a `PreDigest`.
fn sassafras_pre_digest(seal: PreDigest) -> Self;

/// If this item is a `PreDigest`, return it.
fn as_sassafras_pre_digest(&self) -> Option<PreDigest>;

/// Construct a digest item which contains an `AuthoritySignature`.
fn sassafras_seal(signature: AuthoritySignature) -> Self;

/// If this item is an `AuthoritySignature`, return it.
fn as_sassafras_seal(&self) -> Option<AuthoritySignature>;
}

impl CompatibleDigestItem for DigestItem {
fn sassafras_pre_digest(digest: PreDigest) -> Self {
DigestItem::PreRuntime(SASSAFRAS_ENGINE_ID, digest.encode())
}

fn as_sassafras_pre_digest(&self) -> Option<PreDigest> {
self.pre_runtime_try_to(&SASSAFRAS_ENGINE_ID)
}

fn sassafras_seal(signature: AuthoritySignature) -> Self {
DigestItem::Seal(SASSAFRAS_ENGINE_ID, signature.encode())
}

fn as_sassafras_seal(&self) -> Option<AuthoritySignature> {
self.seal_try_to(&SASSAFRAS_ENGINE_ID)
}
}
179 changes: 179 additions & 0 deletions primitives/consensus/sassafras/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Primitives for Sassafras consensus.

#![deny(warnings)]
#![forbid(unsafe_code, missing_docs, unused_variables, unused_imports)]
#![cfg_attr(not(feature = "std"), no_std)]

use scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
use sp_core::crypto::KeyTypeId;
use sp_runtime::{ConsensusEngineId, RuntimeDebug};
use sp_std::vec::Vec;

pub use sp_consensus_slots::{Slot, SlotDuration};
pub use sp_core::bandersnatch::{
ring_vrf::{RingContext, RingProver, RingVerifier, RingVrfSignature},
vrf::{VrfInput, VrfOutput, VrfSignData, VrfSignature},
};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

pub mod digests;
pub mod ticket;

pub use ticket::{
slot_claim_sign_data, slot_claim_vrf_input, ticket_body_sign_data, ticket_id,
ticket_id_threshold, ticket_id_vrf_input, EphemeralPublic, EphemeralSignature, TicketBody,
TicketClaim, TicketEnvelope, TicketId,
};

mod app {
use sp_application_crypto::{app_crypto, bandersnatch, key_types::SASSAFRAS};
app_crypto!(bandersnatch, SASSAFRAS);
}

/// Key type identifier.
pub const KEY_TYPE: KeyTypeId = sp_application_crypto::key_types::SASSAFRAS;

/// Consensus engine identifier.
pub const SASSAFRAS_ENGINE_ID: ConsensusEngineId = *b"SASS";

/// VRF output length for per-slot randomness.
pub const RANDOMNESS_LENGTH: usize = 32;

/// Index of an authority.
pub type AuthorityIndex = u32;

/// Sassafras authority keypair. Necessarily equivalent to the schnorrkel public key used in
/// the main Sassafras module. If that ever changes, then this must, too.
#[cfg(feature = "std")]
pub type AuthorityPair = app::Pair;

/// Sassafras authority signature.
pub type AuthoritySignature = app::Signature;

/// Sassafras authority identifier. Necessarily equivalent to the schnorrkel public key used in
/// the main Sassafras module. If that ever changes, then this must, too.
pub type AuthorityId = app::Public;

/// Weight of a Sassafras block.
/// Primary blocks have a weight of 1 whereas secondary blocks have a weight of 0.
pub type SassafrasBlockWeight = u32;

/// An equivocation proof for multiple block authorships on the same slot (i.e. double vote).
pub type EquivocationProof<H> = sp_consensus_slots::EquivocationProof<H, AuthorityId>;

/// Randomness required by some protocol's operations.
pub type Randomness = [u8; RANDOMNESS_LENGTH];

/// Configuration data that can be modified on epoch change.
#[derive(
Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, MaxEncodedLen, TypeInfo, Default,
)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EpochConfiguration {
/// Tickets threshold redundancy factor.
pub redundancy_factor: u32,
/// Tickets attempts for each validator.
pub attempts_number: u32,
}

/// Sassafras epoch information
#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)]
pub struct Epoch {
/// The epoch index.
pub epoch_idx: u64,
/// The starting slot of the epoch.
pub start_slot: Slot,
/// Slot duration in milliseconds.
pub slot_duration: SlotDuration,
/// Duration of epoch in slots.
pub epoch_duration: u64,
/// Authorities for the epoch.
pub authorities: Vec<AuthorityId>,
/// Randomness for the epoch.
pub randomness: Randomness,
/// Epoch configuration.
pub config: EpochConfiguration,
}

/// An opaque type used to represent the key ownership proof at the runtime API boundary.
///
/// The inner value is an encoded representation of the actual key ownership proof which will be
/// parameterized when defining the runtime. At the runtime API boundary this type is unknown and
/// as such we keep this opaque representation, implementors of the runtime API will have to make
/// sure that all usages of `OpaqueKeyOwnershipProof` refer to the same type.
#[derive(Decode, Encode, PartialEq, TypeInfo)]
pub struct OpaqueKeyOwnershipProof(Vec<u8>);

// Runtime API.
sp_api::decl_runtime_apis! {
/// API necessary for block authorship with Sassafras.
pub trait SassafrasApi {
/// Get ring context to be used for ticket construction and verification.
fn ring_context() -> Option<RingContext>;

/// Submit next epoch validator tickets via an unsigned extrinsic.
/// This method returns `false` when creation of the extrinsics fails.
fn submit_tickets_unsigned_extrinsic(tickets: Vec<TicketEnvelope>) -> bool;

/// Get ticket id associated to the given slot.
fn slot_ticket_id(slot: Slot) -> Option<TicketId>;

/// Get ticket id and data associated to the given slot.
fn slot_ticket(slot: Slot) -> Option<(TicketId, TicketBody)>;

/// Current epoch information.
fn current_epoch() -> Epoch;

/// Next epoch information.
fn next_epoch() -> Epoch;

/// Generates a proof of key ownership for the given authority in the current epoch.
///
/// An example usage of this module is coupled with the session historical module to prove
/// that a given authority key is tied to a given staking identity during a specific
/// session. Proofs of key ownership are necessary for submitting equivocation reports.
///
/// NOTE: even though the API takes a `slot` as parameter the current implementations
/// ignores this parameter and instead relies on this method being called at the correct
/// block height, i.e. any point at which the epoch for the given slot is live on-chain.
/// Future implementations will instead use indexed data through an offchain worker, not
/// requiring older states to be available.
fn generate_key_ownership_proof(
slot: Slot,
authority_id: AuthorityId,
) -> Option<OpaqueKeyOwnershipProof>;

/// Submits an unsigned extrinsic to report an equivocation.
///
/// The caller must provide the equivocation proof and a key ownership proof (should be
/// obtained using `generate_key_ownership_proof`). The extrinsic will be unsigned and
/// should only be accepted for local authorship (not to be broadcast to the network). This
/// method returns `None` when creation of the extrinsic fails, e.g. if equivocation
/// reporting is disabled for the given runtime (i.e. this method is hardcoded to return
/// `None`). Only useful in an offchain context.
fn submit_report_equivocation_unsigned_extrinsic(
equivocation_proof: EquivocationProof<Block::Header>,
key_owner_proof: OpaqueKeyOwnershipProof,
) -> bool;
}
}
Loading