feat: Rebrand Polkadot/Substrate references to PezkuwiChain

This commit systematically rebrands various references from Parity Technologies'
Polkadot/Substrate ecosystem to PezkuwiChain within the kurdistan-sdk.

Key changes include:
- Updated external repository URLs (zombienet-sdk, parity-db, parity-scale-codec, wasm-instrument) to point to pezkuwichain forks.
- Modified internal documentation and code comments to reflect PezkuwiChain naming and structure.
- Replaced direct references to  with  or specific paths within the  for XCM, Pezkuwi, and other modules.
- Cleaned up deprecated  issue and PR references in various  and  files, particularly in  and  modules.
- Adjusted image and logo URLs in documentation to point to PezkuwiChain assets.
- Removed or rephrased comments related to external Polkadot/Substrate PRs and issues.

This is a significant step towards fully customizing the SDK for the PezkuwiChain ecosystem.
This commit is contained in:
2025-12-14 00:04:10 +03:00
parent 286de54384
commit 1c0e57d984
9084 changed files with 997839 additions and 997557 deletions
@@ -0,0 +1,66 @@
[package]
name = "pezsp-crypto-ec-utils"
version = "0.10.0"
authors.workspace = true
description = "Host functions for common Arkworks elliptic curve operations"
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[dependencies]
ark-bls12-377 = { features = ["curve"], optional = true, workspace = true }
ark-bls12-377-ext = { optional = true, workspace = true }
ark-bls12-381 = { features = ["curve"], optional = true, workspace = true }
ark-bls12-381-ext = { optional = true, workspace = true }
ark-bw6-761 = { optional = true, workspace = true }
ark-bw6-761-ext = { optional = true, workspace = true }
ark-ec = { optional = true, workspace = true }
ark-ed-on-bls12-377 = { optional = true, workspace = true }
ark-ed-on-bls12-377-ext = { optional = true, workspace = true }
ark-ed-on-bls12-381-bandersnatch = { optional = true, workspace = true }
ark-ed-on-bls12-381-bandersnatch-ext = { optional = true, workspace = true }
ark-scale = { features = ["hazmat"], optional = true, workspace = true }
pezsp-runtime-interface = { optional = true, workspace = true }
[features]
default = ["std"]
std = [
"ark-bls12-377-ext?/std",
"ark-bls12-377?/std",
"ark-bls12-381-ext?/std",
"ark-bls12-381?/std",
"ark-bw6-761-ext?/std",
"ark-bw6-761?/std",
"ark-ec?/parallel",
"ark-ec?/std",
"ark-ed-on-bls12-377-ext?/std",
"ark-ed-on-bls12-377?/std",
"ark-ed-on-bls12-381-bandersnatch-ext?/std",
"ark-ed-on-bls12-381-bandersnatch?/std",
"ark-scale?/std",
"pezsp-runtime-interface?/std",
]
common = ["ark-ec", "ark-scale", "pezsp-runtime-interface"]
bls12-377 = ["ark-bls12-377", "ark-bls12-377-ext", "common"]
bls12-381 = ["ark-bls12-381", "ark-bls12-381-ext", "common"]
bw6-761 = ["ark-bw6-761", "ark-bw6-761-ext", "common"]
ed-on-bls12-377 = ["ark-ed-on-bls12-377", "ark-ed-on-bls12-377-ext", "common"]
ed-on-bls12-381-bandersnatch = [
"ark-ed-on-bls12-381-bandersnatch",
"ark-ed-on-bls12-381-bandersnatch-ext",
"common",
]
all-curves = [
"bls12-377",
"bls12-381",
"bw6-761",
"ed-on-bls12-377",
"ed-on-bls12-381-bandersnatch",
]
@@ -0,0 +1,214 @@
// This file is part of Bizinikiwi.
// 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-377* types and host functions.
use crate::utils;
use alloc::vec::Vec;
use ark_bls12_377_ext::CurveHooks;
use ark_ec::{pairing::Pairing, CurveConfig};
use pezsp_runtime_interface::{
pass_by::{AllocateAndReturnByCodec, PassFatPointerAndRead},
runtime_interface,
};
/// First pairing group definitions.
pub mod g1 {
pub use ark_bls12_377_ext::g1::{
G1_GENERATOR_X, G1_GENERATOR_Y, TE_GENERATOR_X, TE_GENERATOR_Y,
};
/// Group configuration.
pub type Config = ark_bls12_377_ext::g1::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G1Affine = ark_bls12_377_ext::g1::G1Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G1Projective = ark_bls12_377_ext::g1::G1Projective<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G1SWAffine = ark_bls12_377_ext::g1::G1SWAffine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G1SWProjective = ark_bls12_377_ext::g1::G1SWProjective<super::HostHooks>;
/// Twisted Edwards form point affine representation.
pub type G1TEAffine = ark_bls12_377_ext::g1::G1TEAffine<super::HostHooks>;
/// Twisted Edwards form point projective representation.
pub type G1TEProjective = ark_bls12_377_ext::g1::G1TEProjective<super::HostHooks>;
}
/// Second pairing group definitions.
pub mod g2 {
pub use ark_bls12_377_ext::g2::{
G2_GENERATOR_X, G2_GENERATOR_X_C0, G2_GENERATOR_X_C1, G2_GENERATOR_Y, G2_GENERATOR_Y_C0,
G2_GENERATOR_Y_C1,
};
/// Group configuration.
pub type Config = ark_bls12_377_ext::g2::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G2Affine = ark_bls12_377_ext::g2::G2Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G2Projective = ark_bls12_377_ext::g2::G2Projective<super::HostHooks>;
}
pub use self::{
g1::{Config as G1Config, G1Affine, G1Projective},
g2::{Config as G2Config, G2Affine, G2Projective},
};
/// Curve hooks jumping into [`host_calls`] host functions.
#[derive(Copy, Clone)]
pub struct HostHooks;
/// Configuration for *BLS12-377* curve.
pub type Config = ark_bls12_377_ext::Config<HostHooks>;
/// *BLS12-377* definition.
///
/// A generic *BLS12* model specialized with *BLS12-377* configuration.
pub type Bls12_377 = ark_bls12_377_ext::Bls12_377<HostHooks>;
impl CurveHooks for HostHooks {
fn multi_miller_loop(
g1: impl Iterator<Item = <Bls12_377 as Pairing>::G1Prepared>,
g2: impl Iterator<Item = <Bls12_377 as Pairing>::G2Prepared>,
) -> <Bls12_377 as Pairing>::TargetField {
host_calls::bls12_377_multi_miller_loop(utils::encode_iter(g1), utils::encode_iter(g2))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn final_exponentiation(
target: <Bls12_377 as Pairing>::TargetField,
) -> <Bls12_377 as Pairing>::TargetField {
host_calls::bls12_377_final_exponentiation(utils::encode(target))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn msm_g1(
bases: &[G1Affine],
scalars: &[<G1Config as CurveConfig>::ScalarField],
) -> G1Projective {
host_calls::bls12_377_msm_g1(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn msm_g2(
bases: &[G2Affine],
scalars: &[<G2Config as CurveConfig>::ScalarField],
) -> G2Projective {
host_calls::bls12_377_msm_g2(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g1(base: &G1Projective, scalar: &[u64]) -> G1Projective {
host_calls::bls12_377_mul_projective_g1(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g2(base: &G2Projective, scalar: &[u64]) -> G2Projective {
host_calls::bls12_377_mul_projective_g2(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
}
/// Interfaces for working with *Arkworks* *BLS12-377* elliptic curve related types
/// from within the runtime.
///
/// All types are (de-)serialized through the wrapper types from the `ark-scale` trait,
/// with `ark_scale::{ArkScale, ArkScaleProjective}`.
///
/// `ArkScale`'s `Usage` generic parameter is expected to be set to "not-validated"
/// and "not-compressed".
#[runtime_interface]
pub trait HostCalls {
/// Pairing multi Miller loop for *BLS12-377*.
///
/// - Receives encoded:
/// - `a`: `ArkScale<Vec<G1Affine>>`.
/// - `b`: `ArkScale<Vec<G2Affine>>`.
/// - Returns encoded: `ArkScale<Bls12_377::TargetField>`.
fn bls12_377_multi_miller_loop(
a: PassFatPointerAndRead<Vec<u8>>,
b: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::multi_miller_loop::<ark_bls12_377::Bls12_377>(a, b)
}
/// Pairing final exponentiation for *BLS12-377.*
///
/// - Receives encoded: `ArkScale<Bls12_377::TargetField>`.
/// - Returns encoded: `ArkScale<Bls12_377::TargetField>`.
fn bls12_377_final_exponentiation(
f: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::final_exponentiation::<ark_bls12_377::Bls12_377>(f)
}
/// Multi scalar multiplication on *G1* for *BLS12-377*.
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G1Affine>>`.
/// - `scalars`: `ArkScale<Vec<G1Config::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<G1Projective>`.
fn bls12_377_msm_g1(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bls12_377::g1::Config>(bases, scalars)
}
/// Multi scalar multiplication on *G2* for *BLS12-377*.
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G2Affine>>`.
/// - `scalars`: `ArkScale<Vec<G2Config::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<G2Projective>`.
fn bls12_377_msm_g2(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bls12_377::g2::Config>(bases, scalars)
}
/// Projective multiplication on *G1* for *BLS12-377*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G1Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<G1Projective>`.
fn bls12_377_mul_projective_g1(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bls12_377::g1::Config>(base, scalar)
}
/// Projective multiplication on *G2* for *BLS12-377*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G2Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<ark_bls12_377::G2Projective>`.
fn bls12_377_mul_projective_g2(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bls12_377::g2::Config>(base, scalar)
}
}
@@ -0,0 +1,204 @@
// This file is part of Bizinikiwi.
// 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* types and host functions.
use crate::utils;
use alloc::vec::Vec;
use ark_bls12_381_ext::CurveHooks;
use ark_ec::{pairing::Pairing, CurveConfig};
use pezsp_runtime_interface::{
pass_by::{AllocateAndReturnByCodec, PassFatPointerAndRead},
runtime_interface,
};
/// First pairing group definitions.
pub mod g1 {
pub use ark_bls12_381_ext::g1::{BETA, G1_GENERATOR_X, G1_GENERATOR_Y};
/// Group configuration.
pub type Config = ark_bls12_381_ext::g1::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G1Affine = ark_bls12_381_ext::g1::G1Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G1Projective = ark_bls12_381_ext::g1::G1Projective<super::HostHooks>;
}
/// Second pairing group definitions.
pub mod g2 {
pub use ark_bls12_381_ext::g2::{
G2_GENERATOR_X, G2_GENERATOR_X_C0, G2_GENERATOR_X_C1, G2_GENERATOR_Y, G2_GENERATOR_Y_C0,
G2_GENERATOR_Y_C1,
};
/// Group configuration.
pub type Config = ark_bls12_381_ext::g2::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G2Affine = ark_bls12_381_ext::g2::G2Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G2Projective = ark_bls12_381_ext::g2::G2Projective<super::HostHooks>;
}
pub use self::{
g1::{Config as G1Config, G1Affine, G1Projective},
g2::{Config as G2Config, G2Affine, G2Projective},
};
/// Curve hooks jumping into [`host_calls`] host functions.
#[derive(Copy, Clone)]
pub struct HostHooks;
/// Configuration for *BLS12-381* curve.
pub type Config = ark_bls12_381_ext::Config<HostHooks>;
/// *BLS12-381* definition.
///
/// A generic *BLS12* model specialized with *BLS12-381* configuration.
pub type Bls12_381 = ark_bls12_381_ext::Bls12_381<HostHooks>;
impl CurveHooks for HostHooks {
fn multi_miller_loop(
g1: impl Iterator<Item = <Bls12_381 as Pairing>::G1Prepared>,
g2: impl Iterator<Item = <Bls12_381 as Pairing>::G2Prepared>,
) -> <Bls12_381 as Pairing>::TargetField {
host_calls::bls12_381_multi_miller_loop(utils::encode_iter(g1), utils::encode_iter(g2))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn final_exponentiation(
target: <Bls12_381 as Pairing>::TargetField,
) -> <Bls12_381 as Pairing>::TargetField {
host_calls::bls12_381_final_exponentiation(utils::encode(target))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn msm_g1(
bases: &[G1Affine],
scalars: &[<G1Config as CurveConfig>::ScalarField],
) -> G1Projective {
host_calls::bls12_381_msm_g1(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn msm_g2(
bases: &[G2Affine],
scalars: &[<G2Config as CurveConfig>::ScalarField],
) -> G2Projective {
host_calls::bls12_381_msm_g2(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g1(base: &G1Projective, scalar: &[u64]) -> G1Projective {
host_calls::bls12_381_mul_projective_g1(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g2(base: &G2Projective, scalar: &[u64]) -> G2Projective {
host_calls::bls12_381_mul_projective_g2(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
}
/// Interfaces for working with *Arkworks* *BLS12-381* elliptic curve related types
/// from within the runtime.
///
/// All types are (de-)serialized through the wrapper types from the `ark-scale` trait,
/// with `ark_scale::{ArkScale, ArkScaleProjective}`.
///
/// `ArkScale`'s `Usage` generic parameter is expected to be set to "not-validated"
/// and "not-compressed".
#[runtime_interface]
pub trait HostCalls {
/// Pairing multi Miller loop for *BLS12-381*.
///
/// - Receives encoded:
/// - `a`: `ArkScale<Vec<G1Affine>>`.
/// - `b`: `ArkScale<Vec<G2Affine>>`.
/// - Returns encoded: `ArkScale<Bls12_381::TargetField>`.
fn bls12_381_multi_miller_loop(
a: PassFatPointerAndRead<Vec<u8>>,
b: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::multi_miller_loop::<ark_bls12_381::Bls12_381>(a, b)
}
/// Pairing final exponentiation for *BLS12-381*.
///
/// - Receives encoded: `ArkScale<<Bls12_377::TargetField>`.
/// - Returns encoded: `ArkScale<<Bls12_377::TargetField>`
fn bls12_381_final_exponentiation(
f: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::final_exponentiation::<ark_bls12_381::Bls12_381>(f)
}
/// Multi scalar multiplication on *G1* for *BLS12-381*
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G1Affine>>`.
/// - `scalars`: `ArkScale<Vec<G1Config::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<ark_bls12_381::G1Projective>`.
fn bls12_381_msm_g1(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bls12_381::g1::Config>(bases, scalars)
}
/// Multi scalar multiplication on *G2* for *BLS12-381*
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G2Affine>>`.
/// - `scalars`: `ArkScale<Vec<G2Config::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<G2Projective>`.
fn bls12_381_msm_g2(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bls12_381::g2::Config>(bases, scalars)
}
/// Projective multiplication on *G1* for *BLS12-381*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G1Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<G1Projective>`.
fn bls12_381_mul_projective_g1(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bls12_381::g1::Config>(base, scalar)
}
/// Projective multiplication on *G2* for *BLS12-381*
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G2Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<G2Projective>`.
fn bls12_381_mul_projective_g2(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bls12_381::g2::Config>(base, scalar)
}
}
@@ -0,0 +1,201 @@
// This file is part of Bizinikiwi.
// 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.
//! *BW6-761* types and host functions.
use crate::utils;
use alloc::vec::Vec;
use ark_bw6_761_ext::CurveHooks;
use ark_ec::{pairing::Pairing, CurveConfig};
use pezsp_runtime_interface::{
pass_by::{AllocateAndReturnByCodec, PassFatPointerAndRead},
runtime_interface,
};
/// First pairing group definitions.
pub mod g1 {
pub use ark_bw6_761_ext::g1::{G1_GENERATOR_X, G1_GENERATOR_Y};
/// Group configuration.
pub type Config = ark_bw6_761_ext::g1::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G1Affine = ark_bw6_761_ext::g1::G1Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G1Projective = ark_bw6_761_ext::g1::G1Projective<super::HostHooks>;
}
/// Second pairing group definitions.
pub mod g2 {
pub use ark_bw6_761_ext::g2::{G2_GENERATOR_X, G2_GENERATOR_Y};
/// Group configuration.
pub type Config = ark_bw6_761_ext::g2::Config<super::HostHooks>;
/// Short Weierstrass form point affine representation.
pub type G2Affine = ark_bw6_761_ext::g2::G2Affine<super::HostHooks>;
/// Short Weierstrass form point projective representation.
pub type G2Projective = ark_bw6_761_ext::g2::G2Projective<super::HostHooks>;
}
pub use self::{
g1::{Config as G1Config, G1Affine, G1Projective},
g2::{Config as G2Config, G2Affine, G2Projective},
};
/// Curve hooks jumping into [`host_calls`] host functions.
#[derive(Copy, Clone)]
pub struct HostHooks;
/// Configuration for *BW6-361* curve.
pub type Config = ark_bw6_761_ext::Config<HostHooks>;
/// *BW6-361* definition.
///
/// A generic *BW6* model specialized with *BW6-761* configuration.
pub type BW6_761 = ark_bw6_761_ext::BW6_761<HostHooks>;
impl CurveHooks for HostHooks {
fn multi_miller_loop(
g1: impl Iterator<Item = <BW6_761 as Pairing>::G1Prepared>,
g2: impl Iterator<Item = <BW6_761 as Pairing>::G2Prepared>,
) -> <BW6_761 as Pairing>::TargetField {
host_calls::bw6_761_multi_miller_loop(utils::encode_iter(g1), utils::encode_iter(g2))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn final_exponentiation(
target: <BW6_761 as Pairing>::TargetField,
) -> <BW6_761 as Pairing>::TargetField {
host_calls::bw6_761_final_exponentiation(utils::encode(target))
.and_then(|res| utils::decode(res))
.unwrap_or_default()
}
fn msm_g1(
bases: &[G1Affine],
scalars: &[<G1Config as CurveConfig>::ScalarField],
) -> G1Projective {
host_calls::bw6_761_msm_g1(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn msm_g2(
bases: &[G2Affine],
scalars: &[<G2Config as CurveConfig>::ScalarField],
) -> G2Projective {
host_calls::bw6_761_msm_g2(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g1(base: &G1Projective, scalar: &[u64]) -> G1Projective {
host_calls::bw6_761_mul_projective_g1(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_g2(base: &G2Projective, scalar: &[u64]) -> G2Projective {
host_calls::bw6_761_mul_projective_g2(utils::encode_proj_sw(base), utils::encode(scalar))
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
}
/// Interfaces for working with *Arkworks* *BW6-761* elliptic curve related types
/// from within the runtime.
///
/// All types are (de-)serialized through the wrapper types from the `ark-scale` trait,
/// with `ark_scale::{ArkScale, ArkScaleProjective}`.
///
/// `ArkScale`'s `Usage` generic parameter is expected to be set to "not-validated"
/// and "not-compressed".
#[runtime_interface]
pub trait HostCalls {
/// Pairing multi Miller loop for *BW6-761*.
///
/// - Receives encoded:
/// - `a: ArkScale<Vec<G1Affine>>`.
/// - `b: ArkScale<Vec<G2Affine>>`.
/// - Returns encoded: `ArkScale<BW6_761;:TargetField>`.
fn bw6_761_multi_miller_loop(
a: PassFatPointerAndRead<Vec<u8>>,
b: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::multi_miller_loop::<ark_bw6_761::BW6_761>(a, b)
}
/// Pairing final exponentiation for *BW6-761*.
///
/// - Receives encoded: `ArkScale<BW6_761::TargetField>`.
/// - Returns encoded: `ArkScale<BW6_761::TargetField>`.
fn bw6_761_final_exponentiation(
f: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::final_exponentiation::<ark_bw6_761::BW6_761>(f)
}
/// Multi scalar multiplication on *G1* for *BW6-761*.
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G1Affine>>`.
/// - `scalars`: `ArkScale<G1Config::ScalarField>`.
/// - Returns encoded: `ArkScaleProjective<G1Projective>`.
fn bw6_761_msm_g1(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bw6_761::g1::Config>(bases, scalars)
}
/// Multi scalar multiplication on *G2* for *BW6-761*.
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<G2Affine>>`.
/// - `scalars`: `ArkScale<Vec<G2Config::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<G2Projective>`.
fn bw6_761_msm_g2(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_bw6_761::g2::Config>(bases, scalars)
}
/// Projective multiplication on *G1* for *BW6-761*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G1Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<G1Projective>`.
fn bw6_761_mul_projective_g1(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bw6_761::g1::Config>(base, scalar)
}
/// Projective multiplication on *G2* for *BW6-761*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<G2Projective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<G2Projective>`.
fn bw6_761_mul_projective_g2(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_bw6_761::g2::Config>(base, scalar)
}
}
@@ -0,0 +1,95 @@
// This file is part of Bizinikiwi.
// 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.
//! *Ed-on-BLS12-377* types and host functions.
use crate::utils;
use alloc::vec::Vec;
use ark_ec::CurveConfig;
use ark_ed_on_bls12_377_ext::CurveHooks;
use pezsp_runtime_interface::{
pass_by::{AllocateAndReturnByCodec, PassFatPointerAndRead},
runtime_interface,
};
/// Curve hooks jumping into [`host_calls`] host functions.
#[derive(Copy, Clone)]
pub struct HostHooks;
/// Group configuration.
pub type EdwardsConfig = ark_ed_on_bls12_377_ext::EdwardsConfig<HostHooks>;
/// Twisted Edwards form point affine representation.
pub type EdwardsAffine = ark_ed_on_bls12_377_ext::EdwardsAffine<HostHooks>;
/// Twisted Edwards form point projective representation.
pub type EdwardsProjective = ark_ed_on_bls12_377_ext::EdwardsProjective<HostHooks>;
impl CurveHooks for HostHooks {
fn msm(
bases: &[EdwardsAffine],
scalars: &[<EdwardsConfig as CurveConfig>::ScalarField],
) -> EdwardsProjective {
host_calls::ed_on_bls12_377_te_msm(utils::encode(bases), utils::encode(scalars))
.and_then(|res| utils::decode_proj_te(res))
.unwrap_or_default()
}
fn mul_projective(base: &EdwardsProjective, scalar: &[u64]) -> EdwardsProjective {
host_calls::ed_on_bls12_377_te_mul_projective(
utils::encode_proj_te(base),
utils::encode(scalar),
)
.and_then(|res| utils::decode_proj_te(res))
.unwrap_or_default()
}
}
/// Interfaces for working with *Arkworks* *Ed-on-BLS12-377* elliptic curve
/// related types from within the runtime.
///
/// All types are (de-)serialized through the wrapper types from the `ark-scale` trait,
/// with `ark_scale::{ArkScale, ArkScaleProjective}`.
///
/// `ArkScale`'s `Usage` generic parameter is expected to be set to "not-validated"
/// and "not-compressed".
#[runtime_interface]
pub trait HostCalls {
/// Twisted Edwards multi scalar multiplication for *Ed-on-BLS12-377*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<EdwardsProjective>`.
/// - `scalars`: `ArkScale<Vec<EdwardsConfig::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<EdwardsProjective>`.
fn ed_on_bls12_377_te_msm(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_te::<ark_ed_on_bls12_377::EdwardsConfig>(bases, scalars)
}
/// Twisted Edwards projective multiplication for *Ed-on-BLS12-377*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<EdwardsProjective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<EdwardsProjective>`.
fn ed_on_bls12_377_te_mul_projective(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_te::<ark_ed_on_bls12_377::EdwardsConfig>(base, scalar)
}
}
@@ -0,0 +1,154 @@
// This file is part of Bizinikiwi.
// 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.
//! Elliptic Curves host functions to handle some of the *Arkworks* *Ed-on-BLS12-381-Bandersnatch*
//! computationally expensive operations.
use crate::utils;
use alloc::vec::Vec;
use ark_ec::CurveConfig;
use ark_ed_on_bls12_381_bandersnatch_ext::CurveHooks;
use pezsp_runtime_interface::{
pass_by::{AllocateAndReturnByCodec, PassFatPointerAndRead},
runtime_interface,
};
/// Curve hooks jumping into [`host_calls`] host functions.
#[derive(Copy, Clone)]
pub struct HostHooks;
/// Group configuration.
pub type BandersnatchConfig = ark_ed_on_bls12_381_bandersnatch_ext::BandersnatchConfig<HostHooks>;
/// Group configuration for Twisted Edwards form (equal to [`BandersnatchConfig`]).
pub type EdwardsConfig = ark_ed_on_bls12_381_bandersnatch_ext::EdwardsConfig<HostHooks>;
/// Twisted Edwards form point affine representation.
pub type EdwardsAffine = ark_ed_on_bls12_381_bandersnatch_ext::EdwardsAffine<HostHooks>;
/// Twisted Edwards form point projective representation.
pub type EdwardsProjective = ark_ed_on_bls12_381_bandersnatch_ext::EdwardsProjective<HostHooks>;
/// Group configuration for Short Weierstrass form (equal to [`BandersnatchConfig`]).
pub type SWConfig = ark_ed_on_bls12_381_bandersnatch_ext::SWConfig<HostHooks>;
/// Short Weierstrass form point affine representation.
pub type SWAffine = ark_ed_on_bls12_381_bandersnatch_ext::SWAffine<HostHooks>;
/// Short Weierstrass form point projective representation.
pub type SWProjective = ark_ed_on_bls12_381_bandersnatch_ext::SWProjective<HostHooks>;
impl CurveHooks for HostHooks {
fn msm_te(
bases: &[EdwardsAffine],
scalars: &[<EdwardsConfig as CurveConfig>::ScalarField],
) -> EdwardsProjective {
host_calls::ed_on_bls12_381_bandersnatch_te_msm(
utils::encode(bases),
utils::encode(scalars),
)
.and_then(|res| utils::decode_proj_te(res))
.unwrap_or_default()
}
fn mul_projective_te(base: &EdwardsProjective, scalar: &[u64]) -> EdwardsProjective {
host_calls::ed_on_bls12_381_bandersnatch_te_mul_projective(
utils::encode_proj_te(base),
utils::encode(scalar),
)
.and_then(|res| utils::decode_proj_te(res))
.unwrap_or_default()
}
fn msm_sw(
bases: &[SWAffine],
scalars: &[<SWConfig as CurveConfig>::ScalarField],
) -> SWProjective {
host_calls::ed_on_bls12_381_bandersnatch_sw_msm(
utils::encode(bases),
utils::encode(scalars),
)
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
fn mul_projective_sw(base: &SWProjective, scalar: &[u64]) -> SWProjective {
host_calls::ed_on_bls12_381_bandersnatch_sw_mul_projective(
utils::encode_proj_sw(base),
utils::encode(scalar),
)
.and_then(|res| utils::decode_proj_sw(res))
.unwrap_or_default()
}
}
/// Interfaces for working with *Arkworks* *Ed-on-BLS12-381-Bandersnatch* elliptic curve
/// related types from within the runtime.
///
/// All types are (de-)serialized through the wrapper types from the `ark-scale` trait,
/// with `ark_scale::{ArkScale, ArkScaleProjective}`.
///
/// `ArkScale`'s `Usage` generic parameter is expected to be set to "not-validated"
/// and "not-compressed".
#[runtime_interface]
pub trait HostCalls {
/// Twisted Edwards multi scalar multiplication for *Ed-on-BLS12-381-Bandersnatch*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<EdwardsProjective>`.
/// - `scalars`: `ArkScale<Vec<EdwardsConfig::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<EdwardsProjective>`.
fn ed_on_bls12_381_bandersnatch_te_msm(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_te::<ark_ed_on_bls12_381_bandersnatch::EdwardsConfig>(bases, scalars)
}
/// Twisted Edwards projective multiplication for *Ed-on-BLS12-381-Bandersnatch*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<EdwardsProjective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<EdwardsProjective>`.
fn ed_on_bls12_381_bandersnatch_te_mul_projective(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_te::<ark_ed_on_bls12_381_bandersnatch::EdwardsConfig>(base, scalar)
}
/// Short Weierstrass multi scalar multiplication for *Ed-on-BLS12-381-Bandersnatch*.
///
/// - Receives encoded:
/// - `bases`: `ArkScale<Vec<SWAffine>>`.
/// - `scalars`: `ArkScale<Vec<SWConfig::ScalarField>>`.
/// - Returns encoded: `ArkScaleProjective<SWProjective>`.
fn ed_on_bls12_381_bandersnatch_sw_msm(
bases: PassFatPointerAndRead<Vec<u8>>,
scalars: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::msm_sw::<ark_ed_on_bls12_381_bandersnatch::SWConfig>(bases, scalars)
}
/// Short Weierstrass projective multiplication for *Ed-on-BLS12-381-Bandersnatch*.
///
/// - Receives encoded:
/// - `base`: `ArkScaleProjective<SWProjective>`.
/// - `scalar`: `ArkScale<Vec<u64>>`.
/// - Returns encoded: `ArkScaleProjective<SWProjective>`.
fn ed_on_bls12_381_bandersnatch_sw_mul_projective(
base: PassFatPointerAndRead<Vec<u8>>,
scalar: PassFatPointerAndRead<Vec<u8>>,
) -> AllocateAndReturnByCodec<Result<Vec<u8>, ()>> {
utils::mul_projective_sw::<ark_ed_on_bls12_381_bandersnatch::SWConfig>(base, scalar)
}
}
@@ -0,0 +1,55 @@
// This file is part of Bizinikiwi.
// 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.
//! This crate offers elliptic curves types which are compatible with the
//! [Arkworks](https://github.com/arkworks-rs) library functionalities.
//!
//! The implementation has been primarily designed to be used in slow hosted
//! targets (e.g. wasm32) and offloads the most computationally expensive
//! operations to the host by leveraging the
//! [arkworks-extensions](https://github.com/paritytech/arkworks-extensions)
//! library and Bizinikiwi's host functions.
//!
//! The exported types are organized and named in a way that mirrors the structure
//! of the types in the original Arkworks library. This design choice aims to make
//! it easier for users already familiar with the library to understand and utilize
//! the exported types effectively.
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(feature = "bls12-377")]
pub mod bls12_377;
#[cfg(feature = "bls12-381")]
pub mod bls12_381;
#[cfg(feature = "bw6-761")]
pub mod bw6_761;
#[cfg(feature = "ed-on-bls12-377")]
pub mod ed_on_bls12_377;
#[cfg(feature = "ed-on-bls12-381-bandersnatch")]
pub mod ed_on_bls12_381_bandersnatch;
#[cfg(any(
feature = "bls12-377",
feature = "bls12-381",
feature = "bw6-761",
feature = "ed-on-bls12-377",
feature = "ed-on-bls12-381-bandersnatch",
))]
mod utils;
@@ -0,0 +1,122 @@
// This file is part of Bizinikiwi.
// 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.
//! Generic executions of the operations for *Arkworks* elliptic curves.
// As not all functions are used by each elliptic curve and some elliptic
// curve may be excluded by the build we resort to `#[allow(unused)]` to
// suppress the expected warning.
use alloc::vec::Vec;
use ark_ec::{
pairing::{MillerLoopOutput, Pairing},
short_weierstrass::{Affine as SWAffine, Projective as SWProjective, SWCurveConfig},
twisted_edwards::{Affine as TEAffine, Projective as TEProjective, TECurveConfig},
CurveConfig, VariableBaseMSM,
};
use ark_scale::{
ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Compress, Validate},
scale::{Decode, Encode},
};
// SCALE encoding parameters shared by all the enabled modules
const SCALE_USAGE: u8 = ark_scale::make_usage(Compress::No, Validate::No);
type ArkScale<T> = ark_scale::ArkScale<T, SCALE_USAGE>;
type ArkScaleProjective<T> = ark_scale::hazmat::ArkScaleProjective<T>;
#[inline(always)]
#[allow(unused)]
pub fn encode_iter<T: CanonicalSerialize>(iter: impl Iterator<Item = T>) -> Vec<u8> {
encode(iter.collect::<Vec<_>>())
}
#[inline(always)]
pub fn encode<T: CanonicalSerialize>(val: T) -> Vec<u8> {
ArkScale::from(val).encode()
}
#[inline(always)]
pub fn decode<T: CanonicalDeserialize>(buf: Vec<u8>) -> Result<T, ()> {
ArkScale::<T>::decode(&mut &buf[..]).map_err(|_| ()).map(|v| v.0)
}
#[inline(always)]
pub fn encode_proj_sw<T: SWCurveConfig>(val: &SWProjective<T>) -> Vec<u8> {
ArkScaleProjective::from(val).encode()
}
#[inline(always)]
pub fn decode_proj_sw<T: SWCurveConfig>(buf: Vec<u8>) -> Result<SWProjective<T>, ()> {
ArkScaleProjective::decode(&mut &buf[..]).map_err(|_| ()).map(|v| v.0)
}
#[inline(always)]
pub fn encode_proj_te<T: TECurveConfig>(val: &TEProjective<T>) -> Vec<u8> {
ArkScaleProjective::from(val).encode()
}
#[inline(always)]
pub fn decode_proj_te<T: TECurveConfig>(buf: Vec<u8>) -> Result<TEProjective<T>, ()> {
ArkScaleProjective::decode(&mut &buf[..]).map_err(|_| ()).map(|v| v.0)
}
#[allow(unused)]
pub fn multi_miller_loop<T: Pairing>(g1: Vec<u8>, g2: Vec<u8>) -> Result<Vec<u8>, ()> {
let g1 = decode::<Vec<<T as Pairing>::G1Affine>>(g1)?;
let g2 = decode::<Vec<<T as Pairing>::G2Affine>>(g2)?;
let res = T::multi_miller_loop(g1, g2);
Ok(encode(res.0))
}
#[allow(unused)]
pub fn final_exponentiation<T: Pairing>(target: Vec<u8>) -> Result<Vec<u8>, ()> {
let target = decode::<<T as Pairing>::TargetField>(target)?;
let res = T::final_exponentiation(MillerLoopOutput(target)).ok_or(())?;
Ok(encode(res.0))
}
#[allow(unused)]
pub fn msm_sw<T: SWCurveConfig>(bases: Vec<u8>, scalars: Vec<u8>) -> Result<Vec<u8>, ()> {
let bases = decode::<Vec<SWAffine<T>>>(bases)?;
let scalars = decode::<Vec<<T as CurveConfig>::ScalarField>>(scalars)?;
let res = <SWProjective<T> as VariableBaseMSM>::msm(&bases, &scalars).map_err(|_| ())?;
Ok(encode_proj_sw(&res))
}
#[allow(unused)]
pub fn msm_te<T: TECurveConfig>(bases: Vec<u8>, scalars: Vec<u8>) -> Result<Vec<u8>, ()> {
let bases = decode::<Vec<TEAffine<T>>>(bases)?;
let scalars = decode::<Vec<<T as CurveConfig>::ScalarField>>(scalars)?;
let res = <TEProjective<T> as VariableBaseMSM>::msm(&bases, &scalars).map_err(|_| ())?;
Ok(encode_proj_te(&res))
}
#[allow(unused)]
pub fn mul_projective_sw<T: SWCurveConfig>(base: Vec<u8>, scalar: Vec<u8>) -> Result<Vec<u8>, ()> {
let base = decode_proj_sw::<T>(base)?;
let scalar = decode::<Vec<u64>>(scalar)?;
let res = <T as SWCurveConfig>::mul_projective(&base, &scalar);
Ok(encode_proj_sw(&res))
}
#[allow(unused)]
pub fn mul_projective_te<T: TECurveConfig>(base: Vec<u8>, scalar: Vec<u8>) -> Result<Vec<u8>, ()> {
let base = decode_proj_te::<T>(base)?;
let scalar = decode::<Vec<u64>>(scalar)?;
let res = <T as TECurveConfig>::mul_projective(&base, &scalar);
Ok(encode_proj_te(&res))
}
@@ -0,0 +1,46 @@
[package]
name = "pezsp-crypto-hashing"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "Hashing primitives."
documentation = "https://docs.rs/pezsp-crypto-hashing"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[lib]
bench = false
[[bench]]
name = "bench"
harness = false
[dependencies]
blake2b_simd = { workspace = true }
byteorder = { workspace = true }
digest = { workspace = true }
sha2 = { workspace = true }
sha3 = { workspace = true }
twox-hash = { features = ["digest_0_10"], workspace = true }
[dev-dependencies]
criterion = { workspace = true, default-features = true }
pezsp-crypto-hashing-proc-macro = { workspace = true, default-features = true }
[features]
default = ["std"]
std = [
"blake2b_simd/std",
"byteorder/std",
"digest/std",
"sha2/std",
"sha3/std",
"twox-hash/std",
]
@@ -0,0 +1,81 @@
// Copyright (C) Parity Technologies (UK) Ltd.
//
// 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 criterion::{black_box, criterion_group, criterion_main, Bencher, BenchmarkId, Criterion};
// Min 32 bytes buffer
const MIN_EXP: usize = 5;
// Max 1 MB buffer
const MAX_EXP: usize = 20;
fn bench_blake2_128(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::blake2_128(black_box(buf));
});
}
fn bench_twox_128(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::twox_128(black_box(buf));
});
}
fn bench_blake2_256(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::blake2_256(black_box(buf));
});
}
fn bench_twox_256(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::twox_256(black_box(buf));
});
}
fn bench_sha_256(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::sha2_256(black_box(buf));
});
}
fn bench_keccak_256(b: &mut Bencher, buf: &Vec<u8>) {
b.iter(|| {
let _a = pezsp_crypto_hashing::keccak_256(black_box(buf));
});
}
fn bench_hash(c: &mut Criterion) {
let mut group = c.benchmark_group("hashing-128");
let buf = vec![0u8; 1 << MAX_EXP];
for i in MIN_EXP..=MAX_EXP {
let size = 1 << i;
group.bench_with_input(BenchmarkId::new("blake2-128", size), &buf, bench_blake2_128);
group.bench_with_input(BenchmarkId::new("twox-128", size), &buf, bench_twox_128);
}
group.finish();
let mut group = c.benchmark_group("hashing-256");
for i in MIN_EXP..=MAX_EXP {
let size = 1 << i;
group.bench_with_input(BenchmarkId::new("blake2-256", size), &buf, bench_blake2_256);
group.bench_with_input(BenchmarkId::new("twox-256", size), &buf, bench_twox_256);
group.bench_with_input(BenchmarkId::new("sha-256", size), &buf, bench_sha_256);
group.bench_with_input(BenchmarkId::new("keccak-256", size), &buf, bench_keccak_256);
}
group.finish();
}
criterion_group!(benches, bench_hash);
criterion_main!(benches);
@@ -0,0 +1,24 @@
[package]
name = "pezsp-crypto-hashing-proc-macro"
version = "0.1.0"
authors.workspace = true
edition.workspace = true
license = "Apache-2.0"
homepage.workspace = true
repository.workspace = true
description = "Procedural macros for calculating static hashes."
documentation = "https://docs.rs/pezsp-crypto-hashing-proc-macro"
[lints]
workspace = true
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
[lib]
proc-macro = true
[dependencies]
quote = { workspace = true }
pezsp-crypto-hashing = { workspace = true }
syn = { features = ["full", "parsing"], workspace = true }
@@ -0,0 +1,124 @@
// This file is part of Bizinikiwi.
// 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(pezsp_crypto_hashing::twox_64(bytes.as_slice()))
}
pub(super) fn twox_128(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::twox_128(bytes.as_slice()))
}
pub(super) fn blake2b_512(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::blake2_512(bytes.as_slice()))
}
pub(super) fn blake2b_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::blake2_256(bytes.as_slice()))
}
pub(super) fn blake2b_64(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::blake2_64(bytes.as_slice()))
}
pub(super) fn keccak_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::keccak_256(bytes.as_slice()))
}
pub(super) fn keccak_512(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::keccak_512(bytes.as_slice()))
}
pub(super) fn sha2_256(bytes: Vec<u8>) -> TokenStream {
bytes_to_array(pezsp_crypto_hashing::sha2_256(bytes.as_slice()))
}
fn bytes_to_array(bytes: impl IntoIterator<Item = u8>) -> TokenStream {
let bytes = bytes.into_iter();
quote!(
[ #( #bytes ),* ]
)
.into()
}
@@ -0,0 +1,129 @@
// This file is part of Bizinikiwi.
// 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!(
//! pezsp_crypto_hashing_proc_macro::blake2b_256!(b"test"),
//! pezsp_crypto_hashing::blake2_256(b"test"),
//! );
//! assert_eq!(
//! pezsp_crypto_hashing_proc_macro::blake2b_256!([1u8]),
//! pezsp_crypto_hashing::blake2_256(&[1u8]),
//! );
//! assert_eq!(
//! pezsp_crypto_hashing_proc_macro::blake2b_256!([1, 2, 3]),
//! pezsp_crypto_hashing::blake2_256(&[1, 2, 3]),
//! );
//! assert_eq!(
//! pezsp_crypto_hashing_proc_macro::blake2b_256!(identifier),
//! pezsp_crypto_hashing::blake2_256(b"identifier"),
//! );
//! assert_eq!(
//! pezsp_crypto_hashing_proc_macro::blake2b_256!(identifier, b"/string"),
//! pezsp_crypto_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())
}
@@ -0,0 +1,164 @@
// This file is part of Bizinikiwi.
// 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()
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn blake2b() {
assert_eq!(pezsp_crypto_hashing_proc_macro::blake2b_64!(b""), blake2_64(b"")[..]);
assert_eq!(pezsp_crypto_hashing_proc_macro::blake2b_256!(b"test"), blake2_256(b"test")[..]);
assert_eq!(pezsp_crypto_hashing_proc_macro::blake2b_512!(b""), blake2_512(b"")[..]);
}
#[test]
fn keccak() {
assert_eq!(pezsp_crypto_hashing_proc_macro::keccak_256!(b"test"), keccak_256(b"test")[..]);
assert_eq!(pezsp_crypto_hashing_proc_macro::keccak_512!(b"test"), keccak_512(b"test")[..]);
}
#[test]
fn sha2() {
assert_eq!(pezsp_crypto_hashing_proc_macro::sha2_256!(b"test"), sha2_256(b"test")[..]);
}
#[test]
fn twox() {
assert_eq!(pezsp_crypto_hashing_proc_macro::twox_128!(b"test"), twox_128(b"test")[..]);
assert_eq!(pezsp_crypto_hashing_proc_macro::twox_64!(b""), twox_64(b"")[..]);
}
#[test]
fn twox_concats() {
assert_eq!(
pezsp_crypto_hashing_proc_macro::twox_128!(b"test", b"123", b"45", b"", b"67890"),
twox_128(&b"test1234567890"[..]),
);
assert_eq!(
pezsp_crypto_hashing_proc_macro::twox_128!(b"test", test, b"45", b"", b"67890"),
twox_128(&b"testtest4567890"[..]),
);
}
}