From aa75f85e17699cb84926fa33b1cd800d18abac6e Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Tue, 24 Jan 2023 15:11:22 +0100
Subject: [PATCH 01/36] add a benchmark sketch
---
tpke/README.md | 11 ++-
tpke/examples/bench_primitives_size.rs | 98 ++++++++++++++++++++++++++
tpke/src/lib.rs | 4 +-
3 files changed, 110 insertions(+), 3 deletions(-)
create mode 100644 tpke/examples/bench_primitives_size.rs
diff --git a/tpke/README.md b/tpke/README.md
index cf7ddad7..89a0d94b 100644
--- a/tpke/README.md
+++ b/tpke/README.md
@@ -1,9 +1,18 @@
# tpke
-## Benchmarking WASM
+## Benchmarks
+
+### Benchmarking WASM
Based on `centurion.rs` (docs)[https://github.com/bheisler/criterion.rs/blob/version-0.4/book/src/user_guide/wasi.md#webasseblywasi-benchmarking]
+### Benchmarking primitives size
+
+```sh
+cargo run --example bench_primitives_size
+```
+
+
### Setup
```bash
diff --git a/tpke/examples/bench_primitives_size.rs b/tpke/examples/bench_primitives_size.rs
new file mode 100644
index 00000000..f7c691a1
--- /dev/null
+++ b/tpke/examples/bench_primitives_size.rs
@@ -0,0 +1,98 @@
+use ark_serialize::CanonicalSerialize;
+use group_threshold_cryptography::{
+ encrypt, prepare_combine_simple, setup_simple, share_combine_simple,
+};
+use rand_core::RngCore;
+use std::fs::{create_dir_all, OpenOptions};
+use std::io::prelude::*;
+use std::path::Path;
+
+pub fn update_benchmark(
+ threshold: usize,
+ shares_num: usize,
+ pubkey_share_serialized_size: usize,
+ privkey_share_serialized_size: usize,
+) {
+ let dir_path = Path::new("/tmp/benchmark_setup");
+ create_dir_all(dir_path).unwrap();
+
+ let file_path = dir_path.join("results.md");
+ eprintln!("Saving setup results to file: {}", file_path.display());
+
+ if !file_path.exists() {
+ let mut file = OpenOptions::new()
+ .create(true)
+ .write(true)
+ .open(&file_path)
+ .unwrap();
+
+ writeln!(
+ file,
+ "|threshold|shares_num|pubkey_share_serialized_size|privkey_share_serialized_size|",
+ )
+ .unwrap();
+
+ writeln!(file, "|---|---|---|---|",).unwrap();
+ }
+
+ let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
+
+ writeln!(
+ file,
+ "|{}|{}|{}|{}|",
+ threshold,
+ shares_num,
+ pubkey_share_serialized_size,
+ privkey_share_serialized_size,
+ )
+ .unwrap();
+}
+
+type E = ark_bls12_381::Bls12_381;
+
+fn main() {
+ for shares_num in [2, 4, 8, 16, 32, 64] {
+ let rng = &mut rand::thread_rng();
+
+ let msg_size = 256;
+ let threshold = shares_num * 2 / 3;
+
+ let mut msg: Vec = vec![0u8; msg_size];
+ rng.fill_bytes(&mut msg[..]);
+ let aad: &[u8] = "my-aad".as_bytes();
+
+ let (pubkey, _privkey, contexts) =
+ setup_simple::(threshold, shares_num, rng);
+
+ // Ciphertext.commitment is already computed to match U
+ let ciphertext = encrypt::<_, E>(&msg, aad, &pubkey, rng);
+
+ // Creating decryption shares
+ let decryption_shares: Vec<_> = contexts
+ .iter()
+ .map(|context| context.create_share(&ciphertext))
+ .collect();
+
+ let pub_contexts = &contexts[0].public_decryption_contexts;
+ let domain: Vec<_> = pub_contexts.iter().map(|c| c.domain).collect();
+ let lagrange = prepare_combine_simple::(&domain);
+
+ let _shared_secret =
+ share_combine_simple::(&decryption_shares, &lagrange);
+
+ let pub_context = &contexts[0].public_decryption_contexts[0];
+
+ update_benchmark(
+ threshold,
+ shares_num,
+ pub_context
+ .public_key_share
+ .public_key_share
+ .serialized_size(),
+ contexts[0]
+ .private_key_share
+ .private_key_share
+ .serialized_size(),
+ );
+ }
+}
diff --git a/tpke/src/lib.rs b/tpke/src/lib.rs
index b2be3ff6..e7e1c0ae 100644
--- a/tpke/src/lib.rs
+++ b/tpke/src/lib.rs
@@ -208,7 +208,7 @@ pub fn setup_simple(
let pubkey_shares =
subproductdomain::fast_multiexp(&evals.evals, g.into_projective());
let pubkey_share = g.mul(evals.evals[0]);
- assert!(pubkey_shares[0] == E::G1Affine::from(pubkey_share));
+ debug_assert!(pubkey_shares[0] == E::G1Affine::from(pubkey_share));
// Y, but only when b = 1 - private key shares of participants
let privkey_shares =
@@ -221,7 +221,7 @@ pub fn setup_simple(
let privkey = h.mul(x);
let secret = threshold_poly.evaluate(&E::Fr::zero());
- assert_eq!(secret, x);
+ debug_assert!(secret == x);
let mut private_contexts = vec![];
let mut public_contexts = vec![];
From 6c28d48ddc8aa0805b0fdb634564a627baf1f52f Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Fri, 27 Jan 2023 13:31:48 +0100
Subject: [PATCH 02/36] benchmark size of pvss transcripts
---
Cargo.lock | 15 ++--
ferveo/Cargo.toml | 3 +-
ferveo/README.md | 9 ++
ferveo/examples/bench_primitives_size.rs | 107 +++++++++++++++++++++++
tpke/README.md | 7 --
tpke/examples/bench_primitives_size.rs | 98 ---------------------
6 files changed, 126 insertions(+), 113 deletions(-)
create mode 100644 ferveo/README.md
create mode 100644 ferveo/examples/bench_primitives_size.rs
delete mode 100644 tpke/examples/bench_primitives_size.rs
diff --git a/Cargo.lock b/Cargo.lock
index 6e875f54..3384344a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -673,7 +673,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
- "rand_core 0.6.3",
+ "rand_core 0.6.4",
"typenum",
]
@@ -902,6 +902,7 @@ dependencies = [
"pprof",
"rand 0.7.3",
"rand 0.8.5",
+ "rand_core 0.6.4",
"serde",
"serde_bytes",
"serde_json",
@@ -1002,7 +1003,7 @@ dependencies = [
"itertools",
"miracl_core",
"rand 0.8.5",
- "rand_core 0.6.3",
+ "rand_core 0.6.4",
"rayon",
"serde",
"serde_with",
@@ -1647,7 +1648,7 @@ checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha 0.3.1",
- "rand_core 0.6.3",
+ "rand_core 0.6.4",
]
[[package]]
@@ -1667,7 +1668,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
- "rand_core 0.6.3",
+ "rand_core 0.6.4",
]
[[package]]
@@ -1681,9 +1682,9 @@ dependencies = [
[[package]]
name = "rand_core"
-version = "0.6.3"
+version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.7",
]
@@ -2156,7 +2157,7 @@ dependencies = [
"group-threshold-cryptography",
"js-sys",
"rand 0.8.5",
- "rand_core 0.6.3",
+ "rand_core 0.6.4",
"serde",
"serde_with",
"wasm-bindgen",
diff --git a/ferveo/Cargo.toml b/ferveo/Cargo.toml
index 007ac763..37015d77 100644
--- a/ferveo/Cargo.toml
+++ b/ferveo/Cargo.toml
@@ -40,6 +40,7 @@ ark-ed-on-bls12-381 = "0.3.0"
group-threshold-cryptography = { path = "../tpke" }
ferveo-common = { path = "../ferveo-common" }
subproductdomain = { path = "../subproductdomain" }
+rand_core = "0.6.4"
[dependencies.digest]
version = "0.10.0"
@@ -60,4 +61,4 @@ harness = false
[profile.release]
opt-level = 3
-lto = true
\ No newline at end of file
+lto = true
diff --git a/ferveo/README.md b/ferveo/README.md
new file mode 100644
index 00000000..6b63e57b
--- /dev/null
+++ b/ferveo/README.md
@@ -0,0 +1,9 @@
+# ferveo
+
+## Benchmarks
+
+### Benchmarking primitives size
+
+```sh
+cargo run --example bench_primitives_size
+```
diff --git a/ferveo/examples/bench_primitives_size.rs b/ferveo/examples/bench_primitives_size.rs
new file mode 100644
index 00000000..500993ae
--- /dev/null
+++ b/ferveo/examples/bench_primitives_size.rs
@@ -0,0 +1,107 @@
+use ark_serialize::CanonicalSerialize;
+
+use ark_bls12_381::Bls12_381 as EllipticCurve;
+use ferveo::*;
+use ferveo_common::ExternalValidator;
+use rand::prelude::StdRng;
+use rand_core::SeedableRng;
+use std::fs::{create_dir_all, OpenOptions};
+use std::io::prelude::*;
+use std::path::Path;
+
+pub fn save_data(threshold: usize, shares_num: usize, transcript_size: usize) {
+ let dir_path = Path::new("/tmp/benchmark_setup");
+ create_dir_all(dir_path).unwrap();
+ let file_path = dir_path.join("results.md");
+
+ if !file_path.exists() {
+ eprintln!("Creating a new file: {}", file_path.display());
+ let mut file = OpenOptions::new()
+ .create(true)
+ .write(true)
+ .open(&file_path)
+ .unwrap();
+ writeln!(file, "|threshold|shares_num|pvss_transcript_size|",).unwrap();
+ writeln!(file, "|---|---|---|",).unwrap();
+ }
+
+ eprintln!("Appending to file: {}", file_path.display());
+ let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
+ writeln!(file, "|{}|{}|{}|", threshold, shares_num, transcript_size,)
+ .unwrap();
+}
+
+// TODO: Find a way to deduplicate the following methods with benchmarks and test setup
+
+fn gen_keypairs(num: u32) -> Vec> {
+ let rng = &mut ark_std::test_rng();
+ (0..num)
+ .map(|_| ferveo_common::Keypair::::new(rng))
+ .collect()
+}
+
+fn gen_validators(
+ keypairs: &[ferveo_common::Keypair],
+) -> Vec> {
+ (0..keypairs.len())
+ .map(|i| ExternalValidator {
+ address: format!("validator_{}", i),
+ public_key: keypairs[i].public(),
+ })
+ .collect()
+}
+
+fn setup_dkg(
+ validator: usize,
+ shares_num: u32,
+) -> PubliclyVerifiableDkg {
+ let keypairs = gen_keypairs(shares_num);
+ let validators = gen_validators(&keypairs);
+ let me = validators[validator].clone();
+ PubliclyVerifiableDkg::new(
+ validators,
+ Params {
+ tau: 0,
+ security_threshold: shares_num / 3,
+ shares_num,
+ retry_after: 1,
+ },
+ &me,
+ keypairs[validator],
+ )
+ .expect("Setup failed")
+}
+
+fn setup(
+ shares_num: u32,
+ rng: &mut StdRng,
+) -> PubliclyVerifiableDkg {
+ let mut transcripts = vec![];
+ for i in 0..shares_num {
+ let mut dkg = setup_dkg(i as usize, shares_num);
+ transcripts.push(dkg.share(rng).expect("Test failed"));
+ }
+
+ let mut dkg = setup_dkg(0, shares_num);
+ for (sender, pvss) in transcripts.into_iter().enumerate() {
+ dkg.apply_message(dkg.validators[sender].validator.clone(), pvss)
+ .expect("Setup failed");
+ }
+ dkg
+}
+
+fn main() {
+ let rng = &mut StdRng::seed_from_u64(0);
+
+ for shares_num in [2, 4, 8, 16, 32, 64] {
+ let dkg = setup(shares_num as u32, rng);
+ let mut transcript_bytes = vec![];
+ dkg.vss[&0].serialize(&mut transcript_bytes).unwrap();
+
+ save_data(
+ dkg.params.security_threshold as usize,
+ shares_num,
+ transcript_bytes.len(),
+ );
+ }
+}
diff --git a/tpke/README.md b/tpke/README.md
index 89a0d94b..e48dc7ea 100644
--- a/tpke/README.md
+++ b/tpke/README.md
@@ -6,13 +6,6 @@
Based on `centurion.rs` (docs)[https://github.com/bheisler/criterion.rs/blob/version-0.4/book/src/user_guide/wasi.md#webasseblywasi-benchmarking]
-### Benchmarking primitives size
-
-```sh
-cargo run --example bench_primitives_size
-```
-
-
### Setup
```bash
diff --git a/tpke/examples/bench_primitives_size.rs b/tpke/examples/bench_primitives_size.rs
deleted file mode 100644
index f7c691a1..00000000
--- a/tpke/examples/bench_primitives_size.rs
+++ /dev/null
@@ -1,98 +0,0 @@
-use ark_serialize::CanonicalSerialize;
-use group_threshold_cryptography::{
- encrypt, prepare_combine_simple, setup_simple, share_combine_simple,
-};
-use rand_core::RngCore;
-use std::fs::{create_dir_all, OpenOptions};
-use std::io::prelude::*;
-use std::path::Path;
-
-pub fn update_benchmark(
- threshold: usize,
- shares_num: usize,
- pubkey_share_serialized_size: usize,
- privkey_share_serialized_size: usize,
-) {
- let dir_path = Path::new("/tmp/benchmark_setup");
- create_dir_all(dir_path).unwrap();
-
- let file_path = dir_path.join("results.md");
- eprintln!("Saving setup results to file: {}", file_path.display());
-
- if !file_path.exists() {
- let mut file = OpenOptions::new()
- .create(true)
- .write(true)
- .open(&file_path)
- .unwrap();
-
- writeln!(
- file,
- "|threshold|shares_num|pubkey_share_serialized_size|privkey_share_serialized_size|",
- )
- .unwrap();
-
- writeln!(file, "|---|---|---|---|",).unwrap();
- }
-
- let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
-
- writeln!(
- file,
- "|{}|{}|{}|{}|",
- threshold,
- shares_num,
- pubkey_share_serialized_size,
- privkey_share_serialized_size,
- )
- .unwrap();
-}
-
-type E = ark_bls12_381::Bls12_381;
-
-fn main() {
- for shares_num in [2, 4, 8, 16, 32, 64] {
- let rng = &mut rand::thread_rng();
-
- let msg_size = 256;
- let threshold = shares_num * 2 / 3;
-
- let mut msg: Vec = vec![0u8; msg_size];
- rng.fill_bytes(&mut msg[..]);
- let aad: &[u8] = "my-aad".as_bytes();
-
- let (pubkey, _privkey, contexts) =
- setup_simple::(threshold, shares_num, rng);
-
- // Ciphertext.commitment is already computed to match U
- let ciphertext = encrypt::<_, E>(&msg, aad, &pubkey, rng);
-
- // Creating decryption shares
- let decryption_shares: Vec<_> = contexts
- .iter()
- .map(|context| context.create_share(&ciphertext))
- .collect();
-
- let pub_contexts = &contexts[0].public_decryption_contexts;
- let domain: Vec<_> = pub_contexts.iter().map(|c| c.domain).collect();
- let lagrange = prepare_combine_simple::(&domain);
-
- let _shared_secret =
- share_combine_simple::(&decryption_shares, &lagrange);
-
- let pub_context = &contexts[0].public_decryption_contexts[0];
-
- update_benchmark(
- threshold,
- shares_num,
- pub_context
- .public_key_share
- .public_key_share
- .serialized_size(),
- contexts[0]
- .private_key_share
- .private_key_share
- .serialized_size(),
- );
- }
-}
From feb8d8077564b43a5dae255b30e842ae75e2e85b Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Fri, 27 Jan 2023 16:32:55 +0100
Subject: [PATCH 03/36] benchmark per ratio with no duplicates
---
ferveo/examples/bench_primitives_size.rs | 75 ++++++++++++++++--------
1 file changed, 52 insertions(+), 23 deletions(-)
diff --git a/ferveo/examples/bench_primitives_size.rs b/ferveo/examples/bench_primitives_size.rs
index 500993ae..56655aa3 100644
--- a/ferveo/examples/bench_primitives_size.rs
+++ b/ferveo/examples/bench_primitives_size.rs
@@ -1,33 +1,43 @@
use ark_serialize::CanonicalSerialize;
+use std::collections::BTreeSet;
use ark_bls12_381::Bls12_381 as EllipticCurve;
use ferveo::*;
use ferveo_common::ExternalValidator;
+use itertools::iproduct;
use rand::prelude::StdRng;
use rand_core::SeedableRng;
use std::fs::{create_dir_all, OpenOptions};
use std::io::prelude::*;
-use std::path::Path;
+use std::path::PathBuf;
-pub fn save_data(threshold: usize, shares_num: usize, transcript_size: usize) {
- let dir_path = Path::new("/tmp/benchmark_setup");
+const OUTPUT_DIR_PATH: &str = "/tmp/benchmark_setup";
+const OUTPUT_FILE_NAME: &str = "results.md";
+
+pub fn create_or_truncate_output_file() -> std::io::Result<()> {
+ let file_path = PathBuf::from(OUTPUT_DIR_PATH).join(OUTPUT_FILE_NAME);
+ eprintln!("Creating output file at {}", file_path.display());
+
+ let dir_path = PathBuf::from(OUTPUT_DIR_PATH);
create_dir_all(dir_path).unwrap();
- let file_path = dir_path.join("results.md");
-
- if !file_path.exists() {
- eprintln!("Creating a new file: {}", file_path.display());
- let mut file = OpenOptions::new()
- .create(true)
- .write(true)
- .open(&file_path)
- .unwrap();
- writeln!(file, "|threshold|shares_num|pvss_transcript_size|",).unwrap();
- writeln!(file, "|---|---|---|",).unwrap();
- }
+
+ let mut file = OpenOptions::new()
+ .write(true)
+ .create(true)
+ .truncate(true)
+ .open(file_path)?;
+ file.sync_all()?;
+
+ writeln!(file, "|shares_num|threshold|pvss_transcript_size|",)?;
+ writeln!(file, "|---|---|---|---|")
+}
+
+pub fn save_data(shares_num: usize, threshold: usize, transcript_size: usize) {
+ let file_path = PathBuf::from(OUTPUT_DIR_PATH).join(OUTPUT_FILE_NAME);
eprintln!("Appending to file: {}", file_path.display());
let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
- writeln!(file, "|{}|{}|{}|", threshold, shares_num, transcript_size,)
+ writeln!(file, "{}|{}|{}|", shares_num, threshold, transcript_size)
.unwrap();
}
@@ -54,6 +64,7 @@ fn gen_validators(
fn setup_dkg(
validator: usize,
shares_num: u32,
+ security_threshold: u32,
) -> PubliclyVerifiableDkg {
let keypairs = gen_keypairs(shares_num);
let validators = gen_validators(&keypairs);
@@ -62,7 +73,7 @@ fn setup_dkg(
validators,
Params {
tau: 0,
- security_threshold: shares_num / 3,
+ security_threshold,
shares_num,
retry_after: 1,
},
@@ -74,15 +85,16 @@ fn setup_dkg(
fn setup(
shares_num: u32,
+ security_threshold: u32,
rng: &mut StdRng,
) -> PubliclyVerifiableDkg {
let mut transcripts = vec![];
for i in 0..shares_num {
- let mut dkg = setup_dkg(i as usize, shares_num);
+ let mut dkg = setup_dkg(i as usize, shares_num, security_threshold);
transcripts.push(dkg.share(rng).expect("Test failed"));
}
- let mut dkg = setup_dkg(0, shares_num);
+ let mut dkg = setup_dkg(0, shares_num, security_threshold);
for (sender, pvss) in transcripts.into_iter().enumerate() {
dkg.apply_message(dkg.validators[sender].validator.clone(), pvss)
.expect("Setup failed");
@@ -93,14 +105,31 @@ fn setup(
fn main() {
let rng = &mut StdRng::seed_from_u64(0);
- for shares_num in [2, 4, 8, 16, 32, 64] {
- let dkg = setup(shares_num as u32, rng);
+ create_or_truncate_output_file().unwrap();
+
+ let share_num_vec = [2, 4, 8, 16, 32, 64];
+ let threshold_ratio_vec = [0.51, 0.66, 0.8, 1.0];
+
+ // Create benchmark parameters without duplicates
+ let configs = iproduct!(&share_num_vec, &threshold_ratio_vec)
+ .map(|(shares_num, threshold_ratio)| {
+ let threshold =
+ (*shares_num as f64 * threshold_ratio).ceil() as u32;
+ (shares_num, threshold)
+ })
+ .collect::>();
+
+ println!("Running benchmarks for {:?}", configs);
+
+ for (shares_num, threshold) in configs {
+ println!("shares_num: {}, threshold: {}", shares_num, threshold);
+ let dkg = setup(*shares_num as u32, threshold, rng);
let mut transcript_bytes = vec![];
dkg.vss[&0].serialize(&mut transcript_bytes).unwrap();
save_data(
- dkg.params.security_threshold as usize,
- shares_num,
+ threshold as usize,
+ *shares_num as usize,
transcript_bytes.len(),
);
}
From 076f2610c753bb02cd5fe5a2219679f63cdffdea Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Fri, 27 Jan 2023 18:04:18 +0100
Subject: [PATCH 04/36] fix switched columns
---
ferveo/examples/bench_primitives_size.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/ferveo/examples/bench_primitives_size.rs b/ferveo/examples/bench_primitives_size.rs
index 56655aa3..c03a6a94 100644
--- a/ferveo/examples/bench_primitives_size.rs
+++ b/ferveo/examples/bench_primitives_size.rs
@@ -128,8 +128,8 @@ fn main() {
dkg.vss[&0].serialize(&mut transcript_bytes).unwrap();
save_data(
- threshold as usize,
*shares_num as usize,
+ threshold as usize,
transcript_bytes.len(),
);
}
From 6966b28e3ee273f51c73402ac986a03e10743139 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Fri, 27 Jan 2023 22:50:21 +0100
Subject: [PATCH 05/36] set polynomial degree to t-1 in pvss
---
ferveo/src/vss/pvss.rs | 9 +++------
1 file changed, 3 insertions(+), 6 deletions(-)
diff --git a/ferveo/src/vss/pvss.rs b/ferveo/src/vss/pvss.rs
index 719a0ab0..d622e009 100644
--- a/ferveo/src/vss/pvss.rs
+++ b/ferveo/src/vss/pvss.rs
@@ -72,7 +72,7 @@ impl PubliclyVerifiableSS {
) -> Result {
// Our random polynomial, \phi(x) = s + \sum_{i=1}^{t-1} a_i x^i
let mut phi = DensePolynomial::::rand(
- (dkg.params.shares_num - dkg.params.security_threshold) as usize,
+ (dkg.params.security_threshold - 1) as usize,
rng,
);
phi.coeffs[0] = *s; // setting the first coefficient to secret value
@@ -302,10 +302,7 @@ mod test_pvss {
// check that the chosen secret coefficient is correct
assert_eq!(pvss.coeffs[0], G1::prime_subgroup_generator().mul(s));
//check that a polynomial of the correct degree was created
- assert_eq!(
- pvss.coeffs.len(),
- dkg.params.security_threshold as usize + 1
- );
+ assert_eq!(pvss.coeffs.len(), dkg.params.security_threshold as usize);
// check that the correct number of shares were created
assert_eq!(pvss.shares.len(), dkg.validators.len());
// check that the prove of knowledge is correct
@@ -344,7 +341,7 @@ mod test_pvss {
//check that a polynomial of the correct degree was created
assert_eq!(
aggregate.coeffs.len(),
- dkg.params.security_threshold as usize + 1
+ dkg.params.security_threshold as usize
);
// check that the correct number of shares were created
assert_eq!(aggregate.shares.len(), dkg.validators.len());
From 6f1b7d4c7086517f7960a0388acd17baf78504b1 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Mon, 30 Jan 2023 10:53:55 +0100
Subject: [PATCH 06/36] size is expressed in bytes
---
ferveo/examples/bench_primitives_size.rs | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
diff --git a/ferveo/examples/bench_primitives_size.rs b/ferveo/examples/bench_primitives_size.rs
index c03a6a94..e7a0857b 100644
--- a/ferveo/examples/bench_primitives_size.rs
+++ b/ferveo/examples/bench_primitives_size.rs
@@ -28,17 +28,25 @@ pub fn create_or_truncate_output_file() -> std::io::Result<()> {
.open(file_path)?;
file.sync_all()?;
- writeln!(file, "|shares_num|threshold|pvss_transcript_size|",)?;
+ writeln!(file, "|shares_num|threshold|pvss_transcript_size_bytes|",)?;
writeln!(file, "|---|---|---|---|")
}
-pub fn save_data(shares_num: usize, threshold: usize, transcript_size: usize) {
+pub fn save_data(
+ shares_num: usize,
+ threshold: usize,
+ transcript_size_bytes: usize,
+) {
let file_path = PathBuf::from(OUTPUT_DIR_PATH).join(OUTPUT_FILE_NAME);
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)
- .unwrap();
+ writeln!(
+ file,
+ "{}|{}|{}|",
+ shares_num, threshold, transcript_size_bytes
+ )
+ .unwrap();
}
// TODO: Find a way to deduplicate the following methods with benchmarks and test setup
From 33b2b0954d08261e72a7d206446a689fc6b251ac Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Mon, 30 Jan 2023 22:02:48 +0100
Subject: [PATCH 07/36] update tpke client api
---
.github/workflows/workspace.yml | 21 ++++++++
tpke-wasm/src/lib.rs | 24 +++------
tpke-wasm/tests/node.rs | 4 +-
tpke/src/api.rs | 41 +++++++++++----
tpke/src/ciphertext.rs | 93 ++++++++++++++++++++++++++++++++-
tpke/src/lib.rs | 85 +-----------------------------
6 files changed, 155 insertions(+), 113 deletions(-)
diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml
index 570698ab..db9463b8 100644
--- a/.github/workflows/workspace.yml
+++ b/.github/workflows/workspace.yml
@@ -77,6 +77,27 @@ jobs:
- run: cargo check --all-features
- run: cargo test --release --all-features
+ wasm-test:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ rust:
+ - 1.63 # MSRV
+ - stable
+ target:
+ - wasm32-unknown-unknown
+ steps:
+ - uses: actions/checkout@v1
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ toolchain: ${{ matrix.rust }}
+ target: ${{ matrix.target }}
+ override: true
+ - run: cargo install wasm-pack
+ - run: wasm-pack test --node
+ working-directory: tpke-wasm
+
benchmark:
runs-on: ubuntu-latest
needs: [ test ]
diff --git a/tpke-wasm/src/lib.rs b/tpke-wasm/src/lib.rs
index d59e0d8c..647cb884 100644
--- a/tpke-wasm/src/lib.rs
+++ b/tpke-wasm/src/lib.rs
@@ -5,20 +5,12 @@ extern crate group_threshold_cryptography as tpke;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
+use tpke::api::*;
use utils::set_panic_hook;
use wasm_bindgen::prelude::*;
extern crate wee_alloc;
-pub type E = ark_bls12_381::Bls12_381;
-pub type TpkePublicKey = ark_bls12_381::G1Affine;
-pub type TpkePrivateKey = ark_bls12_381::G2Affine;
-pub type TpkeCiphertext = tpke::Ciphertext;
-pub type TpkeDecryptionShare = tpke::DecryptionShareFast;
-pub type TpkePublicDecryptionContext = tpke::PublicDecryptionContextFast;
-pub type TpkeSharedSecret =
- ::Fqk;
-
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct PrivateDecryptionContext(tpke::api::PrivateDecryptionContext);
@@ -214,7 +206,7 @@ impl Setup {
.collect()
}
- // TODO: Add `decryptorShares` helper method
+ // TODO: Add `decryptorShares` helper method?
}
#[wasm_bindgen]
@@ -231,10 +223,7 @@ pub fn encrypt(
public_key: &PublicKey,
) -> Ciphertext {
set_panic_hook();
-
- let mut rng = rand::thread_rng();
- let ciphertext =
- tpke::encrypt::<_, E>(message, aad, &public_key.0, &mut rng);
+ let ciphertext = tpke::api::encrypt(message, aad, &public_key.0);
Ciphertext {
ciphertext,
aad: aad.to_vec(),
@@ -242,7 +231,10 @@ pub fn encrypt(
}
#[wasm_bindgen]
-pub fn decrypt(ciphertext: &Ciphertext, private_key: &PrivateKey) -> Vec {
+pub fn decrypt_with_private_key(
+ ciphertext: &Ciphertext,
+ private_key: &PrivateKey,
+) -> Vec {
set_panic_hook();
tpke::decrypt_symmetric(
@@ -308,7 +300,7 @@ pub fn decrypt_with_shared_secret(
) -> Vec {
set_panic_hook();
- tpke::decrypt_with_shared_secret(
+ tpke::api::decrypt_with_shared_secret(
&ciphertext.ciphertext,
&ciphertext.aad,
&shared_secret.0,
diff --git a/tpke-wasm/tests/node.rs b/tpke-wasm/tests/node.rs
index ec935180..d9e14972 100644
--- a/tpke-wasm/tests/node.rs
+++ b/tpke-wasm/tests/node.rs
@@ -5,8 +5,6 @@ extern crate wasm_bindgen_test;
use tpke_wasm::*;
use wasm_bindgen_test::*;
-extern crate group_threshold_cryptography as tpke;
-
#[test]
#[wasm_bindgen_test]
pub fn participant_payload_serialization() {
@@ -39,7 +37,7 @@ fn encrypts_and_decrypts() {
let setup = Setup::new(threshold, shares_num);
let ciphertext = encrypt(&message, &aad, &setup.public_key);
- let plaintext = decrypt(&ciphertext, &setup.private_key);
+ let plaintext = decrypt_with_private_key(&ciphertext, &setup.private_key);
// TODO: Plaintext is padded to 32 bytes. Fix this.
assert_eq!(message, plaintext[..message.len()])
diff --git a/tpke/src/api.rs b/tpke/src/api.rs
index 772f63f5..33fa3597 100644
--- a/tpke/src/api.rs
+++ b/tpke/src/api.rs
@@ -4,21 +4,41 @@
// TODO: Refactor this module to deduplicate shared code from tpke-wasm and tpke-wasm.
-use std::convert::TryInto;
-
use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_ff::{BigInteger256, ToBytes};
+use std::convert::TryInto;
// Fixing some of the types here on our target engine
// TODO: Consider fixing on crate::api level instead of bindings level
-type E = ark_bls12_381::Bls12_381;
-type TpkePublicKey = ark_bls12_381::G1Affine;
-type TpkePrivateKey = ark_bls12_381::G2Affine;
-type TpkeCiphertext = crate::Ciphertext;
-type TpkeDecryptionShare = crate::DecryptionShareFast;
-type TpkePublicDecryptionContext = crate::PublicDecryptionContextFast;
-type TpkeSharedSecret =
+pub type E = ark_bls12_381::Bls12_381;
+pub type TpkePublicKey = ark_bls12_381::G1Affine;
+pub type TpkePrivateKey = ark_bls12_381::G2Affine;
+pub type TpkeCiphertext = crate::Ciphertext;
+pub type TpkeDecryptionShare = crate::DecryptionShareFast;
+pub type TpkePublicDecryptionContext = crate::PublicDecryptionContextFast;
+pub type TpkeSharedSecret =
::Fqk;
+pub type TpkeResult = crate::Result;
+
+pub fn encrypt(
+ message: &[u8],
+ aad: &[u8],
+ pubkey: &TpkePublicKey,
+) -> TpkeCiphertext {
+ let rng = &mut rand::thread_rng();
+ crate::encrypt(message, aad, pubkey, rng)
+}
+
+pub fn decrypt_with_shared_secret(
+ ciphertext: &TpkeCiphertext,
+ aad: &[u8],
+ shared_secret: &TpkeSharedSecret,
+) -> TpkeResult> {
+ crate::decrypt_with_shared_secret(ciphertext, aad, shared_secret)
+}
+
+// TODO: There is previous API implementation below. I'm not removing it to avoid breaking bindings.
+// Review it and decide if we need it.
#[derive(Clone, Debug)]
pub struct PrivateDecryptionContext {
@@ -92,11 +112,14 @@ impl DecryptionShare {
}
}
+// TODO: Reconsider contents of ParticipantPayload payload after updating server API.
+
#[derive(Clone, Debug)]
pub struct ParticipantPayload {
pub decryption_context: PrivateDecryptionContext,
pub ciphertext: TpkeCiphertext,
}
+
impl ParticipantPayload {
pub fn new(
decryption_context: &PrivateDecryptionContext,
diff --git a/tpke/src/ciphertext.rs b/tpke/src/ciphertext.rs
index c9d13b9f..ebe75cd1 100644
--- a/tpke/src/ciphertext.rs
+++ b/tpke/src/ciphertext.rs
@@ -9,8 +9,6 @@ use chacha20poly1305::{
};
use rand_core::RngCore;
-use crate::{construct_tag_hash, hash_to_g2};
-
#[derive(Clone, Debug)]
pub struct Ciphertext {
pub commitment: E::G1Affine, // U
@@ -191,3 +189,94 @@ fn nonce_from_commitment(commitment: E::G1Affine) -> Nonce {
let commitment_hash = blake2s_hash(&commitment_bytes);
*Nonce::from_slice(&commitment_hash[..12])
}
+
+fn hash_to_g2(message: &[u8]) -> T {
+ let mut point_ser: Vec = Vec::new();
+ let point = htp_bls12381_g2(message);
+ point.serialize(&mut point_ser).unwrap();
+ T::deserialize(&point_ser[..]).unwrap()
+}
+
+fn construct_tag_hash(
+ u: E::G1Affine,
+ stream_ciphertext: &[u8],
+ aad: &[u8],
+) -> E::G2Affine {
+ let mut hash_input = Vec::::new();
+ u.write(&mut hash_input).unwrap();
+ hash_input.extend_from_slice(stream_ciphertext);
+ hash_input.extend_from_slice(aad);
+
+ hash_to_g2(&hash_input)
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{
+ check_ciphertext_validity, decrypt_symmetric, encrypt, setup_fast,
+ Ciphertext,
+ };
+ use ark_bls12_381::{Fr, G1Projective, G2Projective};
+ use ark_ec::ProjectiveCurve;
+ use ark_ff::PrimeField;
+ use ark_std::{test_rng, UniformRand};
+ use rand::prelude::StdRng;
+
+ type E = ark_bls12_381::Bls12_381;
+
+ #[test]
+ fn ciphertext_serialization() {
+ let rng = &mut test_rng();
+ let msg: &[u8] = "abc".as_bytes();
+ let aad: &[u8] = "my-aad".as_bytes();
+ let pubkey = G1Projective::rand(rng).into_affine();
+ let ciphertext = encrypt::(msg, aad, &pubkey, rng);
+
+ let serialized = ciphertext.to_bytes();
+ let deserialized: Ciphertext = Ciphertext::from_bytes(&serialized);
+
+ assert_eq!(serialized, deserialized.to_bytes())
+ }
+
+ #[test]
+ fn symmetric_encryption() {
+ let rng = &mut test_rng();
+ let msg: &[u8] = "abc".as_bytes();
+ let aad: &[u8] = "my-aad".as_bytes();
+
+ let x = Fr::rand(rng).into_repr();
+ let pubkey = G1Projective::prime_subgroup_generator()
+ .mul(x)
+ .into_affine();
+ let privkey = G2Projective::prime_subgroup_generator()
+ .mul(x)
+ .into_affine();
+
+ let ciphertext = encrypt::(msg, aad, &pubkey, rng);
+ let plaintext = decrypt_symmetric(&ciphertext, aad, privkey).unwrap();
+
+ assert_eq!(msg, plaintext)
+ }
+
+ #[test]
+ fn ciphertext_validity_check() {
+ let rng = &mut test_rng();
+ let shares_num = 16;
+ let threshold = shares_num * 2 / 3;
+ let msg: &[u8] = "abc".as_bytes();
+ let aad: &[u8] = "my-aad".as_bytes();
+ let (pubkey, _, _) = setup_fast::(threshold, shares_num, rng);
+ let mut ciphertext = encrypt::(msg, aad, &pubkey, rng);
+
+ // So far, the ciphertext is valid
+ assert!(check_ciphertext_validity(&ciphertext, aad).is_ok());
+
+ // Malformed the ciphertext
+ ciphertext.ciphertext[0] += 1;
+ assert!(check_ciphertext_validity(&ciphertext, aad).is_err());
+
+ // Malformed the AAD
+ let aad = "bad aad".as_bytes();
+ assert!(check_ciphertext_validity(&ciphertext, aad).is_err());
+ }
+}
diff --git a/tpke/src/lib.rs b/tpke/src/lib.rs
index c961d8df..35d69f67 100644
--- a/tpke/src/lib.rs
+++ b/tpke/src/lib.rs
@@ -2,18 +2,15 @@ use crate::hash_to_curve::htp_bls12381_g2;
use crate::SetupParams;
use ark_ec::{AffineCurve, PairingEngine};
-use ark_ff::{Field, One, PrimeField, ToBytes, UniformRand, Zero};
+use ark_ff::{Field, One, PrimeField, UniformRand, Zero};
use ark_poly::{
univariate::DensePolynomial, EvaluationDomain, Polynomial, UVPolynomial,
};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use itertools::izip;
-
-use subproductdomain::{fast_multiexp, SubproductDomain};
-
use rand_core::RngCore;
use std::usize;
-
+use subproductdomain::{fast_multiexp, SubproductDomain};
use thiserror::Error;
mod ciphertext;
@@ -61,26 +58,6 @@ pub enum ThresholdEncryptionError {
pub type Result = std::result::Result;
-fn hash_to_g2(message: &[u8]) -> T {
- let mut point_ser: Vec = Vec::new();
- let point = htp_bls12381_g2(message);
- point.serialize(&mut point_ser).unwrap();
- T::deserialize(&point_ser[..]).unwrap()
-}
-
-fn construct_tag_hash(
- u: E::G1Affine,
- stream_ciphertext: &[u8],
- aad: &[u8],
-) -> E::G2Affine {
- let mut hash_input = Vec::::new();
- u.write(&mut hash_input).unwrap();
- hash_input.extend_from_slice(stream_ciphertext);
- hash_input.extend_from_slice(aad);
-
- hash_to_g2(&hash_input)
-}
-
pub fn setup_fast(
threshold: usize,
shares_num: usize,
@@ -374,64 +351,6 @@ mod tests {
share_combine_simple::(decryption_shares, &lagrange)
}
- #[test]
- fn ciphertext_serialization() {
- let rng = &mut test_rng();
- let shares_num = 16;
- let threshold = shares_num * 2 / 3;
- let msg: &[u8] = "abc".as_bytes();
- let aad: &[u8] = "my-aad".as_bytes();
-
- let (pubkey, _, _) = setup_fast::(threshold, shares_num, rng);
-
- let ciphertext = encrypt::(msg, aad, &pubkey, rng);
-
- let serialized = ciphertext.to_bytes();
- let deserialized: Ciphertext = Ciphertext::from_bytes(&serialized);
-
- assert_eq!(serialized, deserialized.to_bytes())
- }
-
- #[test]
- fn symmetric_encryption() {
- let rng = &mut test_rng();
- let shares_num = 16;
- let threshold = shares_num * 2 / 3;
- let msg: &[u8] = "abc".as_bytes();
- let aad: &[u8] = "my-aad".as_bytes();
-
- let (pubkey, privkey, _) = setup_fast::(threshold, shares_num, rng);
-
- let ciphertext = encrypt::(msg, aad, &pubkey, rng);
-
- let plaintext = decrypt_symmetric(&ciphertext, aad, privkey).unwrap();
-
- assert_eq!(msg, plaintext)
- }
-
- #[test]
- fn ciphertext_validity_check() {
- let rng = &mut test_rng();
- let shares_num = 16;
- let threshold = shares_num * 2 / 3;
- let msg: &[u8] = "abc".as_bytes();
- let aad: &[u8] = "my-aad".as_bytes();
-
- let (pubkey, _, _) = setup_fast::(threshold, shares_num, rng);
- let mut ciphertext = encrypt::(msg, aad, &pubkey, rng);
-
- // So far, the ciphertext is valid
- assert!(check_ciphertext_validity(&ciphertext, aad).is_ok());
-
- // Malformed the ciphertext
- ciphertext.ciphertext[0] += 1;
- assert!(check_ciphertext_validity(&ciphertext, aad).is_err());
-
- // Malformed the AAD
- let aad = "bad aad".as_bytes();
- assert!(check_ciphertext_validity(&ciphertext, aad).is_err());
- }
-
#[test]
fn fast_decryption_share_validation() {
let rng = &mut test_rng();
From 9b0a4c6a532f477c5e581ad65d9ebc747824fce3 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Tue, 31 Jan 2023 12:57:22 +0100
Subject: [PATCH 08/36] setup ferveo-python for server api
---
Cargo.lock | 21 +
Cargo.toml | 1 +
ferveo-python/.gitignore | 7 +
ferveo-python/Cargo.toml | 16 +
ferveo-python/LICENSE | 675 ++++++++++++++++++++++++++++++
ferveo-python/MANIFEST.in | 4 +
ferveo-python/README.md | 5 +
ferveo-python/build.rs | 3 +
ferveo-python/ferveo/__init__.py | 4 +
ferveo-python/ferveo/__init__.pyi | 22 +
ferveo-python/ferveo/py.typed | 0
ferveo-python/pyproject.toml | 2 +
ferveo-python/setup.py | 39 ++
ferveo-python/src/lib.rs | 37 ++
ferveo/src/api.rs | 41 ++
ferveo/src/dkg.rs | 1 +
ferveo/src/dkg/pv.rs | 1 +
ferveo/src/lib.rs | 37 +-
tpke-python/src/lib.rs | 5 -
19 files changed, 894 insertions(+), 27 deletions(-)
create mode 100644 ferveo-python/.gitignore
create mode 100644 ferveo-python/Cargo.toml
create mode 100755 ferveo-python/LICENSE
create mode 100644 ferveo-python/MANIFEST.in
create mode 100644 ferveo-python/README.md
create mode 100644 ferveo-python/build.rs
create mode 100644 ferveo-python/ferveo/__init__.py
create mode 100644 ferveo-python/ferveo/__init__.pyi
create mode 100644 ferveo-python/ferveo/py.typed
create mode 100644 ferveo-python/pyproject.toml
create mode 100644 ferveo-python/setup.py
create mode 100644 ferveo-python/src/lib.rs
create mode 100644 ferveo/src/api.rs
diff --git a/Cargo.lock b/Cargo.lock
index 6e875f54..c19b5168 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -811,6 +811,17 @@ dependencies = [
"syn",
]
+[[package]]
+name = "derive_more"
+version = "0.99.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "digest"
version = "0.9.0"
@@ -925,6 +936,16 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "ferveo-python"
+version = "0.1.0"
+dependencies = [
+ "derive_more",
+ "ferveo",
+ "pyo3",
+ "pyo3-build-config",
+]
+
[[package]]
name = "findshlibs"
version = "0.10.2"
diff --git a/Cargo.toml b/Cargo.toml
index 72edf305..94d18e5a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,6 +3,7 @@
members = [
"ferveo",
"ferveo-common",
+ "ferveo-python",
"subproductdomain",
"tpke",
"tpke-wasm",
diff --git a/ferveo-python/.gitignore b/ferveo-python/.gitignore
new file mode 100644
index 00000000..b2417b63
--- /dev/null
+++ b/ferveo-python/.gitignore
@@ -0,0 +1,7 @@
+__pycache__
+*.egg-info
+*.so
+build/
+dist/
+docs/_build
+
diff --git a/ferveo-python/Cargo.toml b/ferveo-python/Cargo.toml
new file mode 100644
index 00000000..d8f14035
--- /dev/null
+++ b/ferveo-python/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "ferveo-python"
+authors = ["Piotr Roslaniec "]
+version = "0.1.0"
+edition = "2018"
+
+[lib]
+crate-type = ["cdylib"]
+
+[dependencies]
+pyo3 = "0.17.3"
+ferveo = { path = "../ferveo" }
+derive_more = { version = "0.99", default-features = false, features = ["from", "as_ref"] }
+
+[build-dependencies]
+pyo3-build-config = "*"
diff --git a/ferveo-python/LICENSE b/ferveo-python/LICENSE
new file mode 100755
index 00000000..2fb2e74d
--- /dev/null
+++ b/ferveo-python/LICENSE
@@ -0,0 +1,675 @@
+### GNU GENERAL PUBLIC LICENSE
+
+Version 3, 29 June 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc.
+
+
+Everyone is permitted to copy and distribute verbatim copies of this
+license document, but changing it is not allowed.
+
+### Preamble
+
+The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom
+to share and change all versions of a program--to make sure it remains
+free software for all its users. We, the Free Software Foundation, use
+the GNU General Public License for most of our software; it applies
+also to any other work released this way by its authors. You can apply
+it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you
+have certain responsibilities if you distribute copies of the
+software, or if you modify it: responsibilities to respect the freedom
+of others.
+
+For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the
+manufacturer can do so. This is fundamentally incompatible with the
+aim of protecting users' freedom to change the software. The
+systematic pattern of such abuse occurs in the area of products for
+individuals to use, which is precisely where it is most unacceptable.
+Therefore, we have designed this version of the GPL to prohibit the
+practice for those products. If such problems arise substantially in
+other domains, we stand ready to extend this provision to those
+domains in future versions of the GPL, as needed to protect the
+freedom of users.
+
+Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish
+to avoid the special danger that patents applied to a free program
+could make it effectively proprietary. To prevent this, the GPL
+assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+### TERMS AND CONDITIONS
+
+#### 0. Definitions.
+
+"This License" refers to version 3 of the GNU General Public License.
+
+"Copyright" also means copyright-like laws that apply to other kinds
+of works, such as semiconductor masks.
+
+"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of
+an exact copy. The resulting work is called a "modified version" of
+the earlier work or a work "based on" the earlier work.
+
+A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user
+through a computer network, with no transfer of a copy, is not
+conveying.
+
+An interactive user interface displays "Appropriate Legal Notices" to
+the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+#### 1. Source Code.
+
+The "source code" for a work means the preferred form of the work for
+making modifications to it. "Object code" means any non-source form of
+a work.
+
+A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can
+regenerate automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same
+work.
+
+#### 2. Basic Permissions.
+
+All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey,
+without conditions so long as your license otherwise remains in force.
+You may convey covered works to others for the sole purpose of having
+them make modifications exclusively for you, or provide you with
+facilities for running those works, provided that you comply with the
+terms of this License in conveying all material for which you do not
+control copyright. Those thus making or running the covered works for
+you must do so exclusively on your behalf, under your direction and
+control, on terms that prohibit them from making any copies of your
+copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under the
+conditions stated below. Sublicensing is not allowed; section 10 makes
+it unnecessary.
+
+#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such
+circumvention is effected by exercising rights under this License with
+respect to the covered work, and you disclaim any intention to limit
+operation or modification of the work as a means of enforcing, against
+the work's users, your or third parties' legal rights to forbid
+circumvention of technological measures.
+
+#### 4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+#### 5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these
+conditions:
+
+- a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+- b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under
+ section 7. This requirement modifies the requirement in section 4
+ to "keep intact all notices".
+- c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+- d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+#### 6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms of
+sections 4 and 5, provided that you also convey the machine-readable
+Corresponding Source under the terms of this License, in one of these
+ways:
+
+- a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+- b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the Corresponding
+ Source from a network server at no charge.
+- c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+- d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+- e) Convey the object code using peer-to-peer transmission,
+ provided you inform other peers where the object code and
+ Corresponding Source of the work are being offered to the general
+ public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal,
+family, or household purposes, or (2) anything designed or sold for
+incorporation into a dwelling. In determining whether a product is a
+consumer product, doubtful cases shall be resolved in favor of
+coverage. For a particular product received by a particular user,
+"normally used" refers to a typical or common use of that class of
+product, regardless of the status of the particular user or of the way
+in which the particular user actually uses, or expects or is expected
+to use, the product. A product is a consumer product regardless of
+whether the product has substantial commercial, industrial or
+non-consumer uses, unless such uses represent the only significant
+mode of use of the product.
+
+"Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to
+install and execute modified versions of a covered work in that User
+Product from a modified version of its Corresponding Source. The
+information must suffice to ensure that the continued functioning of
+the modified object code is in no case prevented or interfered with
+solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or
+updates for a work that has been modified or installed by the
+recipient, or for the User Product in which it has been modified or
+installed. Access to a network may be denied when the modification
+itself materially and adversely affects the operation of the network
+or violates the rules and protocols for communication across the
+network.
+
+Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+#### 7. Additional Terms.
+
+"Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders
+of that material) supplement the terms of this License with terms:
+
+- a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+- b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+- c) Prohibiting misrepresentation of the origin of that material,
+ or requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+- d) Limiting the use for publicity purposes of names of licensors
+ or authors of the material; or
+- e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+- f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions
+ of it) with contractual assumptions of liability to the recipient,
+ for any liability that these contractual assumptions directly
+ impose on those licensors and authors.
+
+All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions; the
+above requirements apply either way.
+
+#### 8. Termination.
+
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+However, if you cease all violation of this License, then your license
+from a particular copyright holder is reinstated (a) provisionally,
+unless and until the copyright holder explicitly and finally
+terminates your license, and (b) permanently, if the copyright holder
+fails to notify you of the violation by some reasonable means prior to
+60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+#### 9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or run
+a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+#### 10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+#### 11. Patents.
+
+A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+A contributor's "essential patent claims" are all patent claims owned
+or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+A patent license is "discriminatory" if it does not include within the
+scope of its coverage, prohibits the exercise of, or is conditioned on
+the non-exercise of one or more of the rights that are specifically
+granted under this License. You may not convey a covered work if you
+are a party to an arrangement with a third party that is in the
+business of distributing software, under which you make payment to the
+third party based on the extent of your activity of conveying the
+work, and under which the third party grants, to any of the parties
+who would receive the covered work from you, a discriminatory patent
+license (a) in connection with copies of the covered work conveyed by
+you (or copies made from those copies), or (b) primarily for and in
+connection with specific products or compilations that contain the
+covered work, unless you entered into that arrangement, or that patent
+license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+#### 12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under
+this License and any other pertinent obligations, then as a
+consequence you may not convey it at all. For example, if you agree to
+terms that obligate you to collect a royalty for further conveying
+from those to whom you convey the Program, the only way you could
+satisfy both those terms and this License would be to refrain entirely
+from conveying the Program.
+
+#### 13. Use with the GNU Affero General Public License.
+
+Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+#### 14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions
+of the GNU General Public License from time to time. Such new versions
+will be similar in spirit to the present version, but may differ in
+detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies that a certain numbered version of the GNU General Public
+License "or any later version" applies to it, you have the option of
+following the terms and conditions either of that numbered version or
+of any later version published by the Free Software Foundation. If the
+Program does not specify a version number of the GNU General Public
+License, you may choose any version ever published by the Free
+Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions
+of the GNU General Public License can be used, that proxy's public
+statement of acceptance of a version permanently authorizes you to
+choose that version for the Program.
+
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+#### 15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
+WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
+PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
+DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
+CORRECTION.
+
+#### 16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
+CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
+ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
+NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
+LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
+TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
+PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+#### 17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+### How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these
+terms.
+
+To do so, attach the following notices to the program. It is safest to
+attach them to the start of each source file to most effectively state
+the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper
+mail.
+
+If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands \`show w' and \`show c' should show the
+appropriate parts of the General Public License. Of course, your
+program's commands might be different; for a GUI interface, you would
+use an "about box".
+
+You should also get your employer (if you work as a programmer) or
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. For more information on this, and how to apply and follow
+the GNU GPL, see .
+
+The GNU General Public License does not permit incorporating your
+program into proprietary programs. If your program is a subroutine
+library, you may consider it more useful to permit linking proprietary
+applications with the library. If this is what you want to do, use the
+GNU Lesser General Public License instead of this License. But first,
+please read .
diff --git a/ferveo-python/MANIFEST.in b/ferveo-python/MANIFEST.in
new file mode 100644
index 00000000..2dff285a
--- /dev/null
+++ b/ferveo-python/MANIFEST.in
@@ -0,0 +1,4 @@
+include Cargo.toml
+include README.md
+include LICENSE
+recursive-include src *
diff --git a/ferveo-python/README.md b/ferveo-python/README.md
new file mode 100644
index 00000000..3d067b6b
--- /dev/null
+++ b/ferveo-python/README.md
@@ -0,0 +1,5 @@
+# Python bindings for `ferveo`
+
+## Build
+
+You will need to have `setuptools-rust` installed. Then, for development, you can just do `pip install -e .` as usual.
diff --git a/ferveo-python/build.rs b/ferveo-python/build.rs
new file mode 100644
index 00000000..dace4a9b
--- /dev/null
+++ b/ferveo-python/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ pyo3_build_config::add_extension_module_link_args();
+}
diff --git a/ferveo-python/ferveo/__init__.py b/ferveo-python/ferveo/__init__.py
new file mode 100644
index 00000000..77a421a9
--- /dev/null
+++ b/ferveo-python/ferveo/__init__.py
@@ -0,0 +1,4 @@
+from ._ferveo import (
+ DecryptionShare,
+ ParticipantPayload
+)
diff --git a/ferveo-python/ferveo/__init__.pyi b/ferveo-python/ferveo/__init__.pyi
new file mode 100644
index 00000000..ed8e880d
--- /dev/null
+++ b/ferveo-python/ferveo/__init__.pyi
@@ -0,0 +1,22 @@
+from typing import Sequence
+
+
+class ExternalValidator:
+
+ # TODO: Add a proper constructor. Currently, breaks `pip install`.
+ def __init__(self):
+ ...
+
+
+class PubliclyVerifiableDkg:
+
+ def __init__(
+ self,
+ validators: Sequence[ExternalValidator],
+ me: ExternalValidator,
+ threshold: int,
+ shares_num: int,
+ ):
+ ...
+
+
diff --git a/ferveo-python/ferveo/py.typed b/ferveo-python/ferveo/py.typed
new file mode 100644
index 00000000..e69de29b
diff --git a/ferveo-python/pyproject.toml b/ferveo-python/pyproject.toml
new file mode 100644
index 00000000..31ffe048
--- /dev/null
+++ b/ferveo-python/pyproject.toml
@@ -0,0 +1,2 @@
+[build-system]
+requires = ["setuptools", "wheel", "setuptools-rust"]
diff --git a/ferveo-python/setup.py b/ferveo-python/setup.py
new file mode 100644
index 00000000..29d57adc
--- /dev/null
+++ b/ferveo-python/setup.py
@@ -0,0 +1,39 @@
+from setuptools import setup
+from setuptools_rust import Binding, RustExtension
+
+from pathlib import Path
+this_directory = Path(__file__).parent
+long_description = (this_directory / "README.md").read_text()
+
+setup(
+ name="ferveo",
+ description="Ferveo DKG scheme",
+ long_description=long_description,
+ long_description_content_type="text/markdown",
+ version="0.1.0",
+ author="Piotr Roslaniec",
+ author_email="p.roslaniec@gmail.com",
+ url="https://github.com/nucypher/ferveo/tree/master/ferveo-python",
+ rust_extensions=[RustExtension(
+ "ferveo._ferveo", binding=Binding.PyO3, debug=False)],
+ packages=["ferveo"],
+ package_data={
+ 'ferveo': ['py.typed', '__init__.pyi'],
+ },
+ # rust extensions are not zip safe, just like C-extensions.
+ zip_safe=False,
+ classifiers=[
+ "Development Status :: 3 - Alpha",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
+ "Natural Language :: English",
+ "Programming Language :: Rust",
+ "Programming Language :: Python :: Implementation :: CPython",
+ "Programming Language :: Python :: 3 :: Only",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Topic :: Security :: Cryptography",
+ ],
+)
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
new file mode 100644
index 00000000..7b5b6e3d
--- /dev/null
+++ b/ferveo-python/src/lib.rs
@@ -0,0 +1,37 @@
+extern crate alloc;
+
+use pyo3::prelude::*;
+
+#[pyclass(module = "ferveo")]
+#[derive(Clone, derive_more::From, derive_more::AsRef)]
+pub struct ExternalValidator(ferveo::api::ExternalValidator);
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct PubliclyVerifiableDkg(ferveo::api::PubliclyVerifiableDkg);
+
+#[pymethods]
+impl PubliclyVerifiableDkg {
+ #[new]
+ pub fn new(
+ validators: Vec,
+ me: ExternalValidator,
+ threshold: u32,
+ shares_num: u32,
+ ) -> Self {
+ let validators = validators.into_iter().map(|v| v.0).collect();
+ let me = me.0;
+ Self(ferveo::api::PubliclyVerifiableDkg::new(
+ validators, me, threshold, shares_num,
+ ))
+ }
+}
+
+/// A Python module implemented in Rust.
+#[pymodule]
+fn _ferveo(_py: Python, m: &PyModule) -> PyResult<()> {
+ m.add_class::()?;
+ m.add_class::()?;
+
+ Ok(())
+}
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
new file mode 100644
index 00000000..7f7dca0b
--- /dev/null
+++ b/ferveo/src/api.rs
@@ -0,0 +1,41 @@
+pub type E = ark_bls12_381::Bls12_381;
+
+#[derive(Clone)]
+pub struct ExternalValidator(ferveo_common::ExternalValidator);
+
+pub struct PubliclyVerifiableDkg(crate::PubliclyVerifiableDkg);
+
+impl PubliclyVerifiableDkg {
+ pub fn new(
+ validators: Vec,
+ me: ExternalValidator,
+ // session_keypair: ferveo_common::Keypair,
+ // tau: u32,
+ security_threshold: u32,
+ shares_num: u32,
+ // retry_after: u32,
+ ) -> Self {
+ let validators = validators
+ .into_iter()
+ .map(|v| v.0)
+ .collect::>>();
+ let me = me.0;
+ let params = crate::Params {
+ tau: 0,
+ security_threshold,
+ shares_num,
+ retry_after: 0,
+ };
+ let session_keypair = ferveo_common::Keypair:: {
+ decryption_key: ark_ff::UniformRand::rand(&mut ark_std::test_rng()),
+ };
+ let dkg = crate::PubliclyVerifiableDkg::::new(
+ validators,
+ params,
+ &me,
+ session_keypair,
+ )
+ .unwrap();
+ Self(dkg)
+ }
+}
diff --git a/ferveo/src/dkg.rs b/ferveo/src/dkg.rs
index 93aebf7f..5487e10b 100644
--- a/ferveo/src/dkg.rs
+++ b/ferveo/src/dkg.rs
@@ -24,6 +24,7 @@ pub use pv::*;
// DKG parameters
#[derive(Copy, Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
pub struct Params {
+ // TODO: Do we need tau? Do we need to distinguish between DKG instances using such an identifier?
pub tau: u64,
pub security_threshold: u32,
pub shares_num: u32,
diff --git a/ferveo/src/dkg/pv.rs b/ferveo/src/dkg/pv.rs
index 358610a1..a57e1290 100644
--- a/ferveo/src/dkg/pv.rs
+++ b/ferveo/src/dkg/pv.rs
@@ -13,6 +13,7 @@ use std::collections::BTreeMap;
pub struct PubliclyVerifiableDkg {
pub params: Params,
pub pvss_params: PubliclyVerifiableParams,
+ // TODO: What is session_keypair?
pub session_keypair: ferveo_common::Keypair,
pub validators: Vec>,
pub vss: BTreeMap>,
diff --git a/ferveo/src/lib.rs b/ferveo/src/lib.rs
index 4bca1dfc..e7af3129 100644
--- a/ferveo/src/lib.rs
+++ b/ferveo/src/lib.rs
@@ -1,39 +1,32 @@
#![allow(unused_imports)]
-pub mod dkg;
-pub mod msg;
-pub mod vss;
-
-pub mod primitives;
-
-use itertools::{izip, zip_eq};
-pub use primitives::*;
-
-use ferveo_common::Rng;
-
-use crate::dkg::*;
-use crate::msg::*;
-
+use anyhow::{anyhow, Result};
+use ark_ec::msm::FixedBaseMSM;
+use ark_ec::PairingEngine;
use ark_ec::{AffineCurve, ProjectiveCurve};
+use ark_ff::PrimeField;
use ark_ff::{Field, One, Zero};
use ark_poly::{
polynomial::univariate::DensePolynomial, polynomial::UVPolynomial,
EvaluationDomain,
};
use ark_std::{end_timer, start_timer};
-use serde::*;
+use ferveo_common::Rng;
+use itertools::{izip, zip_eq};
+use measure_time::print_time;
+use serde::{Deserialize, Serialize};
+
+pub mod api;
+pub mod dkg;
+pub mod msg;
+pub mod primitives;
+pub mod vss;
-use anyhow::{anyhow, Result};
pub use dkg::*;
pub use msg::*;
+pub use primitives::*;
pub use vss::*;
-use ark_ec::msm::FixedBaseMSM;
-use ark_ec::PairingEngine;
-use ark_ff::PrimeField;
-
-use measure_time::print_time;
-
#[cfg(test)]
mod test_dkg_full {
use super::*;
diff --git a/tpke-python/src/lib.rs b/tpke-python/src/lib.rs
index 0e616760..c1b8d56f 100644
--- a/tpke-python/src/lib.rs
+++ b/tpke-python/src/lib.rs
@@ -1,8 +1,3 @@
-// Clippy shows false positives in PyO3 methods.
-// See https://github.com/rust-lang/rust-clippy/issues/8971
-// Will probably be fixed by Rust 1.65
-#![allow(clippy::borrow_deref_ref)]
-
extern crate alloc;
extern crate group_threshold_cryptography as tpke;
From c85ea43d8e2b961aa3871c524c079df04224af4a Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Wed, 1 Feb 2023 18:05:44 +0100
Subject: [PATCH 09/36] remove dependency on block time
---
ferveo-python/src/lib.rs | 11 +-
ferveo/benches/benchmarks/validity_checks.rs | 1 -
ferveo/examples/pvdkg.rs | 1 -
ferveo/src/api.rs | 11 +-
ferveo/src/dkg.rs | 9 +-
ferveo/src/dkg/pv.rs | 116 -------------------
6 files changed, 13 insertions(+), 136 deletions(-)
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
index 7b5b6e3d..dc1568b5 100644
--- a/ferveo-python/src/lib.rs
+++ b/ferveo-python/src/lib.rs
@@ -14,15 +14,20 @@ pub struct PubliclyVerifiableDkg(ferveo::api::PubliclyVerifiableDkg);
impl PubliclyVerifiableDkg {
#[new]
pub fn new(
+ tau: u64,
+ shares_num: u32,
+ security_threshold: u32,
validators: Vec,
me: ExternalValidator,
- threshold: u32,
- shares_num: u32,
) -> Self {
let validators = validators.into_iter().map(|v| v.0).collect();
let me = me.0;
Self(ferveo::api::PubliclyVerifiableDkg::new(
- validators, me, threshold, shares_num,
+ tau,
+ shares_num,
+ security_threshold,
+ validators,
+ me,
))
}
}
diff --git a/ferveo/benches/benchmarks/validity_checks.rs b/ferveo/benches/benchmarks/validity_checks.rs
index 19b31c0e..a564ab67 100644
--- a/ferveo/benches/benchmarks/validity_checks.rs
+++ b/ferveo/benches/benchmarks/validity_checks.rs
@@ -44,7 +44,6 @@ fn setup_dkg(
tau: 0,
security_threshold: shares_num / 3,
shares_num,
- retry_after: 1,
},
&me,
keypairs[validator],
diff --git a/ferveo/examples/pvdkg.rs b/ferveo/examples/pvdkg.rs
index 82968d1c..be2e92c5 100644
--- a/ferveo/examples/pvdkg.rs
+++ b/ferveo/examples/pvdkg.rs
@@ -45,7 +45,6 @@ pub fn setup_dkg(
tau: 0,
security_threshold: shares_num / 3,
shares_num,
- retry_after: 1,
},
&me,
keypairs[validator],
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
index 7f7dca0b..1b7c6e8e 100644
--- a/ferveo/src/api.rs
+++ b/ferveo/src/api.rs
@@ -7,13 +7,11 @@ pub struct PubliclyVerifiableDkg(crate::PubliclyVerifiableDkg);
impl PubliclyVerifiableDkg {
pub fn new(
+ tau: u64,
+ shares_num: u32,
+ security_threshold: u32,
validators: Vec,
me: ExternalValidator,
- // session_keypair: ferveo_common::Keypair,
- // tau: u32,
- security_threshold: u32,
- shares_num: u32,
- // retry_after: u32,
) -> Self {
let validators = validators
.into_iter()
@@ -21,10 +19,9 @@ impl PubliclyVerifiableDkg {
.collect::>>();
let me = me.0;
let params = crate::Params {
- tau: 0,
+ tau,
security_threshold,
shares_num,
- retry_after: 0,
};
let session_keypair = ferveo_common::Keypair:: {
decryption_key: ark_ff::UniformRand::rand(&mut ark_std::test_rng()),
diff --git a/ferveo/src/dkg.rs b/ferveo/src/dkg.rs
index 5487e10b..7ccc9e82 100644
--- a/ferveo/src/dkg.rs
+++ b/ferveo/src/dkg.rs
@@ -24,17 +24,10 @@ pub use pv::*;
// DKG parameters
#[derive(Copy, Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
pub struct Params {
- // TODO: Do we need tau? Do we need to distinguish between DKG instances using such an identifier?
+ // TODO: Rename to ritual_id?
pub tau: u64,
pub security_threshold: u32,
pub shares_num: u32,
- pub retry_after: u32, // TODO: Remove. Not relevant in our scheme.
-}
-
-#[derive(Clone, Debug, Eq, PartialEq)]
-pub enum PvssScheduler {
- Wait,
- Issue,
}
#[derive(Debug, Clone)]
diff --git a/ferveo/src/dkg/pv.rs b/ferveo/src/dkg/pv.rs
index a57e1290..b2d6d907 100644
--- a/ferveo/src/dkg/pv.rs
+++ b/ferveo/src/dkg/pv.rs
@@ -20,7 +20,6 @@ pub struct PubliclyVerifiableDkg {
pub domain: ark_poly::Radix2EvaluationDomain,
pub state: DkgState,
pub me: usize,
- pub window: (u32, u32),
}
impl PubliclyVerifiableDkg {
@@ -49,9 +48,6 @@ impl PubliclyVerifiableDkg {
let validators = make_validators(validators);
- // TODO: Remove my_partition
- let my_partition =
- params.retry_after * (2 * me as u32 / params.retry_after);
Ok(Self {
session_keypair,
params,
@@ -67,38 +63,9 @@ impl PubliclyVerifiableDkg {
},
me,
validators,
- // TODO: Remove window
- window: (my_partition, my_partition + params.retry_after),
})
}
- /// Increment the number of blocks processed since the DKG protocol
- /// began if we are still sharing PVSS transcripts.
- ///
- /// Returns a value indicating if we should issue a PVSS transcript
- pub fn increase_block(&mut self) -> PvssScheduler {
- match self.state {
- DkgState::Sharing { ref mut block, .. }
- if !self.vss.contains_key(&(self.me as u32)) =>
- {
- *block += 1;
- // if our scheduled window begins, issue PVSS
- if self.window.0 + 1 == *block {
- PvssScheduler::Issue
- } else if &self.window.1 < block {
- // reset the window during which we try to get our
- // PVSS on chain
- *block = self.window.0 + 1;
- // reissue PVSS
- PvssScheduler::Issue
- } else {
- PvssScheduler::Wait
- }
- }
- _ => PvssScheduler::Wait,
- }
- }
-
/// Create a new PVSS instance within this DKG session, contributing to the final key
/// `rng` is a cryptographic random number generator
/// Returns a PVSS dealing message to post on-chain
@@ -316,7 +283,6 @@ pub(crate) mod test_common {
tau: 0,
security_threshold,
shares_num,
- retry_after: 2,
},
&me,
keypairs[my_index],
@@ -387,7 +353,6 @@ mod test_dkg_init {
tau: 0,
security_threshold: 4,
shares_num: 8,
- retry_after: 2,
},
&ExternalValidator:: {
address: "non-existant-validator".into(),
@@ -401,16 +366,6 @@ mod test_dkg_init {
"could not find this validator in the provided validator set"
)
}
-
- /// Test that the windows of a validator are correctly
- /// computed from the `retry_after` param
- #[test]
- fn test_validator_windows() {
- for i in 0..4_u32 {
- let dkg = setup_dkg(i as usize);
- assert_eq!(dkg.window, (2 * i, 2 * i + 2));
- }
- }
}
/// Test the dealing phase of the DKG
@@ -625,77 +580,6 @@ mod test_dealing {
assert!(dkg.apply_message(sender, pvss).is_ok());
assert!(matches!(dkg.state, DkgState::Dealt))
}
-
- /// Check that if a validators window has not arrived,
- /// the DKG advises us to wait
- #[test]
- fn test_pvss_wait_before_window() {
- let mut dkg = setup_dkg(1);
- if let DkgState::Sharing { block, .. } = dkg.state {
- assert!(dkg.window.0 > block);
- } else {
- panic!("Test failed");
- }
- assert_eq!(dkg.increase_block(), PvssScheduler::Wait);
- }
-
- /// Test that the DKG advises us to not issue a PVSS transcript
- /// if we are not in state [`DkgState::Sharing{..}`]
- #[test]
- fn test_pvss_wait_if_not_in_sharing_state() {
- let mut dkg = setup_dkg(0);
- for state in vec![
- Dealt,
- DkgState::Success {
- final_key: G1::zero(),
- },
- DkgState::Invalid,
- ] {
- dkg.state = state;
- assert_eq!(dkg.increase_block(), PvssScheduler::Wait);
- }
- }
-
- /// Test that if we already have our PVSS on chain,
- /// the DKG advises us not to issue a new one
- #[test]
- fn test_pvss_wait_if_already_applied() {
- let rng = &mut ark_std::test_rng();
- let mut dkg = setup_dkg(0);
- let pvss = dkg.share(rng).expect("Test failed");
- let sender = dkg.validators[0].validator.clone();
- // check that verification fails
- assert!(dkg.verify_message(&sender, &pvss).is_ok());
- assert!(dkg.apply_message(sender, pvss).is_ok());
- assert_eq!(dkg.increase_block(), PvssScheduler::Wait);
- }
-
- /// Test that if our own PVSS transcript is not on chain
- /// after the retry window, the DKG advises us to issue again.
- #[test]
- fn test_pvss_reissue() {
- let mut dkg = setup_dkg(0);
- dkg.state = DkgState::Sharing {
- accumulated_shares: 0,
- block: 2,
- };
- assert_eq!(dkg.increase_block(), PvssScheduler::Issue);
- assert_eq!(dkg.increase_block(), PvssScheduler::Wait);
- }
-
- /// Test that we are only advised to issue a PVSS at the
- /// beginning of our window, not for every block in it
- #[test]
- fn test_pvss_wait_middle_of_window() {
- let mut dkg = setup_dkg(0);
- assert_eq!(dkg.increase_block(), PvssScheduler::Issue);
- if let DkgState::Sharing { block, .. } = dkg.state {
- assert!(dkg.window.0 < block && block < dkg.window.1);
- } else {
- panic!("Test failed");
- }
- assert_eq!(dkg.increase_block(), PvssScheduler::Wait);
- }
}
/// Test aggregating transcripts into final key
From 5ba7451f1ae54995e90570b2e970263124ffa803 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Thu, 2 Feb 2023 15:01:50 +0100
Subject: [PATCH 10/36] sketch the server api
---
ferveo-python/src/lib.rs | 89 +++++++++++++++++---
ferveo/benches/benchmarks/validity_checks.rs | 2 +-
ferveo/examples/pvdkg.rs | 2 +-
ferveo/src/api.rs | 81 +++++++++++++++---
ferveo/src/dkg/common.rs | 2 +-
ferveo/src/dkg/pv.rs | 24 ++++--
ferveo/src/vss/pvss.rs | 3 +-
tpke-wasm/src/lib.rs | 2 +-
tpke/src/api.rs | 11 ++-
9 files changed, 178 insertions(+), 38 deletions(-)
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
index dc1568b5..7ed856ea 100644
--- a/ferveo-python/src/lib.rs
+++ b/ferveo-python/src/lib.rs
@@ -4,30 +4,89 @@ use pyo3::prelude::*;
#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::From, derive_more::AsRef)]
-pub struct ExternalValidator(ferveo::api::ExternalValidator);
+pub struct Validator(ferveo::api::Validator);
+
+#[pyclass(module = "ferveo")]
+#[derive(Clone, derive_more::From, derive_more::AsRef)]
+pub struct Transcript(ferveo::api::Transcript);
+
+#[derive(FromPyObject)]
+pub struct ValidatorMessage(Validator, Transcript);
#[pyclass(module = "ferveo")]
#[derive(derive_more::From, derive_more::AsRef)]
-pub struct PubliclyVerifiableDkg(ferveo::api::PubliclyVerifiableDkg);
+pub struct Dkg(ferveo::api::Dkg);
#[pymethods]
-impl PubliclyVerifiableDkg {
+impl Dkg {
#[new]
pub fn new(
tau: u64,
shares_num: u32,
security_threshold: u32,
- validators: Vec,
- me: ExternalValidator,
+ validators: Vec,
+ me: Validator,
) -> Self {
- let validators = validators.into_iter().map(|v| v.0).collect();
- let me = me.0;
- Self(ferveo::api::PubliclyVerifiableDkg::new(
+ let validators: Vec<_> = validators.into_iter().map(|v| v.0).collect();
+ Self(ferveo::api::Dkg::new(
tau,
shares_num,
security_threshold,
- validators,
- me,
+ &validators,
+ &me.0,
+ ))
+ }
+
+ pub fn generate_transcript(&self) -> Transcript {
+ Transcript(self.0.generate_transcript())
+ }
+
+ pub fn aggregate_transcripts(
+ &self,
+ messages: Vec,
+ ) -> AggregatedTranscript {
+ let messages = messages
+ .into_iter()
+ .map(|message| (message.0 .0, message.1 .0))
+ .collect();
+ AggregatedTranscript(self.0.aggregate_transcripts(messages))
+ }
+}
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct Ciphertext(ferveo::api::Ciphertext);
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct UnblindingKey(ferveo::api::UnblindingKey);
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct DecryptionShare(ferveo::api::DecryptionShare);
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct AggregatedTranscript(ferveo::api::AggregatedTranscript);
+
+#[pymethods]
+impl AggregatedTranscript {
+ pub fn validate(&self, dkg: &Dkg) -> bool {
+ self.0.validate(&dkg.0)
+ }
+
+ pub fn create_decryption_share(
+ &self,
+ dkg: &Dkg,
+ ciphertext: &Ciphertext,
+ aad: &[u8],
+ unblinding_key: &UnblindingKey,
+ ) -> DecryptionShare {
+ DecryptionShare(self.0.create_decryption_share(
+ &dkg.0,
+ &ciphertext.0,
+ aad,
+ &unblinding_key.0,
))
}
}
@@ -35,8 +94,12 @@ impl PubliclyVerifiableDkg {
/// A Python module implemented in Rust.
#[pymodule]
fn _ferveo(_py: Python, m: &PyModule) -> PyResult<()> {
- m.add_class::()?;
- m.add_class::()?;
-
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
Ok(())
}
diff --git a/ferveo/benches/benchmarks/validity_checks.rs b/ferveo/benches/benchmarks/validity_checks.rs
index a564ab67..c9d6a33d 100644
--- a/ferveo/benches/benchmarks/validity_checks.rs
+++ b/ferveo/benches/benchmarks/validity_checks.rs
@@ -39,7 +39,7 @@ fn setup_dkg(
let validators = gen_validators(&keypairs);
let me = validators[validator].clone();
PubliclyVerifiableDkg::new(
- validators,
+ &validators,
Params {
tau: 0,
security_threshold: shares_num / 3,
diff --git a/ferveo/examples/pvdkg.rs b/ferveo/examples/pvdkg.rs
index be2e92c5..bca8d077 100644
--- a/ferveo/examples/pvdkg.rs
+++ b/ferveo/examples/pvdkg.rs
@@ -40,7 +40,7 @@ pub fn setup_dkg(
let validators = gen_validators(&keypairs);
let me = validators[validator].clone();
PubliclyVerifiableDkg::new(
- validators,
+ &validators,
Params {
tau: 0,
security_threshold: shares_num / 3,
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
index 1b7c6e8e..be5c1328 100644
--- a/ferveo/src/api.rs
+++ b/ferveo/src/api.rs
@@ -1,23 +1,31 @@
+use ark_poly::EvaluationDomain;
+use group_threshold_cryptography as tpke;
+use rand::thread_rng;
+
pub type E = ark_bls12_381::Bls12_381;
#[derive(Clone)]
-pub struct ExternalValidator(ferveo_common::ExternalValidator);
+pub struct Validator(ferveo_common::ExternalValidator);
-pub struct PubliclyVerifiableDkg(crate::PubliclyVerifiableDkg);
+#[derive(Clone)]
+pub struct Transcript(crate::PubliclyVerifiableSS);
-impl PubliclyVerifiableDkg {
+#[derive(Clone)]
+pub struct Dkg(crate::PubliclyVerifiableDkg);
+
+impl Dkg {
pub fn new(
tau: u64,
shares_num: u32,
security_threshold: u32,
- validators: Vec,
- me: ExternalValidator,
+ validators: &[Validator],
+ me: &Validator,
) -> Self {
- let validators = validators
- .into_iter()
- .map(|v| v.0)
+ let validators = &validators
+ .iter()
+ .map(|v| v.0.clone())
.collect::>>();
- let me = me.0;
+ let me = &me.0;
let params = crate::Params {
tau,
security_threshold,
@@ -29,10 +37,63 @@ impl PubliclyVerifiableDkg {
let dkg = crate::PubliclyVerifiableDkg::::new(
validators,
params,
- &me,
+ me,
session_keypair,
)
.unwrap();
Self(dkg)
}
+
+ pub fn generate_transcript(&self) -> Transcript {
+ let rng = &mut thread_rng();
+ Transcript(self.0.create_share(rng).unwrap())
+ }
+
+ pub fn aggregate_transcripts(
+ &self,
+ messages: Vec<(Validator, Transcript)>,
+ ) -> AggregatedTranscript {
+ // Avoid mutating current state
+ // TODO: Rewrite `apply_message` to not require mutability after validating this API design
+ let mut dkg = self.0.clone();
+ for (validator, transcript) in messages {
+ dkg.apply_message(validator.0, crate::Message::Deal(transcript.0))
+ .unwrap();
+ }
+
+ AggregatedTranscript(crate::pvss::aggregate(&self.0))
+ }
+}
+
+pub struct Ciphertext(tpke::api::TpkeCiphertext);
+
+pub struct UnblindingKey(tpke::api::TpkeUnblindingKey);
+
+pub struct DecryptionShare(tpke::api::TpkeDecryptionShareSimplePrecomputed);
+
+pub struct AggregatedTranscript(
+ crate::PubliclyVerifiableSS,
+);
+
+impl AggregatedTranscript {
+ pub fn validate(&self, dkg: &Dkg) -> bool {
+ self.0.verify_full(&dkg.0)
+ }
+
+ pub fn create_decryption_share(
+ &self,
+ dkg: &Dkg,
+ ciphertext: &Ciphertext,
+ aad: &[u8],
+ unblinding_key: &UnblindingKey,
+ ) -> DecryptionShare {
+ let domain_points: Vec<_> = dkg.0.domain.elements().collect();
+ DecryptionShare(self.0.make_decryption_share_simple_precomputed(
+ &ciphertext.0,
+ aad,
+ &unblinding_key.0,
+ dkg.0.me,
+ &domain_points,
+ ))
+ }
}
diff --git a/ferveo/src/dkg/common.rs b/ferveo/src/dkg/common.rs
index c519db1b..a96cebbb 100644
--- a/ferveo/src/dkg/common.rs
+++ b/ferveo/src/dkg/common.rs
@@ -3,7 +3,7 @@ use ferveo_common::ExternalValidator;
use itertools::izip;
pub fn make_validators(
- validators: Vec>,
+ validators: &[ExternalValidator],
) -> Vec> {
validators
.iter()
diff --git a/ferveo/src/dkg/pv.rs b/ferveo/src/dkg/pv.rs
index b2d6d907..07d6cd82 100644
--- a/ferveo/src/dkg/pv.rs
+++ b/ferveo/src/dkg/pv.rs
@@ -6,10 +6,14 @@ use ark_ff::Field;
use ark_serialize::*;
use ark_std::{end_timer, start_timer};
use ferveo_common::{ExternalValidator, PublicKey};
+use rand::RngCore;
use std::collections::BTreeMap;
/// The DKG context that holds all of the local state for participating in the DKG
-#[derive(Debug, CanonicalSerialize, CanonicalDeserialize)]
+// TODO: Consider removing Clone to avoid accidentally NOT-mutating state.
+// Currently, we're assuming that the DKG is only mutated by the owner of the instance.
+// Consider removing Clone after finalizing ferveo::api
+#[derive(Clone, Debug, CanonicalSerialize, CanonicalDeserialize)]
pub struct PubliclyVerifiableDkg {
pub params: Params,
pub pvss_params: PubliclyVerifiableParams,
@@ -30,7 +34,7 @@ impl PubliclyVerifiableDkg {
/// `me` the validator creating this instance
/// `session_keypair` the keypair for `me`
pub fn new(
- validators: Vec>,
+ validators: &[ExternalValidator],
params: Params,
me: &ExternalValidator,
session_keypair: ferveo_common::Keypair,
@@ -69,10 +73,10 @@ impl PubliclyVerifiableDkg {
/// Create a new PVSS instance within this DKG session, contributing to the final key
/// `rng` is a cryptographic random number generator
/// Returns a PVSS dealing message to post on-chain
- pub fn share(&mut self, rng: &mut R) -> Result> {
+ pub fn share(&mut self, rng: &mut R) -> Result> {
use ark_std::UniformRand;
print_time!("PVSS Sharing");
- let vss = Pvss::::new(&E::Fr::rand(rng), self, rng)?;
+ let vss = self.create_share(rng)?;
match self.state {
DkgState::Sharing { .. } | DkgState::Dealt => {
Ok(Message::Deal(vss))
@@ -83,6 +87,14 @@ impl PubliclyVerifiableDkg {
}
}
+ pub fn create_share(
+ &self,
+ rng: &mut R,
+ ) -> Result> {
+ use ark_std::UniformRand;
+ Pvss::::new(&E::Fr::rand(rng), self, rng)
+ }
+
/// Aggregate all received PVSS messages into a single message, prepared to post on-chain
pub fn aggregate(&self) -> Result> {
match self.state {
@@ -278,7 +290,7 @@ pub(crate) mod test_common {
let validators = gen_n_validators(&keypairs, shares_num);
let me = validators[my_index].clone();
PubliclyVerifiableDkg::new(
- validators,
+ &validators,
Params {
tau: 0,
security_threshold,
@@ -348,7 +360,7 @@ mod test_dkg_init {
let keypairs = gen_keypairs();
let keypair = ferveo_common::Keypair::::new(rng);
let err = PubliclyVerifiableDkg::::new(
- gen_validators(&keypairs),
+ &gen_validators(&keypairs),
Params {
tau: 0,
security_threshold: 4,
diff --git a/ferveo/src/vss/pvss.rs b/ferveo/src/vss/pvss.rs
index 5d0a92bf..83ee87b0 100644
--- a/ferveo/src/vss/pvss.rs
+++ b/ferveo/src/vss/pvss.rs
@@ -14,6 +14,7 @@ use group_threshold_cryptography::{
DecryptionShareSimple, DecryptionShareSimplePrecomputed, PrivateKeyShare,
};
use itertools::{zip_eq, Itertools};
+use rand::RngCore;
use subproductdomain::fast_multiexp;
/// These are the blinded evaluations of shares of a single random polynomial
@@ -70,7 +71,7 @@ impl PubliclyVerifiableSS {
/// `s`: the secret constant coefficient to share
/// `dkg`: the current DKG session
/// `rng` a cryptographic random number generator
- pub fn new(
+ pub fn new(
s: &E::Fr,
dkg: &PubliclyVerifiableDkg,
rng: &mut R,
diff --git a/tpke-wasm/src/lib.rs b/tpke-wasm/src/lib.rs
index 647cb884..3ad5bfb2 100644
--- a/tpke-wasm/src/lib.rs
+++ b/tpke-wasm/src/lib.rs
@@ -252,7 +252,7 @@ pub struct SharedSecret(TpkeSharedSecret);
#[wasm_bindgen]
#[derive(Clone, Debug)]
pub struct SharedSecretBuilder {
- shares: Vec,
+ shares: Vec,
contexts: Vec,
}
diff --git a/tpke/src/api.rs b/tpke/src/api.rs
index 33fa3597..29bb947f 100644
--- a/tpke/src/api.rs
+++ b/tpke/src/api.rs
@@ -13,8 +13,11 @@ use std::convert::TryInto;
pub type E = ark_bls12_381::Bls12_381;
pub type TpkePublicKey = ark_bls12_381::G1Affine;
pub type TpkePrivateKey = ark_bls12_381::G2Affine;
+pub type TpkeUnblindingKey = ark_bls12_381::Fr;
pub type TpkeCiphertext = crate::Ciphertext;
-pub type TpkeDecryptionShare = crate::DecryptionShareFast;
+pub type TpkeDecryptionShareFast = crate::DecryptionShareFast;
+pub type TpkeDecryptionShareSimplePrecomputed =
+ crate::DecryptionShareSimplePrecomputed;
pub type TpkePublicDecryptionContext = crate::PublicDecryptionContextFast;
pub type TpkeSharedSecret =
::Fqk;
@@ -99,7 +102,7 @@ impl PrivateDecryptionContext {
}
#[derive(Clone, Debug)]
-pub struct DecryptionShare(pub TpkeDecryptionShare);
+pub struct DecryptionShare(pub TpkeDecryptionShareFast);
impl DecryptionShare {
pub fn to_bytes(&self) -> Vec {
@@ -107,7 +110,7 @@ impl DecryptionShare {
}
pub fn from_bytes(bytes: &[u8]) -> Self {
- let share = TpkeDecryptionShare::from_bytes(bytes);
+ let share = TpkeDecryptionShareFast::from_bytes(bytes);
Self(share)
}
}
@@ -162,7 +165,7 @@ impl ParticipantPayload {
.mul(self.decryption_context.b_inv)
.into_affine();
- DecryptionShare(TpkeDecryptionShare {
+ DecryptionShare(TpkeDecryptionShareFast {
decrypter_index: self.decryption_context.decrypter_index,
decryption_share,
})
From 39f7f39cf618e6c46a809707cfc93bf1aae4e49e Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Mon, 6 Feb 2023 12:04:57 +0100
Subject: [PATCH 11/36] simple tdec on server side
---
Cargo.lock | 1 +
ferveo-python/Cargo.toml | 1 +
ferveo-python/src/lib.rs | 17 ++++-
ferveo/benches/bench_main.rs | 3 +-
ferveo/src/api.rs | 136 ++++++++++++++++++++++++++++++++---
ferveo/src/dkg/pv.rs | 16 +++++
ferveo/src/lib.rs | 2 +
ferveo/src/vss/pvss.rs | 6 +-
tpke/src/decryption.rs | 4 +-
9 files changed, 168 insertions(+), 18 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index c19b5168..9f92b10b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -944,6 +944,7 @@ dependencies = [
"ferveo",
"pyo3",
"pyo3-build-config",
+ "rand 0.8.5",
]
[[package]]
diff --git a/ferveo-python/Cargo.toml b/ferveo-python/Cargo.toml
index d8f14035..18ceeeca 100644
--- a/ferveo-python/Cargo.toml
+++ b/ferveo-python/Cargo.toml
@@ -11,6 +11,7 @@ crate-type = ["cdylib"]
pyo3 = "0.17.3"
ferveo = { path = "../ferveo" }
derive_more = { version = "0.99", default-features = false, features = ["from", "as_ref"] }
+rand = "0.8"
[build-dependencies]
pyo3-build-config = "*"
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
index 7ed856ea..ac69ca48 100644
--- a/ferveo-python/src/lib.rs
+++ b/ferveo-python/src/lib.rs
@@ -1,6 +1,7 @@
extern crate alloc;
use pyo3::prelude::*;
+use rand::thread_rng;
#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::From, derive_more::AsRef)]
@@ -10,6 +11,10 @@ pub struct Validator(ferveo::api::Validator);
#[derive(Clone, derive_more::From, derive_more::AsRef)]
pub struct Transcript(ferveo::api::Transcript);
+#[pyclass(module = "ferveo")]
+#[derive(Clone, derive_more::From, derive_more::AsRef)]
+pub struct DkgPublicKey(ferveo::api::DkgPublicKey);
+
#[derive(FromPyObject)]
pub struct ValidatorMessage(Validator, Transcript);
@@ -37,15 +42,21 @@ impl Dkg {
))
}
+ pub fn final_key(&self) -> DkgPublicKey {
+ DkgPublicKey(self.0.final_key())
+ }
+
pub fn generate_transcript(&self) -> Transcript {
- Transcript(self.0.generate_transcript())
+ let rng = &mut thread_rng();
+ Transcript(self.0.generate_transcript(rng))
}
pub fn aggregate_transcripts(
- &self,
+ // TODO: Avoid mutating current state
+ &mut self,
messages: Vec,
) -> AggregatedTranscript {
- let messages = messages
+ let messages = &messages
.into_iter()
.map(|message| (message.0 .0, message.1 .0))
.collect();
diff --git a/ferveo/benches/bench_main.rs b/ferveo/benches/bench_main.rs
index a177b183..fbd7c746 100644
--- a/ferveo/benches/bench_main.rs
+++ b/ferveo/benches/bench_main.rs
@@ -3,7 +3,8 @@ use criterion::criterion_main;
mod benchmarks;
criterion_main! {
- // benchmarks::pairing::micro,//bench_batch_inverse,
+ // benchmarks::pairing::micro,
+ // bench_batch_inverse,
// benchmarks::pairing::ec,
benchmarks::validity_checks::validity_checks,
}
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
index be5c1328..32d14ad0 100644
--- a/ferveo/src/api.rs
+++ b/ferveo/src/api.rs
@@ -1,15 +1,19 @@
use ark_poly::EvaluationDomain;
use group_threshold_cryptography as tpke;
-use rand::thread_rng;
+use rand::rngs::StdRng;
+use rand::{thread_rng, RngCore};
pub type E = ark_bls12_381::Bls12_381;
#[derive(Clone)]
pub struct Validator(ferveo_common::ExternalValidator);
-#[derive(Clone)]
+#[derive(Clone, Debug)]
pub struct Transcript(crate::PubliclyVerifiableSS);
+#[derive(Clone)]
+pub struct DkgPublicKey(tpke::api::TpkePublicKey);
+
#[derive(Clone)]
pub struct Dkg(crate::PubliclyVerifiableDkg);
@@ -44,20 +48,23 @@ impl Dkg {
Self(dkg)
}
- pub fn generate_transcript(&self) -> Transcript {
- let rng = &mut thread_rng();
+ pub fn final_key(&self) -> DkgPublicKey {
+ DkgPublicKey(self.0.final_key())
+ }
+
+ pub fn generate_transcript(&self, rng: &mut R) -> Transcript {
Transcript(self.0.create_share(rng).unwrap())
}
pub fn aggregate_transcripts(
- &self,
- messages: Vec<(Validator, Transcript)>,
+ &mut self,
+ messages: &Vec<(Validator, Transcript)>,
) -> AggregatedTranscript {
// Avoid mutating current state
- // TODO: Rewrite `apply_message` to not require mutability after validating this API design
- let mut dkg = self.0.clone();
+ // TODO: Rewrite `deal` to not require mutability after validating this API design
for (validator, transcript) in messages {
- dkg.apply_message(validator.0, crate::Message::Deal(transcript.0))
+ self.0
+ .deal(validator.0.clone(), transcript.0.clone())
.unwrap();
}
@@ -97,3 +104,114 @@ impl AggregatedTranscript {
))
}
}
+
+#[cfg(test)]
+mod test_ferveo_api {
+ use crate::api::{Ciphertext, Dkg, UnblindingKey, Validator};
+ use crate::dkg::test_common::{
+ gen_n_keypairs, gen_n_validators, setup_dealt_dkg_with_n_validators,
+ setup_dkg_for_n_validators,
+ };
+ use crate::{aggregate, Message, Params, PubliclyVerifiableDkg};
+ use ark_bls12_381::{Bls12_381 as E, Fr, G2Projective};
+ use ark_ec::ProjectiveCurve;
+ use ark_poly::EvaluationDomain;
+ use ark_serialize::CanonicalSerialize;
+ use ark_std::UniformRand;
+ use ferveo_common::PublicKey;
+ use group_threshold_cryptography as tpke;
+ use itertools::{iproduct, izip};
+ use rand::prelude::StdRng;
+ use rand::SeedableRng;
+ use std::collections::HashMap;
+ use std::fmt::format;
+
+ #[test]
+ fn test_server_api_simple_tdec_precomputed() {
+ let rng = &mut StdRng::seed_from_u64(0);
+
+ let tau = 1;
+ let security_threshold = 3;
+ let shares_num = 4;
+
+ let validator_keypairs = gen_n_keypairs(shares_num);
+ let validators = validator_keypairs
+ .iter()
+ .enumerate()
+ .map(|(i, keypair)| {
+ Validator(ferveo_common::ExternalValidator {
+ address: format!("validator-{}", i),
+ public_key: keypair.public(),
+ })
+ })
+ .collect::>();
+
+ // Each validator holds their own DKG instance and generates a transcript every
+ // every validator, including themselves
+ let messages: Vec<_> = validators
+ .iter()
+ .map(|sender| {
+ let dkg = Dkg::new(
+ tau,
+ shares_num,
+ security_threshold,
+ &validators,
+ sender,
+ );
+ (sender.clone(), dkg.generate_transcript(rng))
+ })
+ .collect();
+
+ // Now that every validator holds a dkg instance and a transcript for every other validator,
+ // every validator can aggregate the transcripts
+ let me = validators[0].clone();
+ let mut dkg =
+ Dkg::new(tau, shares_num, security_threshold, &validators, &me);
+ let pvss_aggregated = dkg.aggregate_transcripts(&messages);
+
+ // At this point, any given validator should be able to provide a DKG public key
+ let public_key = dkg.final_key();
+
+ // In the meantime, the client creates a ciphertext and decryption request
+ let msg: &[u8] = "abc".as_bytes();
+ let aad: &[u8] = "my-aad".as_bytes();
+ let ciphertext = tpke::encrypt::<_, E>(msg, aad, &public_key.0, rng);
+
+ // Having aggregated the transcripts, the validators can now create decryption shares
+ let decryption_shares: Vec<_> = izip!(&validators, &validator_keypairs)
+ .map(|(validator, validator_keypair)| {
+ // Each validator holds their own instance of DKG and creates their own aggregate
+ let mut dkg = Dkg::new(
+ tau,
+ shares_num,
+ security_threshold,
+ &validators,
+ validator,
+ );
+ let aggregate = dkg.aggregate_transcripts(&messages);
+ assert!(pvss_aggregated.validate(&dkg));
+ aggregate.create_decryption_share(
+ &dkg,
+ &Ciphertext(ciphertext.clone()),
+ aad,
+ &UnblindingKey(validator_keypair.decryption_key),
+ )
+ })
+ .collect();
+
+ // Now, the decryption share can be used to decrypt the ciphertext
+ // This part is part of the client API
+ let decryption_shares: Vec<_> = decryption_shares
+ .iter()
+ .map(|decryption_share| decryption_share.0.clone())
+ .collect();
+
+ let shared_secret =
+ tpke::share_combine_simple_precomputed::(&decryption_shares);
+
+ let plaintext =
+ tpke::decrypt_with_shared_secret(&ciphertext, aad, &shared_secret)
+ .unwrap();
+ assert_eq!(plaintext, msg);
+ }
+}
diff --git a/ferveo/src/dkg/pv.rs b/ferveo/src/dkg/pv.rs
index 07d6cd82..672cf30c 100644
--- a/ferveo/src/dkg/pv.rs
+++ b/ferveo/src/dkg/pv.rs
@@ -194,6 +194,7 @@ impl PubliclyVerifiableDkg {
} = &mut self.state
{
*accumulated_shares += 1;
+ // TODO: Should be `== self.params.shares_num` instead?
if *accumulated_shares >= self.params.shares_num - self.params.security_threshold {
self.state = DkgState::Dealt;
}
@@ -212,6 +213,21 @@ impl PubliclyVerifiableDkg {
)),
}
}
+
+ pub fn deal(
+ &mut self,
+ sender: ExternalValidator,
+ pvss: Pvss,
+ ) -> Result<()> {
+ // Add the ephemeral public key and pvss transcript
+ let sender = self
+ .validators
+ .iter()
+ .position(|probe| sender.address == probe.validator.address)
+ .context("dkg received unknown dealer")?;
+ self.vss.insert(sender as u32, pvss);
+ Ok(())
+ }
}
#[derive(
diff --git a/ferveo/src/lib.rs b/ferveo/src/lib.rs
index e7af3129..36ba9482 100644
--- a/ferveo/src/lib.rs
+++ b/ferveo/src/lib.rs
@@ -46,6 +46,8 @@ mod test_dkg_full {
Ciphertext, DecryptionShareSimple, DecryptionShareSimplePrecomputed,
};
use itertools::{zip_eq, Itertools};
+ use rand::prelude::StdRng;
+ use rand::SeedableRng;
type Fqk = ::Fqk;
diff --git a/ferveo/src/vss/pvss.rs b/ferveo/src/vss/pvss.rs
index 83ee87b0..07f692cc 100644
--- a/ferveo/src/vss/pvss.rs
+++ b/ferveo/src/vss/pvss.rs
@@ -21,11 +21,11 @@ use subproductdomain::fast_multiexp;
pub type ShareEncryptions = ::G2Affine;
/// Marker struct for unaggregated PVSS transcripts
-#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug)]
+#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct Unaggregated;
/// Marker struct for aggregated PVSS transcripts
-#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug)]
+#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct Aggregated;
/// Trait gate used to add extra methods to aggregated PVSS transcripts
@@ -50,7 +50,7 @@ pub struct PubliclyVerifiableParams {
/// Each validator posts a transcript to the chain. Once enough
/// validators have done this (their total voting power exceeds
/// 2/3 the total), this will be aggregated into a final key
-#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug)]
+#[derive(CanonicalSerialize, CanonicalDeserialize, Clone, Debug, PartialEq)]
pub struct PubliclyVerifiableSS {
/// Used in Feldman commitment to the VSS polynomial, F = g^{\phi}
pub coeffs: Vec,
diff --git a/tpke/src/decryption.rs b/tpke/src/decryption.rs
index d133b207..f401316f 100644
--- a/tpke/src/decryption.rs
+++ b/tpke/src/decryption.rs
@@ -36,7 +36,7 @@ impl DecryptionShareFast {
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq)]
pub struct ValidatorShareChecksum {
// TODO: Consider replacing named inner variable with () syntax
pub checksum: E::G1Affine,
@@ -148,7 +148,7 @@ impl DecryptionShareSimple {
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq)]
pub struct DecryptionShareSimplePrecomputed {
pub decrypter_index: usize,
pub decryption_share: E::Fqk,
From fd47f97510fad4132712dc58714c19fc0fd0d7e4 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Mon, 6 Feb 2023 16:14:44 +0100
Subject: [PATCH 12/36] add ferveo-python example
---
Cargo.lock | 1 +
ferveo-common/src/keypair.rs | 3 +-
ferveo-common/src/lib.rs | 2 -
ferveo-python/Cargo.toml | 3 +-
ferveo-python/examples/server_api.py | 70 ++++++++++++++
ferveo-python/ferveo/__init__.py | 12 ++-
ferveo-python/ferveo/__init__.pyi | 80 +++++++++++++++-
ferveo-python/src/lib.rs | 121 ++++++++++++++++++++++--
ferveo/src/api.rs | 134 +++++++++++++++++++++------
tpke-wasm/src/lib.rs | 5 +-
tpke/src/api.rs | 5 +-
11 files changed, 386 insertions(+), 50 deletions(-)
create mode 100644 ferveo-python/examples/server_api.py
diff --git a/Cargo.lock b/Cargo.lock
index 9f92b10b..e5c860e8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -942,6 +942,7 @@ version = "0.1.0"
dependencies = [
"derive_more",
"ferveo",
+ "group-threshold-cryptography",
"pyo3",
"pyo3-build-config",
"rand 0.8.5",
diff --git a/ferveo-common/src/keypair.rs b/ferveo-common/src/keypair.rs
index b57a3f1c..8feac538 100644
--- a/ferveo-common/src/keypair.rs
+++ b/ferveo-common/src/keypair.rs
@@ -3,6 +3,7 @@ use ark_ec::{AffineCurve, ProjectiveCurve};
use ark_serialize::{
CanonicalDeserialize, CanonicalSerialize, Read, SerializationError, Write,
};
+use ark_std::rand::RngCore;
use serde::*;
#[derive(Copy, Clone, Debug)]
@@ -69,7 +70,7 @@ impl Keypair {
}
/// Creates a new ephemeral session key for participating in the DKG
- pub fn new(rng: &mut R) -> Self {
+ pub fn new(rng: &mut R) -> Self {
use ark_std::UniformRand;
Self {
decryption_key: E::Fr::rand(rng),
diff --git a/ferveo-common/src/lib.rs b/ferveo-common/src/lib.rs
index 7868a5d6..8ae67b93 100644
--- a/ferveo-common/src/lib.rs
+++ b/ferveo-common/src/lib.rs
@@ -22,8 +22,6 @@ pub struct Validator {
pub share_index: usize,
}
-impl Rng for ark_std::rand::prelude::StdRng {}
-
pub trait Rng: ark_std::rand::CryptoRng + ark_std::rand::RngCore {}
pub mod ark_serde {
diff --git a/ferveo-python/Cargo.toml b/ferveo-python/Cargo.toml
index 18ceeeca..6b303b83 100644
--- a/ferveo-python/Cargo.toml
+++ b/ferveo-python/Cargo.toml
@@ -8,8 +8,9 @@ edition = "2018"
crate-type = ["cdylib"]
[dependencies]
-pyo3 = "0.17.3"
+pyo3 = { version = "0.17.3", features = ["macros"] }
ferveo = { path = "../ferveo" }
+group-threshold-cryptography = { path = "../tpke" }
derive_more = { version = "0.99", default-features = false, features = ["from", "as_ref"] }
rand = "0.8"
diff --git a/ferveo-python/examples/server_api.py b/ferveo-python/examples/server_api.py
new file mode 100644
index 00000000..2b9e4c14
--- /dev/null
+++ b/ferveo-python/examples/server_api.py
@@ -0,0 +1,70 @@
+from ferveo import (
+ encrypt,
+ combine_decryption_shares,
+ decrypt_with_shared_secret,
+ Keypair,
+ PublicKey,
+ ExternalValidator,
+ Transcript,
+ Dkg,
+ Ciphertext,
+ UnblindingKey,
+ DecryptionShare,
+ AggregatedTranscript,
+)
+
+tau = 1
+security_threshold = 3
+shares_num = 4
+validator_keypairs = [Keypair.random() for _ in range(0, shares_num)]
+validators = [
+ ExternalValidator(f"validator-{i}", keypair.public_key)
+ for i, keypair in enumerate(validator_keypairs)
+]
+me = validators[0]
+
+messages = []
+for sender in validators:
+ dkg = Dkg(
+ tau=tau,
+ shares_num=shares_num,
+ security_threshold=security_threshold,
+ validators=validators,
+ me=sender,
+ )
+ messages.append((sender, dkg.generate_transcript()))
+
+dkg = Dkg(
+ tau=tau,
+ shares_num=shares_num,
+ security_threshold=security_threshold,
+ validators=validators,
+ me=me,
+)
+pvss_aggregated = dkg.aggregate_transcripts(messages)
+assert pvss_aggregated.validate(dkg)
+
+msg = "abc".encode()
+aad = "my-aad".encode()
+ciphertext = encrypt(msg, aad, dkg.final_key)
+
+decryption_shares = []
+for validator, validator_keypair in zip(validators, validator_keypairs):
+ dkg = Dkg(
+ tau=tau,
+ shares_num=shares_num,
+ security_threshold=security_threshold,
+ validators=validators,
+ me=validator,
+ )
+ aggregate = dkg.aggregate_transcripts(messages)
+ assert pvss_aggregated.validate(dkg)
+ decryption_share = aggregate.create_decryption_share(
+ dkg, ciphertext, aad, validator_keypair
+ )
+ decryption_shares.append(decryption_share)
+
+shared_secret = combine_decryption_shares(decryption_shares)
+
+plaintext = decrypt_with_shared_secret(ciphertext, aad, shared_secret)
+assert bytes(plaintext) == msg
diff --git a/ferveo-python/ferveo/__init__.py b/ferveo-python/ferveo/__init__.py
index 77a421a9..a1c8e436 100644
--- a/ferveo-python/ferveo/__init__.py
+++ b/ferveo-python/ferveo/__init__.py
@@ -1,4 +1,14 @@
from ._ferveo import (
+ encrypt,
+ combine_decryption_shares,
+ decrypt_with_shared_secret,
+ Keypair,
+ PublicKey,
+ ExternalValidator,
+ Transcript,
+ Dkg,
+ Ciphertext,
+ UnblindingKey,
DecryptionShare,
- ParticipantPayload
+ AggregatedTranscript,
)
diff --git a/ferveo-python/ferveo/__init__.pyi b/ferveo-python/ferveo/__init__.pyi
index ed8e880d..4f9fd157 100644
--- a/ferveo-python/ferveo/__init__.pyi
+++ b/ferveo-python/ferveo/__init__.pyi
@@ -1,22 +1,92 @@
from typing import Sequence
+class Keypair:
+ @staticmethod
+ def random() -> Keypair:
+ ...
+
+ @staticmethod
+ def from_bytes(data: bytes) -> PublicKey:
+ ...
+
+ def __bytes__(self) -> bytes:
+ ...
+
+ public_key: PublicKey
+
+
+class PublicKey:
+ @staticmethod
+ def from_bytes(data: bytes) -> PublicKey:
+ ...
+
+ def __bytes__(self) -> bytes:
+ ...
+
+
+class Validator:
+ ...
+
+
class ExternalValidator:
- # TODO: Add a proper constructor. Currently, breaks `pip install`.
- def __init__(self):
+ def __init__(self, address: str, public_key: PublicKey):
...
-class PubliclyVerifiableDkg:
+class Transcript:
+ ...
+
+
+class DkgPublicKey:
+ ...
+
+
+class ExternalValidatorMessage:
+ ...
+
+
+class Dkg:
def __init__(
self,
+ tau: int,
+ shares_num: int,
+ security_threshold: int,
validators: Sequence[ExternalValidator],
me: ExternalValidator,
- threshold: int,
- shares_num: int,
):
...
+ final_key: DkgPublicKey
+
+ def generate_transcript(self) -> Transcript:
+ ...
+
+ def aggregate_transcripts(self, transcripts: Sequence[(ExternalValidator, Transcript)]) -> Transcript:
+ ...
+
+class Ciphertext:
+ ...
+
+
+class UnblindingKey:
+ ...
+
+
+class DecryptionShare:
+ ...
+
+
+class AggregatedTranscript:
+
+ def create_decryption_share(
+ self,
+ dkg: Dkg,
+ ciphertext: Ciphertext,
+ aad: bytes,
+ unblinding_key: UnblindingKey
+ ) -> DecryptionShare:
+ ...
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
index ac69ca48..7b90b6b9 100644
--- a/ferveo-python/src/lib.rs
+++ b/ferveo-python/src/lib.rs
@@ -3,20 +3,117 @@ extern crate alloc;
use pyo3::prelude::*;
use rand::thread_rng;
+#[pyfunction]
+pub fn encrypt(
+ message: &[u8],
+ aad: &[u8],
+ public_key: &DkgPublicKey,
+) -> Ciphertext {
+ Ciphertext(ferveo::api::encrypt(message, aad, &public_key.0))
+}
+
+#[pyfunction]
+pub fn combine_decryption_shares(shares: Vec) -> SharedSecret {
+ let shares = shares
+ .iter()
+ .map(|share| share.0.clone())
+ .collect::>();
+ SharedSecret(ferveo::api::combine_decryption_shares(&shares))
+}
+
+#[pyfunction]
+pub fn decrypt_with_shared_secret(
+ ciphertext: &Ciphertext,
+ aad: &[u8],
+ shared_secret: &SharedSecret,
+) -> Vec {
+ ferveo::api::decrypt_with_shared_secret(
+ &ciphertext.0,
+ aad,
+ &shared_secret.0,
+ )
+}
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct SharedSecret(ferveo::api::SharedSecret);
+
+#[pyclass(module = "ferveo")]
+#[derive(derive_more::From, derive_more::AsRef)]
+pub struct Keypair(ferveo::api::Keypair);
+
+#[pymethods]
+impl Keypair {
+ #[staticmethod]
+ pub fn random() -> Self {
+ Self(ferveo::api::Keypair::random(&mut thread_rng()))
+ }
+
+ #[staticmethod]
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo::api::Keypair::from_bytes(bytes))
+ }
+
+ fn __bytes__(&self) -> Vec {
+ self.0.to_bytes()
+ }
+
+ #[getter]
+ pub fn public_key(&self) -> PublicKey {
+ PublicKey(self.0.public_key())
+ }
+}
+
#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::From, derive_more::AsRef)]
-pub struct Validator(ferveo::api::Validator);
+pub struct PublicKey(ferveo::api::PublicKey);
+
+#[pymethods]
+impl PublicKey {
+ #[staticmethod]
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo::api::PublicKey::from_bytes(bytes))
+ }
+
+ pub fn to_bytes(&self) -> Vec {
+ self.0.to_bytes()
+ }
+}
+
+#[pyclass(module = "ferveo")]
+#[derive(Clone, derive_more::From, derive_more::AsRef)]
+pub struct ExternalValidator(ferveo::api::ExternalValidator);
+
+#[pymethods]
+impl ExternalValidator {
+ #[new]
+ pub fn new(address: String, public_key: PublicKey) -> Self {
+ Self(ferveo::api::ExternalValidator::new(address, public_key.0))
+ }
+}
#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::From, derive_more::AsRef)]
pub struct Transcript(ferveo::api::Transcript);
+#[pymethods]
+impl Transcript {
+ #[staticmethod]
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo::api::Transcript::from_bytes(bytes))
+ }
+
+ pub fn to_bytes(&self) -> Vec {
+ self.0.to_bytes()
+ }
+}
+
#[pyclass(module = "ferveo")]
#[derive(Clone, derive_more::From, derive_more::AsRef)]
pub struct DkgPublicKey(ferveo::api::DkgPublicKey);
#[derive(FromPyObject)]
-pub struct ValidatorMessage(Validator, Transcript);
+pub struct ExternalValidatorMessage(ExternalValidator, Transcript);
#[pyclass(module = "ferveo")]
#[derive(derive_more::From, derive_more::AsRef)]
@@ -29,8 +126,8 @@ impl Dkg {
tau: u64,
shares_num: u32,
security_threshold: u32,
- validators: Vec,
- me: Validator,
+ validators: Vec,
+ me: ExternalValidator,
) -> Self {
let validators: Vec<_> = validators.into_iter().map(|v| v.0).collect();
Self(ferveo::api::Dkg::new(
@@ -42,6 +139,7 @@ impl Dkg {
))
}
+ #[getter]
pub fn final_key(&self) -> DkgPublicKey {
DkgPublicKey(self.0.final_key())
}
@@ -54,7 +152,7 @@ impl Dkg {
pub fn aggregate_transcripts(
// TODO: Avoid mutating current state
&mut self,
- messages: Vec,
+ messages: Vec,
) -> AggregatedTranscript {
let messages = &messages
.into_iter()
@@ -73,7 +171,7 @@ pub struct Ciphertext(ferveo::api::Ciphertext);
pub struct UnblindingKey(ferveo::api::UnblindingKey);
#[pyclass(module = "ferveo")]
-#[derive(derive_more::From, derive_more::AsRef)]
+#[derive(Clone, derive_more::AsRef, derive_more::From)]
pub struct DecryptionShare(ferveo::api::DecryptionShare);
#[pyclass(module = "ferveo")]
@@ -91,13 +189,13 @@ impl AggregatedTranscript {
dkg: &Dkg,
ciphertext: &Ciphertext,
aad: &[u8],
- unblinding_key: &UnblindingKey,
+ validator_keypair: &Keypair,
) -> DecryptionShare {
DecryptionShare(self.0.create_decryption_share(
&dkg.0,
&ciphertext.0,
aad,
- &unblinding_key.0,
+ &validator_keypair.0,
))
}
}
@@ -105,7 +203,12 @@ impl AggregatedTranscript {
/// A Python module implemented in Rust.
#[pymodule]
fn _ferveo(_py: Python, m: &PyModule) -> PyResult<()> {
- m.add_class::()?;
+ m.add_function(wrap_pyfunction!(encrypt, m)?)?;
+ m.add_function(wrap_pyfunction!(combine_decryption_shares, m)?)?;
+ m.add_function(wrap_pyfunction!(decrypt_with_shared_secret, m)?)?;
+ m.add_class::()?;
+ m.add_class::()?;
+ m.add_class::()?;
m.add_class::()?;
m.add_class::()?;
m.add_class::()?;
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
index 32d14ad0..f13a913c 100644
--- a/ferveo/src/api.rs
+++ b/ferveo/src/api.rs
@@ -1,18 +1,107 @@
use ark_poly::EvaluationDomain;
+use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
+use bincode::Options;
use group_threshold_cryptography as tpke;
use rand::rngs::StdRng;
-use rand::{thread_rng, RngCore};
+use rand::{thread_rng, RngCore, SeedableRng};
pub type E = ark_bls12_381::Bls12_381;
+pub fn encrypt(
+ message: &[u8],
+ aad: &[u8],
+ public_key: &DkgPublicKey,
+) -> Ciphertext {
+ Ciphertext(tpke::api::encrypt(message, aad, &public_key.0))
+}
+
+pub fn combine_decryption_shares(
+ decryption_shares: &[DecryptionShare],
+) -> SharedSecret {
+ let shares = decryption_shares
+ .iter()
+ .map(|share| share.0.clone())
+ .collect::>();
+ SharedSecret(tpke::share_combine_simple_precomputed::(&shares))
+}
+
+pub fn decrypt_with_shared_secret(
+ ciphertext: &Ciphertext,
+ aad: &[u8],
+ shared_secret: &SharedSecret,
+) -> Vec {
+ tpke::decrypt_with_shared_secret(&ciphertext.0, aad, &shared_secret.0)
+ .unwrap()
+}
+
+pub struct SharedSecret(tpke::api::TpkeSharedSecret);
+
+pub struct Keypair(ferveo_common::Keypair);
+
+impl Keypair {
+ pub fn random(rng: &mut R) -> Self {
+ Self(ferveo_common::Keypair::::new(rng))
+ }
+
+ pub fn public_key(&self) -> PublicKey {
+ PublicKey(self.0.public())
+ }
+
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo_common::Keypair::::deserialize(bytes).unwrap())
+ }
+
+ pub fn to_bytes(&self) -> Vec {
+ let mut buf = vec![];
+ self.0.serialize(&mut buf).unwrap();
+ buf
+ }
+}
+
+#[derive(Clone)]
+pub struct PublicKey(ferveo_common::PublicKey);
+
+impl PublicKey {
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo_common::PublicKey::::deserialize(bytes).unwrap())
+ }
+
+ pub fn to_bytes(&self) -> Vec {
+ let mut buf = vec![];
+ self.0.serialize(&mut buf).unwrap();
+ buf
+ }
+}
+
#[derive(Clone)]
-pub struct Validator(ferveo_common::ExternalValidator);
+pub struct ExternalValidator(ferveo_common::ExternalValidator);
+
+impl ExternalValidator {
+ pub fn new(address: String, public_key: PublicKey) -> Self {
+ Self(ferveo_common::ExternalValidator {
+ address,
+ public_key: public_key.0,
+ })
+ }
+}
#[derive(Clone, Debug)]
pub struct Transcript(crate::PubliclyVerifiableSS);
+impl Transcript {
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(crate::PubliclyVerifiableSS::::deserialize(bytes).unwrap())
+ }
+
+ pub fn to_bytes(&self) -> Vec {
+ let mut buf = vec![];
+ self.0.serialize(&mut buf).unwrap();
+ buf
+ }
+}
+
#[derive(Clone)]
-pub struct DkgPublicKey(tpke::api::TpkePublicKey);
+pub struct DkgPublicKey(pub tpke::api::TpkeDkgPublicKey);
#[derive(Clone)]
pub struct Dkg(crate::PubliclyVerifiableDkg);
@@ -22,8 +111,8 @@ impl Dkg {
tau: u64,
shares_num: u32,
security_threshold: u32,
- validators: &[Validator],
- me: &Validator,
+ validators: &[ExternalValidator],
+ me: &ExternalValidator,
) -> Self {
let validators = &validators
.iter()
@@ -58,7 +147,7 @@ impl Dkg {
pub fn aggregate_transcripts(
&mut self,
- messages: &Vec<(Validator, Transcript)>,
+ messages: &Vec<(ExternalValidator, Transcript)>,
) -> AggregatedTranscript {
// Avoid mutating current state
// TODO: Rewrite `deal` to not require mutability after validating this API design
@@ -72,10 +161,11 @@ impl Dkg {
}
}
-pub struct Ciphertext(tpke::api::TpkeCiphertext);
+pub struct Ciphertext(pub tpke::api::TpkeCiphertext);
pub struct UnblindingKey(tpke::api::TpkeUnblindingKey);
+#[derive(Clone)]
pub struct DecryptionShare(tpke::api::TpkeDecryptionShareSimplePrecomputed);
pub struct AggregatedTranscript(
@@ -92,13 +182,13 @@ impl AggregatedTranscript {
dkg: &Dkg,
ciphertext: &Ciphertext,
aad: &[u8],
- unblinding_key: &UnblindingKey,
+ validator_keypair: &Keypair,
) -> DecryptionShare {
let domain_points: Vec<_> = dkg.0.domain.elements().collect();
DecryptionShare(self.0.make_decryption_share_simple_precomputed(
&ciphertext.0,
aad,
- &unblinding_key.0,
+ &validator_keypair.0.decryption_key,
dkg.0.me,
&domain_points,
))
@@ -107,12 +197,8 @@ impl AggregatedTranscript {
#[cfg(test)]
mod test_ferveo_api {
- use crate::api::{Ciphertext, Dkg, UnblindingKey, Validator};
- use crate::dkg::test_common::{
- gen_n_keypairs, gen_n_validators, setup_dealt_dkg_with_n_validators,
- setup_dkg_for_n_validators,
- };
- use crate::{aggregate, Message, Params, PubliclyVerifiableDkg};
+ use crate::api::*;
+ use crate::dkg::test_common::*;
use ark_bls12_381::{Bls12_381 as E, Fr, G2Projective};
use ark_ec::ProjectiveCurve;
use ark_poly::EvaluationDomain;
@@ -139,7 +225,7 @@ mod test_ferveo_api {
.iter()
.enumerate()
.map(|(i, keypair)| {
- Validator(ferveo_common::ExternalValidator {
+ ExternalValidator(ferveo_common::ExternalValidator {
address: format!("validator-{}", i),
public_key: keypair.public(),
})
@@ -175,7 +261,7 @@ mod test_ferveo_api {
// In the meantime, the client creates a ciphertext and decryption request
let msg: &[u8] = "abc".as_bytes();
let aad: &[u8] = "my-aad".as_bytes();
- let ciphertext = tpke::encrypt::<_, E>(msg, aad, &public_key.0, rng);
+ let ciphertext = encrypt(msg, aad, &public_key);
// Having aggregated the transcripts, the validators can now create decryption shares
let decryption_shares: Vec<_> = izip!(&validators, &validator_keypairs)
@@ -192,26 +278,20 @@ mod test_ferveo_api {
assert!(pvss_aggregated.validate(&dkg));
aggregate.create_decryption_share(
&dkg,
- &Ciphertext(ciphertext.clone()),
+ &ciphertext,
aad,
- &UnblindingKey(validator_keypair.decryption_key),
+ &Keypair(*validator_keypair),
)
})
.collect();
// Now, the decryption share can be used to decrypt the ciphertext
// This part is part of the client API
- let decryption_shares: Vec<_> = decryption_shares
- .iter()
- .map(|decryption_share| decryption_share.0.clone())
- .collect();
- let shared_secret =
- tpke::share_combine_simple_precomputed::(&decryption_shares);
+ let shared_secret = combine_decryption_shares(&decryption_shares);
let plaintext =
- tpke::decrypt_with_shared_secret(&ciphertext, aad, &shared_secret)
- .unwrap();
+ decrypt_with_shared_secret(&ciphertext, aad, &shared_secret);
assert_eq!(plaintext, msg);
}
}
diff --git a/tpke-wasm/src/lib.rs b/tpke-wasm/src/lib.rs
index 3ad5bfb2..e85d37d3 100644
--- a/tpke-wasm/src/lib.rs
+++ b/tpke-wasm/src/lib.rs
@@ -101,7 +101,7 @@ impl ParticipantPayload {
#[wasm_bindgen]
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct PublicKey(
- #[serde_as(as = "tpke::serialization::SerdeAs")] pub(crate) TpkePublicKey,
+ #[serde_as(as = "tpke::serialization::SerdeAs")] pub(crate) TpkeDkgPublicKey,
);
#[wasm_bindgen]
@@ -109,7 +109,8 @@ impl PublicKey {
#[wasm_bindgen]
pub fn from_bytes(bytes: &[u8]) -> Self {
let mut reader = bytes;
- let pk = TpkePublicKey::deserialize_uncompressed(&mut reader).unwrap();
+ let pk =
+ TpkeDkgPublicKey::deserialize_uncompressed(&mut reader).unwrap();
PublicKey(pk)
}
diff --git a/tpke/src/api.rs b/tpke/src/api.rs
index 29bb947f..18fa4e09 100644
--- a/tpke/src/api.rs
+++ b/tpke/src/api.rs
@@ -11,7 +11,7 @@ use std::convert::TryInto;
// Fixing some of the types here on our target engine
// TODO: Consider fixing on crate::api level instead of bindings level
pub type E = ark_bls12_381::Bls12_381;
-pub type TpkePublicKey = ark_bls12_381::G1Affine;
+pub type TpkeDkgPublicKey = ark_bls12_381::G1Affine;
pub type TpkePrivateKey = ark_bls12_381::G2Affine;
pub type TpkeUnblindingKey = ark_bls12_381::Fr;
pub type TpkeCiphertext = crate::Ciphertext;
@@ -26,8 +26,9 @@ pub type TpkeResult = crate::Result;
pub fn encrypt(
message: &[u8],
aad: &[u8],
- pubkey: &TpkePublicKey,
+ pubkey: &TpkeDkgPublicKey,
) -> TpkeCiphertext {
+ // TODO: Should rng be a parameter?
let rng = &mut rand::thread_rng();
crate::encrypt(message, aad, pubkey, rng)
}
From 81ea692b10493f81720431750a99392eefba43f3 Mon Sep 17 00:00:00 2001
From: Piotr Roslaniec
Date: Tue, 7 Feb 2023 10:31:07 +0100
Subject: [PATCH 13/36] support server-side persistance
---
ferveo-python/examples/server_api.py | 18 +++++++++++++++++-
ferveo-python/src/lib.rs | 26 ++++++++++++++++++++------
ferveo/src/api.rs | 15 +++++++++++++++
3 files changed, 52 insertions(+), 7 deletions(-)
diff --git a/ferveo-python/examples/server_api.py b/ferveo-python/examples/server_api.py
index 2b9e4c14..9d47695a 100644
--- a/ferveo-python/examples/server_api.py
+++ b/ferveo-python/examples/server_api.py
@@ -21,8 +21,9 @@
ExternalValidator(f"validator-{i}", keypair.public_key)
for i, keypair in enumerate(validator_keypairs)
]
-me = validators[0]
+# Each validator holds their own DKG instance and generates a transcript every
+# validator, including themselves
messages = []
for sender in validators:
dkg = Dkg(
@@ -34,6 +35,9 @@
)
messages.append((sender, dkg.generate_transcript()))
+# Now that every validator holds a dkg instance and a transcript for every other validator,
+# every validator can aggregate the transcripts
+me = validators[0]
dkg = Dkg(
tau=tau,
shares_num=shares_num,
@@ -44,10 +48,19 @@
pvss_aggregated = dkg.aggregate_transcripts(messages)
assert pvss_aggregated.validate(dkg)
+# Server can persist transcript and the aggregated transcript
+transcripts_ser = [bytes(transcript) for _, transcript in messages]
+transcripts_deser = [Transcript.from_bytes(t) for t in transcripts_ser]
+
+agg_transcript_ser = bytes(pvss_aggregated)
+agg_transcript_deser = AggregatedTranscript.from_bytes(agg_transcript_ser)
+
+# In the meantime, the client creates a ciphertext and decryption request
msg = "abc".encode()
aad = "my-aad".encode()
ciphertext = encrypt(msg, aad, dkg.final_key)
+# Having aggregated the transcripts, the validators can now create decryption shares
decryption_shares = []
for validator, validator_keypair in zip(validators, validator_keypairs):
dkg = Dkg(
@@ -64,6 +77,9 @@
)
decryption_shares.append(decryption_share)
+# Now, the decryption share can be used to decrypt the ciphertext
+# This part is part of the client API
+
shared_secret = combine_decryption_shares(decryption_shares)
plaintext = decrypt_with_shared_secret(ciphertext, aad, shared_secret)
diff --git a/ferveo-python/src/lib.rs b/ferveo-python/src/lib.rs
index 7b90b6b9..410a96f3 100644
--- a/ferveo-python/src/lib.rs
+++ b/ferveo-python/src/lib.rs
@@ -1,6 +1,7 @@
extern crate alloc;
use pyo3::prelude::*;
+use pyo3::types::PyBytes;
use rand::thread_rng;
#[pyfunction]
@@ -54,8 +55,9 @@ impl Keypair {
Self(ferveo::api::Keypair::from_bytes(bytes))
}
- fn __bytes__(&self) -> Vec {
- self.0.to_bytes()
+ fn __bytes__(&self) -> PyObject {
+ let serialized = self.0.to_bytes();
+ Python::with_gil(|py| PyBytes::new(py, &serialized).into())
}
#[getter]
@@ -75,8 +77,9 @@ impl PublicKey {
Self(ferveo::api::PublicKey::from_bytes(bytes))
}
- pub fn to_bytes(&self) -> Vec {
- self.0.to_bytes()
+ fn __bytes__(&self) -> PyObject {
+ let serialized = self.0.to_bytes();
+ Python::with_gil(|py| PyBytes::new(py, &serialized).into())
}
}
@@ -103,8 +106,9 @@ impl Transcript {
Self(ferveo::api::Transcript::from_bytes(bytes))
}
- pub fn to_bytes(&self) -> Vec {
- self.0.to_bytes()
+ fn __bytes__(&self) -> PyObject {
+ let serialized = self.0.to_bytes();
+ Python::with_gil(|py| PyBytes::new(py, &serialized).into())
}
}
@@ -198,6 +202,16 @@ impl AggregatedTranscript {
&validator_keypair.0,
))
}
+
+ #[staticmethod]
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(ferveo::api::AggregatedTranscript::from_bytes(bytes))
+ }
+
+ fn __bytes__(&self) -> PyObject {
+ let serialized = self.0.to_bytes();
+ Python::with_gil(|py| PyBytes::new(py, &serialized).into())
+ }
}
/// A Python module implemented in Rust.
diff --git a/ferveo/src/api.rs b/ferveo/src/api.rs
index f13a913c..23f775d2 100644
--- a/ferveo/src/api.rs
+++ b/ferveo/src/api.rs
@@ -193,6 +193,21 @@ impl AggregatedTranscript {
&domain_points,
))
}
+
+ pub fn from_bytes(bytes: &[u8]) -> Self {
+ Self(
+ crate::PubliclyVerifiableSS::::deserialize(
+ bytes,
+ )
+ .unwrap(),
+ )
+ }
+
+ pub fn to_bytes(&self) -> Vec