Skip to content

Commit

Permalink
fix: dkg serialization in wasm bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-roslaniec committed Jun 16, 2023
1 parent 8b6e6f5 commit 1b017a8
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 16 deletions.
4 changes: 2 additions & 2 deletions ferveo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ zeroize = { version = "1.6.0", default-features = false, features = ["derive"] }

# Shared by Python and WASM bindings
derive_more = { version = "0.99", default-features = false, features = ["from", "as_ref", "into"], optional = true }
generic-array = { version = "0.14.7", optional = true }

# Python bindings
pyo3 = { version = "0.18.2", features = ["macros", "multiple-pymethods"], optional = true }
generic-array = { version = "0.14.7", optional = true }

# WASM bindings
console_error_panic_hook = { version = "0.1.7", optional = true }
Expand All @@ -61,7 +61,7 @@ wasm-bindgen = { version = "0.2.86", features = ["serde-serialize"] }

[features]
bindings-python = ["pyo3", "derive_more", "generic-array"]
bindings-wasm = ["console_error_panic_hook", "derive_more", "getrandom", "js-sys", "wasm-bindgen", "wasm-bindgen-derive"]
bindings-wasm = ["console_error_panic_hook", "derive_more", "getrandom", "js-sys", "wasm-bindgen", "wasm-bindgen-derive", "generic-array"]

[[example]]
name = "bench_primitives_size"
Expand Down
11 changes: 8 additions & 3 deletions ferveo/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::UniformRand;
use bincode;
use ferveo_common::serialization;
use generic_array::{typenum::U48, GenericArray};
use group_threshold_cryptography as tpke;
use rand::RngCore;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -75,12 +76,16 @@ pub struct DkgPublicKey(
);

impl DkgPublicKey {
pub fn to_bytes(&self) -> Result<Vec<u8>> {
to_bytes(&self.0)
pub fn to_bytes(&self) -> Result<GenericArray<u8, U48>> {
let as_bytes = to_bytes(&self.0)?;
Ok(GenericArray::<u8, U48>::from_slice(&as_bytes).to_owned())
}

pub fn from_bytes(bytes: &[u8]) -> Result<DkgPublicKey> {
from_bytes(bytes).map(DkgPublicKey)
let bytes =
GenericArray::<u8, U48>::from_exact_iter(bytes.iter().cloned())
.ok_or(Error::InvalidByteLength(48, bytes.len()))?;
from_bytes(&bytes).map(DkgPublicKey)
}

pub fn serialized_size() -> usize {
Expand Down
20 changes: 9 additions & 11 deletions ferveo/src/bindings_python.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::fmt::{Debug, Formatter};

use ferveo_common::serialization::{FromBytes, ToBytes};
use generic_array::{typenum::U48, GenericArray};
use pyo3::{
basic::CompareOp,
create_exception,
Expand Down Expand Up @@ -89,6 +88,12 @@ impl From<FerveoPythonError> for PyErr {
Error::ArkSerializeError(err) => {
SerializationError::new_err(err.to_string())
}
Error::InvalidByteLength(expected, actual) => {
InvalidByteLength::new_err(format!(
"expected: {}, actual: {}",
expected, actual
))
}
},
_ => default(),
}
Expand Down Expand Up @@ -122,6 +127,7 @@ create_exception!(exceptions, InvalidTranscriptAggregate, PyValueError);
create_exception!(exceptions, ValidatorsNotSorted, PyValueError);
create_exception!(exceptions, ValidatorPublicKeyMismatch, PyValueError);
create_exception!(exceptions, SerializationError, PyValueError);
create_exception!(exceptions, InvalidByteLength, PyValueError);

fn from_py_bytes<T: FromBytes>(bytes: &[u8]) -> PyResult<T> {
T::from_bytes(bytes)
Expand Down Expand Up @@ -343,24 +349,16 @@ pub struct DkgPublicKey(api::DkgPublicKey);
impl DkgPublicKey {
#[staticmethod]
pub fn from_bytes(bytes: &[u8]) -> PyResult<Self> {
let bytes =
GenericArray::<u8, U48>::from_exact_iter(bytes.iter().cloned())
.ok_or_else(|| {
FerveoPythonError::Other(
"Invalid length of bytes for DkgPublicKey".to_string(),
)
})?;
Ok(Self(
api::DkgPublicKey::from_bytes(bytes.as_slice())
api::DkgPublicKey::from_bytes(bytes)
.map_err(FerveoPythonError::FerveoError)?,
))
}

fn __bytes__(&self) -> PyResult<PyObject> {
let bytes =
self.0.to_bytes().map_err(FerveoPythonError::FerveoError)?;
let bytes = GenericArray::<u8, U48>::from_slice(bytes.as_slice());
as_py_bytes(bytes)
as_py_bytes(&bytes)
}

#[staticmethod]
Expand Down
23 changes: 23 additions & 0 deletions ferveo/src/bindings_wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,33 @@ generate_common_methods!(DkgPublicKey);

#[wasm_bindgen]
impl DkgPublicKey {
#[wasm_bindgen(js_name = "fromBytes")]
pub fn from_bytes(bytes: &[u8]) -> JsResult<DkgPublicKey> {
api::DkgPublicKey::from_bytes(bytes)
.map_err(map_js_err)
.map(Self)
}

#[wasm_bindgen(js_name = "toBytes")]
pub fn to_bytes(&self) -> JsResult<Box<[u8]>> {
let bytes = self.0.to_bytes().map_err(map_js_err)?;
let bytes: Box<[u8]> = bytes.as_slice().into();
Ok(bytes)
}

#[wasm_bindgen]
pub fn random() -> DkgPublicKey {
Self(api::DkgPublicKey::random())
}

#[wasm_bindgen]
pub fn serialized_size() -> usize {
api::DkgPublicKey::serialized_size()
}

pub fn equals(&self, other: &DkgPublicKey) -> bool {
self.0 == other.0
}
}

#[wasm_bindgen]
Expand Down
3 changes: 3 additions & 0 deletions ferveo/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ pub enum Error {

#[error(transparent)]
ArkSerializeError(#[from] ark_serialize::SerializationError),

#[error("Invalid byte length. Expected {0}, got {1}")]
InvalidByteLength(usize, usize),
}

pub type Result<T> = std::result::Result<T, Error>;
Expand Down

0 comments on commit 1b017a8

Please sign in to comment.