Skip to content

Commit

Permalink
Add a way to mechanically generate MAX_SIZE constants
Browse files Browse the repository at this point in the history
  • Loading branch information
hrxi committed Jun 12, 2024
1 parent f256ff6 commit 91985e4
Show file tree
Hide file tree
Showing 34 changed files with 498 additions and 169 deletions.
12 changes: 12 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ members = [
"rpc-interface",
"rpc-server",
"serde",
"serde/derive",
"spammer",
"tendermint",
"test-log",
Expand Down
9 changes: 5 additions & 4 deletions bls/src/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,16 +139,17 @@ impl From<LazyPublicKey> for CompressedPublicKey {
}
}

impl LazyPublicKey {
pub const SIZE: usize = CompressedPublicKey::SIZE;
}

#[cfg(feature = "serde-derive")]
mod serialization {
use nimiq_serde::SerializedSize;
use serde::{Deserialize, Serialize};

use super::*;

impl SerializedSize for LazyPublicKey {
const SIZE: usize = CompressedPublicKey::SIZE;
}

impl Serialize for LazyPublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
5 changes: 1 addition & 4 deletions bls/src/types/aggregate_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@ use crate::{CompressedSignature, Signature};
#[derive(Clone, Copy)]
#[cfg_attr(
feature = "serde-derive",
derive(serde::Serialize, serde::Deserialize),
derive(serde::Serialize, serde::Deserialize, nimiq_serde::SerializedSize),
serde(transparent)
)]
pub struct AggregateSignature(pub Signature);

impl AggregateSignature {
/// Maximum size in bytes for a single `AggregateSignature` in binary serialization.
pub const SIZE: usize = Signature::SIZE;

/// Creates a new "empty" aggregate signature. It is simply the identity element of the elliptic curve, also known as the point at infinity.
pub fn new() -> Self {
let signature = G1Projective::zero();
Expand Down
5 changes: 3 additions & 2 deletions bls/src/types/compressed_public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ use crate::PublicKey;
feature = "serde-derive",
derive(
nimiq_hash_derive::SerializeContent,
nimiq_serde::Serialize,
nimiq_serde::Deserialize,
nimiq_serde::Serialize,
nimiq_serde::SerializedMaxSize,
)
)]
#[cfg_attr(feature = "serde-derive", serde(transparent))]
pub struct CompressedPublicKey {
#[cfg_attr(feature = "serde-derive", serde(with = "nimiq_serde::HexArray"))]
pub public_key: [u8; 285],
pub public_key: [u8; CompressedPublicKey::SIZE],
}

impl CompressedPublicKey {
Expand Down
15 changes: 8 additions & 7 deletions bls/src/types/compressed_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};

use crate::Signature;

const SIZE: usize = 95;

/// The serialized compressed form of a signature.
/// This form consists of the x-coordinate of the point (in the affine form),
/// one bit indicating the sign of the y-coordinate
Expand All @@ -19,18 +21,17 @@ use crate::Signature;
feature = "serde-derive",
derive(
nimiq_hash_derive::SerializeContent,
nimiq_serde::Serialize,
nimiq_serde::Deserialize,
nimiq_serde::Serialize,
nimiq_serde::SerializedSize,
)
)]
pub struct CompressedSignature {
#[cfg_attr(feature = "serde-derive", serde(with = "nimiq_serde::HexArray"))]
pub signature: [u8; 95],
pub signature: [u8; SIZE],
}

impl CompressedSignature {
pub const SIZE: usize = 95;

/// Transforms the compressed form back into the projective form.
pub fn uncompress(&self) -> Result<Signature, Error> {
let affine_point: G1Affine =
Expand Down Expand Up @@ -72,7 +73,7 @@ impl PartialOrd<CompressedSignature> for CompressedSignature {
impl Default for CompressedSignature {
fn default() -> Self {
CompressedSignature {
signature: [0u8; CompressedSignature::SIZE],
signature: [0u8; SIZE],
}
}
}
Expand All @@ -91,7 +92,7 @@ impl fmt::Display for CompressedSignature {

impl From<G1Projective> for CompressedSignature {
fn from(signature: G1Projective) -> Self {
let mut buffer = [0u8; CompressedSignature::SIZE];
let mut buffer = [0u8; SIZE];
CanonicalSerialize::serialize_compressed(&signature.into_affine(), &mut &mut buffer[..])
.unwrap();
CompressedSignature { signature: buffer }
Expand Down Expand Up @@ -122,7 +123,7 @@ mod serde_derive {

use std::str::FromStr;

use nimiq_serde::Deserialize;
use nimiq_serde::{Deserialize, SerializedSize};

use super::CompressedSignature;
use crate::ParseError;
Expand Down
16 changes: 10 additions & 6 deletions bls/src/types/secret_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use nimiq_utils::key_rng::{CryptoRng, RngCore, SecureGenerate};

use crate::{CompressedSignature, SigHash, Signature};

const SIZE: usize = 95;

#[derive(Clone, Copy)]
pub struct SecretKey {
/// This is simply a number in the finite field Fr.
Expand All @@ -13,8 +15,6 @@ pub struct SecretKey {
}

impl SecretKey {
pub const SIZE: usize = 95;

/// Creates a signature given a message.
pub fn sign<M: Hash>(&self, msg: &M) -> Signature {
self.sign_hash(msg.hash())
Expand Down Expand Up @@ -64,13 +64,13 @@ mod serde_derive {

use ark_mnt6_753::Fr;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use nimiq_serde::Serialize as NimiqSerialize;
use nimiq_serde::{Serialize as _, SerializedSize};
use serde::{
de::{Deserialize, Deserializer, Error as SerializationError},
ser::{Error as DeSerializationError, Serialize, Serializer},
};

use super::SecretKey;
use super::{SecretKey, SIZE};

impl fmt::Display for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
Expand All @@ -84,12 +84,16 @@ mod serde_derive {
}
}

impl SerializedSize for SecretKey {
const SIZE: usize = SIZE;
}

impl Serialize for SecretKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut compressed = [0u8; Self::SIZE];
let mut compressed = [0u8; SIZE];
self.secret_key
.serialize_uncompressed(&mut compressed[..])
.map_err(|_| S::Error::custom("Couldn't compress secret key"))?;
Expand All @@ -105,7 +109,7 @@ mod serde_derive {
where
D: Deserializer<'de>,
{
let compressed: [u8; Self::SIZE] =
let compressed: [u8; SIZE] =
nimiq_serde::FixedSizeByteArray::deserialize(deserializer)?.into_inner();
Ok(SecretKey {
secret_key: Fr::deserialize_uncompressed(&*compressed.to_vec())
Expand Down
8 changes: 5 additions & 3 deletions bls/src/types/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@ pub struct Signature {
}

impl Signature {
/// Maximum size in bytes for a single `Signature` in binary serialization.
pub const SIZE: usize = CompressedSignature::SIZE;

/// Maps an hash to a elliptic curve point in the G1 group, it is known as
/// "hash-to-curve". It is required to create signatures. We use the
/// try-and-increment method to create the EC point.
Expand Down Expand Up @@ -139,13 +136,18 @@ impl From<G1Projective> for Signature {
#[cfg(feature = "serde-derive")]
mod serde_derive {
// TODO: Replace this with a generic serialization using `ToHex` and `FromHex`.
use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::{CompressedSignature, Signature};

impl SerializedSize for Signature {
const SIZE: usize = CompressedSignature::SIZE;
}

impl Serialize for Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
3 changes: 2 additions & 1 deletion collections/src/bitset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign},
};

use nimiq_serde::SerializedMaxSize as _;
use serde::{
de::{Error as _, SeqAccess, Visitor},
ser::SerializeSeq,
Expand Down Expand Up @@ -374,7 +375,7 @@ impl BitSet {
/// Maximum size in bytes for a single `BitSet` in binary serialization.
pub const fn max_size(largest_bit_index: usize) -> usize {
let num_u64 = (largest_bit_index + 63) / 64;
nimiq_serde::vec_max_size(nimiq_serde::U64_MAX_SIZE, num_u64)
nimiq_serde::seq_max_size(u64::MAX_SIZE, num_u64)
}
}

Expand Down
5 changes: 5 additions & 0 deletions keys/src/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,13 +227,18 @@ impl FromDatabaseValue for Address {
mod serde_derive {
use std::borrow::Cow;

use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::Address;

impl SerializedSize for Address {
const SIZE: usize = Address::SIZE;
}

impl Serialize for Address {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
5 changes: 5 additions & 0 deletions keys/src/es256_public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,18 @@ impl std::hash::Hash for ES256PublicKey {
mod serde_derive {
use std::borrow::Cow;

use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::ES256PublicKey;

impl SerializedSize for ES256PublicKey {
const SIZE: usize = ES256PublicKey::SIZE;
}

impl Serialize for ES256PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
5 changes: 5 additions & 0 deletions keys/src/es256_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,18 @@ impl FromStr for ES256Signature {
mod serde_derive {
use std::borrow::Cow;

use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::ES256Signature;

impl SerializedSize for ES256Signature {
const SIZE: usize = ES256Signature::SIZE;
}

impl Serialize for ES256Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
5 changes: 5 additions & 0 deletions keys/src/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,18 @@ impl std::hash::Hash for Ed25519PublicKey {
mod serde_derive {
use std::borrow::Cow;

use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::Ed25519PublicKey;

impl SerializedSize for Ed25519PublicKey {
const SIZE: usize = Ed25519PublicKey::SIZE;
}

impl Serialize for Ed25519PublicKey {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
5 changes: 5 additions & 0 deletions keys/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,18 @@ impl FromStr for Ed25519Signature {
mod serde_derive {
use std::borrow::Cow;

use nimiq_serde::SerializedSize;
use serde::{
de::{Deserialize, Deserializer, Error},
ser::{Serialize, Serializer},
};

use super::Ed25519Signature;

impl SerializedSize for Ed25519Signature {
const SIZE: usize = Ed25519Signature::SIZE;
}

impl Serialize for Ed25519Signature {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
4 changes: 4 additions & 0 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ macro_rules! create_typed_array {
#[macro_export]
macro_rules! add_serialization_fns_typed_arr {
($name: ident, $len: expr) => {
impl ::nimiq_macros::nimiq_serde::SerializedSize for $name {
const SIZE: usize = $len;
}

impl ::nimiq_macros::serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
Expand Down
8 changes: 5 additions & 3 deletions network-libp2p/src/discovery/message_codec/header.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use nimiq_serde::{fixint, Deserialize, Serialize};
use nimiq_serde::{fixint, Deserialize, Serialize, SerializedSize};

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Header {
Expand All @@ -10,11 +10,13 @@ pub struct Header {
pub checksum: u32,
}

impl SerializedSize for Header {
const SIZE: usize = 12;
}

impl Header {
pub const MAGIC: u32 = 0x4204_2042;

pub const SIZE: usize = 12;

pub fn new(size: u32) -> Self {
Self {
magic: Self::MAGIC,
Expand Down
4 changes: 2 additions & 2 deletions network-libp2p/src/discovery/message_codec/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{

use bytes::BytesMut;
use futures::{AsyncRead, Stream};
use nimiq_serde::{Deserialize, DeserializeError};
use nimiq_serde::{Deserialize, DeserializeError, SerializedSize as _};
use pin_project::pin_project;

use super::header::Header;
Expand Down Expand Up @@ -230,7 +230,7 @@ mod tests {

use bytes::{BufMut, BytesMut};
use futures::{io::Cursor, StreamExt};
use nimiq_serde::{Deserialize, Serialize};
use nimiq_serde::{Deserialize, Serialize, SerializedSize};
use nimiq_test_log::test;

use super::{Header, MessageReader};
Expand Down
Loading

0 comments on commit 91985e4

Please sign in to comment.