feat: initialize Kurdistan SDK - independent fork of Polkadot SDK

This commit is contained in:
2025-12-13 15:44:15 +03:00
commit e4778b4576
6838 changed files with 1847450 additions and 0 deletions
@@ -0,0 +1,88 @@
// 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};
use alloc::vec::Vec;
pub use sp_core::bandersnatch::*;
use sp_core::{
crypto::CryptoType,
proof_of_possession::{NonAggregatable, ProofOfPossessionVerifier},
Pair as TraitPair,
};
mod app {
crate::app_crypto!(super, sp_core::testing::BANDERSNATCH);
}
#[cfg(feature = "full_crypto")]
pub use app::Pair as AppPair;
pub use app::{
ProofOfPossession as AppProofOfPossession, Public as AppPublic, Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = 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)
}
fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature> {
sp_io::crypto::bandersnatch_sign(key_type, self, msg.as_ref())
}
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
let sig = AppSignature::from(*signature);
let pub_key = AppPublic::from(*self);
<AppPublic as CryptoType>::Pair::verify(&sig, msg.as_ref(), &pub_key)
}
fn generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession> {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::bandersnatch_sign(key_type, self, &proof_of_possession_statement)
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::Signature,
) -> bool {
let pub_key = AppPublic::from(*self);
<AppPublic as CryptoType>::Pair::verify_proof_of_possession(
owner,
&proof_of_possession,
&pub_key,
)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -0,0 +1,86 @@
// 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.
//! BLS12-381 crypto applications.
use crate::{KeyTypeId, RuntimePublic};
use alloc::vec::Vec;
pub use sp_core::bls::{
bls381::{BlsEngine as Bls381Engine, *},
Pair as BLS_Pair, ProofOfPossession as BLSPoP,
};
use sp_core::{crypto::CryptoType, proof_of_possession::ProofOfPossessionVerifier};
mod app {
crate::app_crypto!(super, sp_core::testing::BLS381);
}
#[cfg(feature = "full_crypto")]
pub use app::Pair as AppPair;
pub use app::{
ProofOfPossession as AppProofOfPossession, Public as AppPublic, Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
/// 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::bls381_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 generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession> {
sp_io::crypto::bls381_generate_proof_of_possession(key_type, self, owner)
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::ProofOfPossession,
) -> bool {
let pub_key = AppPublic::from(*self);
<AppPublic as CryptoType>::Pair::verify_proof_of_possession(
owner,
&proof_of_possession,
&pub_key,
)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -0,0 +1,77 @@
// 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.
//! Ecdsa crypto types.
use crate::{KeyTypeId, RuntimePublic};
use alloc::vec::Vec;
pub use sp_core::ecdsa::*;
use sp_core::proof_of_possession::NonAggregatable;
mod app {
crate::app_crypto!(super, sp_core::testing::ECDSA);
}
pub use app::{
Pair as AppPair, ProofOfPossession as AppProofOfPossession, Public as AppPublic,
Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = Signature;
fn all(key_type: KeyTypeId) -> crate::Vec<Self> {
sp_io::crypto::ecdsa_public_keys(key_type)
}
fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self {
sp_io::crypto::ecdsa_generate(key_type, seed)
}
fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature> {
sp_io::crypto::ecdsa_sign(key_type, self, msg.as_ref())
}
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
sp_io::crypto::ecdsa_verify(signature, msg.as_ref(), self)
}
fn generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::Signature> {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::ecdsa_sign(key_type, self, &proof_of_possession_statement)
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::Signature,
) -> bool {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::ecdsa_verify(&proof_of_possession, &proof_of_possession_statement, &self)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -0,0 +1,171 @@
// 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.
//! ECDSA and BLS12-381 paired crypto applications.
use crate::{KeyTypeId, RuntimePublic};
use alloc::vec::Vec;
pub use sp_core::paired_crypto::ecdsa_bls381::*;
use sp_core::{
bls381,
crypto::CryptoType,
ecdsa, ecdsa_bls381,
proof_of_possession::{NonAggregatable, ProofOfPossessionVerifier},
};
mod app {
crate::app_crypto!(super, sp_core::testing::ECDSA_BLS381);
}
#[cfg(feature = "full_crypto")]
pub use app::Pair as AppPair;
pub use app::{
ProofOfPossession as AppProofOfPossession, Public as AppPublic, Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = ecdsa_bls381::ProofOfPossession;
/// 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::ecdsa_bls381_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 generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession> {
let pub_key_as_bytes = self.to_raw_vec();
let (ecdsa_pub_as_bytes, bls381_pub_as_bytes) = split_pub_key_bytes(&pub_key_as_bytes)?;
let ecdsa_proof_of_possession =
generate_ecdsa_proof_of_possession(key_type, ecdsa_pub_as_bytes, owner)?;
let bls381_proof_of_possession =
generate_bls381_proof_of_possession(key_type, bls381_pub_as_bytes, owner)?;
let combined_proof_of_possession_raw =
combine_proof_of_possession(&ecdsa_proof_of_possession, &bls381_proof_of_possession)?;
Some(Self::ProofOfPossession::from_raw(combined_proof_of_possession_raw))
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::ProofOfPossession,
) -> bool {
let pub_key = AppPublic::from(*self);
<AppPublic as CryptoType>::Pair::verify_proof_of_possession(
owner,
&proof_of_possession,
&pub_key,
)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
/// Helper: Split public key bytes into ECDSA and BLS381 parts
fn split_pub_key_bytes(
pub_key_as_bytes: &[u8],
) -> Option<([u8; ecdsa::PUBLIC_KEY_SERIALIZED_SIZE], [u8; bls381::PUBLIC_KEY_SERIALIZED_SIZE])> {
let ecdsa_pub_as_bytes =
pub_key_as_bytes[..ecdsa::PUBLIC_KEY_SERIALIZED_SIZE].try_into().ok()?;
let bls381_pub_as_bytes =
pub_key_as_bytes[ecdsa::PUBLIC_KEY_SERIALIZED_SIZE..].try_into().ok()?;
Some((ecdsa_pub_as_bytes, bls381_pub_as_bytes))
}
/// Helper: Generate ECDSA proof of possession
fn generate_ecdsa_proof_of_possession(
key_type: KeyTypeId,
ecdsa_pub_as_bytes: [u8; ecdsa::PUBLIC_KEY_SERIALIZED_SIZE],
owner: &[u8],
) -> Option<ecdsa::Signature> {
let ecdsa_pub = ecdsa::Public::from_raw(ecdsa_pub_as_bytes);
let proof_of_possession_statement = ecdsa::Pair::proof_of_possession_statement(owner);
sp_io::crypto::ecdsa_sign(key_type, &ecdsa_pub, &proof_of_possession_statement)
}
/// Helper: Generate BLS381 proof of possession
fn generate_bls381_proof_of_possession(
key_type: KeyTypeId,
bls381_pub_as_bytes: [u8; bls381::PUBLIC_KEY_SERIALIZED_SIZE],
owner: &[u8],
) -> Option<bls381::ProofOfPossession> {
let bls381_pub = bls381::Public::from_raw(bls381_pub_as_bytes);
sp_io::crypto::bls381_generate_proof_of_possession(key_type, &bls381_pub, owner)
}
/// Helper: Combine ECDSA and BLS381 proof_of_possessions into a single raw proof_of_possession
fn combine_proof_of_possession(
ecdsa_proof_of_possession: &ecdsa::Signature,
bls381_proof_of_possession: &bls381::ProofOfPossession,
) -> Option<[u8; ecdsa_bls381::POP_LEN]> {
let mut combined_proof_of_possession_raw = [0u8; ecdsa_bls381::POP_LEN];
combined_proof_of_possession_raw[..ecdsa::SIGNATURE_SERIALIZED_SIZE]
.copy_from_slice(ecdsa_proof_of_possession.as_ref());
combined_proof_of_possession_raw[ecdsa::SIGNATURE_SERIALIZED_SIZE..]
.copy_from_slice(bls381_proof_of_possession.as_ref());
Some(combined_proof_of_possession_raw)
}
#[cfg(test)]
mod tests {
use super::*;
use sp_core::{bls381, crypto::Pair, ecdsa};
/// Helper function to generate test public keys for ECDSA and BLS381
fn generate_test_keys(
) -> ([u8; ecdsa::PUBLIC_KEY_SERIALIZED_SIZE], [u8; bls381::PUBLIC_KEY_SERIALIZED_SIZE]) {
let ecdsa_pair = ecdsa::Pair::generate().0;
let bls381_pair = bls381::Pair::generate().0;
let ecdsa_pub = ecdsa_pair.public();
let bls381_pub = bls381_pair.public();
(ecdsa_pub.to_raw_vec().try_into().unwrap(), bls381_pub.to_raw_vec().try_into().unwrap())
}
#[test]
fn test_split_pub_key_bytes() {
let (ecdsa_pub, bls381_pub) = generate_test_keys();
let mut combined_pub_key = Vec::new();
combined_pub_key.extend_from_slice(&ecdsa_pub);
combined_pub_key.extend_from_slice(&bls381_pub);
let result = split_pub_key_bytes(&combined_pub_key).unwrap();
assert_eq!(result.0, ecdsa_pub, "ECDSA public key does not match");
assert_eq!(result.1, bls381_pub, "BLS381 public key does not match");
}
}
@@ -0,0 +1,80 @@
// 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.
//! Ed25519 crypto types.
use crate::{KeyTypeId, RuntimePublic};
use alloc::vec::Vec;
use sp_core::proof_of_possession::NonAggregatable;
pub use sp_core::{
crypto::{CryptoBytes, SignatureBytes},
ed25519::*,
};
mod app {
crate::app_crypto!(super, sp_core::testing::ED25519);
}
pub use app::{
Pair as AppPair, ProofOfPossession as AppProofOfPossession, Public as AppPublic,
Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = Signature;
fn all(key_type: KeyTypeId) -> crate::Vec<Self> {
sp_io::crypto::ed25519_public_keys(key_type)
}
fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self {
sp_io::crypto::ed25519_generate(key_type, seed)
}
fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature> {
sp_io::crypto::ed25519_sign(key_type, self, msg.as_ref())
}
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
sp_io::crypto::ed25519_verify(signature, msg.as_ref(), self)
}
fn generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession> {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::ed25519_sign(key_type, self, &proof_of_possession_statement)
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::ProofOfPossession,
) -> bool {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::ed25519_verify(&proof_of_possession, &proof_of_possession_statement, &self)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -0,0 +1,791 @@
// 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.
//! Traits and macros for constructing application specific strongly typed crypto wrappers.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
pub use sp_core::crypto::{key_types, CryptoTypeId, DeriveJunction, KeyTypeId, Ss58Codec};
#[doc(hidden)]
pub use sp_core::crypto::{DeriveError, Pair, SecretStringError};
#[doc(hidden)]
pub use sp_core::{
self,
crypto::{ByteArray, CryptoType, Derive, IsWrappedBy, Public, Signature, UncheckedFrom, Wraps},
proof_of_possession::{ProofOfPossessionGenerator, ProofOfPossessionVerifier},
RuntimeDebug,
};
#[doc(hidden)]
pub use alloc::vec::Vec;
#[doc(hidden)]
pub use codec;
#[doc(hidden)]
pub use core::ops::Deref;
#[doc(hidden)]
pub use scale_info;
#[doc(hidden)]
#[cfg(feature = "serde")]
pub use serde;
#[cfg(feature = "bandersnatch-experimental")]
pub mod bandersnatch;
#[cfg(feature = "bls-experimental")]
pub mod bls381;
pub mod ecdsa;
#[cfg(feature = "bls-experimental")]
pub mod ecdsa_bls381;
pub mod ed25519;
pub mod sr25519;
mod traits;
pub use traits::*;
/// Declares `Public`, `Pair`, `Signature` and `ProofOfPossession` types which are functionally
/// equivalent to the corresponding types defined by `$module` but are new application-specific
/// types whose identifier is `$key_type`.
///
/// ```rust
/// # use sp_application_crypto::{app_crypto, ed25519, KeyTypeId};
/// // Declare a new set of crypto types using ed25519 logic that identifies as `KeyTypeId`
/// // of value `b"fuba"`.
/// app_crypto!(ed25519, KeyTypeId(*b"fuba"));
/// ```
#[cfg(feature = "full_crypto")]
#[macro_export]
macro_rules! app_crypto {
($module:ident, $key_type:expr) => {
$crate::app_crypto_public_full_crypto!($module::Public, $key_type, $module::CRYPTO_ID);
$crate::app_crypto_public_common!(
$module::Public,
$module::Signature,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_signature_full_crypto!(
$module::Signature,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_signature_common!($module::Signature, $key_type);
$crate::app_crypto_proof_of_possession_full_crypto!(
$module::ProofOfPossession,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_proof_of_possession_common!($module::ProofOfPossession, $key_type);
$crate::app_crypto_pair_common!($module::Pair, $key_type, $module::CRYPTO_ID);
};
}
/// Declares `Public`, `Pair` and `Signature` types which are functionally equivalent
/// to the corresponding types defined by `$module` but that are new application-specific
/// types whose identifier is `$key_type`.
///
/// ```rust
/// # use sp_application_crypto::{app_crypto, ed25519, KeyTypeId};
/// // Declare a new set of crypto types using ed25519 logic that identifies as `KeyTypeId`
/// // of value `b"fuba"`.
/// app_crypto!(ed25519, KeyTypeId(*b"fuba"));
/// ```
#[cfg(not(feature = "full_crypto"))]
#[macro_export]
macro_rules! app_crypto {
($module:ident, $key_type:expr) => {
$crate::app_crypto_public_not_full_crypto!($module::Public, $key_type, $module::CRYPTO_ID);
$crate::app_crypto_public_common!(
$module::Public,
$module::Signature,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_signature_not_full_crypto!(
$module::Signature,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_signature_common!($module::Signature, $key_type);
$crate::app_crypto_proof_of_possession_not_full_crypto!(
$module::ProofOfPossession,
$key_type,
$module::CRYPTO_ID
);
$crate::app_crypto_proof_of_possession_common!($module::ProofOfPossession, $key_type);
$crate::app_crypto_pair_common!($module::Pair, $key_type, $module::CRYPTO_ID);
};
}
/// Declares `Pair` type which is functionally equivalent to `$pair`, but is
/// new application-specific type whose identifier is `$key_type`.
/// It is a common part shared between full_crypto and non full_crypto environments.
#[macro_export]
macro_rules! app_crypto_pair_common {
($pair:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $pair crypto; this has no specific App.
#[derive(Clone)]
pub struct Pair($pair);
}
impl $crate::CryptoType for Pair {
type Pair = Pair;
}
impl $crate::Pair for Pair {
type Public = Public;
type Seed = <$pair as $crate::Pair>::Seed;
type Signature = Signature;
type ProofOfPossession = <$pair as $crate::Pair>::ProofOfPossession;
$crate::app_crypto_pair_functions_if_std!($pair);
$crate::app_crypto_pair_functions_if_full_crypto!($pair);
fn from_phrase(
phrase: &str,
password: Option<&str>,
) -> Result<(Self, Self::Seed), $crate::SecretStringError> {
<$pair>::from_phrase(phrase, password).map(|r| (Self(r.0), r.1))
}
fn derive<Iter: Iterator<Item = $crate::DeriveJunction>>(
&self,
path: Iter,
seed: Option<Self::Seed>,
) -> Result<(Self, Option<Self::Seed>), $crate::DeriveError> {
self.0.derive(path, seed).map(|x| (Self(x.0), x.1))
}
fn from_seed(seed: &Self::Seed) -> Self {
Self(<$pair>::from_seed(seed))
}
fn from_seed_slice(seed: &[u8]) -> Result<Self, $crate::SecretStringError> {
<$pair>::from_seed_slice(seed).map(Self)
}
fn verify<M: AsRef<[u8]>>(
sig: &Self::Signature,
message: M,
pubkey: &Self::Public,
) -> bool {
<$pair>::verify(&sig.0, message, pubkey.as_ref())
}
fn public(&self) -> Self::Public {
Public(self.0.public())
}
fn to_raw_vec(&self) -> $crate::Vec<u8> {
self.0.to_raw_vec()
}
}
impl $crate::ProofOfPossessionVerifier for Pair {
fn verify_proof_of_possession(
owner: &[u8],
proof_of_possession: &Self::ProofOfPossession,
allegedly_possessed_pubkey: &Self::Public,
) -> bool {
<$pair>::verify_proof_of_possession(
owner,
&proof_of_possession,
allegedly_possessed_pubkey.as_ref(),
)
}
}
impl $crate::AppCrypto for Pair {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
impl $crate::AppPair for Pair {
type Generic = $pair;
}
impl Pair {
/// Convert into wrapped generic key pair type.
pub fn into_inner(self) -> $pair {
self.0
}
}
};
}
/// Implements functions for the `Pair` trait when `feature = "std"` is enabled.
#[doc(hidden)]
#[cfg(feature = "std")]
#[macro_export]
macro_rules! app_crypto_pair_functions_if_std {
($pair:ty) => {
fn generate_with_phrase(password: Option<&str>) -> (Self, String, Self::Seed) {
let r = <$pair>::generate_with_phrase(password);
(Self(r.0), r.1, r.2)
}
};
}
#[doc(hidden)]
#[cfg(not(feature = "std"))]
#[macro_export]
macro_rules! app_crypto_pair_functions_if_std {
($pair:ty) => {};
}
/// Implements functions for the `Pair` trait when `feature = "full_crypto"` is enabled.
#[doc(hidden)]
#[cfg(feature = "full_crypto")]
#[macro_export]
macro_rules! app_crypto_pair_functions_if_full_crypto {
($pair:ty) => {
fn sign(&self, msg: &[u8]) -> Self::Signature {
Signature(self.0.sign(msg))
}
};
}
#[doc(hidden)]
#[cfg(not(feature = "full_crypto"))]
#[macro_export]
macro_rules! app_crypto_pair_functions_if_full_crypto {
($pair:ty) => {};
}
/// Declares `Public` type which is functionally equivalent to `$public` but is
/// new application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_public_common!` must be called too.
/// Can only be used with `full_crypto` feature.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_public_full_crypto {
($public:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(
Clone, Eq, Hash, PartialEq, PartialOrd, Ord,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::codec::MaxEncodedLen,
$crate::scale_info::TypeInfo,
)]
#[codec(crate = $crate::codec)]
pub struct Public($public);
}
impl $crate::CryptoType for Public {
type Pair = Pair;
}
impl $crate::AppCrypto for Public {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `Public` type which is functionally equivalent to `$public` but is
/// new application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_public_common!` must be called too.
/// Can only be used without `full_crypto` feature.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_public_not_full_crypto {
($public:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(
Clone, Eq, Hash, PartialEq, Ord, PartialOrd,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::codec::MaxEncodedLen,
$crate::scale_info::TypeInfo,
)]
pub struct Public($public);
}
impl $crate::CryptoType for Public {
type Pair = Pair;
}
impl $crate::AppCrypto for Public {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `Public` type which is functionally equivalent to `$public` but is
/// new application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_public_(not)_full_crypto!` must be called too.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_public_common {
($public:ty, $sig:ty, $key_type:expr, $crypto_type:expr) => {
$crate::app_crypto_public_common_if_serde!();
impl AsRef<[u8]> for Public {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for Public {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
impl $crate::ByteArray for Public {
const LEN: usize = <$public>::LEN;
}
impl $crate::Public for Public {}
impl $crate::AppPublic for Public {
type Generic = $public;
}
impl<'a> TryFrom<&'a [u8]> for Public {
type Error = ();
fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
<$public>::try_from(data).map(Into::into)
}
}
impl Public {
/// Convert into wrapped generic public key type.
pub fn into_inner(self) -> $public {
self.0
}
}
};
}
#[doc(hidden)]
pub mod module_format_string_prelude {
#[cfg(all(not(feature = "std"), feature = "serde"))]
pub use alloc::{format, string::String};
#[cfg(feature = "std")]
pub use std::{format, string::String};
}
/// Implements traits for the public key type if `feature = "serde"` is enabled.
#[cfg(feature = "serde")]
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_public_common_if_serde {
() => {
impl $crate::Derive for Public {
fn derive<Iter: Iterator<Item = $crate::DeriveJunction>>(
&self,
path: Iter,
) -> Option<Self> {
self.0.derive(path).map(Self)
}
}
impl core::fmt::Display for Public {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
use $crate::Ss58Codec;
write!(f, "{}", self.0.to_ss58check())
}
}
impl $crate::serde::Serialize for Public {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: $crate::serde::Serializer,
{
use $crate::Ss58Codec;
serializer.serialize_str(&self.to_ss58check())
}
}
impl<'de> $crate::serde::Deserialize<'de> for Public {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: $crate::serde::Deserializer<'de>,
{
use $crate::{module_format_string_prelude::*, Ss58Codec};
Public::from_ss58check(&String::deserialize(deserializer)?)
.map_err(|e| $crate::serde::de::Error::custom(format!("{:?}", e)))
}
}
};
}
#[cfg(not(feature = "serde"))]
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_public_common_if_serde {
() => {
impl $crate::Derive for Public {}
};
}
/// Declares Signature type which is functionally equivalent to `$sig`, but is new
/// Application-specific type whose identifier is `$key_type`.
/// For full functionality, app_crypto_public_common! must be called too.
/// Can only be used with `full_crypto` feature
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_signature_full_crypto {
($sig:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(Clone, Eq, PartialEq,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::scale_info::TypeInfo,
)]
#[derive(Hash)]
pub struct Signature($sig);
}
impl $crate::CryptoType for Signature {
type Pair = Pair;
}
impl $crate::AppCrypto for Signature {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `Signature` type which is functionally equivalent to `$sig`, but is new
/// application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_signature_common` must be called too.
/// Can only be used without `full_crypto` feature.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_signature_not_full_crypto {
($sig:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(Clone, Eq, PartialEq,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::scale_info::TypeInfo,
)]
pub struct Signature($sig);
}
impl $crate::CryptoType for Signature {
type Pair = Pair;
}
impl $crate::AppCrypto for Signature {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `Signature` type which is functionally equivalent to `$sig`, but is new
/// application-specific type whose identifier is `$key_type`.
/// For full functionality, app_crypto_signature_(not)_full_crypto! must be called too.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_signature_common {
($sig:ty, $key_type:expr) => {
impl $crate::Deref for Signature {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for Signature {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
impl $crate::AppSignature for Signature {
type Generic = $sig;
}
impl<'a> TryFrom<&'a [u8]> for Signature {
type Error = ();
fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
<$sig>::try_from(data).map(Into::into)
}
}
impl TryFrom<$crate::Vec<u8>> for Signature {
type Error = ();
fn try_from(data: $crate::Vec<u8>) -> Result<Self, Self::Error> {
Self::try_from(&data[..])
}
}
impl $crate::Signature for Signature {}
impl $crate::ByteArray for Signature {
const LEN: usize = <$sig>::LEN;
}
impl Signature {
/// Convert into wrapped generic signature type.
pub fn into_inner(self) -> $sig {
self.0
}
}
};
}
/// Declares ProofOfPossession type which is functionally equivalent to `$sig`, but is new
/// Application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_proof_of_possession_common` must be called too.
/// Can only be used with `full_crypto` feature
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_proof_of_possession_full_crypto {
($sig:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(Clone, Eq, PartialEq, Hash,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::scale_info::TypeInfo,
)]
pub struct ProofOfPossession($sig);
}
impl $crate::CryptoType for ProofOfPossession {
type Pair = Pair;
}
impl $crate::AppCrypto for ProofOfPossession {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `ProofOfPossession` type which is functionally equivalent to `$sig`, but is new
/// application-specific type whose identifier is `$key_type`.
/// For full functionality, `app_crypto_proof_of_possession_common` must be called too.
/// Can only be used without `full_crypto` feature.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_proof_of_possession_not_full_crypto {
($sig:ty, $key_type:expr, $crypto_type:expr) => {
$crate::wrap! {
/// A generic `AppPublic` wrapper type over $public crypto; this has no specific App.
#[derive(Clone, Eq, PartialEq,
$crate::codec::Encode,
$crate::codec::Decode,
$crate::codec::DecodeWithMemTracking,
$crate::RuntimeDebug,
$crate::scale_info::TypeInfo,
)]
pub struct ProofOfPossession($sig);
}
impl $crate::CryptoType for ProofOfPossession {
type Pair = Pair;
}
impl $crate::AppCrypto for ProofOfPossession {
type Public = Public;
type Pair = Pair;
type Signature = Signature;
type ProofOfPossession = ProofOfPossession;
const ID: $crate::KeyTypeId = $key_type;
const CRYPTO_ID: $crate::CryptoTypeId = $crypto_type;
}
};
}
/// Declares `ProofOfPossession` type which is functionally equivalent to `$sig`, but is new
/// application-specific type whose identifier is `$key_type`.
/// For full functionality, app_crypto_proof_of_possession_(not)_full_crypto! must be called too.
#[doc(hidden)]
#[macro_export]
macro_rules! app_crypto_proof_of_possession_common {
($sig:ty, $key_type:expr) => {
impl $crate::Deref for ProofOfPossession {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
impl AsRef<[u8]> for ProofOfPossession {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsMut<[u8]> for ProofOfPossession {
fn as_mut(&mut self) -> &mut [u8] {
self.0.as_mut()
}
}
impl $crate::AppSignature for ProofOfPossession {
type Generic = $sig;
}
impl<'a> TryFrom<&'a [u8]> for ProofOfPossession {
type Error = ();
fn try_from(data: &'a [u8]) -> Result<Self, Self::Error> {
<$sig>::try_from(data).map(Into::into)
}
}
impl TryFrom<$crate::Vec<u8>> for ProofOfPossession {
type Error = ();
fn try_from(data: $crate::Vec<u8>) -> Result<Self, Self::Error> {
Self::try_from(&data[..])
}
}
impl $crate::Signature for ProofOfPossession {}
impl $crate::ByteArray for ProofOfPossession {
const LEN: usize = <$sig>::LEN;
}
impl ProofOfPossession {
/// Convert into wrapped generic signature type.
pub fn into_inner(self) -> $sig {
self.0
}
}
};
}
/// Implement bidirectional `From` and on-way `AsRef`/`AsMut` for two types, `$inner` and `$outer`.
///
/// ```rust
/// sp_application_crypto::wrap! {
/// pub struct Wrapper(u32);
/// }
/// ```
#[macro_export]
macro_rules! wrap {
($( #[ $attr:meta ] )* struct $outer:ident($inner:ty);) => {
$( #[ $attr ] )*
struct $outer( $inner );
$crate::wrap!($inner, $outer);
};
($( #[ $attr:meta ] )* pub struct $outer:ident($inner:ty);) => {
$( #[ $attr ] )*
pub struct $outer( $inner );
$crate::wrap!($inner, $outer);
};
($inner:ty, $outer:ty) => {
impl $crate::Wraps for $outer {
type Inner = $inner;
}
impl From<$inner> for $outer {
fn from(inner: $inner) -> Self {
Self(inner)
}
}
impl From<$outer> for $inner {
fn from(outer: $outer) -> Self {
outer.0
}
}
impl AsRef<$inner> for $outer {
fn as_ref(&self) -> &$inner {
&self.0
}
}
impl AsMut<$inner> for $outer {
fn as_mut(&mut self) -> &mut $inner {
&mut self.0
}
}
}
}
/// Generate the given code if the pair type is available.
///
/// The pair type is available when `feature = "std"` || `feature = "full_crypto"`.
///
/// # Example
///
/// ```
/// sp_application_crypto::with_pair! {
/// pub type Pair = ();
/// }
/// ```
#[macro_export]
#[cfg(any(feature = "std", feature = "full_crypto"))]
macro_rules! with_pair {
( $( $def:tt )* ) => {
$( $def )*
}
}
#[doc(hidden)]
#[macro_export]
#[cfg(all(not(feature = "std"), not(feature = "full_crypto")))]
macro_rules! with_pair {
( $( $def:tt )* ) => {};
}
@@ -0,0 +1,77 @@
// 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.
//! Sr25519 crypto types.
use crate::{KeyTypeId, RuntimePublic};
use alloc::vec::Vec;
use sp_core::proof_of_possession::NonAggregatable;
pub use sp_core::sr25519::*;
mod app {
crate::app_crypto!(super, sp_core::testing::SR25519);
}
pub use app::{
Pair as AppPair, ProofOfPossession as AppProofOfPossession, Public as AppPublic,
Signature as AppSignature,
};
impl RuntimePublic for Public {
type Signature = Signature;
type ProofOfPossession = Signature;
fn all(key_type: KeyTypeId) -> crate::Vec<Self> {
sp_io::crypto::sr25519_public_keys(key_type)
}
fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self {
sp_io::crypto::sr25519_generate(key_type, seed)
}
fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature> {
sp_io::crypto::sr25519_sign(key_type, self, msg.as_ref())
}
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
sp_io::crypto::sr25519_verify(signature, msg.as_ref(), self)
}
fn generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession> {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::sr25519_sign(key_type, self, &proof_of_possession_statement)
}
fn verify_proof_of_possession(
&self,
owner: &[u8],
proof_of_possession: &Self::ProofOfPossession,
) -> bool {
let proof_of_possession_statement = Pair::proof_of_possession_statement(owner);
sp_io::crypto::sr25519_verify(&proof_of_possession, &proof_of_possession_statement, &self)
}
fn to_raw_vec(&self) -> Vec<u8> {
sp_core::crypto::ByteArray::to_raw_vec(self)
}
}
@@ -0,0 +1,259 @@
// 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.
use codec::Codec;
use scale_info::TypeInfo;
use alloc::vec::Vec;
use core::fmt::Debug;
use sp_core::crypto::{CryptoType, CryptoTypeId, IsWrappedBy, KeyTypeId, Pair, Public, Signature};
/// 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.
///
/// 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 + Sized + CryptoType {
/// Identifier for application-specific key type.
const ID: KeyTypeId;
/// Identifier of the crypto type of this application-specific key type.
const CRYPTO_ID: CryptoTypeId;
/// The corresponding public key type in this application scheme.
type Public: AppPublic;
/// The corresponding signature type in this application scheme.
type Signature: AppSignature;
/// The corresponding proof of possession type in this application scheme.
type ProofOfPossession: AppSignature;
/// The corresponding key pair type in this application scheme.
type Pair: AppPair;
}
/// Type which implements Hash in std, not when no-std (std variant).
pub trait MaybeHash: core::hash::Hash {}
impl<T: core::hash::Hash> MaybeHash for T {}
/// Application-specific key pair.
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>;
}
/// 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 and Proof Of Possession
pub trait AppSignature: AppCrypto + Signature + Eq + PartialEq + Debug + Clone {
/// The wrapped type which is just a plain instance of `Signature`.
type Generic: IsWrappedBy<Self> + Signature + Eq + PartialEq + Debug;
}
/// 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;
/// The Proof Of Possession the corresponding private key.
type ProofOfPossession: Debug + Eq + PartialEq + Clone;
/// Returns all public keys for the given key type in the keystore.
fn all(key_type: KeyTypeId) -> crate::Vec<Self>;
/// Generate a public/private pair for the given key type with an optional `seed` and
/// store it in the keystore.
///
/// The `seed` needs to be valid utf8.
///
/// Returns the generated public key.
fn generate_pair(key_type: KeyTypeId, seed: Option<Vec<u8>>) -> Self;
/// Sign the given message with the corresponding private key of this public key.
///
/// The private key will be requested from the keystore using the given key type.
///
/// Returns the signature or `None` if the private key could not be found or some other error
/// occurred.
fn sign<M: AsRef<[u8]>>(&self, key_type: KeyTypeId, msg: &M) -> Option<Self::Signature>;
/// Verify that the given signature matches the given message using this public key.
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
/// Generates the necessary proof(s) usually as a signature or list of signatures, for the
/// corresponding public key to be accepted as legitimate by the network.
///
/// This includes attestation of the owner of the public key in the form of signing the owner's
/// identity. It might also includes other signatures such as signature obtained by signing
/// the corresponding public in different context than normal signatures in case of BLS
/// key pair.
///
/// The `owner` is an arbitrary byte array representing the identity of the owner of
/// the key which has been signed by the private key in process of generating the proof.
///
/// The private key will be requested from the keystore using the given key type.
///
/// Returns the proof of possession or `None` if it failed or is not able to do
/// so.
fn generate_proof_of_possession(
&mut self,
key_type: KeyTypeId,
owner: &[u8],
) -> Option<Self::ProofOfPossession>;
/// Verifies that the given proof is valid for the corresponding public key.
/// The proof is usually a signature or list of signatures, for the corresponding
/// public key to be accepted by the network. It include attestation of the owner of
/// the public key in the form signing the owner's identity but might also includes
/// other signatures.
///
/// The `owner` is an arbitrary byte array representing the identity of the owner of
/// the key which has been signed by the private key in process of generating the proof.
///
/// Returns `true` if the proof is deemed correct by the cryto type.
fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool;
/// Returns `Self` as raw vec.
fn to_raw_vec(&self) -> Vec<u8>;
}
/// Runtime interface for an application's public key.
pub trait RuntimeAppPublic: Sized {
/// An identifier for this application-specific key type.
const ID: KeyTypeId;
/// The signature that will be generated when signing with the corresponding private key.
type Signature: Debug + Eq + PartialEq + Clone + TypeInfo + Codec;
/// The Proof Of Possession the corresponding private key.
type ProofOfPossession: Debug + Eq + PartialEq + TypeInfo + Clone;
/// Returns all public keys for this application in the keystore.
fn all() -> crate::Vec<Self>;
/// Generate a public/private pair with an optional `seed` and store it in the keystore.
///
/// The `seed` needs to be valid utf8.
///
/// Returns the generated public key.
fn generate_pair(seed: Option<Vec<u8>>) -> Self;
/// Sign the given message with the corresponding private key of this public key.
///
/// The private key will be requested from the keystore.
///
/// Returns the signature or `None` if the private key could not be found or some other error
/// occurred.
fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature>;
/// Verify that the given signature matches the given message using this public key.
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool;
/// Generate proof of legitimacy for the corresponding public key
///
/// Returns the proof of possession, usually a signature or a list of signature, or `None` if
/// it failed or is not able to do so.
fn generate_proof_of_possession(&mut self, owner: &[u8]) -> Option<Self::ProofOfPossession>;
/// Verify that the given proof of possession is valid for the corresponding public key.
fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool;
/// Returns `Self` as raw vec.
fn to_raw_vec(&self) -> Vec<u8>;
}
impl<T> RuntimeAppPublic for T
where
T: AppPublic + AsRef<<T as AppPublic>::Generic> + AsMut<<T as AppPublic>::Generic>,
<T as AppPublic>::Generic: RuntimePublic,
<T as AppCrypto>::Signature: TypeInfo
+ Codec
+ From<<<T as AppPublic>::Generic as RuntimePublic>::Signature>
+ AsRef<<<T as AppPublic>::Generic as RuntimePublic>::Signature>,
<T as AppCrypto>::ProofOfPossession: TypeInfo
+ Codec
+ From<<<T as AppPublic>::Generic as RuntimePublic>::ProofOfPossession>
+ AsRef<<<T as AppPublic>::Generic as RuntimePublic>::ProofOfPossession>,
{
const ID: KeyTypeId = <T as AppCrypto>::ID;
type Signature = <T as AppCrypto>::Signature;
type ProofOfPossession = <T as AppCrypto>::ProofOfPossession;
fn all() -> crate::Vec<Self> {
<<T as AppPublic>::Generic as RuntimePublic>::all(Self::ID)
.into_iter()
.map(|p| p.into())
.collect()
}
fn generate_pair(seed: Option<Vec<u8>>) -> Self {
<<T as AppPublic>::Generic as RuntimePublic>::generate_pair(Self::ID, seed).into()
}
fn sign<M: AsRef<[u8]>>(&self, msg: &M) -> Option<Self::Signature> {
<<T as AppPublic>::Generic as RuntimePublic>::sign(self.as_ref(), Self::ID, msg)
.map(|s| s.into())
}
fn verify<M: AsRef<[u8]>>(&self, msg: &M, signature: &Self::Signature) -> bool {
<<T as AppPublic>::Generic as RuntimePublic>::verify(self.as_ref(), msg, signature.as_ref())
}
fn generate_proof_of_possession(&mut self, owner: &[u8]) -> Option<Self::ProofOfPossession> {
<<T as AppPublic>::Generic as RuntimePublic>::generate_proof_of_possession(
self.as_mut(),
Self::ID,
owner,
)
.map(|s| s.into())
}
fn verify_proof_of_possession(&self, owner: &[u8], pop: &Self::ProofOfPossession) -> bool {
<<T as AppPublic>::Generic as RuntimePublic>::verify_proof_of_possession(
self.as_ref(),
owner,
pop.as_ref(),
)
}
fn to_raw_vec(&self) -> Vec<u8> {
<<T as AppPublic>::Generic as RuntimePublic>::to_raw_vec(self.as_ref())
}
}
/// Something that is bound to a fixed [`RuntimeAppPublic`].
pub trait BoundToRuntimeAppPublic {
/// The [`RuntimeAppPublic`] this type is bound to.
type Public: RuntimeAppPublic;
}
impl<T: RuntimeAppPublic> BoundToRuntimeAppPublic for T {
type Public = Self;
}