Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sassafras primitives #1249

Merged
merged 14 commits into from
Aug 31, 2023
16 changes: 16 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ members = [
"substrate/primitives/consensus/common",
"substrate/primitives/consensus/grandpa",
"substrate/primitives/consensus/pow",
"substrate/primitives/consensus/sassafras",
"substrate/primitives/consensus/slots",
"substrate/primitives/core",
"substrate/primitives/core/hashing",
Expand Down
64 changes: 64 additions & 0 deletions substrate/primitives/consensus/sassafras/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
[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" }

# Temporary workaround, remove as soon as 'bandersnatch' is stable.
#
# Sassafras requires to enable `bandersnatch-experimental` feature for some of its dependencies
# and this ends up being transitively enabled in `sp-keystore` crate.
#
# E.g. sp-application-crypto → sp-io → sp-keystore
#
# Follows that Bandersnatch api ends up being exposed by the `Keystore` trait and thus we require
# to expose these functions implementations in the client keystore (`sc-keystore`) as well.
#
# The crate feature should be enabled only for `std` builds (keep it disabled by default).
sc-keystore = { path = "../../../client/keystore", optional = true}
davxy marked this conversation as resolved.
Show resolved Hide resolved

[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",
"sc-keystore/bandersnatch-experimental"
]

# 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 substrate/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.
98 changes: 98 additions & 0 deletions substrate/primitives/consensus/sassafras/src/digests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// 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, vrf::VrfSignature, AuthorityId, AuthorityIndex, AuthoritySignature,
EpochConfiguration, Randomness, Slot, SASSAFRAS_ENGINE_ID,
};

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

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

/// Epoch slot claim digest entry.
///
/// This is mandatory for each block.
#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct SlotClaim {
/// 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 mandatory 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,
/// Epoch configurable parameters.
///
/// If not present previous epoch parameters are used.
pub config: Option<EpochConfiguration>,
}

/// Runtime digest entries.
///
/// Entries which may be generated by on-chain code.
#[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),
}

impl TryFrom<&DigestItem> for SlotClaim {
type Error = ();
fn try_from(item: &DigestItem) -> Result<Self, Self::Error> {
item.pre_runtime_try_to(&SASSAFRAS_ENGINE_ID).ok_or(())
}
}

impl From<&SlotClaim> for DigestItem {
fn from(claim: &SlotClaim) -> Self {
DigestItem::PreRuntime(SASSAFRAS_ENGINE_ID, claim.encode())
}
}

impl TryFrom<&DigestItem> for AuthoritySignature {
type Error = ();
fn try_from(item: &DigestItem) -> Result<Self, Self::Error> {
item.seal_try_to(&SASSAFRAS_ENGINE_ID).ok_or(())
}
}

impl From<&AuthoritySignature> for DigestItem {
fn from(signature: &AuthoritySignature) -> Self {
DigestItem::Seal(SASSAFRAS_ENGINE_ID, signature.encode())
}
}
175 changes: 175 additions & 0 deletions substrate/primitives/consensus/sassafras/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
// 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};

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

pub mod digests;
pub mod ticket;
pub mod vrf;

pub use ticket::{
ticket_id_threshold, 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,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Creating this struct with Default will initialize everything to zero, including the attempts_number. Shouldn't that be at least 1 by 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>);
davxy marked this conversation as resolved.
Show resolved Hide resolved

// 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<vrf::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
davxy marked this conversation as resolved.
Show resolved Hide resolved
/// 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