Move cryptographic hashing procedures to crypto folder. (#2306)

Step towards https://github.com/paritytech/polkadot-sdk/issues/1975

As reported
https://github.com/paritytech/polkadot-sdk/issues/1975#issuecomment-1774534225
I'd like to encapsulate crypto related stuff in a dedicated folder.

Currently all cryptographic primitive wrappers are all sparsed in
`substrate/core` which contains "misc core" stuff.

To simplify the process, as the first step with this PR I propose to
move the cryptographic hashing there.

The `substrate/crypto` folder was already created to contains `ec-utils`
crate.

Notes:
- rename `sp-core-hashing` to `sp-crypto-hashing`
- rename `sp-core-hashing-proc-macro` to `sp-crypto-hashing-proc-macro`
- As the crates name is changed I took the freedom to restart fresh from
version 0.1.0 for both crates

---------

Co-authored-by: Robert Hambrock <roberthambrock@gmail.com>
This commit is contained in:
Davide Galassi
2024-01-23 00:36:14 +01:00
committed by GitHub
parent 95ff9b2c54
commit 4c10fd2a41
96 changed files with 484 additions and 326 deletions
+4 -5
View File
@@ -53,7 +53,7 @@ libsecp256k1 = { version = "0.7", default-features = false, features = ["static-
schnorrkel = { version = "0.11.4", features = ["preaudit_deprecated"], default-features = false }
merlin = { version = "3.0", default-features = false }
secp256k1 = { version = "0.28.0", default-features = false, features = ["alloc", "recovery"], optional = true }
sp-core-hashing = { path = "hashing", default-features = false, optional = true }
sp-crypto-hashing = { path = "../crypto/hashing", default-features = false, optional = true }
sp-runtime-interface = { path = "../runtime-interface", default-features = false }
# bls crypto
@@ -66,7 +66,6 @@ criterion = "0.4.0"
serde_json = "1.0.111"
lazy_static = "1.4.0"
regex = "1.6.0"
sp-core-hashing-proc-macro = { path = "hashing/proc-macro" }
[[bench]]
name = "bench"
@@ -110,7 +109,7 @@ std = [
"secp256k1/std",
"secrecy/alloc",
"serde/std",
"sp-core-hashing/std",
"sp-crypto-hashing/std",
"sp-debug-derive/std",
"sp-externalities/std",
"sp-runtime-interface/std",
@@ -136,7 +135,7 @@ serde = [
"primitive-types/serde_no_std",
"scale-info/serde",
"secrecy/alloc",
"sp-core-hashing",
"sp-crypto-hashing",
"sp-storage/serde",
]
@@ -149,7 +148,7 @@ full_crypto = [
"ed25519-zebra",
"libsecp256k1",
"secp256k1",
"sp-core-hashing",
"sp-crypto-hashing",
"sp-runtime-interface/disable_target_static_assertions",
]
+3 -68
View File
@@ -12,66 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use criterion::{black_box, criterion_group, criterion_main, Bencher, BenchmarkId, Criterion};
use sp_core::{
crypto::Pair as _,
hashing::{blake2_128, twox_128},
};
const MAX_KEY_SIZE: u32 = 32;
fn get_key(key_size: u32) -> Vec<u8> {
use rand::{Rng, SeedableRng};
let rnd: [u8; 32] = rand::rngs::StdRng::seed_from_u64(12).gen();
let mut rnd = rnd.iter().cycle();
(0..key_size).map(|_| *rnd.next().unwrap()).collect()
}
fn bench_blake2_128(b: &mut Bencher, key: &Vec<u8>) {
b.iter(|| {
let _a = blake2_128(black_box(key));
});
}
fn bench_twox_128(b: &mut Bencher, key: &Vec<u8>) {
b.iter(|| {
let _a = twox_128(black_box(key));
});
}
fn bench_hash_128_fix_size(c: &mut Criterion) {
let mut group = c.benchmark_group("fix size hashing");
let key = get_key(MAX_KEY_SIZE);
group.bench_with_input("blake2_128", &key, bench_blake2_128);
group.bench_with_input("twox_128", &key, bench_twox_128);
group.finish();
}
fn bench_hash_128_dyn_size(c: &mut Criterion) {
let mut group = c.benchmark_group("dyn size hashing");
for i in (2..MAX_KEY_SIZE).step_by(4) {
let key = get_key(i);
group.bench_with_input(
BenchmarkId::new("blake2_128", format!("{}", i)),
&key,
bench_blake2_128,
);
group.bench_with_input(
BenchmarkId::new("twox_128", format!("{}", i)),
&key,
bench_twox_128,
);
}
group.finish();
}
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use sp_core::crypto::Pair as _;
fn bench_ed25519(c: &mut Criterion) {
let mut group = c.benchmark_group("ed25519");
@@ -145,12 +87,5 @@ fn bench_ecdsa(c: &mut Criterion) {
group.finish();
}
criterion_group!(
benches,
bench_hash_128_fix_size,
bench_hash_128_dyn_size,
bench_ed25519,
bench_sr25519,
bench_ecdsa,
);
criterion_group!(benches, bench_ed25519, bench_sr25519, bench_ecdsa,);
criterion_main!(benches);
@@ -1,35 +0,0 @@
[package]
name = "sp-core-hashing"
version = "9.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage = "https://substrate.io"
repository.workspace = true
description = "Primitive core crate hashing implementation."
documentation = "https://docs.rs/sp-core-hashing"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
blake2b_simd = { version = "1.0.1", default-features = false }
byteorder = { version = "1.3.2", default-features = false }
digest = { version = "0.10.3", default-features = false }
sha2 = { version = "0.10.7", default-features = false }
sha3 = { version = "0.10.0", default-features = false }
twox-hash = { version = "1.6.3", default-features = false, features = ["digest_0_10"] }
[features]
default = ["std"]
std = [
"blake2b_simd/std",
"byteorder/std",
"digest/std",
"sha2/std",
"sha3/std",
"twox-hash/std",
]
@@ -1,24 +0,0 @@
[package]
name = "sp-core-hashing-proc-macro"
version = "9.0.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage = "https://substrate.io"
repository.workspace = true
description = "This crate provides procedural macros for calculating static hash."
documentation = "https://docs.rs/sp-core-hashing-proc-macro"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[lib]
proc-macro = true
[dependencies]
quote = "1.0.28"
syn = { version = "2.0.48", features = ["full", "parsing"] }
sp-core-hashing = { path = "..", default-features = false }
@@ -1,124 +0,0 @@
// 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 quote::quote;
use syn::parse::{Parse, ParseStream};
use proc_macro::TokenStream;
pub(super) struct InputBytes(pub Vec<u8>);
pub(super) struct MultipleInputBytes(pub Vec<Vec<u8>>);
impl MultipleInputBytes {
pub(super) fn concatenated(mut self) -> Vec<u8> {
if self.0.is_empty() {
Vec::new()
} else {
let mut result = core::mem::take(&mut self.0[0]);
for other in self.0[1..].iter_mut() {
result.append(other);
}
result
}
}
}
impl Parse for InputBytes {
fn parse(input: ParseStream) -> syn::Result<Self> {
match syn::ExprArray::parse(input) {
Ok(array) => {
let mut bytes = Vec::<u8>::new();
for expr in array.elems.iter() {
match expr {
syn::Expr::Lit(lit) => match &lit.lit {
syn::Lit::Int(b) => bytes.push(b.base10_parse()?),
syn::Lit::Byte(b) => bytes.push(b.value()),
_ =>
return Err(syn::Error::new(
input.span(),
"Expected array of u8 elements.".to_string(),
)),
},
_ =>
return Err(syn::Error::new(
input.span(),
"Expected array of u8 elements.".to_string(),
)),
}
}
return Ok(InputBytes(bytes))
},
Err(_e) => (),
}
// use rust names as a vec of their utf8 bytecode.
match syn::Ident::parse(input) {
Ok(ident) => return Ok(InputBytes(ident.to_string().as_bytes().to_vec())),
Err(_e) => (),
}
Ok(InputBytes(syn::LitByteStr::parse(input)?.value()))
}
}
impl Parse for MultipleInputBytes {
fn parse(input: ParseStream) -> syn::Result<Self> {
let elts =
syn::punctuated::Punctuated::<InputBytes, syn::token::Comma>::parse_terminated(input)?;
Ok(MultipleInputBytes(elts.into_iter().map(|elt| elt.0).collect()))
}
}
pub(super) fn twox_64(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::twox_64(bytes.as_slice()))
}
pub(super) fn twox_128(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::twox_128(bytes.as_slice()))
}
pub(super) fn blake2b_512(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::blake2_512(bytes.as_slice()))
}
pub(super) fn blake2b_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::blake2_256(bytes.as_slice()))
}
pub(super) fn blake2b_64(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::blake2_64(bytes.as_slice()))
}
pub(super) fn keccak_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::keccak_256(bytes.as_slice()))
}
pub(super) fn keccak_512(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::keccak_512(bytes.as_slice()))
}
pub(super) fn sha2_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(sp_core_hashing::sha2_256(bytes.as_slice()))
}
fn bytes_to_array(bytes: impl IntoIterator<Item = u8>) -> TokenStream {
let bytes = bytes.into_iter();
quote!(
[ #( #bytes ),* ]
)
.into()
}
@@ -1,129 +0,0 @@
// 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.
//! Macros to calculate constant hash bytes result.
//!
//! Macros from this crate does apply a specific hash function on input.
//! Input can be literal byte array as `b"content"` or array of bytes
//! as `[1, 2, 3]`.
//! Rust identifier can also be use, in this case we use their utf8 string
//! byte representation, for instance if the ident is `MyStruct`, then
//! `b"MyStruct"` will be hashed.
//! If multiple arguments comma separated are passed, they are concatenated
//! then hashed.
//!
//! Examples:
//!
//! ```rust
//! assert_eq!(
//! sp_core_hashing_proc_macro::blake2b_256!(b"test"),
//! sp_core_hashing::blake2_256(b"test"),
//! );
//! assert_eq!(
//! sp_core_hashing_proc_macro::blake2b_256!([1u8]),
//! sp_core_hashing::blake2_256(&[1u8]),
//! );
//! assert_eq!(
//! sp_core_hashing_proc_macro::blake2b_256!([1, 2, 3]),
//! sp_core_hashing::blake2_256(&[1, 2, 3]),
//! );
//! assert_eq!(
//! sp_core_hashing_proc_macro::blake2b_256!(identifier),
//! sp_core_hashing::blake2_256(b"identifier"),
//! );
//! assert_eq!(
//! sp_core_hashing_proc_macro::blake2b_256!(identifier, b"/string"),
//! sp_core_hashing::blake2_256(b"identifier/string"),
//! );
//! ```
mod impls;
use impls::MultipleInputBytes;
use proc_macro::TokenStream;
/// Process a Blake2 64-bit hash of bytes parameter outputs a `[u8; 8]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn blake2b_64(input: TokenStream) -> TokenStream {
impls::blake2b_64(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a Blake2 256-bit hash of bytes parameter, outputs a `[u8; 32]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn blake2b_256(input: TokenStream) -> TokenStream {
impls::blake2b_256(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a Blake2 512-bit hash of bytes parameter, outputs a `[u8; 64]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn blake2b_512(input: TokenStream) -> TokenStream {
impls::blake2b_512(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a XX 64-bit hash on its bytes parameter, outputs a `[u8; 8]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn twox_64(input: TokenStream) -> TokenStream {
impls::twox_64(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a XX 128-bit hash on its bytes parameter, outputs a `[u8; 16]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn twox_128(input: TokenStream) -> TokenStream {
impls::twox_128(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a keccak 256-bit hash on its bytes parameter, outputs a `[u8; 32]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn keccak_256(input: TokenStream) -> TokenStream {
impls::keccak_256(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a keccak 512-bit hash on its bytes parameter, outputs a `[u8; 64]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn keccak_512(input: TokenStream) -> TokenStream {
impls::keccak_512(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
/// Apply a sha2 256-bit hash on its bytes parameter, outputs a `[u8; 32]`.
/// Multiple inputs are concatenated before hashing.
/// Input can be identifier (name of identifier as bytes is used), byte string or
/// array of bytes.
#[proc_macro]
pub fn sha2_256(input: TokenStream) -> TokenStream {
impls::sha2_256(syn::parse_macro_input!(input as MultipleInputBytes).concatenated())
}
@@ -1,123 +0,0 @@
// 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.
//! Hashing Functions.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
use core::hash::Hasher;
use byteorder::{ByteOrder, LittleEndian};
use digest::Digest;
#[inline(always)]
fn blake2<const N: usize>(data: &[u8]) -> [u8; N] {
blake2b_simd::Params::new()
.hash_length(N)
.hash(data)
.as_bytes()
.try_into()
.expect("slice is always the necessary length")
}
/// Do a Blake2 512-bit hash and place result in `dest`.
pub fn blake2_512_into(data: &[u8], dest: &mut [u8; 64]) {
*dest = blake2(data);
}
/// Do a Blake2 512-bit hash and return result.
pub fn blake2_512(data: &[u8]) -> [u8; 64] {
blake2(data)
}
/// Do a Blake2 256-bit hash and return result.
pub fn blake2_256(data: &[u8]) -> [u8; 32] {
blake2(data)
}
/// Do a Blake2 128-bit hash and return result.
pub fn blake2_128(data: &[u8]) -> [u8; 16] {
blake2(data)
}
/// Do a Blake2 64-bit hash and return result.
pub fn blake2_64(data: &[u8]) -> [u8; 8] {
blake2(data)
}
/// Do a XX 64-bit hash and place result in `dest`.
pub fn twox_64_into(data: &[u8], dest: &mut [u8; 8]) {
let r0 = twox_hash::XxHash::with_seed(0).chain_update(data).finish();
LittleEndian::write_u64(&mut dest[0..8], r0);
}
/// Do a XX 64-bit hash and return result.
pub fn twox_64(data: &[u8]) -> [u8; 8] {
let mut r: [u8; 8] = [0; 8];
twox_64_into(data, &mut r);
r
}
/// Do a XX 128-bit hash and place result in `dest`.
pub fn twox_128_into(data: &[u8], dest: &mut [u8; 16]) {
let r0 = twox_hash::XxHash::with_seed(0).chain_update(data).finish();
let r1 = twox_hash::XxHash::with_seed(1).chain_update(data).finish();
LittleEndian::write_u64(&mut dest[0..8], r0);
LittleEndian::write_u64(&mut dest[8..16], r1);
}
/// Do a XX 128-bit hash and return result.
pub fn twox_128(data: &[u8]) -> [u8; 16] {
let mut r: [u8; 16] = [0; 16];
twox_128_into(data, &mut r);
r
}
/// Do a XX 256-bit hash and place result in `dest`.
pub fn twox_256_into(data: &[u8], dest: &mut [u8; 32]) {
let r0 = twox_hash::XxHash::with_seed(0).chain_update(data).finish();
let r1 = twox_hash::XxHash::with_seed(1).chain_update(data).finish();
let r2 = twox_hash::XxHash::with_seed(2).chain_update(data).finish();
let r3 = twox_hash::XxHash::with_seed(3).chain_update(data).finish();
LittleEndian::write_u64(&mut dest[0..8], r0);
LittleEndian::write_u64(&mut dest[8..16], r1);
LittleEndian::write_u64(&mut dest[16..24], r2);
LittleEndian::write_u64(&mut dest[24..32], r3);
}
/// Do a XX 256-bit hash and return result.
pub fn twox_256(data: &[u8]) -> [u8; 32] {
let mut r: [u8; 32] = [0; 32];
twox_256_into(data, &mut r);
r
}
/// Do a keccak 256-bit hash and return result.
pub fn keccak_256(data: &[u8]) -> [u8; 32] {
sha3::Keccak256::digest(data).into()
}
/// Do a keccak 512-bit hash and return result.
pub fn keccak_512(data: &[u8]) -> [u8; 64] {
sha3::Keccak512::digest(data).into()
}
/// Do a sha2 256-bit hash and return result.
pub fn sha2_256(data: &[u8]) -> [u8; 32] {
sha2::Sha256::digest(data).into()
}
@@ -258,7 +258,7 @@ impl TraitPair for Pair {
_seed: Option<Seed>,
) -> Result<(Pair, Option<Seed>), DeriveError> {
let derive_hard = |seed, cc| -> Seed {
("bandersnatch-vrf-HDKD", seed, cc).using_encoded(sp_core_hashing::blake2_256)
("bandersnatch-vrf-HDKD", seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
};
let mut seed = self.seed();
+1 -1
View File
@@ -428,7 +428,7 @@ trait HardJunctionId {
/// Derive a single hard junction.
#[cfg(feature = "full_crypto")]
fn derive_hard_junction<T: HardJunctionId>(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
(T::ID, secret_seed, cc).using_encoded(sp_core_hashing::blake2_256)
(T::ID, secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
}
#[cfg(feature = "full_crypto")]
+1 -1
View File
@@ -152,7 +152,7 @@ impl DeriveJunction {
let mut cc: [u8; JUNCTION_ID_LEN] = Default::default();
index.using_encoded(|data| {
if data.len() > JUNCTION_ID_LEN {
cc.copy_from_slice(&sp_core_hashing::blake2_256(data));
cc.copy_from_slice(&sp_crypto_hashing::blake2_256(data));
} else {
cc[0..data.len()].copy_from_slice(data);
}
+11 -13
View File
@@ -27,10 +27,7 @@ use crate::crypto::{
ByteArray, CryptoType, CryptoTypeId, Derive, Public as TraitPublic, UncheckedFrom,
};
#[cfg(feature = "full_crypto")]
use crate::{
crypto::{DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError},
hashing::blake2_256,
};
use crate::crypto::{DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError};
#[cfg(all(feature = "full_crypto", not(feature = "std")))]
use secp256k1::Secp256k1;
#[cfg(feature = "std")]
@@ -328,7 +325,7 @@ impl Signature {
/// Recover the public key from this signature and a message.
#[cfg(feature = "full_crypto")]
pub fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Public> {
self.recover_prehashed(&blake2_256(message.as_ref()))
self.recover_prehashed(&sp_crypto_hashing::blake2_256(message.as_ref()))
}
/// Recover the public key from this signature and a pre-hashed message.
@@ -365,7 +362,7 @@ impl From<RecoverableSignature> for Signature {
/// Derive a single hard junction.
#[cfg(feature = "full_crypto")]
fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
("Secp256k1HDKD", secret_seed, cc).using_encoded(sp_core_hashing::blake2_256)
("Secp256k1HDKD", secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
}
/// A key pair.
@@ -423,7 +420,7 @@ impl TraitPair for Pair {
/// Sign a message.
fn sign(&self, message: &[u8]) -> Signature {
self.sign_prehashed(&blake2_256(message))
self.sign_prehashed(&sp_crypto_hashing::blake2_256(message))
}
/// Verify a signature on a message. Returns true if the signature is good.
@@ -481,7 +478,8 @@ impl Pair {
/// Parses Signature using parse_overflowing_slice.
#[deprecated(note = "please use `verify` instead")]
pub fn verify_deprecated<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
let message = libsecp256k1::Message::parse(&blake2_256(message.as_ref()));
let message =
libsecp256k1::Message::parse(&sp_crypto_hashing::blake2_256(message.as_ref()));
let parse_signature_overflowing = |x: [u8; SIGNATURE_SERIALIZED_SIZE]| {
let sig = libsecp256k1::Signature::parse_overflowing_slice(&x[..64]).ok()?;
@@ -766,7 +764,7 @@ mod test {
// using pre-hashed `msg` works
let msg = b"this should be hashed";
let sig1 = pair.sign_prehashed(&blake2_256(msg));
let sig1 = pair.sign_prehashed(&sp_crypto_hashing::blake2_256(msg));
let sig2 = pair.sign(msg);
assert_eq!(sig1, sig2);
}
@@ -776,12 +774,12 @@ mod test {
let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
// `msg` and `sig` match
let msg = blake2_256(b"this should be hashed");
let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
let sig = pair.sign_prehashed(&msg);
assert!(Pair::verify_prehashed(&sig, &msg, &pair.public()));
// `msg` and `sig` don't match
let msg = blake2_256(b"this is a different message");
let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
assert!(!Pair::verify_prehashed(&sig, &msg, &pair.public()));
}
@@ -790,7 +788,7 @@ mod test {
let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
// recovered key matches signing key
let msg = blake2_256(b"this should be hashed");
let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
let sig = pair.sign_prehashed(&msg);
let key = sig.recover_prehashed(&msg).unwrap();
assert_eq!(pair.public(), key);
@@ -799,7 +797,7 @@ mod test {
assert!(Pair::verify_prehashed(&sig, &msg, &key));
// recovered key and signing key don't match
let msg = blake2_256(b"this is a different message");
let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
let key = sig.recover_prehashed(&msg).unwrap();
assert_ne!(pair.public(), key);
}
+1 -1
View File
@@ -372,7 +372,7 @@ impl Derive for Public {}
/// Derive a single hard junction.
#[cfg(feature = "full_crypto")]
fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
("Ed25519HDKD", secret_seed, cc).using_encoded(sp_core_hashing::blake2_256)
("Ed25519HDKD", secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
}
#[cfg(feature = "full_crypto")]
+2 -2
View File
@@ -32,7 +32,7 @@ pub mod blake2 {
const LENGTH: usize = 32;
fn hash(x: &[u8]) -> Self::Out {
crate::hashing::blake2_256(x).into()
sp_crypto_hashing::blake2_256(x).into()
}
}
}
@@ -52,7 +52,7 @@ pub mod keccak {
const LENGTH: usize = 32;
fn hash(x: &[u8]) -> Self::Out {
crate::hashing::keccak_256(x).into()
sp_crypto_hashing::keccak_256(x).into()
}
}
}
-66
View File
@@ -1,66 +0,0 @@
// 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.
//! Hashing functions.
//!
//! This module is gated by `full-crypto` feature. If you intend to use any of the functions
//! defined here within your runtime, you should most likely rather use `sp_io::hashing` instead,
//! unless you know what you're doing. Using `sp_io` will be more performant, since instead of
//! computing the hash in WASM it delegates that computation to the host client.
pub use sp_core_hashing::*;
#[cfg(test)]
mod test {
use super::*;
#[test]
fn blake2b() {
assert_eq!(sp_core_hashing_proc_macro::blake2b_64!(b""), blake2_64(b"")[..]);
assert_eq!(sp_core_hashing_proc_macro::blake2b_256!(b"test"), blake2_256(b"test")[..]);
assert_eq!(sp_core_hashing_proc_macro::blake2b_512!(b""), blake2_512(b"")[..]);
}
#[test]
fn keccak() {
assert_eq!(sp_core_hashing_proc_macro::keccak_256!(b"test"), keccak_256(b"test")[..]);
assert_eq!(sp_core_hashing_proc_macro::keccak_512!(b"test"), keccak_512(b"test")[..]);
}
#[test]
fn sha2() {
assert_eq!(sp_core_hashing_proc_macro::sha2_256!(b"test"), sha2_256(b"test")[..]);
}
#[test]
fn twox() {
assert_eq!(sp_core_hashing_proc_macro::twox_128!(b"test"), twox_128(b"test")[..]);
assert_eq!(sp_core_hashing_proc_macro::twox_64!(b""), twox_64(b"")[..]);
}
#[test]
fn twox_concats() {
assert_eq!(
sp_core_hashing_proc_macro::twox_128!(b"test", b"123", b"45", b"", b"67890"),
super::twox_128(&b"test1234567890"[..]),
);
assert_eq!(
sp_core_hashing_proc_macro::twox_128!(b"test", test, b"45", b"", b"67890"),
super::twox_128(&b"testtest4567890"[..]),
);
}
}
+5 -3
View File
@@ -47,10 +47,12 @@ pub use sp_debug_derive::RuntimeDebug;
pub use impl_serde::serialize as bytes;
#[cfg(feature = "full_crypto")]
pub mod hashing;
#[deprecated(
since = "27.0.0",
note = "`sp-crypto-hashing` re-exports will be removed after June 2024. Use `sp-crypto-hashing` instead."
)]
pub use sp_crypto_hashing::{self as hashing, *};
#[cfg(feature = "full_crypto")]
pub use hashing::{blake2_128, blake2_256, keccak_256, twox_128, twox_256, twox_64};
pub mod const_hex2array;
pub mod crypto;
pub mod hexdisplay;