Bandersnatch VRF (#14412)

* Introduce bandersnatch vrf

* Some documentation

* Fix tests

* Fix docs refs

* Some more docs

* Comments about key derivation

* Make clippy happy

* Fix ring context enc/dec test

* Fix docs

* Switch to upstream ring-vrf

* Use sub-domains to construct VrfInput

* Bandersnatch VRF experimental feature

* Restore upstream dep

* Fix feature flags

* Apply typo fix

Co-authored-by: Anton <anton.kalyaev@gmail.com>

* Bump bandersnatch-vrfs

* Weiestrass form has been selected

* Rename bandersnatch testing app crypto id

* Support for seed recovery

* Clarified domain size <-> key size relationship

* cargo fmt

* Trigger CI

* Some required tweaks to crypto types

* Remove leftovers from Cargo.toml

* Remove some TODO notes

* Simplification of structs construction

* Trigger CI

* Apply review suggestion

Co-authored-by: Koute <koute@users.noreply.github.com>

* Docs typo

* Fix keystore tests

* Consistence

* Add ref to git rependency

* Static check of MAX_VRF_IOS value

* Clarify behavior for out of ring keys signatures

* Add test for ring-vrf to the keystore

* Fix docs

---------

Co-authored-by: Anton <anton.kalyaev@gmail.com>
Co-authored-by: Koute <koute@users.noreply.github.com>
This commit is contained in:
Davide Galassi
2023-08-09 17:09:47 +02:00
committed by GitHub
parent 8321cee4f5
commit 314109d87b
23 changed files with 1900 additions and 59 deletions
@@ -52,9 +52,18 @@ full_crypto = [
"sp-io/disable_oom",
]
# This feature adds BLS crypto primitives. It should not be used in production since
# the BLS implementation and interface may still be subject to significant change.
# This feature adds BLS crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bls-experimental = [
"sp-core/bls-experimental",
"sp-io/bls-experimental",
]
# This feature adds Bandersnatch crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bandersnatch-experimental = [
"sp-core/bandersnatch-experimental",
"sp-io/bandersnatch-experimental",
]
@@ -0,0 +1,57 @@
// 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.
//! Bandersnatch VRF application crypto types.
use crate::{KeyTypeId, RuntimePublic};
pub use sp_core::bandersnatch::*;
use sp_std::vec::Vec;
mod app {
crate::app_crypto!(super, sp_core::testing::BANDERSNATCH);
}
#[cfg(feature = "full_crypto")]
pub use app::Pair as AppPair;
pub use app::{Public as AppPublic, Signature as AppSignature};
impl RuntimePublic for Public {
type Signature = Signature;
/// Dummy implementation. Returns an empty vector.
fn all(_key_type: KeyTypeId) -> Vec<Self> {
Vec::new()
}
fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self {
sp_io::crypto::bandersnatch_generate(key_type, seed)
}
/// Dummy implementation. Returns `None`.
fn sign<M: AsRef<[u8]>>(&self, _key_type: KeyTypeId, _msg: &M) -> Option<Self::Signature> {
None
}
/// Dummy implementation. Returns `false`.
fn verify<M: AsRef<[u8]>>(&self, _msg: &M, _signature: &Self::Signature) -> bool {
false
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -43,6 +43,8 @@ pub use serde;
#[doc(hidden)]
pub use sp_std::{ops::Deref, vec::Vec};
#[cfg(feature = "bandersnatch-experimental")]
pub mod bandersnatch;
#[cfg(feature = "bls-experimental")]
pub mod bls377;
#[cfg(feature = "bls-experimental")]
@@ -23,7 +23,7 @@ use sp_core::crypto::Pair;
use sp_core::crypto::{CryptoType, CryptoTypeId, IsWrappedBy, KeyTypeId, Public};
use sp_std::{fmt::Debug, vec::Vec};
/// An application-specific cryptographic object.
/// Application-specific cryptographic object.
///
/// Combines all the core types and constants that are defined by a particular
/// cryptographic scheme when it is used in a specific application domain.
@@ -31,7 +31,7 @@ use sp_std::{fmt::Debug, vec::Vec};
/// Typically, the implementers of this trait are its associated types themselves.
/// This provides a convenient way to access generic information about the scheme
/// given any of the associated types.
pub trait AppCrypto: 'static + Send + Sync + Sized + CryptoType + Clone {
pub trait AppCrypto: 'static + Sized + CryptoType {
/// Identifier for application-specific key type.
const ID: KeyTypeId;
@@ -61,38 +61,30 @@ pub trait MaybeHash {}
#[cfg(all(not(feature = "std"), not(feature = "full_crypto")))]
impl<T> MaybeHash for T {}
/// A application's public key.
pub trait AppPublic:
AppCrypto + Public + Ord + PartialOrd + Eq + PartialEq + Debug + MaybeHash + Codec
{
/// The wrapped type which is just a plain instance of `Public`.
type Generic: IsWrappedBy<Self>
+ Public
+ Ord
+ PartialOrd
+ Eq
+ PartialEq
+ Debug
+ MaybeHash
+ Codec;
}
/// A application's key pair.
/// Application-specific key pair.
#[cfg(feature = "full_crypto")]
pub trait AppPair: AppCrypto + Pair<Public = <Self as AppCrypto>::Public> {
pub trait AppPair:
AppCrypto + Pair<Public = <Self as AppCrypto>::Public, Signature = <Self as AppCrypto>::Signature>
{
/// The wrapped type which is just a plain instance of `Pair`.
type Generic: IsWrappedBy<Self>
+ Pair<Public = <<Self as AppCrypto>::Public as AppPublic>::Generic>
+ Pair<Signature = <<Self as AppCrypto>::Signature as AppSignature>::Generic>;
}
/// A application's signature.
pub trait AppSignature: AppCrypto + Eq + PartialEq + Debug {
/// Application-specific public key.
pub trait AppPublic: AppCrypto + Public + Debug + MaybeHash + Codec {
/// The wrapped type which is just a plain instance of `Public`.
type Generic: IsWrappedBy<Self> + Public + Debug + MaybeHash + Codec;
}
/// Application-specific signature.
pub trait AppSignature: AppCrypto + Eq + PartialEq + Debug + Clone {
/// The wrapped type which is just a plain instance of `Signature`.
type Generic: IsWrappedBy<Self> + Eq + PartialEq + Debug;
}
/// A runtime interface for a public key.
/// Runtime interface for a public key.
pub trait RuntimePublic: Sized {
/// The signature that will be generated when signing with the corresponding private key.
type Signature: Debug + Eq + PartialEq + Clone;
@@ -123,7 +115,7 @@ pub trait RuntimePublic: Sized {
fn to_raw_vec(&self) -> Vec<u8>;
}
/// A runtime interface for an application's public key.
/// Runtime interface for an application's public key.
pub trait RuntimeAppPublic: Sized {
/// An identifier for this application-specific key type.
const ID: KeyTypeId;
+14 -2
View File
@@ -13,6 +13,7 @@ documentation = "https://docs.rs/sp-core"
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
arrayvec = { version = "0.7.2", default-features = false }
codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive","max-encoded-len"] }
scale-info = { version = "2.5.0", default-features = false, features = ["derive"] }
log = { version = "0.4.17", default-features = false }
@@ -53,8 +54,11 @@ merlin = { version = "2.0", default-features = false }
secp256k1 = { version = "0.24.0", default-features = false, features = ["recovery", "alloc"], optional = true }
sp-core-hashing = { version = "9.0.0", path = "./hashing", default-features = false, optional = true }
sp-runtime-interface = { version = "17.0.0", default-features = false, path = "../runtime-interface" }
# bls crypto
w3f-bls = { version = "0.1.3", default-features = false, optional = true}
# bandersnatch crypto
bandersnatch_vrfs = { git = "https://github.com/w3f/ring-vrf", rev = "c86ebd4", default-features = false, optional = true }
[dev-dependencies]
criterion = "0.4.0"
@@ -71,12 +75,14 @@ bench = false
[features]
default = ["std"]
std = [
"arrayvec/std",
"merlin/std",
"full_crypto",
"log/std",
"thiserror",
"lazy_static",
"parking_lot",
"bandersnatch_vrfs/getrandom",
"bounded-collections/std",
"primitive-types/std",
"primitive-types/serde",
@@ -143,6 +149,12 @@ full_crypto = [
"sp-runtime-interface/disable_target_static_assertions",
]
# This feature adds BLS crypto primitives. It should not be used in production since
# the BLS implementation and interface may still be subject to significant change.
# This feature adds BLS crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bls-experimental = ["w3f-bls"]
# This feature adds Bandersnatch crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bandersnatch-experimental = ["bandersnatch_vrfs"]
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -15,9 +15,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// tag::description[]
//! Cryptographic utilities.
// end::description[]
use crate::{ed25519, sr25519};
#[cfg(feature = "std")]
@@ -486,7 +484,7 @@ pub trait ByteArray: AsRef<[u8]> + AsMut<[u8]> + for<'a> TryFrom<&'a [u8], Error
}
/// Trait suitable for typical cryptographic key public type.
pub trait Public: CryptoType + ByteArray + Derive + PartialEq + Eq + Clone + Send {}
pub trait Public: CryptoType + ByteArray + Derive + PartialEq + Eq + Clone + Send + Sync {}
/// An opaque 32-byte cryptographic identifier.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, MaxEncodedLen, TypeInfo)]
+1 -1
View File
@@ -417,7 +417,7 @@ impl TraitPair for Pair {
}
/// Verify a signature on a message. Returns true if the signature is good.
fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, public: &Self::Public) -> bool {
fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, public: &Public) -> bool {
sig.recover(message).map(|actual| actual == *public).unwrap_or_default()
}
+1 -1
View File
@@ -421,7 +421,7 @@ impl TraitPair for Pair {
/// Verify a signature on a message.
///
/// Returns true if the signature is good.
fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, public: &Self::Public) -> bool {
fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, public: &Public) -> bool {
let Ok(public) = VerificationKey::try_from(public.as_slice()) else { return false };
let Ok(signature) = ed25519_zebra::Signature::try_from(sig.as_ref()) else { return false };
public.verify(&signature, message.as_ref()).is_ok()
+2
View File
@@ -55,6 +55,8 @@ pub mod crypto;
pub mod hexdisplay;
pub use paste;
#[cfg(feature = "bandersnatch-experimental")]
pub mod bandersnatch;
#[cfg(feature = "bls-experimental")]
pub mod bls;
pub mod defer;
+2 -2
View File
@@ -504,7 +504,7 @@ impl TraitPair for Pair {
self.0.sign(context.bytes(message)).into()
}
fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool {
fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
let Ok(signature) = schnorrkel::Signature::from_bytes(sig.as_ref()) else { return false };
let Ok(public) = PublicKey::from_bytes(pubkey.as_ref()) else { return false };
public.verify_simple(SIGNING_CTX, message.as_ref(), &signature).is_ok()
@@ -568,7 +568,7 @@ pub mod vrf {
impl VrfTranscript {
/// Build a new transcript instance.
///
/// Each `data` element is a tuple `(domain, message)` composing the transcipt.
/// Each `data` element is a tuple `(domain, message)` used to build the transcript.
pub fn new(label: &'static [u8], data: &[(&'static [u8], &[u8])]) -> Self {
let mut transcript = merlin::Transcript::new(label);
data.iter().for_each(|(l, b)| transcript.append_message(l, b));
+3 -1
View File
@@ -21,10 +21,12 @@ use crate::crypto::KeyTypeId;
/// Key type for generic Ed25519 key.
pub const ED25519: KeyTypeId = KeyTypeId(*b"ed25");
/// Key type for generic Sr 25519 key.
/// Key type for generic Sr25519 key.
pub const SR25519: KeyTypeId = KeyTypeId(*b"sr25");
/// Key type for generic ECDSA key.
pub const ECDSA: KeyTypeId = KeyTypeId(*b"ecds");
/// Key type for generic Bandersnatch key.
pub const BANDERSNATCH: KeyTypeId = KeyTypeId(*b"band");
/// Key type for generic BLS12-377 key.
pub const BLS377: KeyTypeId = KeyTypeId(*b"bls7");
/// Key type for generic BLS12-381 key.
+10 -2
View File
@@ -93,8 +93,16 @@ disable_allocator = []
# runtime without first upgrading your host client!
improved_panic_error_reporting = []
# This feature adds BLS crypto primitives. It should not be used in production since
# the BLS implementation and interface may still be subject to significant change.
# This feature adds BLS crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bls-experimental = [
"sp-keystore/bls-experimental",
]
# This feature adds Bandersnatch crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bandersnatch-experimental = [
"sp-keystore/bandersnatch-experimental",
]
+22 -1
View File
@@ -92,6 +92,8 @@ use sp_core::{
#[cfg(feature = "std")]
use sp_keystore::KeystoreExt;
#[cfg(feature = "bandersnatch-experimental")]
use sp_core::bandersnatch;
use sp_core::{
crypto::KeyTypeId,
ecdsa, ed25519,
@@ -1190,13 +1192,13 @@ pub trait Crypto {
Ok(pubkey.serialize())
}
#[cfg(feature = "bls-experimental")]
/// Generate an `bls12-377` key for the given key type using an optional `seed` and
/// store it in the keystore.
///
/// The `seed` needs to be a valid utf8.
///
/// Returns the public key.
#[cfg(feature = "bls-experimental")]
fn bls377_generate(&mut self, id: KeyTypeId, seed: Option<Vec<u8>>) -> bls377::Public {
let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
self.extension::<KeystoreExt>()
@@ -1204,6 +1206,25 @@ pub trait Crypto {
.bls377_generate_new(id, seed)
.expect("`bls377_generate` failed")
}
/// Generate a `bandersnatch` key pair for the given key type using an optional
/// `seed` and store it in the keystore.
///
/// The `seed` needs to be a valid utf8.
///
/// Returns the public key.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_generate(
&mut self,
id: KeyTypeId,
seed: Option<Vec<u8>>,
) -> bandersnatch::Public {
let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!"));
self.extension::<KeystoreExt>()
.expect("No `keystore` associated for the current context!")
.bandersnatch_generate_new(id, seed)
.expect("`bandernatch_generate` failed")
}
}
/// Interface that provides functions for hashing with different algorithms.
+6
View File
@@ -18,3 +18,9 @@ lazy_static = "1.4.0"
strum = { version = "0.24.1", features = ["derive"], default-features = false }
sp-core = { version = "21.0.0", path = "../core" }
sp-runtime = { version = "24.0.0", path = "../runtime" }
[features]
# This feature adds Bandersnatch crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bandersnatch-experimental = ["sp-core/bandersnatch-experimental"]
@@ -0,0 +1,209 @@
// 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.
//! A set of well-known keys used for testing.
pub use sp_core::bandersnatch;
use sp_core::{
bandersnatch::{Pair, Public, Signature},
crypto::UncheckedFrom,
ByteArray, Pair as PairT,
};
use lazy_static::lazy_static;
use std::{collections::HashMap, ops::Deref, sync::Mutex};
/// Set of test accounts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, strum::EnumIter)]
pub enum Keyring {
Alice,
Bob,
Charlie,
Dave,
Eve,
Ferdie,
One,
Two,
}
const PUBLIC_RAW_LEN: usize = <Public as ByteArray>::LEN;
impl Keyring {
pub fn from_public(who: &Public) -> Option<Keyring> {
Self::iter().find(|&k| &Public::from(k) == who)
}
pub fn from_raw_public(who: [u8; PUBLIC_RAW_LEN]) -> Option<Keyring> {
Self::from_public(&Public::unchecked_from(who))
}
pub fn to_raw_public(self) -> [u8; PUBLIC_RAW_LEN] {
*Public::from(self).as_ref()
}
pub fn to_raw_public_vec(self) -> Vec<u8> {
Public::from(self).to_raw_vec()
}
pub fn sign(self, msg: &[u8]) -> Signature {
Pair::from(self).sign(msg)
}
pub fn pair(self) -> Pair {
Pair::from_string(&format!("//{}", <&'static str>::from(self)), None)
.expect("static values are known good; qed")
}
/// Returns an iterator over all test accounts.
pub fn iter() -> impl Iterator<Item = Keyring> {
<Self as strum::IntoEnumIterator>::iter()
}
pub fn public(self) -> Public {
self.pair().public()
}
pub fn to_seed(self) -> String {
format!("//{}", self)
}
/// Create a crypto `Pair` from a numeric value.
pub fn numeric(idx: usize) -> Pair {
Pair::from_string(&format!("//{}", idx), None).expect("numeric values are known good; qed")
}
}
impl From<Keyring> for &'static str {
fn from(k: Keyring) -> Self {
match k {
Keyring::Alice => "Alice",
Keyring::Bob => "Bob",
Keyring::Charlie => "Charlie",
Keyring::Dave => "Dave",
Keyring::Eve => "Eve",
Keyring::Ferdie => "Ferdie",
Keyring::One => "One",
Keyring::Two => "Two",
}
}
}
#[derive(Debug)]
pub struct ParseKeyringError;
impl std::fmt::Display for ParseKeyringError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ParseKeyringError")
}
}
impl std::str::FromStr for Keyring {
type Err = ParseKeyringError;
fn from_str(s: &str) -> Result<Self, <Self as std::str::FromStr>::Err> {
match s {
"Alice" => Ok(Keyring::Alice),
"Bob" => Ok(Keyring::Bob),
"Charlie" => Ok(Keyring::Charlie),
"Dave" => Ok(Keyring::Dave),
"Eve" => Ok(Keyring::Eve),
"Ferdie" => Ok(Keyring::Ferdie),
"One" => Ok(Keyring::One),
"Two" => Ok(Keyring::Two),
_ => Err(ParseKeyringError),
}
}
}
lazy_static! {
static ref PRIVATE_KEYS: Mutex<HashMap<Keyring, Pair>> =
Mutex::new(Keyring::iter().map(|who| (who, who.pair())).collect());
static ref PUBLIC_KEYS: HashMap<Keyring, Public> = PRIVATE_KEYS
.lock()
.unwrap()
.iter()
.map(|(&who, pair)| (who, pair.public()))
.collect();
}
impl From<Keyring> for Public {
fn from(k: Keyring) -> Self {
*(*PUBLIC_KEYS).get(&k).unwrap()
}
}
impl From<Keyring> for Pair {
fn from(k: Keyring) -> Self {
k.pair()
}
}
impl From<Keyring> for [u8; PUBLIC_RAW_LEN] {
fn from(k: Keyring) -> Self {
*(*PUBLIC_KEYS).get(&k).unwrap().as_ref()
}
}
impl From<Keyring> for &'static [u8; PUBLIC_RAW_LEN] {
fn from(k: Keyring) -> Self {
PUBLIC_KEYS.get(&k).unwrap().as_ref()
}
}
impl AsRef<[u8; PUBLIC_RAW_LEN]> for Keyring {
fn as_ref(&self) -> &[u8; PUBLIC_RAW_LEN] {
PUBLIC_KEYS.get(self).unwrap().as_ref()
}
}
impl AsRef<Public> for Keyring {
fn as_ref(&self) -> &Public {
PUBLIC_KEYS.get(self).unwrap()
}
}
impl Deref for Keyring {
type Target = [u8; PUBLIC_RAW_LEN];
fn deref(&self) -> &[u8; PUBLIC_RAW_LEN] {
PUBLIC_KEYS.get(self).unwrap().as_ref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::{bandersnatch::Pair, Pair as PairT};
#[test]
fn should_work() {
assert!(Pair::verify(
&Keyring::Alice.sign(b"I am Alice!"),
b"I am Alice!",
&Keyring::Alice.public(),
));
assert!(!Pair::verify(
&Keyring::Alice.sign(b"I am Alice!"),
b"I am Bob!",
&Keyring::Alice.public(),
));
assert!(!Pair::verify(
&Keyring::Alice.sign(b"I am Alice!"),
b"I am Alice!",
&Keyring::Bob.public(),
));
}
}
+6
View File
@@ -23,11 +23,17 @@ pub mod sr25519;
/// Test account crypto for ed25519.
pub mod ed25519;
/// Test account crypto for bandersnatch.
#[cfg(feature = "bandersnatch-experimental")]
pub mod bandersnatch;
/// Convenience export: Sr25519's Keyring is exposed as `AccountKeyring`,
/// since it tends to be used for accounts (although it may also be used
/// by authorities).
pub use sr25519::Keyring as AccountKeyring;
#[cfg(feature = "bandersnatch-experimental")]
pub use bandersnatch::Keyring as BandersnatchKeyring;
pub use ed25519::Keyring as Ed25519Keyring;
pub use sr25519::Keyring as Sr25519Keyring;
+8 -2
View File
@@ -31,6 +31,12 @@ std = [
"sp-externalities/std",
]
# This feature adds BLS crypto primitives. It should not be used in production since
# the BLS implementation and interface may still be subject to significant change.
# This feature adds BLS crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bls-experimental = ["sp-core/bls-experimental"]
# This feature adds Bandersnatch crypto primitives.
# It should not be used in production since the implementation and interface may still
# be subject to significant changes.
bandersnatch-experimental = ["sp-core/bandersnatch-experimental"]
+155 -6
View File
@@ -19,6 +19,8 @@
pub mod testing;
#[cfg(feature = "bandersnatch-experimental")]
use sp_core::bandersnatch;
#[cfg(feature = "bls-experimental")]
use sp_core::{bls377, bls381};
use sp_core::{
@@ -174,6 +176,91 @@ pub trait Keystore: Send + Sync {
msg: &[u8; 32],
) -> Result<Option<ecdsa::Signature>, Error>;
/// Returns all the bandersnatch public keys for the given key type.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_public_keys(&self, key_type: KeyTypeId) -> Vec<bandersnatch::Public>;
/// Generate a new bandersnatch key pair for the given key type and an optional seed.
///
/// Returns an `bandersnatch::Public` key of the generated key pair or an `Err` if
/// something failed during key generation.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_generate_new(
&self,
key_type: KeyTypeId,
seed: Option<&str>,
) -> Result<bandersnatch::Public, Error>;
/// Generate an bandersnatch signature for a given message.
///
/// Receives [`KeyTypeId`] and an [`bandersnatch::Public`] key to be able to map
/// them to a private key that exists in the keystore.
///
/// Returns an [`bandersnatch::Signature`] or `None` in case the given `key_type`
/// and `public` combination doesn't exist in the keystore.
/// An `Err` will be returned if generating the signature itself failed.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
msg: &[u8],
) -> Result<Option<bandersnatch::Signature>, Error>;
/// Generate a bandersnatch VRF signature for the given data.
///
/// Receives [`KeyTypeId`] and an [`bandersnatch::Public`] key to be able to map
/// them to a private key that exists in the keystore.
///
/// Returns `None` if the given `key_type` and `public` combination doesn't
/// exist in the keystore or an `Err` when something failed.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfSignData,
) -> Result<Option<bandersnatch::vrf::VrfSignature>, Error>;
/// Generate a bandersnatch VRF (pre)output for a given input data.
///
/// Receives [`KeyTypeId`] and an [`bandersnatch::Public`] key to be able to map
/// them to a private key that exists in the keystore.
///
/// Returns `None` if the given `key_type` and `public` combination doesn't
/// exist in the keystore or an `Err` when something failed.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_output(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfInput,
) -> Result<Option<bandersnatch::vrf::VrfOutput>, Error>;
/// Generate a bandersnatch ring-VRF signature for the given data.
///
/// Receives [`KeyTypeId`] and an [`bandersnatch::Public`] key to be able to map
/// them to a private key that exists in the keystore.
///
/// Also takes a [`bandersnatch::ring_vrf::RingProver`] instance obtained from
/// a valid [`bandersnatch::ring_vrf::RingContext`].
///
/// The ring signature is verifiable if the public key corresponding to the
/// signing [`bandersnatch::Pair`] is part of the ring from which the
/// [`bandersnatch::ring_vrf::RingProver`] has been constructed.
/// If not, the produced signature is just useless.
///
/// Returns `None` if the given `key_type` and `public` combination doesn't
/// exist in the keystore or an `Err` when something failed.
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_ring_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfSignData,
prover: &bandersnatch::ring_vrf::RingProver,
) -> Result<Option<bandersnatch::ring_vrf::RingVrfSignature>, Error>;
/// Returns all bls12-381 public keys for the given key type.
#[cfg(feature = "bls-experimental")]
fn bls381_public_keys(&self, id: KeyTypeId) -> Vec<bls381::Public>;
@@ -258,6 +345,7 @@ pub trait Keystore: Send + Sync {
/// - sr25519
/// - ed25519
/// - ecdsa
/// - bandersnatch
/// - bls381
/// - bls377
///
@@ -291,6 +379,12 @@ pub trait Keystore: Send + Sync {
self.ecdsa_sign(id, &public, msg)?.map(|s| s.encode())
},
#[cfg(feature = "bandersnatch-experimental")]
bandersnatch::CRYPTO_ID => {
let public = bandersnatch::Public::from_slice(public)
.map_err(|_| Error::ValidationError("Invalid public key format".into()))?;
self.bandersnatch_sign(id, &public, msg)?.map(|s| s.encode())
},
#[cfg(feature = "bls-experimental")]
bls381::CRYPTO_ID => {
let public = bls381::Public::from_slice(public)
@@ -400,16 +494,59 @@ impl<T: Keystore + ?Sized> Keystore for Arc<T> {
(**self).ecdsa_sign_prehashed(key_type, public, msg)
}
fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> {
(**self).insert(key_type, suri, public)
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_public_keys(&self, key_type: KeyTypeId) -> Vec<bandersnatch::Public> {
(**self).bandersnatch_public_keys(key_type)
}
fn keys(&self, key_type: KeyTypeId) -> Result<Vec<Vec<u8>>, Error> {
(**self).keys(key_type)
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_generate_new(
&self,
key_type: KeyTypeId,
seed: Option<&str>,
) -> Result<bandersnatch::Public, Error> {
(**self).bandersnatch_generate_new(key_type, seed)
}
fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
(**self).has_keys(public_keys)
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
msg: &[u8],
) -> Result<Option<bandersnatch::Signature>, Error> {
(**self).bandersnatch_sign(key_type, public, msg)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfSignData,
) -> Result<Option<bandersnatch::vrf::VrfSignature>, Error> {
(**self).bandersnatch_vrf_sign(key_type, public, input)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_output(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfInput,
) -> Result<Option<bandersnatch::vrf::VrfOutput>, Error> {
(**self).bandersnatch_vrf_output(key_type, public, input)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_ring_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfSignData,
prover: &bandersnatch::ring_vrf::RingProver,
) -> Result<Option<bandersnatch::ring_vrf::RingVrfSignature>, Error> {
(**self).bandersnatch_ring_vrf_sign(key_type, public, input, prover)
}
#[cfg(feature = "bls-experimental")]
@@ -459,6 +596,18 @@ impl<T: Keystore + ?Sized> Keystore for Arc<T> {
) -> Result<Option<bls377::Signature>, Error> {
(**self).bls377_sign(key_type, public, msg)
}
fn insert(&self, key_type: KeyTypeId, suri: &str, public: &[u8]) -> Result<(), ()> {
(**self).insert(key_type, suri, public)
}
fn keys(&self, key_type: KeyTypeId) -> Result<Vec<Vec<u8>>, Error> {
(**self).keys(key_type)
}
fn has_keys(&self, public_keys: &[(Vec<u8>, KeyTypeId)]) -> bool {
(**self).has_keys(public_keys)
}
}
/// A shared pointer to a keystore implementation.
+127 -2
View File
@@ -19,6 +19,8 @@
use crate::{Error, Keystore, KeystorePtr};
#[cfg(feature = "bandersnatch-experimental")]
use sp_core::bandersnatch;
#[cfg(feature = "bls-experimental")]
use sp_core::{bls377, bls381};
use sp_core::{
@@ -214,6 +216,64 @@ impl Keystore for MemoryKeystore {
Ok(sig)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_public_keys(&self, key_type: KeyTypeId) -> Vec<bandersnatch::Public> {
self.public_keys::<bandersnatch::Pair>(key_type)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_generate_new(
&self,
key_type: KeyTypeId,
seed: Option<&str>,
) -> Result<bandersnatch::Public, Error> {
self.generate_new::<bandersnatch::Pair>(key_type, seed)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
msg: &[u8],
) -> Result<Option<bandersnatch::Signature>, Error> {
self.sign::<bandersnatch::Pair>(key_type, public, msg)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
data: &bandersnatch::vrf::VrfSignData,
) -> Result<Option<bandersnatch::vrf::VrfSignature>, Error> {
self.vrf_sign::<bandersnatch::Pair>(key_type, public, data)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_ring_vrf_sign(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
data: &bandersnatch::vrf::VrfSignData,
prover: &bandersnatch::ring_vrf::RingProver,
) -> Result<Option<bandersnatch::ring_vrf::RingVrfSignature>, Error> {
let sig = self
.pair::<bandersnatch::Pair>(key_type, public)
.map(|pair| pair.ring_vrf_sign(data, prover));
Ok(sig)
}
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_output(
&self,
key_type: KeyTypeId,
public: &bandersnatch::Public,
input: &bandersnatch::vrf::VrfInput,
) -> Result<Option<bandersnatch::vrf::VrfOutput>, Error> {
self.vrf_output::<bandersnatch::Pair>(key_type, public, input)
}
#[cfg(feature = "bls-experimental")]
fn bls381_public_keys(&self, key_type: KeyTypeId) -> Vec<bls381::Public> {
self.public_keys::<bls381::Pair>(key_type)
@@ -330,7 +390,7 @@ mod tests {
}
#[test]
fn vrf_sign() {
fn sr25519_vrf_sign() {
let store = MemoryKeystore::new();
let secret_uri = "//Alice";
@@ -359,7 +419,7 @@ mod tests {
}
#[test]
fn vrf_output() {
fn sr25519_vrf_output() {
let store = MemoryKeystore::new();
let secret_uri = "//Alice";
@@ -406,4 +466,69 @@ mod tests {
let res = store.ecdsa_sign_prehashed(ECDSA, &pair.public(), &msg).unwrap();
assert!(res.is_some());
}
#[test]
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_vrf_sign() {
use sp_core::testing::BANDERSNATCH;
let store = MemoryKeystore::new();
let secret_uri = "//Alice";
let key_pair =
bandersnatch::Pair::from_string(secret_uri, None).expect("Generates key pair");
let in1 = bandersnatch::vrf::VrfInput::new("in", "foo");
let sign_data =
bandersnatch::vrf::VrfSignData::new_unchecked(b"Test", Some("m1"), Some(in1));
let result = store.bandersnatch_vrf_sign(BANDERSNATCH, &key_pair.public(), &sign_data);
assert!(result.unwrap().is_none());
store
.insert(BANDERSNATCH, secret_uri, key_pair.public().as_ref())
.expect("Inserts unknown key");
let result = store.bandersnatch_vrf_sign(BANDERSNATCH, &key_pair.public(), &sign_data);
assert!(result.unwrap().is_some());
}
#[test]
#[cfg(feature = "bandersnatch-experimental")]
fn bandersnatch_ring_vrf_sign() {
use sp_core::testing::BANDERSNATCH;
let store = MemoryKeystore::new();
let ring_ctx = bandersnatch::ring_vrf::RingContext::new_testing();
let mut pks: Vec<_> = (0..16)
.map(|i| bandersnatch::Pair::from_seed(&[i as u8; 32]).public())
.collect();
let prover_idx = 3;
let prover = ring_ctx.prover(&pks, prover_idx).unwrap();
let secret_uri = "//Alice";
let pair = bandersnatch::Pair::from_string(secret_uri, None).expect("Generates key pair");
pks[prover_idx] = pair.public();
let in1 = bandersnatch::vrf::VrfInput::new("in1", "foo");
let sign_data =
bandersnatch::vrf::VrfSignData::new_unchecked(b"Test", &["m1", "m2"], [in1]);
let result =
store.bandersnatch_ring_vrf_sign(BANDERSNATCH, &pair.public(), &sign_data, &prover);
assert!(result.unwrap().is_none());
store
.insert(BANDERSNATCH, secret_uri, pair.public().as_ref())
.expect("Inserts unknown key");
let result =
store.bandersnatch_ring_vrf_sign(BANDERSNATCH, &pair.public(), &sign_data, &prover);
assert!(result.unwrap().is_some());
}
}