Skip to content

Commit

Permalink
[refactor]: Remove Box from PrivateKey
Browse files Browse the repository at this point in the history
Signed-off-by: Daniil Polyakov <arjentix@gmail.com>
  • Loading branch information
Arjentix committed Jan 29, 2024
1 parent ae46d36 commit 5b67256
Show file tree
Hide file tree
Showing 7 changed files with 35 additions and 29 deletions.
4 changes: 2 additions & 2 deletions config/src/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub enum ParsedConfiguration {
/// The peer is responsible for submitting the genesis block
Full {
/// Genesis account key pair
key_pair: KeyPair,
key_pair: Box<KeyPair>,
/// Raw genesis block
raw_block: RawGenesisBlock,
},
Expand All @@ -69,7 +69,7 @@ impl Configuration {
.map_err(|report| ParseError::File { path, report })?;

Ok(ParsedConfiguration::Full {
key_pair: KeyPair::new(self.public_key, private_key)?,
key_pair: Box::new(KeyPair::new(self.public_key, private_key)?),
raw_block,
})
}
Expand Down
2 changes: 2 additions & 0 deletions core/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -770,7 +770,9 @@ mod tests {
)
.with_instructions(instructions);
tx.set_ttl(Duration::from_millis(10));
let now = std::time::Instant::now();
let tx = tx.sign(alice_key);
println!("Signing time: {}ms", now.elapsed().as_millis());
let limits = TransactionLimits {
max_instruction_number: 4096,
max_wasm_size_bytes: 0,
Expand Down
12 changes: 6 additions & 6 deletions crypto/src/kex/x25519.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#[cfg(not(feature = "std"))]
use alloc::{borrow::ToOwned as _, boxed::Box};
use alloc::borrow::ToOwned as _;
use core::borrow::Borrow;

use arrayref::array_ref;
use iroha_primitives::const_vec::ConstVec;
Expand Down Expand Up @@ -47,7 +48,7 @@ impl KeyExchangeScheme for X25519Sha256 {
(pk, sk)
}
KeyGenOption::FromPrivateKey(ref s) => {
let crate::PrivateKey::Ed25519(s) = s else {
let crate::PrivateKey::Ed25519(s) = s.borrow() else {
panic!("Wrong private key type, expected `Ed25519`, got {s:?}")
};
let sk = StaticSecret::from(*array_ref!(s.as_bytes(), 0, 32));
Expand All @@ -70,9 +71,7 @@ impl KeyExchangeScheme for X25519Sha256 {
"Ed25519 public key should be possible to create from X25519 public key",
),
),
PrivateKey::Ed25519(Box::new(crate::ed25519::PrivateKey::from_bytes(
sk.as_bytes(),
))),
PrivateKey::Ed25519(crate::ed25519::PrivateKey::from_bytes(sk.as_bytes())),
)
}

Expand Down Expand Up @@ -128,7 +127,8 @@ mod tests {
.unwrap();
assert_eq!(shared_secret1.payload(), shared_secret2.payload());

let (public_key2, _secret_key1) = scheme.keypair(KeyGenOption::FromPrivateKey(secret_key1));
let (public_key2, _secret_key1) =
scheme.keypair(KeyGenOption::FromPrivateKey(Box::new(secret_key1)));
assert_eq!(public_key2, public_key1);
}
}
20 changes: 10 additions & 10 deletions crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub enum KeyGenOption {
/// Use seed
UseSeed(Vec<u8>),
/// Derive from private key
FromPrivateKey(PrivateKey),
FromPrivateKey(Box<PrivateKey>),
}

ffi::ffi_item! {
Expand Down Expand Up @@ -158,9 +158,9 @@ impl KeyGenConfiguration {

/// Construct using private key with [`Ed25519`](Algorithm::Ed25519) algorithm
#[must_use]
pub fn from_private_key(private_key: PrivateKey) -> Self {
pub fn from_private_key(private_key: impl Into<Box<PrivateKey>>) -> Self {
Self {
key_gen_option: KeyGenOption::FromPrivateKey(private_key),
key_gen_option: KeyGenOption::FromPrivateKey(private_key.into()),
algorithm: Algorithm::default(),
}
}
Expand Down Expand Up @@ -253,7 +253,7 @@ impl From<(ed25519::PublicKey, ed25519::PrivateKey)> for KeyPair {
fn from((public_key, private_key): (ed25519::PublicKey, ed25519::PrivateKey)) -> Self {
Self {
public_key: PublicKey::Ed25519(public_key),
private_key: PrivateKey::Ed25519(Box::new(private_key)),
private_key: PrivateKey::Ed25519(private_key),
}
}
}
Expand Down Expand Up @@ -516,7 +516,7 @@ impl PublicKey {
impl From<PrivateKey> for PublicKey {
fn from(private_key: PrivateKey) -> Self {
let digest_function = private_key.algorithm();
let key_gen_option = KeyGenOption::FromPrivateKey(private_key);
let key_gen_option = KeyGenOption::FromPrivateKey(Box::new(private_key));

match digest_function {
Algorithm::Ed25519 => {
Expand All @@ -537,9 +537,9 @@ ffi::ffi_item! {
/// Private Key used in signatures.
#[derive(Clone)]
#[cfg_attr(all(feature = "ffi_export", not(feature = "ffi_import")), ffi_type(opaque))]
#[allow(missing_docs)]
#[allow(missing_docs, variant_size_differences)]
pub enum PrivateKey {
Ed25519(Box<ed25519::PrivateKey>),
Ed25519(ed25519::PrivateKey),
Secp256k1(secp256k1::PrivateKey),
BlsNormal(bls::BlsNormalPrivateKey),
BlsSmall(bls::BlsSmallPrivateKey),
Expand Down Expand Up @@ -568,9 +568,9 @@ impl PrivateKey {
/// - If the given payload is not a valid private key for the given digest function
pub fn from_raw(algorithm: Algorithm, payload: &[u8]) -> Result<Self, ParseError> {
match algorithm {
Algorithm::Ed25519 => ed25519::Ed25519Sha512::parse_private_key(payload)
.map(Box::new)
.map(Self::Ed25519),
Algorithm::Ed25519 => {
ed25519::Ed25519Sha512::parse_private_key(payload).map(Self::Ed25519)
}
Algorithm::Secp256k1 => {
secp256k1::EcdsaSecp256k1Sha256::parse_private_key(payload).map(Self::Secp256k1)
}
Expand Down
12 changes: 6 additions & 6 deletions crypto/src/signature/ed25519.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::convert::TryFrom;
use core::{borrow::Borrow as _, convert::TryFrom};

use arrayref::array_ref;
use ed25519_dalek::Signature;
Expand Down Expand Up @@ -33,7 +33,7 @@ impl Ed25519Sha512 {
PrivateKey::generate(&mut rng)
}
KeyGenOption::FromPrivateKey(ref s) => {
let crate::PrivateKey::Ed25519(s) = s else {
let crate::PrivateKey::Ed25519(s) = s.borrow() else {
panic!("Wrong private key type, expected `Ed25519`, got {s:?}")
};
PrivateKey::clone(s)
Expand Down Expand Up @@ -93,10 +93,10 @@ mod test {
#[test]
fn ed25519_load_keys() {
let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap();
let (p1, s1) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret));
let (p1, s1) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(Box::new(secret)));

assert_eq!(
PrivateKey::Ed25519(Box::new(s1)),
PrivateKey::Ed25519(s1),
PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap()
);
assert_eq!(
Expand All @@ -108,7 +108,7 @@ mod test {
#[test]
fn ed25519_verify() {
let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap();
let (p, _) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret));
let (p, _) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(Box::new(secret)));

Ed25519Sha512::verify(MESSAGE_1, hex::decode(SIGNATURE_1).unwrap().as_slice(), &p).unwrap();

Expand All @@ -129,7 +129,7 @@ mod test {
#[test]
fn ed25519_sign() {
let secret = PrivateKey::from_hex(Algorithm::Ed25519, PRIVATE_KEY).unwrap();
let (p, s) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(secret));
let (p, s) = Ed25519Sha512::keypair(KeyGenOption::FromPrivateKey(Box::new(secret)));

let sig = Ed25519Sha512::sign(MESSAGE_1, &s);
Ed25519Sha512::verify(MESSAGE_1, &sig, &p).unwrap();
Expand Down
3 changes: 3 additions & 0 deletions crypto/src/signature/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ impl<T> SignatureOf<T> {
///
/// # Errors
/// Fails if signing fails
#[inline]
fn from_hash(key_pair: KeyPair, hash: HashOf<T>) -> Self {
Self(Signature::new(key_pair, hash.as_ref()), PhantomData)
}
Expand All @@ -217,6 +218,7 @@ impl<T: parity_scale_codec::Encode> SignatureOf<T> {
///
/// # Errors
/// Fails if signing fails
#[inline]
pub fn new(key_pair: KeyPair, value: &T) -> Self {
Self::from_hash(key_pair, HashOf::new(value))
}
Expand Down Expand Up @@ -469,6 +471,7 @@ impl<T: Encode> SignaturesOf<T> {
///
/// # Errors
/// Forwards [`SignatureOf::new`] errors
#[inline]
pub fn new(key_pair: KeyPair, value: &T) -> Self {
SignatureOf::new(key_pair, value).into()
}
Expand Down
11 changes: 6 additions & 5 deletions crypto/src/signature/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ impl EcdsaSecp256k1Sha256 {
mod ecdsa_secp256k1 {
#[cfg(not(feature = "std"))]
use alloc::{format, string::ToString as _, vec::Vec};
use core::borrow::Borrow;

use arrayref::array_ref;
use digest::Digest as _;
Expand Down Expand Up @@ -68,7 +69,7 @@ mod ecdsa_secp256k1 {
.expect("Creating private key from seed should always succeed")
}
KeyGenOption::FromPrivateKey(ref s) => {
let crate::PrivateKey::Secp256k1(s) = s else {
let crate::PrivateKey::Secp256k1(s) = s.borrow() else {
panic!("Wrong private key type, expected `Secp256k1`, got {s:?}")
};
s.clone()
Expand Down Expand Up @@ -153,9 +154,9 @@ mod test {
#[test]
fn secp256k1_compatibility() {
let secret = private_key();
let (p, s) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(
let (p, s) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(Box::new(
crate::PrivateKey::Secp256k1(secret),
));
)));

let _sk = secp256k1::SecretKey::from_slice(&s.to_bytes()).unwrap();
let _pk = secp256k1::PublicKey::from_slice(&p.to_sec1_bytes()).unwrap();
Expand Down Expand Up @@ -205,9 +206,9 @@ mod test {
#[test]
fn secp256k1_sign() {
let secret = private_key();
let (pk, sk) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(
let (pk, sk) = EcdsaSecp256k1Sha256::keypair(KeyGenOption::FromPrivateKey(Box::new(
crate::PrivateKey::Secp256k1(secret),
));
)));

let sig = EcdsaSecp256k1Sha256::sign(MESSAGE_1, &sk);
EcdsaSecp256k1Sha256::verify(MESSAGE_1, &sig, &pk).unwrap();
Expand Down

0 comments on commit 5b67256

Please sign in to comment.