Skip to content

Commit

Permalink
feat!: add ciphertext header to ciphertext api
Browse files Browse the repository at this point in the history
  • Loading branch information
piotr-roslaniec committed Aug 16, 2023
1 parent 4337c3c commit 8078fea
Show file tree
Hide file tree
Showing 18 changed files with 246 additions and 113 deletions.
1 change: 1 addition & 0 deletions ferveo-python/ferveo/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
Transcript,
Dkg,
Ciphertext,
CiphertextHeader,
DecryptionShareSimple,
DecryptionSharePrecomputed,
AggregatedTranscript,
Expand Down
13 changes: 13 additions & 0 deletions ferveo-python/ferveo/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,19 @@ class Dkg:

@final
class Ciphertext:
header: CiphertextHeader
payload: bytes

@staticmethod
def from_bytes(data: bytes) -> Ciphertext:
...

def __bytes__(self) -> bytes:
...


@final
class CiphertextHeader:
@staticmethod
def from_bytes(data: bytes) -> Ciphertext:
...
Expand Down
4 changes: 2 additions & 2 deletions ferveo-wasm/tests/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ fn tdec_simple() {
aggregate
.create_decryption_share_simple(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
&aad,
&keypair,
)
Expand Down Expand Up @@ -179,7 +179,7 @@ fn tdec_precomputed() {
aggregate
.create_decryption_share_precomputed(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
&aad,
&keypair,
)
Expand Down
2 changes: 1 addition & 1 deletion ferveo/benches/benchmarks/validity_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn gen_keypairs(num: u32) -> Vec<ferveo_common::Keypair<EllipticCurve>> {
}

pub fn gen_address(i: usize) -> EthereumAddress {
EthereumAddress::from_str(&format!("0x{:040}", i)).unwrap()
EthereumAddress::from_str(&format!("0x{i:040}")).unwrap()
}

fn gen_validators(
Expand Down
7 changes: 3 additions & 4 deletions ferveo/examples/bench_ark_sizes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ pub fn save_data(
let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
writeln!(
file,
"{}|{}|{}|",
n_of_elements, type_of_element, serialized_size_in_bytes
"{n_of_elements}|{type_of_element}|{serialized_size_in_bytes}|"
)
.unwrap();
}
Expand All @@ -66,10 +65,10 @@ fn main() {
.map(|(n, element)| (n, element))
.collect::<BTreeSet<_>>();

println!("Running benchmarks for {:?}", configs);
println!("Running benchmarks for {configs:?}");

for (n, element) in configs {
println!("number_of_elements: {}, type_of_elements: {}", n, element);
println!("number_of_elements: {n}, type_of_elements: {element}");

let g1_affine =
(0..*n).map(|_| G1Affine::rand(rng)).collect::<Vec<_>>();
Expand Down
14 changes: 5 additions & 9 deletions ferveo/examples/bench_primitives_size.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,8 @@ pub fn save_data(

eprintln!("Appending to file: {}", file_path.display());
let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
writeln!(
file,
"{}|{}|{}|",
shares_num, threshold, transcript_size_bytes
)
.unwrap();
writeln!(file, "{shares_num}|{threshold}|{transcript_size_bytes}|")
.unwrap();
}

// TODO: Find a way to deduplicate the following methods with benchmarks and test setup
Expand All @@ -60,7 +56,7 @@ fn gen_keypairs(num: u32) -> Vec<ferveo_common::Keypair<EllipticCurve>> {
}

pub fn gen_address(i: usize) -> EthereumAddress {
EthereumAddress::from_str(&format!("0x{:040}", i)).unwrap()
EthereumAddress::from_str(&format!("0x{i:040}")).unwrap()
}

fn gen_validators(
Expand Down Expand Up @@ -132,10 +128,10 @@ fn main() {
})
.collect::<BTreeSet<_>>();

println!("Running benchmarks for {:?}", configs);
println!("Running benchmarks for {configs:?}");

for (shares_num, threshold) in configs {
println!("shares_num: {}, threshold: {}", shares_num, threshold);
println!("shares_num: {shares_num}, threshold: {threshold}");
let dkg = setup(*shares_num as u32, threshold, rng);
let transcript = &dkg.vss.values().next().unwrap();
let transcript_bytes = bincode::serialize(&transcript).unwrap();
Expand Down
58 changes: 33 additions & 25 deletions ferveo/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use serde::{Deserialize, Serialize};
use serde_with::serde_as;
pub use tpke::api::{
prepare_combine_simple, share_combine_precomputed, share_combine_simple,
Ciphertext, Fr, G1Affine, G1Prepared, SecretBox, E,
Fr, G1Affine, G1Prepared, G2Affine, SecretBox, E,
};

pub type PublicKey = ferveo_common::PublicKey<E>;
Expand Down Expand Up @@ -55,7 +55,7 @@ pub fn encrypt(
) -> Result<Ciphertext> {
let mut rng = rand::thread_rng();
let ciphertext = tpke::api::encrypt(message, aad, &pubkey.0, &mut rng)?;
Ok(ciphertext)
Ok(Ciphertext(ciphertext))
}

pub fn decrypt_with_shared_secret(
Expand All @@ -65,14 +65,31 @@ pub fn decrypt_with_shared_secret(
) -> Result<Vec<u8>> {
let dkg_public_params = DkgPublicParameters::default();
tpke::api::decrypt_with_shared_secret(
ciphertext,
&ciphertext.0,
aad,
&shared_secret.0,
&dkg_public_params.g1_inv,
)
.map_err(Error::from)
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Eq)]
pub struct Ciphertext(tpke::api::Ciphertext);

impl Ciphertext {
pub fn header(&self) -> Result<CiphertextHeader> {
Ok(CiphertextHeader(self.0.header()?))
}

pub fn payload(&self) -> Vec<u8> {
self.0.payload()
}
}

#[serde_as]
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct CiphertextHeader(tpke::api::CiphertextHeader);

/// The ferveo variant to use for the decryption share derivation.
#[derive(
PartialEq, Eq, Debug, Serialize, Deserialize, Copy, Clone, PartialOrd,
Expand Down Expand Up @@ -286,7 +303,7 @@ impl AggregatedTranscript {
pub fn create_decryption_share_precomputed(
&self,
dkg: &Dkg,
ciphertext: &Ciphertext,
ciphertext_header: &CiphertextHeader,
aad: &[u8],
validator_keypair: &Keypair,
) -> Result<DecryptionSharePrecomputed> {
Expand All @@ -297,7 +314,7 @@ impl AggregatedTranscript {
.take(dkg.0.dkg_params.shares_num as usize)
.collect();
self.0.make_decryption_share_simple_precomputed(
ciphertext,
&ciphertext_header.0,
aad,
&validator_keypair.decryption_key,
dkg.0.me.share_index,
Expand All @@ -309,12 +326,12 @@ impl AggregatedTranscript {
pub fn create_decryption_share_simple(
&self,
dkg: &Dkg,
ciphertext: &Ciphertext,
ciphertext_header: &CiphertextHeader,
aad: &[u8],
validator_keypair: &Keypair,
) -> Result<DecryptionShareSimple> {
let share = self.0.make_decryption_share_simple(
ciphertext,
&ciphertext_header.0,
aad,
&validator_keypair.decryption_key,
dkg.0.me.share_index,
Expand Down Expand Up @@ -458,14 +475,10 @@ mod test_ferveo_api {
// In the meantime, the client creates a ciphertext and decryption request
let msg = "my-msg".as_bytes().to_vec();
let aad: &[u8] = "my-aad".as_bytes();
let rng = &mut thread_rng();
let ciphertext = tpke::api::encrypt(
SecretBox::new(msg.clone()),
aad,
&dkg_public_key.0,
rng,
)
.unwrap();
let _rng = &mut thread_rng();
let ciphertext =
encrypt(SecretBox::new(msg.clone()), aad, &dkg_public_key)
.unwrap();

// Having aggregated the transcripts, the validators can now create decryption shares
let decryption_shares: Vec<_> =
Expand All @@ -490,7 +503,7 @@ mod test_ferveo_api {
aggregate
.create_decryption_share_precomputed(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
aad,
validator_keypair,
)
Expand Down Expand Up @@ -557,14 +570,9 @@ mod test_ferveo_api {
// In the meantime, the client creates a ciphertext and decryption request
let msg = "my-msg".as_bytes().to_vec();
let aad: &[u8] = "my-aad".as_bytes();
let rng = &mut thread_rng();
let ciphertext = tpke::api::encrypt(
SecretBox::new(msg.clone()),
aad,
&public_key.0,
rng,
)
.unwrap();
let _rng = &mut thread_rng();
let ciphertext =
encrypt(SecretBox::new(msg.clone()), aad, &public_key).unwrap();

// Having aggregated the transcripts, the validators can now create decryption shares
let decryption_shares: Vec<_> =
Expand All @@ -587,7 +595,7 @@ mod test_ferveo_api {
aggregate
.create_decryption_share_simple(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
aad,
validator_keypair,
)
Expand Down
45 changes: 38 additions & 7 deletions ferveo/src/bindings_python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,38 @@ impl Dkg {
)]
pub struct Ciphertext(api::Ciphertext);

#[pymethods]
impl Ciphertext {
#[getter]
pub fn header(&self) -> PyResult<CiphertextHeader> {
let header = self.0.header().map_err(FerveoPythonError::from)?;
Ok(CiphertextHeader(header))
}

#[getter]
pub fn payload(&self) -> Vec<u8> {
self.0.payload().to_vec()
}
}

generate_bytes_serialization!(Ciphertext);

#[pyclass(module = "ferveo")]
#[derive(
Clone,
Debug,
PartialEq,
Eq,
Serialize,
Deserialize,
derive_more::From,
derive_more::AsRef,
derive_more::Into,
)]
pub struct CiphertextHeader(api::CiphertextHeader);

generate_bytes_serialization!(CiphertextHeader);

#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::AsRef, derive_more::From)]
pub struct DecryptionShareSimple(api::DecryptionShareSimple);
Expand Down Expand Up @@ -555,15 +585,15 @@ impl AggregatedTranscript {
pub fn create_decryption_share_precomputed(
&self,
dkg: &Dkg,
ciphertext: &Ciphertext,
ciphertext_header: &CiphertextHeader,
aad: &[u8],
validator_keypair: &Keypair,
) -> PyResult<DecryptionSharePrecomputed> {
let decryption_share = self
.0
.create_decryption_share_precomputed(
&dkg.0,
&ciphertext.0,
&ciphertext_header.0,
aad,
&validator_keypair.0,
)
Expand All @@ -574,15 +604,15 @@ impl AggregatedTranscript {
pub fn create_decryption_share_simple(
&self,
dkg: &Dkg,
ciphertext: &Ciphertext,
ciphertext_header: &CiphertextHeader,
aad: &[u8],
validator_keypair: &Keypair,
) -> PyResult<DecryptionShareSimple> {
let decryption_share = self
.0
.create_decryption_share_simple(
&dkg.0,
&ciphertext.0,
&ciphertext_header.0,
aad,
&validator_keypair.0,
)
Expand Down Expand Up @@ -628,6 +658,7 @@ pub fn make_ferveo_py_module(py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<Transcript>()?;
m.add_class::<Dkg>()?;
m.add_class::<Ciphertext>()?;
m.add_class::<CiphertextHeader>()?;
m.add_class::<DecryptionShareSimple>()?;
m.add_class::<DecryptionSharePrecomputed>()?;
m.add_class::<AggregatedTranscript>()?;
Expand Down Expand Up @@ -712,7 +743,7 @@ mod test_ferveo_python {
.iter()
.enumerate()
.map(|(i, keypair)| {
Validator::new(format!("0x{:040}", i), &keypair.public_key())
Validator::new(format!("0x{i:040}"), &keypair.public_key())
.unwrap()
})
.collect();
Expand Down Expand Up @@ -799,7 +830,7 @@ mod test_ferveo_python {
aggregate
.create_decryption_share_precomputed(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
aad,
validator_keypair,
)
Expand Down Expand Up @@ -876,7 +907,7 @@ mod test_ferveo_python {
aggregate
.create_decryption_share_simple(
&dkg,
&ciphertext,
&ciphertext.header().unwrap(),
aad,
validator_keypair,
)
Expand Down
Loading

0 comments on commit 8078fea

Please sign in to comment.