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

Changes needed for ACP, ThresholdMessageKit work in nucypher-core #156

Merged
merged 11 commits into from
Aug 27, 2023
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ A preprint paper describing the construction of Ferveo and the novel cryptosyste

## Build

A Rust toolchain with version `>= 1.65.0` is required. In the future, Ferveo will target the `stable` toolchain.
A Rust toolchain with version `>= 1.67.0` is required. In the future, Ferveo will target the `stable` toolchain.
Installation via [rustup](https://rustup.rs/) is recommended.

Run `cargo build --release` to build.
Expand Down
7 changes: 3 additions & 4 deletions ferveo-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ impl fmt::Display for Error {
Error::InvalidByteLength(expected, actual) => {
write!(
f,
"Invalid byte length: expected {}, actual {}",
expected, actual
"Invalid byte length: expected {expected}, actual {actual}"
)
}
Error::SerializationError(e) => {
write!(f, "Serialization error: {}", e)
write!(f, "Serialization error: {e}")
}
Error::InvalidSeedLength(len) => {
write!(f, "Invalid seed length: {}", len)
write!(f, "Invalid seed length: {len}")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion ferveo-python/examples/server_api_precomputed.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def gen_eth_addr(i: int) -> str:

# Create a decryption share for the ciphertext
decryption_share = aggregate.create_decryption_share_precomputed(
dkg, ciphertext, aad, validator_keypair
dkg, ciphertext.header, aad, validator_keypair
)
decryption_shares.append(decryption_share)

Expand Down
2 changes: 1 addition & 1 deletion ferveo-python/examples/server_api_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def gen_eth_addr(i: int) -> str:

# Create a decryption share for the ciphertext
decryption_share = aggregate.create_decryption_share_simple(
dkg, ciphertext, aad, validator_keypair
dkg, ciphertext.header, aad, validator_keypair
)
decryption_shares.append(decryption_share)

Expand Down
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
17 changes: 15 additions & 2 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 Expand Up @@ -159,7 +172,7 @@ class AggregatedTranscript:
def create_decryption_share_simple(
self,
dkg: Dkg,
ciphertext: Ciphertext,
ciphertext_header: CiphertextHeader,
aad: bytes,
validator_keypair: Keypair
) -> DecryptionShareSimple:
Expand All @@ -168,7 +181,7 @@ class AggregatedTranscript:
def create_decryption_share_precomputed(
self,
dkg: Dkg,
ciphertext: Ciphertext,
ciphertext_header: CiphertextHeader,
aad: bytes,
validator_keypair: Keypair
) -> DecryptionSharePrecomputed:
Expand Down
2 changes: 1 addition & 1 deletion ferveo-python/test/test_ferveo.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def scenario_for_variant(variant: FerveoVariant, shares_num, threshold, shares_t
assert pvss_aggregated.verify(shares_num, messages)

decryption_share = decryption_share_for_variant(variant, pvss_aggregated)(
dkg, ciphertext, aad, validator_keypair
dkg, ciphertext.header, aad, validator_keypair
)
decryption_shares.append(decryption_share)

Expand Down
10 changes: 5 additions & 5 deletions ferveo-wasm/examples/node/src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ function setupTest() {
const sharesNum = 4;
const threshold = Math.floor((sharesNum * 2) / 3);

const validator_keypairs: Keypair[] = [];
const validatorKeypairs: Keypair[] = [];
const validators: Validator[] = [];
for (let i = 0; i < sharesNum; i++) {
const keypair = Keypair.random();
validator_keypairs.push(keypair);
validatorKeypairs.push(keypair);
const validator = new Validator(genEthAddr(i), keypair.publicKey);
validators.push(validator);
}
Expand Down Expand Up @@ -66,7 +66,7 @@ function setupTest() {
tau,
sharesNum,
threshold,
validatorKeypairs: validator_keypairs,
validatorKeypairs,
validators,
dkg,
messages,
Expand Down Expand Up @@ -103,7 +103,7 @@ describe("ferveo-wasm", () => {

const decryptionShare = aggregate.createDecryptionShareSimple(
dkg,
ciphertext,
ciphertext.header,
aad,
keypair
);
Expand Down Expand Up @@ -150,7 +150,7 @@ describe("ferveo-wasm", () => {

const decryptionShare = aggregate.createDecryptionSharePrecomputed(
dkg,
ciphertext,
ciphertext.header,
aad,
keypair
);
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
Loading
Loading