Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce reliance on blake2 internals, move RequestCommon::*serialize* #2009

Merged
merged 4 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion bls/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ keywords.workspace = true
workspace = true

[dependencies]
blake2-rfc = "0.2"
byteorder = "1.5.0"
hex = "0.4"
log = { package = "tracing", version = "0.1", features = ["log"] }
Expand Down
4 changes: 2 additions & 2 deletions bls/src/types/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::fmt;
use ark_ec::{AffineRepr, Group};
use ark_ff::{One, PrimeField, ToConstraintField};
use ark_mnt6_753::{Fq, G1Affine, G1Projective};
use nimiq_hash::{blake2s::Blake2sWithParameterBlock, HashOutput};
use nimiq_hash::{blake2s::Blake2xParameters, HashOutput};

use crate::{CompressedSignature, SigHash};

Expand Down Expand Up @@ -36,7 +36,7 @@ impl Signature {
let mut bytes = vec![];

for i in 0..3 {
let blake2x = Blake2sWithParameterBlock::new_blake2x(i, 0xffff);
let blake2x = Blake2xParameters::new(i, 0xffff);

let mut result = blake2x.evaluate(hash.as_bytes());

Expand Down
60 changes: 14 additions & 46 deletions hash/src/blake2s.rs
Original file line number Diff line number Diff line change
@@ -1,44 +1,22 @@
use blake2_rfc::blake2s::Blake2s;

#[derive(Clone)]
pub struct Blake2sWithParameterBlock {
pub output_size: u8,
pub key_size: u8,
pub fan_out: u8,
pub depth: u8,
pub leaf_length: u32,
pub node_offset: u32,
pub xof_output_size: u16,
pub node_depth: u8,
pub inner_length: u8,
pub salt: [u8; 8],
pub personalization: [u8; 8],
pub struct Blake2xParameters {
output_size: u8,
key_size: u8,
fan_out: u8,
depth: u8,
leaf_length: u32,
node_offset: u32,
xof_output_size: u16,
node_depth: u8,
inner_length: u8,
salt: [u8; 8],
personalization: [u8; 8],
}

impl Default for Blake2sWithParameterBlock {
fn default() -> Self {
Self::new()
}
}

impl Blake2sWithParameterBlock {
pub fn new() -> Self {
Self {
output_size: 32,
key_size: 0,
fan_out: 1,
depth: 1,
leaf_length: 0,
node_offset: 0,
xof_output_size: 0,
node_depth: 0,
inner_length: 0,
salt: [0; 8],
personalization: [0; 8],
}
}

pub fn new_blake2x(i: usize, xof_output_size: u16) -> Self {
impl Blake2xParameters {
pub fn new(i: usize, xof_output_size: u16) -> Self {
Self {
output_size: 32,
key_size: 0,
Expand Down Expand Up @@ -85,14 +63,4 @@ impl Blake2sWithParameterBlock {
b.update(input);
b.finalize().as_bytes().into()
}

pub fn evaluate_fixed(&self, input: &[u8]) -> [u8; 32] {
let mut b = Blake2s::with_parameter_block(&self.parameters());
b.update(input);
let res = b.finalize();
assert_eq!(res.len(), 32);
let mut ret = [0; 32];
ret.copy_from_slice(res.as_bytes());
ret
}
}
4 changes: 4 additions & 0 deletions network-interface/src/request/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,9 @@ pub trait RequestCommon:
type Response: Deserialize + Serialize + Send;
const MAX_REQUESTS: u32;
const TIME_WINDOW: Duration = DEFAULT_MAX_REQUEST_RESPONSE_TIME_WINDOW;
}

pub trait RequestSerialize: RequestCommon {
/// Serializes a request.
/// A serialized request is composed of:
/// - A varint for the Type ID of the request
Expand Down Expand Up @@ -177,6 +179,8 @@ pub trait RequestCommon:
}
}

impl<T: RequestCommon> RequestSerialize for T {}

pub trait Request: RequestCommon<Kind = RequestMarker> {}
pub trait Message: RequestCommon<Kind = MessageMarker, Response = ()> {}

Expand Down
2 changes: 1 addition & 1 deletion network-libp2p/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use nimiq_network_interface::{
peer_info::{PeerInfo, Services},
request::{
peek_type, InboundRequestError, Message, OutboundRequestError, Request, RequestCommon,
RequestError, RequestType,
RequestError, RequestSerialize, RequestType,
},
};
use nimiq_primitives::task_executor::TaskExecutor;
Expand Down
23 changes: 1 addition & 22 deletions network-libp2p/tests/request_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use nimiq_network_libp2p::{
discovery::{self, peer_contacts::PeerContact},
Config, Network,
};
use nimiq_serde::{Deserialize, DeserializeError, Serialize};
use nimiq_serde::{Deserialize, Serialize};
use nimiq_test_log::test;
use rand::{thread_rng, Rng};
use tokio::time::Duration;
Expand All @@ -47,27 +47,6 @@ impl RequestCommon for TestRequest {
type Response = TestResponse;

const MAX_REQUESTS: u32 = MAX_REQUEST_RESPONSE_TEST_REQUEST;

fn serialize_request(&self) -> Vec<u8> {
let mut data = Vec::with_capacity(self.serialized_request_size());
nimiq_network_interface::request::RequestType::from_request::<Self>()
.serialize_to_writer(&mut data)
.unwrap();
Serialize::serialize_to_writer(self, &mut data).unwrap();
data
}

fn deserialize_request(buffer: &[u8]) -> Result<Self, DeserializeError> {
// Check for correct type.
let (ty, message_buf) = <u16>::deserialize_take(buffer)?;
if ty != nimiq_network_interface::request::RequestType::from_request::<Self>().0 {
return Err(DeserializeError::bad_encoding());
}

let message: Self = Deserialize::deserialize_from_vec(message_buf)?;

Ok(message)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
struct TestResponse {
Expand Down
2 changes: 1 addition & 1 deletion network-mock/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use nimiq_network_interface::{
peer_info::{PeerInfo, Services},
request::{
InboundRequestError, Message, OutboundRequestError, Request, RequestCommon, RequestError,
RequestKind, RequestType,
RequestKind, RequestSerialize, RequestType,
},
};
use nimiq_serde::{Deserialize, DeserializeError, Serialize};
Expand Down
4 changes: 2 additions & 2 deletions zkp-circuits/src/gadgets/mnt6/hash_to_curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use ark_r1cs_std::{
};
use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
use ark_std::Zero;
use nimiq_hash::blake2s::Blake2sWithParameterBlock;
use nimiq_hash::blake2s::Blake2xParameters;

use crate::{blake2s::evaluate_blake2s_with_parameters, gadgets::y_to_bit::YToBitGadget};

Expand All @@ -25,7 +25,7 @@ impl HashToCurve {

for i in 0..3 {
// Initialize Blake2s parameters.
let blake2s_parameters = Blake2sWithParameterBlock::new_blake2x(i, 0xffff);
let blake2s_parameters = Blake2xParameters::new(i, 0xffff);

// Calculate hash.
hash_out.extend(evaluate_blake2s_with_parameters(
Expand Down
12 changes: 4 additions & 8 deletions zkp-primitives/pedersen-generators/src/rand_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
//!
//! 624314 -> 000000000000000000132006558a816203cb442aeb9162ba1d8f6dac5f0a00ec

use nimiq_hash::blake2s::Blake2sWithParameterBlock;
use nimiq_hash::{Blake2bHash, Hash};

/// This function will return 32 verifiably random bytes.
pub fn generate_random_seed(personalization: u64) -> [u8; 32] {
Expand All @@ -75,12 +75,8 @@ pub fn generate_random_seed(personalization: u64) -> [u8; 32] {
"{block_00}{block_01}{block_02}{block_03}{block_04}{block_05}{block_06}{block_07}{block_08}{block_09}{block_10}{block_11}{block_12}{block_13}{block_14}"
);

let random_bytes = hex::decode(concatenated).unwrap();
let mut random_bytes = hex::decode(concatenated).unwrap();
random_bytes.extend_from_slice(&personalization.to_be_bytes());

// Initialize Blake2s parameters.
let mut blake2s = Blake2sWithParameterBlock::new();
blake2s.personalization = personalization.to_be_bytes();

// Calculate the Blake2s hash.
blake2s.evaluate_fixed(random_bytes.as_ref())
random_bytes.hash::<Blake2bHash>().0
}
Loading