refactor(hlapi): remove wrapping of booleans

This commit removes the wrapping of the `tfhe::boolean`
that was done in the HLAPI, effectively making the HLAPI
only wrapping `tfhe::integer`.

FheBool is now reused to be a single shortint block
compatible with other type FheUint8,16,etc (previously they were not).

In the future, `tfhe::boolean` could be re-wrapped in hlapi, but
this time, to be used as a base for all integers and not just
FheBool.

BREAKING CHANGE:
- hlapi no longer wraps tfhe::boolean API.
- tfhe::ConfigBuilder::enable_bool/disable_bool/all_disabled/all_enabled
  removed. Now default configuration should be done using
  `tfhe::ConfigBuilder::default()`.
- `tfhe::ConfigBuilder::use_default_small_integer` removed
  use `tfhe::CondifBuilder::default_with_small_encryption()`
- Uninitialied{ClientKey, PublicKey, CompressedPublicKey} error types
  removed as these erros are no longer possible
This commit is contained in:
tmontaigu
2023-10-25 23:26:26 +02:00
parent 5272c95de4
commit ec27d3dc6f
63 changed files with 719 additions and 2023 deletions

View File

@@ -70,9 +70,7 @@ use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint32, FheUint8};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Basic configuration to use homomorphic integers
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
// Key generation
let (client_key, server_keys) = generate_keys(config);

View File

@@ -6,7 +6,7 @@ use tfhe_trivium::KreyviumStream;
use criterion::Criterion;
pub fn kreyvium_bool_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB000000000000".to_string();
@@ -41,7 +41,7 @@ pub fn kreyvium_bool_gen(c: &mut Criterion) {
}
pub fn kreyvium_bool_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB000000000000".to_string();

View File

@@ -6,9 +6,8 @@ use tfhe_trivium::{KreyviumStreamByte, TransCiphering};
use criterion::Criterion;
pub fn kreyvium_byte_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let (client_key, server_key) = generate_keys(config);
@@ -36,9 +35,8 @@ pub fn kreyvium_byte_gen(c: &mut Criterion) {
}
pub fn kreyvium_byte_trans(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let (client_key, server_key) = generate_keys(config);
@@ -67,9 +65,8 @@ pub fn kreyvium_byte_trans(c: &mut Criterion) {
}
pub fn kreyvium_byte_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -8,9 +8,7 @@ use tfhe_trivium::{KreyviumStreamShortint, TransCiphering};
use criterion::Criterion;
pub fn kreyvium_shortint_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();
@@ -60,9 +58,7 @@ pub fn kreyvium_shortint_warmup(c: &mut Criterion) {
}
pub fn kreyvium_shortint_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();
@@ -107,9 +103,7 @@ pub fn kreyvium_shortint_gen(c: &mut Criterion) {
}
pub fn kreyvium_shortint_trans(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();

View File

@@ -6,7 +6,7 @@ use tfhe_trivium::TriviumStream;
use criterion::Criterion;
pub fn trivium_bool_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -41,7 +41,7 @@ pub fn trivium_bool_gen(c: &mut Criterion) {
}
pub fn trivium_bool_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();

View File

@@ -6,9 +6,7 @@ use tfhe_trivium::{TransCiphering, TriviumStreamByte};
use criterion::Criterion;
pub fn trivium_byte_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -35,9 +33,7 @@ pub fn trivium_byte_gen(c: &mut Criterion) {
}
pub fn trivium_byte_trans(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -65,9 +61,7 @@ pub fn trivium_byte_trans(c: &mut Criterion) {
}
pub fn trivium_byte_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();

View File

@@ -8,9 +8,7 @@ use tfhe_trivium::{TransCiphering, TriviumStreamShortint};
use criterion::Criterion;
pub fn trivium_shortint_warmup(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();
@@ -60,9 +58,7 @@ pub fn trivium_shortint_warmup(c: &mut Criterion) {
}
pub fn trivium_shortint_gen(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();
@@ -107,9 +103,7 @@ pub fn trivium_shortint_gen(c: &mut Criterion) {
}
pub fn trivium_shortint_trans(c: &mut Criterion) {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();

View File

@@ -170,7 +170,7 @@ fn kreyvium_test_4() {
#[test]
fn kreyvium_test_fhe_long() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB000000000000".to_string();
@@ -217,9 +217,7 @@ use tfhe::shortint::prelude::*;
#[test]
fn kreyvium_test_shortint_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();
@@ -302,9 +300,8 @@ fn kreyvium_test_clear_byte() {
#[test]
fn kreyvium_test_byte_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let (client_key, server_key) = generate_keys(config);
@@ -342,9 +339,8 @@ fn kreyvium_test_byte_long() {
#[test]
fn kreyvium_test_fhe_byte_transciphering_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -232,7 +232,7 @@ fn trivium_test_clear_byte() {
#[test]
fn trivium_test_fhe_long() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -277,9 +277,7 @@ fn trivium_test_fhe_long() {
#[test]
fn trivium_test_fhe_byte_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -316,9 +314,7 @@ fn trivium_test_fhe_byte_long() {
#[test]
fn trivium_test_fhe_byte_transciphering_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
let key_string = "0053A6F94C9FF24598EB".to_string();
@@ -357,9 +353,7 @@ use tfhe::shortint::prelude::*;
#[test]
fn trivium_test_shortint_long() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (hl_client_key, hl_server_key) = generate_keys(config);
let underlying_ck: tfhe::shortint::ClientKey = (*hl_client_key.as_ref()).clone().into();
let underlying_sk: tfhe::shortint::ServerKey = (*hl_server_key.as_ref()).clone().into();

View File

@@ -99,8 +99,7 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_integers_small(&builder);
config_builder_default(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;

View File

@@ -243,8 +243,7 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_integers_small(&builder);
config_builder_default(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;

View File

@@ -102,8 +102,7 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_bool(&builder);
config_builder_default(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;

View File

@@ -238,8 +238,8 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_custom_integers(&builder,
config_builder_default(&builder);
config_builder_use_custom_parameters(&builder,
SHORTINT_PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
config_builder_build(builder, &config);
@@ -266,8 +266,8 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_custom_integers(&builder,
config_builder_default(&builder);
config_builder_use_custom_parameters(&builder,
SHORTINT_PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
config_builder_build(builder, &config);

View File

@@ -203,9 +203,7 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
ok = config_builder_all_disabled(&builder);
assert(ok == 0);
ok = config_builder_enable_default_integers(&builder);
ok = config_builder_default(&builder);
assert(ok == 0);
ok = config_builder_build(builder, &config);
assert(ok == 0);
@@ -242,9 +240,7 @@ int main(void) {
ConfigBuilder *builder;
Config *config;
ok = config_builder_all_disabled(&builder);
assert(ok == 0);
ok = config_builder_enable_default_integers_small(&builder);
ok = config_builder_default_with_small_encryption(&builder);
assert(ok == 0);
ok = config_builder_build(builder, &config);
assert(ok == 0);

View File

@@ -40,8 +40,7 @@ use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8};
use tfhe::prelude::*;
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
let config = ConfigBuilder::default()
.build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -78,7 +78,7 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheInt8, FheUint8};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_integers().build();
let config = ConfigBuilder::default().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
@@ -134,7 +134,7 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint8};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_integers().build();
let config = ConfigBuilder::default().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
@@ -188,7 +188,7 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheInt8};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_integers().build();
let config = ConfigBuilder::default().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
@@ -236,7 +236,7 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint8};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_integers().build();
let config = ConfigBuilder::default().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
@@ -274,9 +274,7 @@ use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheInt32};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Basic configuration to use homomorphic integers
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
// Key generation
let (client_key, server_keys) = generate_keys(config);
@@ -321,9 +319,7 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheInt16, FheUint8, FheUint32, FheUint16};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
// Casting requires server_key to set

View File

@@ -18,9 +18,7 @@ use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8};
use tfhe::prelude::*;
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
// Client-side
let (client_key, server_key) = generate_keys(config);
@@ -76,9 +74,8 @@ The config is generated by first creating a builder with all types deactivated.
use tfhe::{ConfigBuilder, generate_keys};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
}
@@ -98,9 +95,7 @@ This function will **move** the server key to an internal state of the crate and
use tfhe::{ConfigBuilder, generate_keys, set_server_key};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -13,9 +13,7 @@ use tfhe::prelude::*;
use tfhe::{ConfigBuilder, generate_keys, set_server_key, CompressedFheUint16};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let clear = 12_837u16;
@@ -48,9 +46,7 @@ use tfhe::{
};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let cks = ClientKey::generate(config);
let compressed_sks = CompressedServerKey::new(&cks);
@@ -92,9 +88,7 @@ use tfhe::prelude::*;
use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8, CompressedPublicKey};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let compressed_public_key = CompressedPublicKey::new(&client_key);
@@ -122,8 +116,8 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, CompressedCompactPublicKey, ConfigBuilder, FheUint8};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
)

View File

@@ -10,8 +10,8 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint32};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
tfhe::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -41,8 +41,8 @@ use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint32};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
tfhe::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS.with_deterministic_execution(),
None,
)

View File

@@ -12,9 +12,7 @@ use tfhe::prelude::*;
use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8, PublicKey};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let public_key = PublicKey::new(&client_key);
@@ -34,8 +32,8 @@ use tfhe::prelude::*;
use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8, CompactPublicKey};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
)

View File

@@ -26,9 +26,7 @@ use tfhe::{ConfigBuilder, ServerKey, generate_keys, set_server_key, FheUint8};
use tfhe::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>>{
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let ( client_key, server_key) = generate_keys(config);

View File

@@ -68,8 +68,7 @@ pub fn ex4<FheType, ClearType>(a: FheType, b: FheType, pt: ClearType) -> FheType
}
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
let config = ConfigBuilder::default()
.build();
let (client_key, server_keys) = generate_keys(config);

View File

@@ -11,9 +11,7 @@ the server can do a *trivial encryption*
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint8};
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);
@@ -38,9 +36,7 @@ value if the ciphertext/clear-value operation (often called scalar operation) yo
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint32};
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);

View File

@@ -131,8 +131,7 @@ impl FheAsciiString {
}
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
let config = ConfigBuilder::default()
.build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -15,13 +15,11 @@ This function returns a Boolean that will be either `true` or `false` so that th
### Non-generic version.
To use Booleans, the `booleans` feature in our Cargo.toml must be enabled:
```toml
# Cargo.toml
# Default configuration for x86 Unix machines:
tfhe = { version = "0.4.0", features = ["boolean", "x86_64-unix"]}
tfhe = { version = "0.4.0", features = ["integer", "x86_64-unix"]}
```
Other configurations can be found [here](../getting_started/installation.md).
@@ -129,7 +127,7 @@ fn check_parity_bit_validity(bits: &[bool], mode: ParityMode, parity_bit: bool)
}
fn main() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -347,7 +345,7 @@ fn check_parity_bit_validity(bits: &[bool], mode: ParityMode, parity_bit: bool)
}
fn main() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let ( client_key, server_key) = generate_keys(config);

View File

@@ -40,8 +40,8 @@ pub fn cpk_and_cctl_sizes(results_file: &Path) {
{
let params = PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS;
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(params, None)
let config = ConfigBuilder::default()
.use_custom_parameters(params, None)
.build();
let (client_key, _) = generate_keys(config);
let test_name = format!("hlapi_sizes_{}_cpk", params.name());
@@ -99,8 +99,8 @@ pub fn cpk_and_cctl_sizes(results_file: &Path) {
{
let params = PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS;
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(params, None)
let config = ConfigBuilder::default()
.use_custom_parameters(params, None)
.build();
let (client_key, _) = generate_keys(config);
let test_name = format!("hlapi_sizes_{}_cpk", params.name());
@@ -159,8 +159,8 @@ pub fn cpk_and_cctl_sizes(results_file: &Path) {
// 256 bits
{
let params = PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS;
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(params, None)
let config = ConfigBuilder::default()
.use_custom_parameters(params, None)
.build();
let (client_key, _) = generate_keys(config);
@@ -208,8 +208,8 @@ pub fn cpk_and_cctl_sizes(results_file: &Path) {
{
let params = PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS;
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(params, None)
let config = ConfigBuilder::default()
.use_custom_parameters(params, None)
.build();
let (client_key, _) = generate_keys(config);

View File

@@ -35,8 +35,7 @@ init_panic_hook();
test('hlapi_client_key_encrypt_decrypt_int8_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
let clientKey = TfheClientKey.generate(config);
@@ -58,8 +57,7 @@ test('hlapi_client_key_encrypt_decrypt_int8_big', (t) => {
});
test('hlapi_compressed_public_client_int8_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
let clientKey = TfheClientKey.generate(config);
@@ -82,11 +80,9 @@ test('hlapi_compressed_public_client_int8_big', (t) => {
});
test('hlapi_public_key_encrypt_decrypt_int32_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
let clientKey = TfheClientKey.generate(config);
let publicKey = TfhePublicKey.new(clientKey);
@@ -106,8 +102,7 @@ test('hlapi_public_key_encrypt_decrypt_int32_small', (t) => {
});
test('hlapi_decompress_public_key_then_encrypt_decrypt_int32_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
@@ -141,8 +136,7 @@ test('hlapi_decompress_public_key_then_encrypt_decrypt_int32_small', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_int128_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
let clientKey = TfheClientKey.generate(config);
@@ -179,11 +173,9 @@ test('hlapi_client_key_encrypt_decrypt_int128_big', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_int128_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
let clientKey = TfheClientKey.generate(config);
let encrypted = FheInt128.encrypt_with_client_key(I128_MIN, clientKey);
@@ -218,8 +210,7 @@ test('hlapi_client_key_encrypt_decrypt_int128_small', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_int256_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
@@ -268,8 +259,7 @@ test('hlapi_client_key_encrypt_decrypt_int256_big', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_int256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
@@ -316,8 +306,7 @@ test('hlapi_client_key_encrypt_decrypt_int256_small', (t) => {
});
test('hlapi_decompress_public_key_then_encrypt_decrypt_int256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
@@ -342,10 +331,7 @@ test('hlapi_decompress_public_key_then_encrypt_decrypt_int256_small', (t) => {
});
test('hlapi_public_key_encrypt_decrypt_int256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
let publicKey = TfhePublicKey.new(clientKey);
@@ -392,8 +378,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int32_single(config) {
test('hlapi_compact_public_key_encrypt_decrypt_int32_big_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_single(config);
@@ -401,8 +387,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int32_big_single', (t) => {
test('hlapi_compact_public_key_encrypt_decrypt_int32_small_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_single(config);
@@ -430,8 +416,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int32_single_compact(config) {
test('hlapi_compact_public_key_encrypt_decrypt_int32_small_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_single_compact(config);
@@ -439,8 +425,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int32_small_single_compact', (t)
test('hlapi_compact_public_key_encrypt_decrypt_int32_big_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_single_compact(config);
@@ -478,8 +464,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int32_list_compact(config) {
test('hlapi_compact_public_key_encrypt_decrypt_int32_small_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_list_compact(config);
@@ -487,8 +473,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int32_small_list_compact', (t) =>
test('hlapi_compact_public_key_encrypt_decrypt_int32_big_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int32_list_compact(config);
@@ -520,8 +506,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int256_single(config) {
test('hlapi_compact_public_key_encrypt_decrypt_int256_big_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_single(config);
@@ -529,8 +515,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int256_big_single', (t) => {
test('hlapi_compact_public_key_encrypt_decrypt_int256_small_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_single(config);
@@ -558,8 +544,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int256_single_compact(config)
test('hlapi_compact_public_key_encrypt_decrypt_int256_small_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_single_compact(config);
@@ -567,8 +553,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int256_small_single_compact', (t)
test('hlapi_compact_public_key_encrypt_decrypt_int256_big_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_single_compact(config);
@@ -606,8 +592,8 @@ function hlapi_compact_public_key_encrypt_decrypt_int256_list_compact(config) {
test('hlapi_compact_public_key_encrypt_decrypt_int256_small_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_list_compact(config);
@@ -615,8 +601,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_int256_small_list_compact', (t) =
test('hlapi_compact_public_key_encrypt_decrypt_int256_big_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_int256_list_compact(config);

View File

@@ -1,6 +1,6 @@
const test = require('node:test');
const assert = require('node:assert').strict;
const { performance } = require('perf_hooks');
const {performance} = require('perf_hooks');
const {
init_panic_hook,
ShortintParametersName,
@@ -40,7 +40,7 @@ init_panic_hook();
// but we try to use them, so an error should be returned
// as the underlying panic should have been trapped
test('hlapi_panic', (t) => {
let config = TfheConfigBuilder.all_disabled()
let config = TfheConfigBuilder.default()
.build();
let clientKey = TfheClientKey.generate(config);
@@ -58,8 +58,7 @@ test('hlapi_panic', (t) => {
});
test('hlapi_key_gen_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
@@ -77,11 +76,9 @@ test('hlapi_key_gen_big', (t) => {
});
test('hlapi_key_gen_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default_with_small_encryption()
.build();
let clientKey = TfheClientKey.generate(config);
let compressedServerKey = TfheCompressedServerKey.new(clientKey);
let publicKey = TfhePublicKey.new(clientKey);
@@ -92,8 +89,7 @@ test('hlapi_key_gen_small', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_uint8_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
@@ -116,8 +112,7 @@ test('hlapi_client_key_encrypt_decrypt_uint8_big', (t) => {
});
test('hlapi_compressed_public_client_uint8_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
let clientKey = TfheClientKey.generate(config);
@@ -140,9 +135,7 @@ test('hlapi_compressed_public_client_uint8_big', (t) => {
});
test('hlapi_public_key_encrypt_decrypt_uint32_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
@@ -164,9 +157,7 @@ test('hlapi_public_key_encrypt_decrypt_uint32_small', (t) => {
});
test('hlapi_decompress_public_key_then_encrypt_decrypt_uint32_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
@@ -199,8 +190,7 @@ test('hlapi_decompress_public_key_then_encrypt_decrypt_uint32_small', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_uint128_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
@@ -238,9 +228,7 @@ test('hlapi_client_key_encrypt_decrypt_uint128_big', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_uint128_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
@@ -277,8 +265,7 @@ test('hlapi_client_key_encrypt_decrypt_uint128_small', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_uint256_big', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers()
let config = TfheConfigBuilder.default()
.build();
@@ -316,9 +303,7 @@ test('hlapi_client_key_encrypt_decrypt_uint256_big', (t) => {
});
test('hlapi_client_key_encrypt_decrypt_uint256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
@@ -355,9 +340,7 @@ test('hlapi_client_key_encrypt_decrypt_uint256_small', (t) => {
});
test('hlapi_decompress_public_key_then_encrypt_decrypt_uint256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
@@ -381,10 +364,7 @@ test('hlapi_decompress_public_key_then_encrypt_decrypt_uint256_small', (t) => {
});
test('hlapi_public_key_encrypt_decrypt_uint256_small', (t) => {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
let clientKey = TfheClientKey.generate(config);
let publicKey = TfhePublicKey.new(clientKey);
@@ -405,7 +385,6 @@ test('hlapi_public_key_encrypt_decrypt_uint256_small', (t) => {
});
//////////////////////////////////////////////////////////////////////////////
/// 32 bits compact
//////////////////////////////////////////////////////////////////////////////
@@ -431,8 +410,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint32_single(config) {
test('hlapi_compact_public_key_encrypt_decrypt_uint32_big_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_single(config);
@@ -440,8 +419,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint32_big_single', (t) => {
test('hlapi_compact_public_key_encrypt_decrypt_uint32_small_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_single(config);
@@ -469,8 +448,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint32_single_compact(config)
test('hlapi_compact_public_key_encrypt_decrypt_uint32_small_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_single_compact(config);
@@ -478,8 +457,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint32_small_single_compact', (t)
test('hlapi_compact_public_key_encrypt_decrypt_uint32_big_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_single_compact(config);
@@ -517,8 +496,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint32_list_compact(config) {
test('hlapi_compact_public_key_encrypt_decrypt_uint32_small_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_list_compact(config);
@@ -526,8 +505,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint32_small_list_compact', (t) =
test('hlapi_compact_public_key_encrypt_decrypt_uint32_big_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint32_list_compact(config);
@@ -559,8 +538,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint256_single(config) {
test('hlapi_compact_public_key_encrypt_decrypt_uint256_big_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_single(config);
@@ -568,8 +547,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint256_big_single', (t) => {
test('hlapi_compact_public_key_encrypt_decrypt_uint256_small_single', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_single(config);
@@ -597,8 +576,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint256_single_compact(config)
test('hlapi_compact_public_key_encrypt_decrypt_uint256_small_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_single_compact(config);
@@ -606,8 +585,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint256_small_single_compact', (t
test('hlapi_compact_public_key_encrypt_decrypt_uint256_big_single_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_single_compact(config);
@@ -645,8 +624,8 @@ function hlapi_compact_public_key_encrypt_decrypt_uint256_list_compact(config) {
test('hlapi_compact_public_key_encrypt_decrypt_uint256_small_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_list_compact(config);
@@ -654,8 +633,8 @@ test('hlapi_compact_public_key_encrypt_decrypt_uint256_small_list_compact', (t)
test('hlapi_compact_public_key_encrypt_decrypt_uint256_big_list_compact', (t) => {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
hlapi_compact_public_key_encrypt_decrypt_uint256_list_compact(config);

View File

@@ -8,16 +8,40 @@ impl_destroy_on_type!(ConfigBuilder);
impl_destroy_on_type!(Config);
#[no_mangle]
pub unsafe extern "C" fn config_builder_all_disabled(result: *mut *mut ConfigBuilder) -> c_int {
pub unsafe extern "C" fn config_builder_default(result: *mut *mut ConfigBuilder) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let inner_builder = crate::high_level_api::ConfigBuilder::all_disabled();
let inner_builder = crate::high_level_api::ConfigBuilder::default();
*result = Box::into_raw(Box::new(ConfigBuilder(inner_builder)));
})
}
#[no_mangle]
pub unsafe extern "C" fn config_builder_default_with_small_encryption(
builder: *mut *mut ConfigBuilder,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(builder).unwrap();
let inner_builder = crate::high_level_api::ConfigBuilder::default_with_small_encryption();
*builder = Box::into_raw(Box::new(ConfigBuilder(inner_builder)));
})
}
#[no_mangle]
pub unsafe extern "C" fn config_builder_default_with_big_encryption(
builder: *mut *mut ConfigBuilder,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(builder).unwrap();
let inner_builder = crate::high_level_api::ConfigBuilder::default_with_big_encryption();
*builder = Box::into_raw(Box::new(ConfigBuilder(inner_builder)));
})
}
#[no_mangle]
pub unsafe extern "C" fn config_builder_clone(
input: *const ConfigBuilder,
@@ -32,61 +56,22 @@ pub unsafe extern "C" fn config_builder_clone(
})
}
macro_rules! define_enable_default_fn(
($type_name:ident) => {
::paste::paste!{
#[no_mangle]
pub unsafe extern "C" fn [<config_builder_enable_default_ $type_name>](
builder: *mut *mut ConfigBuilder,
) -> ::std::os::raw::c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(builder).unwrap();
let inner = Box::from_raw(*builder).0.[<enable_default_ $type_name>]();
*builder = Box::into_raw(Box::new(ConfigBuilder(inner)));
})
}
}
};
($type_name:ident @small) => {
::paste::paste!{
#[no_mangle]
pub unsafe extern "C" fn [<config_builder_enable_default_ $type_name _small>](
builder: *mut *mut ConfigBuilder,
) -> ::std::os::raw::c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(builder).unwrap();
let inner = Box::from_raw(*builder).0.[<enable_default_ $type_name _small>]();
*builder = Box::into_raw(Box::new(ConfigBuilder(inner)));
})
}
}
}
);
#[cfg(feature = "boolean")]
define_enable_default_fn!(bool);
#[cfg(feature = "integer")]
define_enable_default_fn!(integers);
#[cfg(feature = "integer")]
define_enable_default_fn!(integers @small);
#[no_mangle]
pub unsafe extern "C" fn config_builder_enable_custom_integers(
pub unsafe extern "C" fn config_builder_use_custom_parameters(
builder: *mut *mut ConfigBuilder,
shortint_block_parameters: crate::c_api::shortint::parameters::ShortintPBSParameters,
) -> ::std::os::raw::c_int {
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(builder).unwrap();
let params: crate::shortint::ClassicPBSParameters = shortint_block_parameters.into();
let inner = Box::from_raw(*builder)
.0
.enable_custom_integers(params, None);
.use_custom_parameters(params, None);
*builder = Box::into_raw(Box::new(ConfigBuilder(inner)));
})
}
/// Takes ownership of the builder
#[no_mangle]
pub unsafe extern "C" fn config_builder_build(

View File

@@ -52,13 +52,20 @@ pub unsafe extern "C" fn set_server_key(server_key: *const ServerKey) -> c_int {
}
/// result can be null
///
/// `result` may be set to null if no previous server key was set
#[no_mangle]
pub unsafe extern "C" fn unset_server_key(result: *mut *mut ServerKey) -> c_int {
catch_panic(|| {
let previous_key = crate::high_level_api::unset_server_key();
if !result.is_null() {
*result = Box::into_raw(Box::new(ServerKey(previous_key)))
match previous_key {
None => {
*result = std::ptr::null_mut();
}
Some(key) => *result = Box::into_raw(Box::new(ServerKey(key))),
}
}
})
}

View File

@@ -1,32 +0,0 @@
use crate::boolean::client_key::ClientKey;
use crate::core_crypto::commons::generators::DeterministicSeeder;
use crate::core_crypto::prelude::ActivatedRandomGenerator;
use concrete_csprng::seeders::Seed;
use serde::{Deserialize, Serialize};
use super::FheBoolParameters;
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FheBoolClientKey {
pub(in crate::high_level_api::booleans) key: ClientKey,
}
impl FheBoolClientKey {
pub(crate) fn with_seed(parameters: FheBoolParameters, seed: Seed) -> Self {
let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(seed);
let key = crate::boolean::engine::BooleanEngine::new_from_seeder(&mut seeder)
.create_client_key(parameters.into());
Self { key }
}
}
impl From<FheBoolParameters> for FheBoolClientKey {
fn from(parameters: FheBoolParameters) -> Self {
Self {
key: ClientKey::new(&parameters.into()),
}
}
}

View File

@@ -1,5 +0,0 @@
define_key_structs! {
Boolean {
bool: FheBool,
}
}

View File

@@ -1,17 +1,234 @@
pub(crate) use keys::{
BooleanClientKey, BooleanCompressedPublicKey, BooleanCompressedServerKey, BooleanConfig,
BooleanPublicKey, BooleanServerKey,
use std::borrow::Borrow;
use std::ops::{BitAnd, BitOr, BitXor};
use crate::errors::Type;
use crate::high_level_api::global_state::WithGlobalKey;
use crate::high_level_api::internal_traits::TypeIdentifier;
use crate::high_level_api::keys::{ClientKey, PublicKey};
use crate::high_level_api::traits::{
FheDecrypt, FheEq, FheTrivialEncrypt, FheTryEncrypt, FheTryTrivialEncrypt,
};
pub use parameters::FheBoolParameters;
pub use types::{CompressedFheBool, FheBool};
mod client_key;
mod keys;
mod public_key;
mod server_key;
mod types;
mod parameters;
use crate::shortint::{Ciphertext, CompressedCiphertext};
use crate::CompressedPublicKey;
use serde::{Deserialize, Serialize};
#[cfg(test)]
mod tests;
#[derive(Copy, Clone, Serialize, Deserialize)]
struct FheBoolId;
impl TypeIdentifier for FheBoolId {
fn type_variant(&self) -> Type {
Type::FheBool
}
}
impl WithGlobalKey for FheBoolId {
type Key = crate::high_level_api::integers::IntegerServerKey;
fn with_unwrapped_global<R, F>(self, func: F) -> R
where
F: FnOnce(&Self::Key) -> R,
{
crate::high_level_api::global_state::with_internal_keys(|keys| func(&keys.integer_key))
}
}
/// The FHE boolean data type.
///
/// # Example
///
/// ```rust
/// use tfhe::prelude::*;
/// use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheBool};
///
/// let config = ConfigBuilder::default().build();
///
/// let (client_key, server_key) = generate_keys(config);
///
/// let ttrue = FheBool::encrypt(true, &client_key);
/// let ffalse = FheBool::encrypt(false, &client_key);
///
/// // Do not forget to set the server key before doing any computation
/// set_server_key(server_key);
///
/// let fhe_result = ttrue & ffalse;
///
/// let clear_result = fhe_result.decrypt(&client_key);
/// assert_eq!(clear_result, false);
/// ```
#[derive(Clone, Serialize, Deserialize)]
pub struct FheBool {
pub(in crate::high_level_api::booleans) ciphertext: Ciphertext,
id: FheBoolId,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct CompressedFheBool {
pub(in crate::high_level_api::booleans) ciphertext: CompressedCiphertext,
}
impl FheBool {
pub(in crate::high_level_api::booleans) fn new(ciphertext: Ciphertext) -> Self {
Self {
ciphertext,
id: FheBoolId,
}
}
}
impl<B> FheEq<B> for FheBool
where
B: Borrow<Self>,
{
type Output = Self;
fn eq(&self, other: B) -> Self {
let ciphertext = self.id.with_unwrapped_global(|key| {
key.pbs_key()
.key
.equal(&self.ciphertext, &other.borrow().ciphertext)
});
Self::new(ciphertext)
}
fn ne(&self, other: B) -> Self {
let ciphertext = self.id.with_unwrapped_global(|key| {
key.pbs_key()
.key
.not_equal(&self.ciphertext, &other.borrow().ciphertext)
});
Self::new(ciphertext)
}
}
impl CompressedFheBool {
fn new(ciphertext: CompressedCiphertext) -> Self {
Self { ciphertext }
}
}
impl From<CompressedFheBool> for FheBool {
fn from(value: CompressedFheBool) -> Self {
let block: Ciphertext = value.ciphertext.into();
Self::new(block)
}
}
impl FheTryEncrypt<bool, ClientKey> for CompressedFheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &ClientKey) -> Result<Self, Self::Error> {
let integer_client_key = &key.key.key;
let ciphertext = integer_client_key.key.encrypt_compressed(u64::from(value));
Ok(CompressedFheBool::new(ciphertext))
}
}
impl FheTryEncrypt<bool, ClientKey> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &ClientKey) -> Result<Self, Self::Error> {
let integer_client_key = &key.key.key;
let ciphertext = integer_client_key.encrypt_one_block(u64::from(value));
Ok(FheBool::new(ciphertext))
}
}
impl FheTryTrivialEncrypt<bool> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt_trivial(value: bool) -> Result<Self, Self::Error> {
let ciphertext = FheBoolId
.with_unwrapped_global(|key| key.pbs_key().key.create_trivial(u64::from(value)));
Ok(FheBool::new(ciphertext))
}
}
impl FheTrivialEncrypt<bool> for FheBool {
#[track_caller]
fn encrypt_trivial(value: bool) -> Self {
Self::try_encrypt_trivial(value).unwrap()
}
}
impl FheTryEncrypt<bool, CompressedPublicKey> for crate::FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &CompressedPublicKey) -> Result<Self, Self::Error> {
let key = &key.key;
let ciphertext = key.key.encrypt(u64::from(value));
Ok(FheBool::new(ciphertext))
}
}
impl FheTryEncrypt<bool, PublicKey> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &PublicKey) -> Result<Self, Self::Error> {
let key = &key.key;
let ciphertext = key.key.encrypt(u64::from(value));
Ok(FheBool::new(ciphertext))
}
}
impl FheDecrypt<bool> for FheBool {
fn decrypt(&self, key: &ClientKey) -> bool {
let integer_client_key = &key.key.key;
integer_client_key.decrypt_one_block(&self.ciphertext) != 0
}
}
macro_rules! fhe_bool_impl_operation(
($trait_name:ident($trait_method:ident) => $key_method:ident) => {
impl<B> $trait_name<B> for FheBool
where B: Borrow<FheBool>,
{
type Output = FheBool;
fn $trait_method(self, rhs: B) -> Self::Output {
<&Self as $trait_name<B>>::$trait_method(&self, rhs)
}
}
impl<B> $trait_name<B> for &FheBool
where B: Borrow<FheBool>,
{
type Output = FheBool;
fn $trait_method(self, rhs: B) -> Self::Output {
let ciphertext = self.id.with_unwrapped_global(|key| {
key.pbs_key().key.$key_method(&self.ciphertext, &rhs.borrow().ciphertext)
});
FheBool::new(ciphertext)
}
}
};
);
fhe_bool_impl_operation!(BitAnd(bitand) => bitand);
fhe_bool_impl_operation!(BitOr(bitor) => bitor);
fhe_bool_impl_operation!(BitXor(bitxor) => bitxor);
impl ::std::ops::Not for FheBool {
type Output = Self;
fn not(self) -> Self::Output {
let ciphertext = self
.id
.with_unwrapped_global(|key| key.pbs_key().key.scalar_bitxor(&self.ciphertext, 1));
Self::new(ciphertext)
}
}
impl ::std::ops::Not for &FheBool {
type Output = FheBool;
fn not(self) -> Self::Output {
let ciphertext = self
.id
.with_unwrapped_global(|key| key.pbs_key().key.scalar_bitxor(&self.ciphertext, 1));
FheBool::new(ciphertext)
}
}

View File

@@ -1,75 +0,0 @@
use crate::boolean::parameters::{
BooleanParameters, DecompositionBaseLog, DecompositionLevelCount, EncryptionKeyChoice,
GlweDimension, LweDimension, PolynomialSize, StandardDev,
};
pub use crate::boolean::parameters::{DEFAULT_PARAMETERS, PARAMETERS_ERROR_PROB_2_POW_MINUS_165};
use serde::{Deserialize, Serialize};
/// Parameters for [FheBool].
///
/// [FheBool]: crate::high_level_api::FheBool
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FheBoolParameters {
pub lwe_dimension: LweDimension,
pub glwe_dimension: GlweDimension,
pub polynomial_size: PolynomialSize,
pub lwe_modular_std_dev: StandardDev,
pub glwe_modular_std_dev: StandardDev,
pub pbs_base_log: DecompositionBaseLog,
pub pbs_level: DecompositionLevelCount,
pub ks_base_log: DecompositionBaseLog,
pub ks_level: DecompositionLevelCount,
pub encryption_key_choice: EncryptionKeyChoice,
}
impl FheBoolParameters {
pub fn tfhe_lib() -> Self {
Self::from_static(&PARAMETERS_ERROR_PROB_2_POW_MINUS_165)
}
fn from_static(params: &'static BooleanParameters) -> Self {
(*params).into()
}
}
impl Default for FheBoolParameters {
fn default() -> Self {
Self::from_static(&DEFAULT_PARAMETERS)
}
}
impl From<FheBoolParameters> for BooleanParameters {
fn from(params: FheBoolParameters) -> Self {
Self {
lwe_dimension: params.lwe_dimension,
glwe_dimension: params.glwe_dimension,
polynomial_size: params.polynomial_size,
lwe_modular_std_dev: params.lwe_modular_std_dev,
glwe_modular_std_dev: params.glwe_modular_std_dev,
pbs_base_log: params.pbs_base_log,
pbs_level: params.pbs_level,
ks_base_log: params.ks_base_log,
ks_level: params.ks_level,
encryption_key_choice: params.encryption_key_choice,
}
}
}
impl From<BooleanParameters> for FheBoolParameters {
fn from(params: BooleanParameters) -> FheBoolParameters {
Self {
lwe_dimension: params.lwe_dimension,
glwe_dimension: params.glwe_dimension,
polynomial_size: params.polynomial_size,
lwe_modular_std_dev: params.lwe_modular_std_dev,
glwe_modular_std_dev: params.glwe_modular_std_dev,
pbs_base_log: params.pbs_base_log,
pbs_level: params.pbs_level,
ks_base_log: params.ks_base_log,
ks_level: params.ks_level,
encryption_key_choice: params.encryption_key_choice,
}
}
}

View File

@@ -1,35 +0,0 @@
use serde::{Deserialize, Serialize};
use super::client_key::FheBoolClientKey;
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FheBoolPublicKey {
pub(in crate::high_level_api::booleans) key: crate::boolean::public_key::PublicKey,
}
impl FheBoolPublicKey {
pub fn new(client_key: &FheBoolClientKey) -> Self {
let key = crate::boolean::public_key::PublicKey::new(&client_key.key);
Self { key }
}
}
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FheBoolCompressedPublicKey {
pub(in crate::high_level_api::booleans) key: crate::boolean::public_key::CompressedPublicKey,
}
impl FheBoolCompressedPublicKey {
pub fn new(client_key: &FheBoolClientKey) -> Self {
let key = crate::boolean::public_key::CompressedPublicKey::new(&client_key.key);
Self { key }
}
pub fn decompress(self) -> FheBoolPublicKey {
FheBoolPublicKey {
key: crate::boolean::public_key::PublicKey::from(self.key),
}
}
}

View File

@@ -1,90 +0,0 @@
use super::client_key::FheBoolClientKey;
use super::types::FheBool;
use crate::boolean::server_key::{BinaryBooleanGates, CompressedServerKey, ServerKey};
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct FheBoolServerKey {
pub(in crate::high_level_api::booleans) key: ServerKey,
}
impl FheBoolServerKey {
pub(crate) fn new(key: &FheBoolClientKey) -> Self {
Self {
key: ServerKey::new(&key.key),
}
}
pub(in crate::high_level_api::booleans) fn and(&self, lhs: &FheBool, rhs: &FheBool) -> FheBool {
let ciphertext = self.key.and(&lhs.ciphertext, &rhs.ciphertext);
FheBool::new(ciphertext)
}
pub(in crate::high_level_api::booleans) fn or(&self, lhs: &FheBool, rhs: &FheBool) -> FheBool {
let ciphertext = self.key.or(&lhs.ciphertext, &rhs.ciphertext);
FheBool::new(ciphertext)
}
pub(in crate::high_level_api::booleans) fn xor(&self, lhs: &FheBool, rhs: &FheBool) -> FheBool {
let ciphertext = self.key.xor(&lhs.ciphertext, &rhs.ciphertext);
FheBool::new(ciphertext)
}
pub(in crate::high_level_api::booleans) fn xnor(
&self,
lhs: &FheBool,
rhs: &FheBool,
) -> FheBool {
let ciphertext = self.key.xnor(&lhs.ciphertext, &rhs.ciphertext);
FheBool::new(ciphertext)
}
pub(in crate::high_level_api::booleans) fn nand(
&self,
lhs: &FheBool,
rhs: &FheBool,
) -> FheBool {
let ciphertext = self.key.nand(&lhs.ciphertext, &rhs.ciphertext);
FheBool::new(ciphertext)
}
pub(in crate::high_level_api::booleans) fn not(&self, lhs: &FheBool) -> FheBool {
let ciphertext = self.key.not(&lhs.ciphertext);
FheBool::new(ciphertext)
}
#[allow(dead_code)]
pub(in crate::high_level_api::booleans) fn mux(
&self,
condition: &FheBool,
then_result: &FheBool,
else_result: &FheBool,
) -> FheBool {
let ciphertext = self.key.mux(
&condition.ciphertext,
&then_result.ciphertext,
&else_result.ciphertext,
);
FheBool::new(ciphertext)
}
}
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct FheBoolCompressedServerKey {
pub(in crate::high_level_api::booleans) key: CompressedServerKey,
}
impl FheBoolCompressedServerKey {
pub(in crate::high_level_api::booleans) fn new(client_key: &FheBoolClientKey) -> Self {
Self {
key: CompressedServerKey::new(&client_key.key),
}
}
pub(in crate::high_level_api::booleans) fn decompress(self) -> FheBoolServerKey {
FheBoolServerKey {
key: self.key.into(),
}
}
}

View File

@@ -1,4 +1,4 @@
// Without this, clippy will conplain about equal expressions to `ffalse & ffalse`
// Without this, clippy will complain about equal expressions to `ffalse & ffalse`
// However since we overloaded these operators, we want to test them to see
// if they are correct
#![allow(clippy::eq_op)]
@@ -8,23 +8,11 @@ use std::ops::{BitAnd, BitOr, BitXor, Not};
use crate::high_level_api::prelude::*;
use crate::high_level_api::{
generate_keys, set_server_key, ClientKey, CompressedFheBool, ConfigBuilder, FheBool,
FheBoolParameters,
};
use crate::CompressedPublicKey;
fn setup_static_default() -> ClientKey {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let (my_keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
my_keys
}
fn setup_static_tfhe() -> ClientKey {
let config = ConfigBuilder::all_disabled()
.enable_custom_bool(FheBoolParameters::tfhe_lib())
.build();
let config = ConfigBuilder::default().build();
let (my_keys, server_keys) = generate_keys(config);
@@ -71,47 +59,6 @@ fn test_not_truth_table_static_default() {
not_truth_table(&ttrue, &ffalse, &keys);
}
#[test]
fn test_xor_truth_table_static_tfhe() {
let keys = setup_static_tfhe();
let ttrue = FheBool::encrypt(true, &keys);
let ffalse = FheBool::encrypt(false, &keys);
xor_truth_table(&ttrue, &ffalse, &keys);
}
#[test]
fn test_and_truth_table_static_tfhe() {
let keys = setup_static_tfhe();
let ttrue = FheBool::encrypt(true, &keys);
let ffalse = FheBool::encrypt(false, &keys);
and_truth_table(&ttrue, &ffalse, &keys);
}
#[test]
fn test_or_truth_table_static_tfhe() {
let keys = setup_static_tfhe();
let ttrue = FheBool::encrypt(true, &keys);
let ffalse = FheBool::encrypt(false, &keys);
or_truth_table(&ttrue, &ffalse, &keys);
}
#[test]
fn test_not_truth_table_static_tfhe() {
let keys = setup_static_tfhe();
let ttrue = FheBool::encrypt(true, &keys);
let ffalse = FheBool::encrypt(false, &keys);
not_truth_table(&ttrue, &ffalse, &keys);
}
fn xor_truth_table<'a, BoolType>(ttrue: &'a BoolType, ffalse: &'a BoolType, key: &ClientKey)
where
&'a BoolType: BitXor<&'a BoolType, Output = BoolType>,
@@ -205,7 +152,7 @@ fn test_trivial_bool() {
#[test]
fn test_compressed_public_key_encrypt() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let public_key = CompressedPublicKey::new(&client_key);
@@ -217,7 +164,7 @@ fn test_compressed_public_key_encrypt() {
#[test]
fn test_decompressed_public_key_encrypt() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let compressed_public_key = CompressedPublicKey::new(&client_key);

View File

@@ -1,265 +0,0 @@
use std::borrow::Borrow;
use std::ops::{BitAnd, BitOr, BitXor};
use crate::boolean::ciphertext::{Ciphertext, CompressedCiphertext};
use crate::errors::{Type, UnwrapResultExt};
use crate::CompressedPublicKey;
use serde::{Deserialize, Serialize};
use crate::high_level_api::global_state::WithGlobalKey;
use crate::high_level_api::keys::{
ClientKey, PublicKey, RefKeyFromKeyChain, RefKeyFromPublicKeyChain,
};
use crate::high_level_api::traits::{
FheDecrypt, FheEq, FheTrivialEncrypt, FheTryEncrypt, FheTryTrivialEncrypt,
};
use super::static_::{FheBoolClientKey, FheBoolPublicKey, FheBoolServerKey};
#[derive(Copy, Clone, Serialize, Deserialize)]
struct FheBoolId;
impl_with_global_key!(
for FheBoolId {
key_type: FheBoolServerKey,
keychain_member: boolean_key.bool_key,
type_variant: Type::FheBool,
}
);
impl_ref_key_from_keychain!(
for FheBoolId {
key_type: FheBoolClientKey,
keychain_member: boolean_key.bool_key,
type_variant: Type::FheBool,
}
);
impl_ref_key_from_public_keychain!(
for FheBoolId {
key_type: FheBoolPublicKey,
keychain_member: boolean_key.bool_key,
type_variant: Type::FheBool,
}
);
/// The FHE boolean data type.
///
/// To be able to use this type, the cargo feature `booleans` must be enabled,
/// and your config should also enable the type with either default parameters or custom ones.
///
/// # Example
/// ```rust
/// use tfhe::prelude::*;
/// use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheBool};
///
/// // Enable booleans in the config
/// let config = ConfigBuilder::all_disabled().enable_default_bool().build();
///
/// // With the booleans enabled in the config, the needed keys and details
/// // can be taken care of.
/// let (client_key, server_key) = generate_keys(config);
///
/// let ttrue = FheBool::encrypt(true, &client_key);
/// let ffalse = FheBool::encrypt(false, &client_key);
///
/// // Do not forget to set the server key before doing any computation
/// set_server_key(server_key);
///
/// let fhe_result = ttrue & ffalse;
///
/// let clear_result = fhe_result.decrypt(&client_key);
/// assert_eq!(clear_result, false);
/// ```
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
#[derive(Clone, Serialize, Deserialize)]
pub struct FheBool {
pub(in crate::high_level_api::booleans) ciphertext: Ciphertext,
id: FheBoolId,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct CompressedFheBool {
pub(in crate::high_level_api::booleans) ciphertext: CompressedCiphertext,
}
impl FheBool {
pub(in crate::high_level_api::booleans) fn new(ciphertext: Ciphertext) -> Self {
Self {
ciphertext,
id: FheBoolId,
}
}
pub fn nand(&self, rhs: &Self) -> Self {
self.id.with_unwrapped_global(|key| key.nand(self, rhs))
}
}
impl<B> FheEq<B> for FheBool
where
B: Borrow<Self>,
{
type Output = Self;
fn eq(&self, other: B) -> Self {
self.id
.with_unwrapped_global(|key| key.xnor(self, other.borrow()))
}
fn ne(&self, other: B) -> Self {
self.id
.with_unwrapped_global(|key| key.xor(self, other.borrow()))
}
}
#[allow(dead_code)]
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "boolean"))]
pub fn if_then_else<B1, B2>(ct_condition: B1, ct_then: B2, ct_else: B2) -> FheBool
where
B1: Borrow<FheBool>,
B2: Borrow<FheBool>,
{
let ct_condition = ct_condition.borrow();
ct_condition
.id
.with_unwrapped_global(|key| key.mux(ct_condition, ct_then.borrow(), ct_else.borrow()))
}
impl CompressedFheBool {
fn new(ciphertext: CompressedCiphertext) -> Self {
Self { ciphertext }
}
}
impl From<CompressedFheBool> for FheBool {
fn from(value: CompressedFheBool) -> Self {
Self::new(value.ciphertext.into())
}
}
impl FheTryEncrypt<bool, ClientKey> for CompressedFheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &ClientKey) -> Result<Self, Self::Error> {
let id = FheBoolId;
let key = <FheBoolId as RefKeyFromKeyChain>::ref_key(id, key)?;
let ciphertext = key.key.encrypt_compressed(value);
Ok(CompressedFheBool::new(ciphertext))
}
}
impl FheTryEncrypt<bool, ClientKey> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &ClientKey) -> Result<Self, Self::Error> {
let id = FheBoolId;
let key = <FheBoolId as RefKeyFromKeyChain>::ref_key(id, key)?;
let ciphertext = key.key.encrypt(value);
Ok(FheBool::new(ciphertext))
}
}
impl FheTryTrivialEncrypt<bool> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt_trivial(value: bool) -> Result<Self, Self::Error> {
FheBoolId.with_global(|key| {
let ciphertext = key.key.trivial_encrypt(value);
Ok(FheBool::new(ciphertext))
})?
}
}
impl FheTrivialEncrypt<bool> for FheBool {
#[track_caller]
fn encrypt_trivial(value: bool) -> Self {
Self::try_encrypt_trivial(value).unwrap()
}
}
impl FheTryEncrypt<bool, CompressedPublicKey> for crate::FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &CompressedPublicKey) -> Result<Self, Self::Error> {
let ciphertext = key
.boolean_key
.bool_key
.as_ref()
.ok_or(
crate::high_level_api::errors::UninitializedCompressedPublicKey(
crate::high_level_api::errors::Type::FheBool,
),
)
.unwrap_display()
.key
.encrypt(value);
Ok(FheBool::new(ciphertext))
}
}
impl FheTryEncrypt<bool, PublicKey> for FheBool {
type Error = crate::high_level_api::errors::Error;
fn try_encrypt(value: bool, key: &PublicKey) -> Result<Self, Self::Error> {
let id = FheBoolId;
let key = <FheBoolId as RefKeyFromPublicKeyChain>::ref_key(id, key)?;
let ciphertext = key.key.encrypt(value);
Ok(FheBool::new(ciphertext))
}
}
impl FheDecrypt<bool> for FheBool {
#[track_caller]
fn decrypt(&self, key: &ClientKey) -> bool {
let id = FheBoolId;
let key = <FheBoolId as RefKeyFromKeyChain>::unwrapped_ref_key(id, key);
key.key.decrypt(&self.ciphertext)
}
}
macro_rules! fhe_bool_impl_operation(
($trait_name:ident($trait_method:ident) => $key_method:ident) => {
impl<B> $trait_name<B> for FheBool
where B: Borrow<FheBool>,
{
type Output = FheBool;
fn $trait_method(self, rhs: B) -> Self::Output {
<&Self as $trait_name<B>>::$trait_method(&self, rhs)
}
}
impl<B> $trait_name<B> for &FheBool
where B: Borrow<FheBool>,
{
type Output = FheBool;
fn $trait_method(self, rhs: B) -> Self::Output {
self.id.with_unwrapped_global(|key| {
key.$key_method(self, rhs.borrow())
})
}
}
};
);
fhe_bool_impl_operation!(BitAnd(bitand) => and);
fhe_bool_impl_operation!(BitOr(bitor) => or);
fhe_bool_impl_operation!(BitXor(bitxor) => xor);
impl ::std::ops::Not for FheBool {
type Output = Self;
fn not(self) -> Self::Output {
self.id.with_unwrapped_global(|key| key.not(&self))
}
}
impl ::std::ops::Not for &FheBool {
type Output = FheBool;
fn not(self) -> Self::Output {
self.id.with_unwrapped_global(|key| key.not(self))
}
}

View File

@@ -1,4 +0,0 @@
pub use base::{CompressedFheBool, FheBool};
mod base;
pub(in crate::high_level_api) mod static_;

View File

@@ -1,9 +0,0 @@
// This contains re-export to keep working a macro that expect these to be here
pub(in crate::high_level_api) use crate::high_level_api::booleans::client_key::FheBoolClientKey;
pub(in crate::high_level_api) use crate::high_level_api::booleans::parameters::FheBoolParameters;
pub(in crate::high_level_api) use crate::high_level_api::booleans::public_key::{
FheBoolCompressedPublicKey, FheBoolPublicKey,
};
pub(in crate::high_level_api) use crate::high_level_api::booleans::server_key::{
FheBoolCompressedServerKey, FheBoolServerKey,
};

View File

@@ -1,107 +1,64 @@
#[cfg(feature = "boolean")]
use crate::high_level_api::booleans::{BooleanConfig, FheBoolParameters};
#[cfg(feature = "integer")]
use crate::high_level_api::integers::IntegerConfig;
/// The config type
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Config {
#[cfg(feature = "boolean")]
pub(crate) boolean_config: BooleanConfig,
#[cfg(feature = "integer")]
pub(crate) integer_config: IntegerConfig,
pub(crate) inner: IntegerConfig,
}
/// The builder to create your config
///
/// This struct is what you will to use to build your
/// configuration.
///
/// # Why ?
///
/// The configuration is needed to select which types you are going to use or not
/// and which parameters you wish to use for these types (whether it is the default parameters or
/// some custom parameters).
///
/// To be able to configure a type, its "cargo feature kind" must be enabled (see the [table]).
///
/// The configuration is needed for the crate to be able to initialize and generate
/// all the needed client and server keys as well as other internal details.
///
/// As generating these keys and details for types that you are not going to use would be
/// a waste of time and space (both memory and disk if you serialize), generating a config is an
/// important step.
///
/// [table]: index.html#data-types
/// The configuration is needed to select parameters you wish to use for these types
/// (whether it is the default parameters or some custom parameters).
#[derive(Clone)]
pub struct ConfigBuilder {
config: Config,
}
impl Default for ConfigBuilder {
fn default() -> Self {
Self::default_with_big_encryption()
}
}
impl ConfigBuilder {
/// Create a new builder with all the data types activated with their default parameters
pub fn all_enabled() -> Self {
Self {
config: Config {
#[cfg(feature = "boolean")]
boolean_config: BooleanConfig::all_default(),
#[cfg(feature = "integer")]
integer_config: IntegerConfig::all_default(),
},
}
}
/// Create a new builder with all the data types disabled
pub fn all_disabled() -> Self {
Self {
config: Config {
#[cfg(feature = "boolean")]
boolean_config: BooleanConfig::all_none(),
#[cfg(feature = "integer")]
integer_config: IntegerConfig::all_none(),
},
}
}
#[cfg(feature = "boolean")]
pub fn enable_default_bool(mut self) -> Self {
self.config.boolean_config.bool_params = Some(Default::default());
self
}
#[cfg(feature = "boolean")]
pub fn enable_custom_bool(mut self, params: FheBoolParameters) -> Self {
self.config.boolean_config.bool_params = Some(params);
self
}
#[cfg(feature = "boolean")]
pub fn disable_bool(mut self) -> Self {
self.config.boolean_config.bool_params = None;
self
}
#[cfg(feature = "integer")]
pub fn enable_default_integers(mut self) -> Self {
self.config.integer_config = IntegerConfig::default_big();
self
}
#[cfg(feature = "integer")]
pub fn enable_default_integers_small(mut self) -> Self {
self.config.integer_config = IntegerConfig::default_small();
self
}
#[doc(hidden)]
#[cfg(feature = "integer")]
pub fn enable_function_evaluation_integers(mut self) -> Self {
self.config.integer_config.enable_wopbs();
pub fn enable_function_evaluation(mut self) -> Self {
self.config.inner.enable_wopbs();
self
}
#[cfg(feature = "integer")]
pub fn enable_custom_integers<P>(
pub fn default_with_big_encryption() -> Self {
Self {
config: Config {
inner: IntegerConfig::default_big(),
},
}
}
pub fn default_with_small_encryption() -> Self {
Self {
config: Config {
inner: IntegerConfig::default_small(),
},
}
}
pub fn with_custom_parameters<P>(
block_parameters: P,
wopbs_block_parameters: Option<crate::shortint::WopbsParameters>,
) -> Self
where
P: Into<crate::shortint::PBSParameters>,
{
Self {
config: Config {
inner: IntegerConfig::new(block_parameters.into(), wopbs_block_parameters),
},
}
}
pub fn use_custom_parameters<P>(
mut self,
block_parameters: P,
wopbs_block_parameters: Option<crate::shortint::WopbsParameters>,
@@ -109,14 +66,7 @@ impl ConfigBuilder {
where
P: Into<crate::shortint::PBSParameters>,
{
self.config.integer_config =
IntegerConfig::new(Some(block_parameters.into()), wopbs_block_parameters);
self
}
#[cfg(feature = "integer")]
pub fn disable_integers(mut self) -> Self {
self.config.integer_config = IntegerConfig::all_none();
self.config.inner = IntegerConfig::new(block_parameters.into(), wopbs_block_parameters);
self
}

View File

@@ -1,217 +0,0 @@
#[cfg(feature = "boolean")]
macro_rules! define_key_structs {
(
$base_struct_name:ident {
$(
$name:ident: $base_ty_name:ident
),*
$(,)?
}
) => {
::paste::paste!{
$(
use super::types::static_::{
[<$base_ty_name Parameters>],
[<$base_ty_name ClientKey>],
[<$base_ty_name PublicKey>],
[<$base_ty_name CompressedPublicKey>],
[<$base_ty_name ServerKey>],
[<$base_ty_name CompressedServerKey>],
};
)*
///////////////////////
// Config
///////////////////////
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct [<$base_struct_name Config>] {
$(
pub(crate) [<$name _params>]: Option<[<$base_ty_name Parameters>]>,
)*
}
impl [<$base_struct_name Config>] {
pub(crate) fn all_default() -> Self {
Self {
$(
[<$name _params>]: Some(Default::default()),
)*
}
}
pub(crate) fn all_none() -> Self {
Self {
$(
[<$name _params>]: None,
)*
}
}
}
///////////////////////
// Client Key
///////////////////////
#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
pub(crate) struct [<$base_struct_name ClientKey>] {
$(
pub(super) [<$name _key>]: Option<[<$base_ty_name ClientKey>]>,
pub(super) [<$name _params>]: Option<[<$base_ty_name Parameters>]>,
)*
}
impl [<$base_struct_name ClientKey>] {
pub(crate) fn with_seed(
config: [<$base_struct_name Config>],
seed: ::concrete_csprng::seeders::Seed
) -> Self {
Self {
$(
[<$name _params>]: None,
[<$name _key>]: config
.[<$name _params>]
.map(|params| {
<[<$base_ty_name ClientKey>]>::with_seed(params, seed)
}),
)*
}
}
}
impl From<[<$base_struct_name Config>]> for [<$base_struct_name ClientKey>] {
fn from(config: [<$base_struct_name Config>]) -> Self {
Self {
$(
[<$name _params>]: None,
[<$name _key>]: config.[<$name _params>].map(<[<$base_ty_name ClientKey>]>::from),
)*
}
}
}
///////////////////////
// Public Key
///////////////////////
#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
pub(crate) struct [<$base_struct_name PublicKey>] {
$(
pub(super) [<$name _key>]: Option<[<$base_ty_name PublicKey>]>,
)*
}
impl [<$base_struct_name PublicKey>] {
pub(crate) fn new(client_key: &[<$base_struct_name ClientKey>]) -> Self {
Self {
$(
[<$name _key>]: client_key
.[<$name _key>]
.as_ref()
.map(<[<$base_ty_name PublicKey>]>::new),
)*
}
}
}
///////////////////////
// Compressed Public Key
///////////////////////
#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
pub(crate) struct [<$base_struct_name CompressedPublicKey>] {
$(
pub(super) [<$name _key>]: Option<[<$base_ty_name CompressedPublicKey>]>,
)*
}
impl [<$base_struct_name CompressedPublicKey>] {
pub(crate) fn new(client_key: &[<$base_struct_name ClientKey>]) -> Self {
Self {
$(
[<$name _key>]: client_key
.[<$name _key>]
.as_ref()
.map(<[<$base_ty_name CompressedPublicKey>]>::new),
)*
}
}
pub(crate) fn decompress(self) -> [<$base_struct_name PublicKey>] {
[<$base_struct_name PublicKey>] {
$(
[<$name _key>]: self.[<$name _key>]
.map(|key| key.decompress()),
)*
}
}
}
///////////////////////
// Server Key
///////////////////////
#[derive(Clone, ::serde::Deserialize, ::serde::Serialize)]
pub(crate) struct [<$base_struct_name ServerKey>] {
$(
pub(super) [<$name _key>]: Option<[<$base_ty_name ServerKey>]>,
)*
}
impl [<$base_struct_name ServerKey>] {
pub(crate) fn new(client_key: &[<$base_struct_name ClientKey>]) -> Self {
Self {
$(
[<$name _key>]: client_key.[<$name _key>].as_ref().map(<[<$base_ty_name ServerKey>]>::new),
)*
}
}
}
impl Default for [<$base_struct_name ServerKey>] {
fn default() -> Self {
Self {
$(
[<$name _key>]: None,
)*
}
}
}
/////////////////////////
// Compressed Server Key
/////////////////////////
#[derive(Clone, ::serde::Deserialize, ::serde::Serialize)]
pub(crate) struct [<$base_struct_name CompressedServerKey>] {
$(
pub(super) [<$name _key>]: Option<[<$base_ty_name CompressedServerKey>]>,
)*
}
impl [<$base_struct_name CompressedServerKey>] {
pub(crate) fn new(client_key: &[<$base_struct_name ClientKey>]) -> Self {
Self {
$(
[<$name _key>]: client_key.[<$name _key>].as_ref().map(<[<$base_ty_name CompressedServerKey>]>::new),
)*
}
}
pub(crate) fn decompress(self) -> [<$base_struct_name ServerKey>] {
[<$base_struct_name ServerKey>] {
$(
[<$name _key>]: self.[<$name _key>].map(|compressed_key| compressed_key.decompress()),
)*
}
}
}
impl Default for [<$base_struct_name CompressedServerKey>] {
fn default() -> Self {
Self {
$(
[<$name _key>]: None,
)*
}
}
}
}
}
}

View File

@@ -27,119 +27,45 @@ where
/// Mainly used to provide good errors.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Type {
#[cfg(feature = "boolean")]
FheBool,
#[cfg(feature = "shortint")]
FheUint2,
#[cfg(feature = "shortint")]
FheUint3,
#[cfg(feature = "shortint")]
FheUint4,
#[cfg(feature = "integer")]
FheUint8,
#[cfg(feature = "integer")]
FheUint10,
#[cfg(feature = "integer")]
FheUint12,
#[cfg(feature = "integer")]
FheUint14,
#[cfg(feature = "integer")]
FheUint16,
#[cfg(feature = "integer")]
FheUint32,
#[cfg(feature = "integer")]
FheUint64,
#[cfg(feature = "integer")]
FheUint128,
#[cfg(feature = "integer")]
FheUint256,
#[cfg(feature = "integer")]
FheInt8,
#[cfg(feature = "integer")]
FheInt16,
#[cfg(feature = "integer")]
FheInt32,
#[cfg(feature = "integer")]
FheInt64,
#[cfg(feature = "integer")]
FheInt128,
#[cfg(feature = "integer")]
FheInt256,
}
/// The server key of a given type was not initialized
/// The server key was not initialized
#[derive(Debug)]
pub struct UninitializedServerKey(pub(crate) Type);
pub struct UninitializedServerKey;
impl Display for UninitializedServerKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"The server key for the type '{:?}' was not properly initialized\n\
"The server key was not properly initialized.\n\
Did you forget to call `set_server_key` in this thread or forget to
enable the type in the config ?
",
self.0
)
}
}
impl std::error::Error for UninitializedServerKey {}
/// The client key of a given type was not initialized
#[derive(Debug)]
pub struct UninitializedClientKey(pub(crate) Type);
impl Display for UninitializedClientKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"The client key for the type '{:?}' was not properly initialized\n\
Did you forget to enable the type in the config ?
",
self.0
)
}
}
impl std::error::Error for UninitializedClientKey {}
/// The public key of a given type was not initialized
#[derive(Debug)]
pub struct UninitializedPublicKey(pub(crate) Type);
impl Display for UninitializedPublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"The public key for the type '{:?}' was not properly initialized\n\
Did you forget do enable the type in the config ?
",
self.0
)
}
}
impl std::error::Error for UninitializedPublicKey {}
/// The compresesd public key of a given type was not initialized
#[derive(Debug)]
pub struct UninitializedCompressedPublicKey(pub(crate) Type);
impl Display for UninitializedCompressedPublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"The compressed public key for the type '{:?}' was not properly initialized\n\
Did you forget do enable the type in the config ?
",
self.0
)
}
}
impl std::error::Error for UninitializedCompressedPublicKey {}
/// Error when trying to create a short integer from a value that was too big to be represented
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct OutOfRangeError;
@@ -156,9 +82,7 @@ impl std::error::Error for OutOfRangeError {}
#[derive(Debug, Eq, PartialEq)]
pub enum Error {
OutOfRange,
UninitializedClientKey(Type),
UninitializedPublicKey(Type),
UninitializedServerKey(Type),
UninitializedServerKey,
}
impl From<OutOfRangeError> for Error {
@@ -167,38 +91,14 @@ impl From<OutOfRangeError> for Error {
}
}
impl From<UninitializedClientKey> for Error {
fn from(value: UninitializedClientKey) -> Self {
Self::UninitializedClientKey(value.0)
}
}
impl From<UninitializedPublicKey> for Error {
fn from(value: UninitializedPublicKey) -> Self {
Self::UninitializedPublicKey(value.0)
}
}
impl From<UninitializedServerKey> for Error {
fn from(value: UninitializedServerKey) -> Self {
Self::UninitializedServerKey(value.0)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Error::OutOfRange => {
write!(f, "{OutOfRangeError}")
}
Error::UninitializedClientKey(ty) => {
write!(f, "{}", UninitializedClientKey(*ty))
}
Error::UninitializedPublicKey(ty) => {
write!(f, "{}", UninitializedPublicKey(*ty))
}
Error::UninitializedServerKey(ty) => {
write!(f, "{}", UninitializedServerKey(*ty))
Error::UninitializedServerKey => {
write!(f, "{}", UninitializedServerKey)
}
}
}

View File

@@ -11,7 +11,7 @@ use crate::high_level_api::keys::ServerKey;
/// (eg a web server that processes multiple requests in multiple threads).
/// The user however, has to initialize the internal keys each time it starts a thread.
thread_local! {
static INTERNAL_KEYS: RefCell<ServerKey> = RefCell::new(ServerKey::default());
static INTERNAL_KEYS: RefCell<Option<ServerKey>> = RefCell::new(None);
}
/// The function used to initialize internal keys.
@@ -27,7 +27,7 @@ thread_local! {
/// ```
/// use tfhe;
///
/// # let config = tfhe::ConfigBuilder::all_disabled().build();
/// # let config = tfhe::ConfigBuilder::default().build();
/// let (client_key, server_key) = tfhe::generate_keys(config);
///
/// tfhe::set_server_key(server_key);
@@ -42,7 +42,7 @@ thread_local! {
/// use tfhe;
/// use tfhe::ConfigBuilder;
///
/// # let config = tfhe::ConfigBuilder::all_disabled().build();
/// # let config = tfhe::ConfigBuilder::default().build();
/// let (client_key, server_key) = tfhe::generate_keys(config);
/// let server_key_2 = server_key.clone();
///
@@ -60,11 +60,11 @@ thread_local! {
/// th1.join();
/// ```
pub fn set_server_key(keys: ServerKey) {
INTERNAL_KEYS.with(|internal_keys| internal_keys.replace_with(|_old| keys));
INTERNAL_KEYS.with(|internal_keys| internal_keys.replace_with(|_old| Some(keys)));
}
pub fn unset_server_key() -> ServerKey {
INTERNAL_KEYS.with(|internal_keys| internal_keys.replace_with(|_old| Default::default()))
pub fn unset_server_key() -> Option<ServerKey> {
INTERNAL_KEYS.with(|internal_keys| internal_keys.replace_with(|_old| None))
}
pub fn with_server_key_as_context<T, F>(keys: ServerKey, f: F) -> (T, ServerKey)
@@ -74,11 +74,10 @@ where
set_server_key(keys);
let result = f();
let keys = unset_server_key();
(result, keys)
(result, keys.unwrap()) // unwrap is ok since we know we did set_server_key
}
/// Convenience function that allows to write functions that needs to access the internal keys.
#[cfg(any(feature = "integer", feature = "shortint", feature = "boolean"))]
#[inline]
pub(crate) fn with_internal_keys<T, F>(func: F) -> T
where
@@ -86,68 +85,20 @@ where
{
// Should use `with_borrow` when its stabilized
INTERNAL_KEYS.with(|keys| {
let key = &*keys.borrow();
let maybe_key = &*keys.borrow();
let key = maybe_key
.as_ref()
.ok_or(UninitializedServerKey)
.unwrap_display();
func(key)
})
}
/// Helper macro to help reduce boiler plate
/// needed to implement `WithGlobalKey` since for
/// our keys, the implementation is the same, only a few things change.
///
/// It expects:
/// - The implementor type
/// - The `name` of the key type for which the trait will be implemented.
/// - The identifier (or identifier chain) that points to the member in the `ServerKey` that holds
/// the key for which the trait is implemented.
/// - Type Variant used to identify the type at runtime (see `error.rs`)
#[cfg(feature = "boolean")]
macro_rules! impl_with_global_key {
(
for $implementor:ty {
key_type: $key_type:ty,
keychain_member: $($member:ident).*,
type_variant: $enum_variant:expr,
}
) => {
impl crate::high_level_api::global_state::WithGlobalKey for $implementor {
type Key = $key_type;
fn with_global<R, F>(self, func: F) -> Result<R, crate::high_level_api::errors::UninitializedServerKey>
where
F: FnOnce(&Self::Key) -> R,
{
crate::high_level_api::global_state::with_internal_keys(|keys| {
keys$(.$member)*
.as_ref()
.map(func)
.ok_or(crate::high_level_api::errors::UninitializedServerKey($enum_variant))
})
}
}
}
}
/// Global key access trait
///
/// Each type we will expose to the user is going to need to have some internal keys.
/// This trait is there to make each of these internal keys have a convenience function that gives
/// access to the internal keys of its type.
///
/// Typically, the implementation of the trait will be on the 'internal' key type
/// and will call [with_internal_keys] and select the right member of the [ServerKey] type.
pub trait WithGlobalKey: Sized {
type Key;
fn with_global<R, F>(self, func: F) -> Result<R, UninitializedServerKey>
where
F: FnOnce(&Self::Key) -> R;
#[track_caller]
fn with_unwrapped_global<R, F>(self, func: F) -> R
where
F: FnOnce(&Self::Key) -> R,
{
self.with_global(func).unwrap_display()
}
F: FnOnce(&Self::Key) -> R;
}

View File

@@ -10,13 +10,13 @@ use crate::shortint::EncryptionKeyChoice;
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct IntegerConfig {
pub(crate) block_parameters: Option<crate::shortint::PBSParameters>,
pub(crate) block_parameters: crate::shortint::PBSParameters,
pub(crate) wopbs_block_parameters: Option<crate::shortint::WopbsParameters>,
}
impl IntegerConfig {
pub(crate) fn new(
block_parameters: Option<crate::shortint::PBSParameters>,
block_parameters: crate::shortint::PBSParameters,
wopbs_block_parameters: Option<crate::shortint::WopbsParameters>,
) -> Self {
Self {
@@ -25,38 +25,22 @@ impl IntegerConfig {
}
}
pub(in crate::high_level_api) fn all_default() -> Self {
Self::default_big()
}
pub(in crate::high_level_api) fn all_none() -> Self {
Self::new(None, None)
}
pub(in crate::high_level_api) fn default_big() -> Self {
Self {
block_parameters: Some(
crate::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS.into(),
),
block_parameters: crate::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS.into(),
wopbs_block_parameters: None,
}
}
pub(in crate::high_level_api) fn default_small() -> Self {
Self {
block_parameters: Some(
crate::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_PBS_KS.into(),
),
block_parameters: crate::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_PBS_KS.into(),
wopbs_block_parameters: None,
}
}
pub fn enable_wopbs(&mut self) {
let block_parameter = self
.block_parameters
.get_or_insert(crate::shortint::parameters::PARAM_MESSAGE_2_CARRY_2_KS_PBS.into());
let wopbs_block_parameters = match block_parameter.encryption_key_choice() {
let wopbs_block_parameters = match self.block_parameters.encryption_key_choice() {
EncryptionKeyChoice::Big => crate::shortint::parameters::parameters_wopbs_message_carry::WOPBS_PARAM_MESSAGE_2_CARRY_2_KS_PBS,
_ => panic!("WOPBS only support KS_PBS parameters")
};
@@ -67,19 +51,17 @@ impl IntegerConfig {
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct IntegerClientKey {
pub(crate) key: Option<crate::integer::ClientKey>,
pub(crate) key: crate::integer::ClientKey,
pub(crate) wopbs_block_parameters: Option<crate::shortint::WopbsParameters>,
}
impl IntegerClientKey {
pub(crate) fn with_seed(config: IntegerConfig, seed: Seed) -> Self {
let key = config.block_parameters.map(|params| {
let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(seed);
let cks = crate::shortint::engine::ShortintEngine::new_from_seeder(&mut seeder)
.new_client_key(params.into())
.unwrap();
crate::integer::ClientKey::from(cks)
});
let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(seed);
let cks = crate::shortint::engine::ShortintEngine::new_from_seeder(&mut seeder)
.new_client_key(config.block_parameters.into())
.unwrap();
let key = crate::integer::ClientKey::from(cks);
Self {
key,
wopbs_block_parameters: config.wopbs_block_parameters,
@@ -87,20 +69,14 @@ impl IntegerClientKey {
}
#[cfg(feature = "__wasm_api")]
pub(crate) fn block_parameters(&self) -> Option<crate::shortint::parameters::PBSParameters> {
self.key.as_ref().map(|key| key.parameters())
pub(crate) fn block_parameters(&self) -> crate::shortint::parameters::PBSParameters {
self.key.parameters()
}
}
impl From<IntegerConfig> for IntegerClientKey {
fn from(config: IntegerConfig) -> Self {
let key = match config.block_parameters {
Some(params) => {
let cks = crate::integer::ClientKey::new(params);
Some(cks)
}
None => None,
};
let key = crate::integer::ClientKey::new(config.block_parameters);
Self {
key,
wopbs_block_parameters: config.wopbs_block_parameters,
@@ -108,17 +84,15 @@ impl From<IntegerConfig> for IntegerClientKey {
}
}
#[derive(Clone, Default, serde::Serialize, serde::Deserialize)]
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct IntegerServerKey {
pub(crate) key: Option<crate::integer::ServerKey>,
pub(crate) key: crate::integer::ServerKey,
pub(crate) wopbs_key: Option<crate::integer::wopbs::WopbsKey>,
}
impl IntegerServerKey {
pub(in crate::high_level_api) fn new(client_key: &IntegerClientKey) -> Self {
let Some(cks) = &client_key.key else {
return Self::default();
};
let cks = &client_key.key;
assert_eq!(
cks.parameters().message_modulus().0,
4,
@@ -132,28 +106,24 @@ impl IntegerServerKey {
crate::integer::wopbs::WopbsKey::new_wopbs_key(cks, &base_integer_key, wopbs_params)
});
Self {
key: Some(base_integer_key),
key: base_integer_key,
wopbs_key,
}
}
pub(in crate::high_level_api::integers) fn pbs_key(&self) -> &crate::integer::ServerKey {
self.key
.as_ref()
.expect("Integer ServerKey is not initialized")
pub(in crate::high_level_api) fn pbs_key(&self) -> &crate::integer::ServerKey {
&self.key
}
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct IntegerCompressedServerKey {
pub(crate) key: Option<crate::integer::CompressedServerKey>,
pub(crate) key: crate::integer::CompressedServerKey,
}
impl IntegerCompressedServerKey {
pub(in crate::high_level_api) fn new(client_key: &IntegerClientKey) -> Self {
let Some(integer_key) = &client_key.key else {
return Self { key: None };
};
let integer_key = &client_key.key;
if client_key.wopbs_block_parameters.is_some() {
panic!(
"The configuration used to create the ClientKey \
@@ -165,12 +135,12 @@ impl IntegerCompressedServerKey {
);
}
let key = crate::integer::CompressedServerKey::new(integer_key);
Self { key: Some(key) }
Self { key }
}
pub(in crate::high_level_api) fn decompress(self) -> IntegerServerKey {
IntegerServerKey {
key: self.key.map(crate::integer::ServerKey::from),
key: crate::integer::ServerKey::from(self.key),
wopbs_key: None,
}
}
@@ -178,7 +148,7 @@ impl IntegerCompressedServerKey {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(in crate::high_level_api) struct IntegerCompactPublicKey {
pub(in crate::high_level_api) key: Option<CompactPublicKey>,
pub(in crate::high_level_api) key: CompactPublicKey,
}
impl IntegerCompactPublicKey {
@@ -187,50 +157,42 @@ impl IntegerCompactPublicKey {
}
pub(in crate::high_level_api) fn try_new(client_key: &IntegerClientKey) -> Option<Self> {
let Some(cks) = client_key.key.as_ref() else {
return Some(Self { key: None });
};
let cks = &client_key.key;
let key = CompactPublicKey::try_new(cks)?;
Some(Self { key: Some(key) })
Some(Self { key })
}
pub(in crate::high_level_api::integers) fn try_encrypt_compact<T>(
&self,
values: &[T],
num_blocks: usize,
) -> Option<CompactCiphertextList>
) -> CompactCiphertextList
where
T: crate::integer::block_decomposition::DecomposableInto<u64>,
{
let Some(key) = self.key.as_ref() else {
return None;
};
let ct = key.encrypt_slice_radix_compact(values, num_blocks);
Some(ct)
self.key.encrypt_slice_radix_compact(values, num_blocks)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(in crate::high_level_api) struct IntegerCompressedCompactPublicKey {
pub(in crate::high_level_api) key: Option<CompressedCompactPublicKey>,
pub(in crate::high_level_api) key: CompressedCompactPublicKey,
}
impl IntegerCompressedCompactPublicKey {
pub(in crate::high_level_api) fn new(client_key: &IntegerClientKey) -> Self {
let Some(cks) = client_key.key.as_ref() else {
return Self { key: None };
};
let cks = &client_key.key;
let key = CompressedCompactPublicKey::new(cks);
Self { key: Some(key) }
Self { key }
}
pub(in crate::high_level_api) fn decompress(self) -> IntegerCompactPublicKey {
IntegerCompactPublicKey {
key: self.key.map(CompressedCompactPublicKey::decompress),
key: CompressedCompactPublicKey::decompress(self.key),
}
}
}

View File

@@ -9,9 +9,7 @@ use rand::prelude::*;
#[test]
fn test_signed_integer_compressed() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let clear = -1234i16;
@@ -25,9 +23,7 @@ fn test_signed_integer_compressed() {
fn test_integer_compressed_small() {
let mut rng = thread_rng();
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default_with_small_encryption().build();
let (client_key, _) = generate_keys(config);
let clear = rng.gen::<i16>();
@@ -41,9 +37,7 @@ fn test_integer_compressed_small() {
fn test_int32_compare() {
let mut rng = thread_rng();
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -144,9 +138,7 @@ fn test_int32_compare() {
#[test]
fn test_int32_bitwise() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (cks, sks) = generate_keys(config);
@@ -280,16 +272,14 @@ fn fhe_int64_rotate(config: Config) {
}
#[test]
fn test_int64_rotate() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
fhe_int64_rotate(config);
}
#[test]
fn test_multi_bit_rotate() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -373,16 +363,14 @@ fn fhe_int32_div_rem(config: Config) {
#[test]
fn test_int32_div_rem() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
fhe_int32_div_rem(config);
}
#[test]
fn test_multi_div_rem() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -391,9 +379,7 @@ fn test_multi_div_rem() {
}
#[test]
fn test_integer_casting() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
@@ -474,9 +460,7 @@ fn test_integer_casting() {
#[test]
fn test_if_then_else() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -507,9 +491,7 @@ fn test_if_then_else() {
#[test]
fn test_abs() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -527,9 +509,7 @@ fn test_abs() {
#[test]
fn test_trivial_fhe_int8() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);
@@ -542,9 +522,7 @@ fn test_trivial_fhe_int8() {
#[test]
fn test_trivial_fhe_int256_small() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default_with_small_encryption().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);
@@ -556,8 +534,8 @@ fn test_trivial_fhe_int256_small() {
}
#[test]
fn test_compact_public_key_big() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
)
@@ -573,8 +551,8 @@ fn test_compact_public_key_big() {
#[test]
fn test_compact_public_key_small() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk
::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS,
None,
@@ -591,8 +569,8 @@ fn test_compact_public_key_small() {
#[test]
fn test_compact_public_key_list_big() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
@@ -603,8 +581,8 @@ crate::shortint::parameters::parameters_compact_pk::PARAM_MESSAGE_2_CARRY_2_COMP
#[test]
fn test_compact_public_key_list_small() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk
::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS,
None,

View File

@@ -11,9 +11,7 @@ use crate::{
#[test]
fn test_quickstart_uint8() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -36,9 +34,7 @@ fn test_quickstart_uint8() {
#[test]
fn test_uint8_compare() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -139,9 +135,7 @@ fn test_uint8_compare() {
#[test]
fn test_integer_compressed_can_be_serialized() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let clear = U256::from(u64::MAX);
@@ -157,9 +151,7 @@ fn test_integer_compressed_can_be_serialized() {
#[test]
fn test_integer_compressed() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let clear = 12_837u16;
@@ -171,9 +163,7 @@ fn test_integer_compressed() {
#[test]
fn test_integer_compressed_small() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default_with_small_encryption().build();
let (client_key, _) = generate_keys(config);
let clear = 12_837u16;
@@ -185,9 +175,7 @@ fn test_integer_compressed_small() {
#[test]
fn test_uint32() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (cks, sks) = generate_keys(config);
@@ -272,9 +260,7 @@ fn fhe_uint32_shift(config: Config) {
#[test]
fn test_uint32_bitwise() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (cks, sks) = generate_keys(config);
@@ -352,16 +338,14 @@ fn test_uint32_bitwise() {
#[test]
fn test_bit_shift() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
fhe_uint32_shift(config);
}
#[test]
fn test_multi_bit_shift() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -428,16 +412,14 @@ fn fhe_uint32_rotate(config: Config) {
#[test]
fn test_uint32_rotate() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
fhe_uint32_rotate(config);
}
#[test]
fn test_multi_bit_rotate() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -516,16 +498,14 @@ fn fhe_uint32_div_rem(config: Config) {
#[test]
fn test_uint32_div_rem() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
fhe_uint32_div_rem(config);
}
#[test]
fn test_multi_div_rem() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::PARAM_MULTI_BIT_MESSAGE_2_CARRY_2_GROUP_3_KS_PBS,
None,
)
@@ -535,9 +515,7 @@ fn test_multi_div_rem() {
#[test]
fn test_uint64() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (cks, sks) = generate_keys(config);
@@ -560,9 +538,7 @@ fn test_uint64() {
#[test]
fn test_small_uint128() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default_with_small_encryption().build();
let (cks, sks) = generate_keys(config);
@@ -585,9 +561,7 @@ fn test_small_uint128() {
#[test]
fn test_integer_compressed_public_key() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let public_key = CompressedPublicKey::new(&client_key);
@@ -599,9 +573,7 @@ fn test_integer_compressed_public_key() {
#[test]
fn test_decompressed_public_key_encrypt() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _) = generate_keys(config);
let compressed_public_key = CompressedPublicKey::new(&client_key);
@@ -614,8 +586,8 @@ fn test_decompressed_public_key_encrypt() {
#[test]
fn test_compact_public_key_big() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
)
@@ -631,8 +603,8 @@ fn test_compact_public_key_big() {
#[test]
fn test_compact_public_key_list_big() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS,
None,
)
@@ -642,8 +614,8 @@ fn test_compact_public_key_list_big() {
#[test]
fn test_compact_public_key_list_small() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk
::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS,
None,
@@ -690,8 +662,8 @@ fn test_compact_public_key_list(config: Config) {
#[test]
fn test_compact_public_key_small() {
let config = ConfigBuilder::all_disabled()
.enable_custom_integers(
let config = ConfigBuilder::default()
.use_custom_parameters(
crate::shortint::parameters::parameters_compact_pk
::PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS,
None,
@@ -708,9 +680,7 @@ fn test_compact_public_key_small() {
#[test]
fn test_trivial_fhe_uint8() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);
@@ -723,9 +693,7 @@ fn test_trivial_fhe_uint8() {
#[test]
fn test_trivial_fhe_uint256_small() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default_with_small_encryption().build();
let (client_key, sks) = generate_keys(config);
set_server_key(sks);
@@ -738,9 +706,7 @@ fn test_trivial_fhe_uint256_small() {
#[test]
fn test_integer_casting() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
@@ -821,9 +787,7 @@ fn test_integer_casting() {
#[test]
fn test_if_then_else() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -5,15 +5,11 @@ use std::ops::{
};
use crate::conformance::ParameterSetConformant;
use crate::errors::{
UninitializedClientKey, UninitializedCompressedPublicKey, UninitializedPublicKey,
UnwrapResultExt,
};
use crate::high_level_api::global_state::WithGlobalKey;
use crate::high_level_api::integers::parameters::IntegerParameter;
use crate::high_level_api::integers::IntegerServerKey;
use crate::high_level_api::internal_traits::{DecryptionKey, EncryptionKey, TypeIdentifier};
use crate::high_level_api::keys::{CompressedPublicKey, RefKeyFromKeyChain};
use crate::high_level_api::keys::CompressedPublicKey;
use crate::high_level_api::traits::{
DivRem, FheBootstrap, FheDecrypt, FheEq, FheMax, FheMin, FheOrd, FheTrivialEncrypt,
FheTryEncrypt, FheTryTrivialEncrypt, RotateLeft, RotateLeftAssign, RotateRight,
@@ -27,35 +23,6 @@ use crate::integer::{IntegerCiphertext, SignedRadixCiphertext, I256, U256};
use crate::named::Named;
use crate::CompactPublicKey;
/// A Generic FHE unsigned integer
///
/// Contrary to *shortints*, these integers can in theory by parametrized to
/// represent integers of any number of bits (eg: 16, 24, 32, 64).
///
/// However, in practice going above 16 bits may not be ideal as the
/// computations would not scale and become very expensive.
///
/// Integers works by combining together multiple shortints
/// with one of the available representation.
///
/// This struct is generic over some parameters, as its the parameters
/// that controls how many bit they represent.
/// You will need to use one of this type specialization (e.g., [FheUint8], [FheUint12],
/// [FheUint16]).
///
/// Its the type that overloads the operators (`+`, `-`, `*`),
/// since the `GenericInteger` type is not `Copy` the operators are also overloaded
/// to work with references.
///
///
/// To be able to use this type, the cargo feature `integers` must be enabled,
/// and your config should also enable the type with either default parameters or custom ones.
///
///
/// [FheUint8]: crate::high_level_api::FheUint8
/// [FheUint12]: crate::high_level_api::FheUint12
/// [FheUint16]: crate::high_level_api::FheUint16
#[derive(Debug)]
pub enum GenericIntegerBlockError {
NumberOfBlocks(usize, usize),
@@ -94,6 +61,21 @@ impl std::fmt::Display for GenericIntegerBlockError {
}
}
/// A Generic FHE unsigned integer
///
/// This struct is generic over some parameters, as its the parameters
/// that controls how many bit they represent.
///
/// You will need to use one of this type specialization (e.g., [FheUint8], [FheUint12],
/// [FheUint16]).
///
/// Its the type that overloads the operators (`+`, `-`, `*`),
/// since the `GenericInteger` type is not `Copy` the operators are also overloaded
/// to work with references.
///
/// [FheUint8]: crate::high_level_api::FheUint8
/// [FheUint12]: crate::high_level_api::FheUint12
/// [FheUint16]: crate::high_level_api::FheUint16
#[cfg_attr(all(doc, not(doctest)), doc(cfg(feature = "integer")))]
#[derive(Clone, serde::Deserialize, serde::Serialize)]
pub struct GenericInteger<P: IntegerParameter> {
@@ -299,11 +281,10 @@ where
impl<P, ClearType> FheDecrypt<ClearType> for GenericInteger<P>
where
P: IntegerParameter,
P::Id: RefKeyFromKeyChain<Key = crate::integer::ClientKey>,
crate::integer::ClientKey: DecryptionKey<P::InnerCiphertext, ClearType>,
{
fn decrypt(&self, key: &ClientKey) -> ClearType {
let key = self.id.unwrapped_ref_key(key);
let key = &key.key.key;
key.decrypt(&self.ciphertext)
}
}
@@ -319,12 +300,7 @@ where
fn try_encrypt(value: T, key: &ClientKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let integer_client_key = key
.integer_key
.key
.as_ref()
.ok_or(UninitializedClientKey(id.type_variant()))
.unwrap_display();
let integer_client_key = &key.key.key;
let ciphertext = <crate::integer::ClientKey as EncryptionKey<_, _>>::encrypt(
integer_client_key,
(value, P::num_blocks()),
@@ -343,11 +319,7 @@ where
fn try_encrypt(value: T, key: &PublicKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let integer_public_key = key
.base_integer_key
.as_ref()
.ok_or(UninitializedPublicKey(id.type_variant()))
.unwrap_display();
let integer_public_key = &key.key;
let ciphertext = <crate::integer::PublicKey as EncryptionKey<_, _>>::encrypt(
integer_public_key,
(value, P::num_blocks()),
@@ -366,11 +338,7 @@ where
fn try_encrypt(value: T, key: &CompressedPublicKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let integer_public_key = key
.base_integer_key
.as_ref()
.ok_or(UninitializedCompressedPublicKey(id.type_variant()))
.unwrap_display();
let integer_public_key = &key.key;
let ciphertext = <crate::integer::CompressedPublicKey as EncryptionKey<_, _>>::encrypt(
integer_public_key,
(value, P::num_blocks()),
@@ -389,12 +357,7 @@ where
fn try_encrypt(value: T, key: &CompactPublicKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let integer_public_key = key
.integer_key
.key
.as_ref()
.ok_or(UninitializedPublicKey(id.type_variant()))
.unwrap_display();
let integer_public_key = &key.key.key;
let ciphertext =
<crate::integer::public_key::CompactPublicKey as EncryptionKey<_, _>>::encrypt(
integer_public_key,

View File

@@ -1,5 +1,4 @@
use crate::conformance::{ListSizeConstraint, ParameterSetConformant};
use crate::errors::{UninitializedPublicKey, UnwrapResultExt};
use crate::high_level_api::integers::parameters::IntegerParameter;
use crate::high_level_api::integers::types::base::GenericInteger;
use crate::high_level_api::internal_traits::TypeIdentifier;
@@ -62,11 +61,7 @@ where
fn try_encrypt(value: T, key: &CompactPublicKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let ciphertext = key
.integer_key
.try_encrypt_compact(&[value], P::num_blocks())
.ok_or(UninitializedPublicKey(id.type_variant()))
.unwrap_display();
let ciphertext = key.key.try_encrypt_compact(&[value], P::num_blocks());
Ok(Self {
list: ciphertext,
id,
@@ -84,11 +79,7 @@ where
fn try_encrypt(values: &'a [T], key: &CompactPublicKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let ciphertext = key
.integer_key
.try_encrypt_compact(values, P::num_blocks())
.ok_or(UninitializedPublicKey(id.type_variant()))
.unwrap_display();
let ciphertext = key.key.try_encrypt_compact(values, P::num_blocks());
Ok(Self {
list: ciphertext,
id,
@@ -151,9 +142,7 @@ mod test {
fn test_invalid_generic_compact_integer() {
type Ct = CompactFheUint8;
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _server_key) = generate_keys(config);
@@ -228,9 +217,7 @@ mod test {
fn test_invalid_generic_compact_integer_list() {
type Ct = CompactFheUint8List;
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _server_key) = generate_keys(config);
@@ -294,9 +281,7 @@ mod test {
#[test]
fn test_valid_generic_compact_integer() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);
@@ -340,9 +325,7 @@ mod test {
#[test]
fn test_valid_generic_compact_integer_list() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, server_key) = generate_keys(config);

View File

@@ -1,5 +1,4 @@
use crate::conformance::ParameterSetConformant;
use crate::errors::{UninitializedClientKey, UnwrapResultExt};
use crate::high_level_api::integers::parameters::IntegerParameter;
use crate::high_level_api::integers::types::base::GenericInteger;
use crate::high_level_api::internal_traits::{EncryptionKey, TypeIdentifier};
@@ -79,12 +78,7 @@ where
fn try_encrypt(value: T, key: &ClientKey) -> Result<Self, Self::Error> {
let id = P::Id::default();
let integer_client_key = key
.integer_key
.key
.as_ref()
.ok_or(UninitializedClientKey(id.type_variant()))
.unwrap_display();
let integer_client_key = &key.key.key;
let inner = <crate::integer::ClientKey as EncryptionKey<_, _>>::encrypt(
integer_client_key,
(value, P::num_blocks()),

View File

@@ -113,27 +113,14 @@ macro_rules! static_int_type {
#[cfg_attr(all(doc, not(doctest)), cfg(feature = "integer"))]
pub type [<Compact $name List>] = GenericCompactIntegerList<[<$name Parameters>]>;
impl $crate::high_level_api::keys::RefKeyFromKeyChain for [<$name Id>] {
type Key = crate::integer::ClientKey;
fn ref_key(self, keys: &crate::high_level_api::ClientKey)
-> Result<&Self::Key, $crate::high_level_api::errors::UninitializedClientKey> {
keys
.integer_key
.key
.as_ref()
.ok_or($crate::high_level_api::errors::UninitializedClientKey(self.type_variant()))
}
}
impl $crate::high_level_api::global_state::WithGlobalKey for [<$name Id>] {
type Key = crate::high_level_api::integers::IntegerServerKey;
fn with_global<R, F>(self, func: F) -> Result<R, $crate::high_level_api::errors::UninitializedServerKey>
fn with_unwrapped_global<R, F>(self, func: F) -> R
where
F: FnOnce(&Self::Key) -> R {
$crate::high_level_api::global_state::with_internal_keys(|keys| {
Ok(func(&keys.integer_key))
func(&keys.integer_key)
})
}
}

View File

@@ -4,11 +4,7 @@
use concrete_csprng::seeders::Seed;
#[cfg(feature = "boolean")]
use crate::high_level_api::booleans::BooleanClientKey;
use crate::high_level_api::config::Config;
use crate::high_level_api::errors::{UninitializedClientKey, UnwrapResultExt};
#[cfg(feature = "integer")]
use crate::high_level_api::integers::IntegerClientKey;
use super::{CompressedServerKey, ServerKey};
@@ -21,33 +17,22 @@ use super::{CompressedServerKey, ServerKey};
/// This key **MUST NOT** be sent to the server.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: BooleanClientKey,
#[cfg(feature = "integer")]
pub(crate) integer_key: IntegerClientKey,
pub(crate) key: IntegerClientKey,
}
impl ClientKey {
/// Generates a new keys.
pub fn generate<C: Into<Config>>(config: C) -> ClientKey {
#[allow(unused_variables)]
let config: Config = config.into();
ClientKey {
#[cfg(feature = "boolean")]
boolean_key: BooleanClientKey::from(config.boolean_config),
#[cfg(feature = "integer")]
integer_key: IntegerClientKey::from(config.integer_config),
key: IntegerClientKey::from(config.inner),
}
}
pub fn generate_with_seed<C: Into<Config>>(config: C, seed: Seed) -> ClientKey {
#[allow(unused_variables)]
let config: Config = config.into();
ClientKey {
#[cfg(feature = "boolean")]
boolean_key: BooleanClientKey::with_seed(config.boolean_config, seed),
#[cfg(feature = "integer")]
integer_key: IntegerClientKey::with_seed(config.integer_config, seed),
key: IntegerClientKey::with_seed(config.inner, seed),
}
}
@@ -65,62 +50,8 @@ impl ClientKey {
}
}
#[cfg(feature = "integer")]
impl AsRef<crate::integer::ClientKey> for ClientKey {
fn as_ref(&self) -> &crate::integer::ClientKey {
self.integer_key.key.as_ref().unwrap()
}
}
/// Trait to be implemented on the client key types that have a corresponding member
/// in the `ClientKeyChain`.
///
/// This is to allow the writing of generic functions.
pub trait RefKeyFromKeyChain: Sized {
type Key;
/// The method to implement, shall return a ref to the key or an error if
/// the key member in the key was not initialized
fn ref_key(self, keys: &ClientKey) -> Result<&Self::Key, UninitializedClientKey>;
/// Returns a ref to the key member of the key
///
/// # Panic
///
/// This will panic if the key was not initialized
#[track_caller]
fn unwrapped_ref_key(self, keys: &ClientKey) -> &Self::Key {
self.ref_key(keys).unwrap_display()
}
}
/// Helper macro to help reduce boiler plate
/// needed to implement `RefKeyFromKeyChain` since for
/// our keys, the implementation is the same, only a few things change.
///
/// It expects:
/// - The implementor type
/// - The `name` of the key type for which the trait will be implemented.
/// - The identifier (or identifier chain) that points to the member in the `ClientKey` that holds
/// the key for which the trait is implemented.
/// - Type Variant used to identify the type at runtime (see `error.rs`)
#[cfg(feature = "boolean")]
macro_rules! impl_ref_key_from_keychain {
(
for $implementor:ty {
key_type: $key_type:ty,
keychain_member: $($member:ident).*,
type_variant: $enum_variant:expr,
}
) => {
impl crate::high_level_api::keys::RefKeyFromKeyChain for $implementor {
type Key = $key_type;
fn ref_key(self, keys: &crate::high_level_api::keys::ClientKey) -> Result<&Self::Key, crate::high_level_api::errors::UninitializedClientKey> {
keys$(.$member)*
.as_ref()
.ok_or(crate::high_level_api::errors::UninitializedClientKey($enum_variant))
}
}
&self.key.key
}
}

View File

@@ -5,11 +5,8 @@ mod public;
mod server;
use crate::high_level_api::config::Config;
pub use client::{ClientKey, RefKeyFromKeyChain};
pub use public::{
CompactPublicKey, CompressedCompactPublicKey, CompressedPublicKey, PublicKey,
RefKeyFromCompressedPublicKeyChain, RefKeyFromPublicKeyChain,
};
pub use client::ClientKey;
pub use public::{CompactPublicKey, CompressedCompactPublicKey, CompressedPublicKey, PublicKey};
pub use server::{CompressedServerKey, ServerKey};
/// Generates keys using the provided config.
@@ -17,15 +14,10 @@ pub use server::{CompressedServerKey, ServerKey};
/// # Example
///
/// ```
/// # #[cfg(feature = "integer")]
/// # {
/// use tfhe::{generate_keys, ConfigBuilder};
///
/// let config = ConfigBuilder::all_disabled()
/// .enable_default_integers()
/// .build();
/// let config = ConfigBuilder::default().build();
/// let (client_key, server_key) = generate_keys(config);
/// # }
/// ```
pub fn generate_keys<C: Into<Config>>(config: C) -> (ClientKey, ServerKey) {
let client_kc = ClientKey::generate(config);

View File

@@ -1,211 +1,114 @@
//! This module defines PublicKey
//! This module defines PublicKey types.
//!
//! - [PublicKey] aggregates a key that can be made public, and that allows to encrypt (only)
#[cfg(feature = "boolean")]
use crate::high_level_api::booleans::{BooleanCompressedPublicKey, BooleanPublicKey};
use crate::high_level_api::errors::{UninitializedPublicKey, UnwrapResultExt};
#[cfg(feature = "integer")]
//! Public keys are keys that can only be used to encrypt data,
//! they are meant to be shared publicly.
//!
//! There are currently 2 types of public key:
//! - [PublicKey], Classical public key, works for any parameters, but its size can get large very
//! rapidly.
//! - [CompactPublicKey], This key uses significantly less memory/disk space. It it however, not
//! compatible with all parameters.
//!
//! Each of these two keys have a compressed variant that allows to reduce
//! transfer sizes.
//! - [CompressedPublicKey]
//! - [CompressedCompactPublicKey]
use crate::high_level_api::integers::{IntegerCompactPublicKey, IntegerCompressedCompactPublicKey};
use super::ClientKey;
/// Classical public key.
///
/// Works for any parameters, but uses a lot of memory / disk space
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct PublicKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: BooleanPublicKey,
#[cfg(feature = "integer")]
pub(in crate::high_level_api) base_integer_key: Option<crate::integer::PublicKey>,
pub(in crate::high_level_api) key: crate::integer::PublicKey,
}
impl PublicKey {
/// Creates a PublicKey, derived from the given client key
pub fn new(client_key: &ClientKey) -> Self {
// Silence warning about unused variable when none of these feature is used
#[cfg(not(any(feature = "boolean", feature = "shortint", feature = "integer")))]
let _ = client_key;
let base_integer_key = crate::integer::PublicKey::new(&client_key.key.key);
Self {
#[cfg(feature = "boolean")]
boolean_key: BooleanPublicKey::new(&client_key.boolean_key),
#[cfg(feature = "integer")]
base_integer_key: {
client_key
.integer_key
.key
.as_ref()
.map(crate::integer::PublicKey::new)
},
}
}
}
/// Trait to be implemented on the public key types that have a corresponding member
/// in the `PublicKey`.
///
/// This is to allow the writing of generic functions.
pub trait RefKeyFromPublicKeyChain: Sized {
type Key;
/// The method to implement, shall return a ref to the key or an error if
/// the key member in the key was not initialized
fn ref_key(self, keys: &PublicKey) -> Result<&Self::Key, UninitializedPublicKey>;
/// Returns a mutable ref to the key member of the key
///
/// # Panic
///
/// This will panic if the key was not initialized
#[track_caller]
fn unwrapped_ref_key(self, keys: &PublicKey) -> &Self::Key {
self.ref_key(keys).unwrap_display()
}
}
#[cfg(feature = "boolean")]
macro_rules! impl_ref_key_from_public_keychain {
(
for $implementor:ty {
key_type: $key_type:ty,
keychain_member: $($member:ident).*,
type_variant: $enum_variant:expr,
}
) => {
impl crate::high_level_api::keys::RefKeyFromPublicKeyChain for $implementor {
type Key = $key_type;
fn ref_key(self, keys: &crate::high_level_api::keys::PublicKey) -> Result<&Self::Key, crate::high_level_api::errors::UninitializedPublicKey> {
keys$(.$member)*
.as_ref()
.ok_or(crate::high_level_api::errors::UninitializedPublicKey($enum_variant))
}
key: base_integer_key,
}
}
}
/// Compressed classical public key.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CompressedPublicKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: BooleanCompressedPublicKey,
#[cfg(feature = "integer")]
pub(in crate::high_level_api) base_integer_key: Option<crate::integer::CompressedPublicKey>,
pub(in crate::high_level_api) key: crate::integer::CompressedPublicKey,
}
impl CompressedPublicKey {
pub fn new(client_key: &ClientKey) -> Self {
// Silence warning about unused variable when none of these feature is used
#[cfg(not(any(feature = "boolean", feature = "shortint", feature = "integer")))]
let _ = client_key;
let base_integer_key = crate::integer::CompressedPublicKey::new(&client_key.key.key);
Self {
#[cfg(feature = "boolean")]
boolean_key: BooleanCompressedPublicKey::new(&client_key.boolean_key),
#[cfg(feature = "integer")]
base_integer_key: {
client_key
.integer_key
.key
.as_ref()
.map(crate::integer::CompressedPublicKey::new)
},
key: base_integer_key,
}
}
pub fn decompress(self) -> PublicKey {
PublicKey {
#[cfg(feature = "boolean")]
boolean_key: self.boolean_key.decompress(),
#[cfg(feature = "integer")]
base_integer_key: self.base_integer_key.map(crate::integer::PublicKey::from),
key: crate::integer::PublicKey::from(self.key),
}
}
}
pub trait RefKeyFromCompressedPublicKeyChain: Sized {
type Key;
/// The method to implement, shall return a ref to the key or an error if
/// the key member in the key was not initialized
fn ref_key(self, keys: &CompressedPublicKey) -> Result<&Self::Key, UninitializedPublicKey>;
/// Returns a mutable ref to the key member of the key
///
/// # Panic
///
/// This will panic if the key was not initialized
#[track_caller]
fn unwrapped_ref_key(self, keys: &CompressedPublicKey) -> &Self::Key {
self.ref_key(keys).unwrap_display()
}
}
/// A more compact public key
///
/// Compared to the [PublicKey], this one is much smaller
/// however it supports less parameters.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CompactPublicKey {
#[cfg(feature = "integer")]
pub(in crate::high_level_api) integer_key: IntegerCompactPublicKey,
pub(in crate::high_level_api) key: IntegerCompactPublicKey,
}
impl CompactPublicKey {
/// Creates a CompactPublicKey
///
/// Compared to the [PublicKey], this one is much smaller
/// however it supports less parameters.
/// Creates a CompactPublicKey, derived from the given client key
///
/// # Panic
///
/// This will panic if parameters are not compatible
pub fn new(client_key: &ClientKey) -> Self {
#[cfg(feature = "integer")]
{
Self {
integer_key: IntegerCompactPublicKey::new(&client_key.integer_key),
}
}
#[cfg(not(feature = "integer"))]
{
let _ = client_key;
Self {}
Self {
key: IntegerCompactPublicKey::new(&client_key.key),
}
}
pub fn try_new(client_key: &ClientKey) -> Option<Self> {
#[cfg(feature = "integer")]
{
Some(Self {
integer_key: IntegerCompactPublicKey::try_new(&client_key.integer_key)?,
})
}
#[cfg(not(feature = "integer"))]
{
let _ = client_key;
Some(Self {})
}
Some(Self {
key: IntegerCompactPublicKey::try_new(&client_key.key)?,
})
}
}
/// Compressed variant of [CompactPublicKey]
///
/// The compression of [CompactPublicKey] allows to save disk space
/// an reduce transfer sizes.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CompressedCompactPublicKey {
#[cfg(feature = "integer")]
pub(in crate::high_level_api) integer_key: IntegerCompressedCompactPublicKey,
pub(in crate::high_level_api) key: IntegerCompressedCompactPublicKey,
}
impl CompressedCompactPublicKey {
/// Creates a CompressedCompactPublicKey
///
/// # Panic
///
/// This will panic if parameters are not compatible
pub fn new(client_key: &ClientKey) -> Self {
#[cfg(feature = "integer")]
{
Self {
integer_key: IntegerCompressedCompactPublicKey::new(&client_key.integer_key),
}
}
#[cfg(not(feature = "integer"))]
{
let _ = client_key;
Self {}
Self {
key: IntegerCompressedCompactPublicKey::new(&client_key.key),
}
}
/// Decompresses the key
pub fn decompress(self) -> CompactPublicKey {
CompactPublicKey {
#[cfg(feature = "integer")]
integer_key: self.integer_key.decompress(),
key: self.key.decompress(),
}
}
}

View File

@@ -1,9 +1,5 @@
#[cfg(feature = "boolean")]
use crate::high_level_api::booleans::{BooleanCompressedServerKey, BooleanServerKey};
#[cfg(feature = "integer")]
use crate::high_level_api::integers::{IntegerCompressedServerKey, IntegerServerKey};
#[cfg(any(feature = "boolean", feature = "integer"))]
use std::sync::Arc;
use super::ClientKey;
@@ -18,29 +14,22 @@ use super::ClientKey;
// Keys are stored in an Arc, so that cloning them is cheap
// (compared to an actual clone hundreds of MB / GB), and cheap cloning is needed for
// multithreading with less overhead)
#[derive(Clone, Default)]
#[derive(Clone)]
pub struct ServerKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: Arc<BooleanServerKey>,
#[cfg(feature = "integer")]
pub(crate) integer_key: Arc<IntegerServerKey>,
}
impl ServerKey {
pub fn new(keys: &ClientKey) -> Self {
Self {
#[cfg(feature = "boolean")]
boolean_key: Arc::new(BooleanServerKey::new(&keys.boolean_key)),
#[cfg(feature = "integer")]
integer_key: Arc::new(IntegerServerKey::new(&keys.integer_key)),
integer_key: Arc::new(IntegerServerKey::new(&keys.key)),
}
}
}
#[cfg(feature = "integer")]
impl AsRef<crate::integer::ServerKey> for ServerKey {
fn as_ref(&self) -> &crate::integer::ServerKey {
self.integer_key.key.as_ref().unwrap()
&self.integer_key.key
}
}
@@ -51,7 +40,7 @@ impl AsRef<crate::integer::ServerKey> for ServerKey {
// serde has a `rc` feature to allow deriving on Arc and Rc types
// but activating it in our lib would mean also activate it for all the dependency stack,
// so tfhe-rs users would have this feature enabled on our behalf and we don't want that
// so we implement the serialization / deseriazation ourselves.
// so we implement the serialization / deserialization ourselves.
//
// In the case of our ServerKey, this is fine, we expect programs to only
// serialize and deserialize the same server key only once.
@@ -59,9 +48,6 @@ impl AsRef<crate::integer::ServerKey> for ServerKey {
// in multi-threading scenarios.
#[derive(serde::Serialize)]
struct SerializableServerKey<'a> {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: &'a BooleanServerKey,
#[cfg(feature = "integer")]
pub(crate) integer_key: &'a IntegerServerKey,
}
@@ -71,9 +57,6 @@ impl serde::Serialize for ServerKey {
S: serde::Serializer,
{
SerializableServerKey {
#[cfg(feature = "boolean")]
boolean_key: &self.boolean_key,
#[cfg(feature = "integer")]
integer_key: &self.integer_key,
}
.serialize(serializer)
@@ -82,9 +65,6 @@ impl serde::Serialize for ServerKey {
#[derive(serde::Deserialize)]
struct DeserializableServerKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: BooleanServerKey,
#[cfg(feature = "integer")]
pub(crate) integer_key: IntegerServerKey,
}
@@ -94,9 +74,6 @@ impl<'de> serde::Deserialize<'de> for ServerKey {
D: serde::Deserializer<'de>,
{
DeserializableServerKey::deserialize(deserializer).map(|deserialized| Self {
#[cfg(feature = "boolean")]
boolean_key: Arc::new(deserialized.boolean_key),
#[cfg(feature = "integer")]
integer_key: Arc::new(deserialized.integer_key),
})
}
@@ -104,27 +81,18 @@ impl<'de> serde::Deserialize<'de> for ServerKey {
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct CompressedServerKey {
#[cfg(feature = "boolean")]
pub(crate) boolean_key: BooleanCompressedServerKey,
#[cfg(feature = "integer")]
pub(crate) integer_key: IntegerCompressedServerKey,
}
impl CompressedServerKey {
pub fn new(keys: &ClientKey) -> Self {
Self {
#[cfg(feature = "boolean")]
boolean_key: BooleanCompressedServerKey::new(&keys.boolean_key),
#[cfg(feature = "integer")]
integer_key: IntegerCompressedServerKey::new(&keys.integer_key),
integer_key: IntegerCompressedServerKey::new(&keys.key),
}
}
pub fn decompress(self) -> ServerKey {
ServerKey {
#[cfg(feature = "boolean")]
boolean_key: Arc::new(self.boolean_key.decompress()),
#[cfg(feature = "integer")]
integer_key: Arc::new(self.integer_key.decompress()),
}
}

View File

@@ -2,8 +2,6 @@
// internal helper macro to make it easier to `pub use`
// all necessary stuff tied to a FheUint/FheInt from the given `module_path`.
//
// Note: This is for Integers not Shortints
#[allow(unused)]
macro_rules! expand_pub_use_fhe_type(
(
@@ -36,16 +34,13 @@ pub use keys::{
#[cfg(test)]
mod tests;
#[cfg(feature = "boolean")]
pub use crate::high_level_api::booleans::{CompressedFheBool, FheBool, FheBoolParameters};
#[cfg(feature = "integer")]
pub use crate::high_level_api::booleans::{CompressedFheBool, FheBool};
expand_pub_use_fhe_type!(
pub use crate::high_level_api::integers{
FheUint8, FheUint10, FheUint12, FheUint14, FheUint16, FheUint32, FheUint64, FheUint128,
FheUint256, FheInt8, FheInt16, FheInt32, FheInt64, FheInt128, FheInt256
};
);
#[cfg(feature = "integer")]
#[cfg(feature = "safe-deserialization")]
pub use integers::safe_serialize::{
safe_deserialize_conformant, safe_deserialize_conformant_compact_integer,
@@ -53,8 +48,6 @@ pub use integers::safe_serialize::{
safe_serialize,
};
#[macro_use]
mod details;
#[macro_use]
mod global_state;
#[macro_use]
@@ -63,11 +56,10 @@ mod config;
mod internal_traits;
mod traits;
#[cfg(feature = "boolean")]
mod booleans;
pub mod errors;
#[cfg(feature = "integer")]
mod integers;
/// The tfhe prelude.
pub mod prelude;
pub mod parameters {}

View File

@@ -1,17 +1,11 @@
use crate::high_level_api::prelude::*;
#[cfg(feature = "boolean")]
use crate::high_level_api::FheBool;
#[cfg(any(feature = "boolean", feature = "shortint", feature = "integer"))]
use crate::high_level_api::{generate_keys, ClientKey, ConfigBuilder, PublicKey};
#[cfg(feature = "integer")]
use crate::high_level_api::{FheUint256, FheUint8};
#[cfg(feature = "integer")]
use crate::high_level_api::{
generate_keys, ClientKey, ConfigBuilder, FheBool, FheUint256, FheUint8, PublicKey,
};
use crate::integer::U256;
use crate::{CompactPublicKey, CompressedPublicKey, CompressedServerKey};
#[cfg(any(feature = "boolean", feature = "shortint", feature = "integer"))]
use std::fmt::Debug;
#[cfg(any(feature = "boolean", feature = "shortint", feature = "integer"))]
fn assert_that_public_key_encryption_is_decrypted_by_client_key<FheType, ClearType>(
clear: ClearType,
pks: &PublicKey,
@@ -25,10 +19,9 @@ fn assert_that_public_key_encryption_is_decrypted_by_client_key<FheType, ClearTy
assert_eq!(clear, decrypted);
}
#[cfg(feature = "boolean")]
#[test]
fn test_boolean_public_key() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (cks, _sks) = generate_keys(config);
@@ -40,12 +33,9 @@ fn test_boolean_public_key() {
assert_that_public_key_encryption_is_decrypted_by_client_key::<FheBool, bool>(true, &pks, &cks);
}
#[cfg(feature = "integer")]
#[test]
fn test_integer_public_key() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (cks, _sks) = generate_keys(config);
@@ -54,12 +44,9 @@ fn test_integer_public_key() {
assert_that_public_key_encryption_is_decrypted_by_client_key::<FheUint8, u8>(235, &pks, &cks);
}
#[cfg(feature = "integer")]
#[test]
fn test_small_uint8() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default().build();
let (cks, _sks) = generate_keys(config);
@@ -68,12 +55,9 @@ fn test_small_uint8() {
assert_that_public_key_encryption_is_decrypted_by_client_key::<FheUint8, u8>(235, &pks, &cks);
}
#[cfg(feature = "integer")]
#[test]
fn test_small_uint256() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers_small()
.build();
let config = ConfigBuilder::default().build();
let (cks, _sks) = generate_keys(config);
@@ -87,14 +71,11 @@ fn test_small_uint256() {
);
}
#[cfg(feature = "integer")]
#[test]
fn test_server_key_decompression() -> Result<(), Box<dyn std::error::Error>> {
use crate::set_server_key;
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let cks = ClientKey::generate(config);
let compressed_sks = CompressedServerKey::new(&cks);
@@ -115,15 +96,7 @@ fn test_server_key_decompression() -> Result<(), Box<dyn std::error::Error>> {
#[test]
fn test_with_seed() -> Result<(), Box<dyn std::error::Error>> {
use crate::Seed;
let mut builder = ConfigBuilder::all_disabled();
#[cfg(feature = "integer")]
{
builder = builder.enable_default_integers();
}
#[cfg(feature = "boolean")]
{
builder = builder.enable_default_bool();
}
let builder = ConfigBuilder::default();
let config = builder.build();
let cks1 = ClientKey::generate_with_seed(config.clone(), Seed(125));
@@ -143,23 +116,20 @@ fn test_with_seed() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
#[cfg(feature = "integer")]
#[test]
#[should_panic]
fn test_compressed_server_key_creation_panic_if_function_eval() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.enable_function_evaluation_integers()
let config = ConfigBuilder::default()
.enable_function_evaluation()
.build();
let cks = ClientKey::generate(config);
let _ = CompressedServerKey::new(&cks);
}
#[cfg(feature = "boolean")]
#[test]
fn test_with_context() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let config = ConfigBuilder::default().build();
let (cks, sks) = generate_keys(config);
@@ -175,7 +145,7 @@ fn test_with_context() {
/// the deserialize and serialize traits are implemented
#[test]
fn test_serialize_deserialize_are_implemented() {
let config = ConfigBuilder::all_disabled().build();
let config = ConfigBuilder::default().build();
fn can_be_deserialized<T: serde::de::DeserializeOwned + serde::Serialize>(object: &T) {
let data = bincode::serialize(object).unwrap();

View File

@@ -10,7 +10,7 @@ use crate::shortint::PublicKey as ShortintPublicKey;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PublicKey {
key: ShortintPublicKey,
pub(crate) key: ShortintPublicKey,
}
impl PublicKey {

View File

@@ -11,26 +11,26 @@ pub struct TfheConfigBuilder(pub(crate) hlapi::ConfigBuilder);
#[wasm_bindgen]
impl TfheConfigBuilder {
#[wasm_bindgen]
pub fn all_disabled() -> Self {
Self(hlapi::ConfigBuilder::all_disabled())
pub fn default() -> Self {
Self(hlapi::ConfigBuilder::default())
}
#[wasm_bindgen]
pub fn enable_default_integers(self) -> Self {
Self(self.0.enable_default_integers())
pub fn default_with_small_encryption() -> Self {
Self(hlapi::ConfigBuilder::default_with_small_encryption())
}
#[wasm_bindgen]
pub fn enable_default_integers_small(self) -> Self {
Self(self.0.enable_default_integers_small())
pub fn default_with_big_encryption() -> Self {
Self(hlapi::ConfigBuilder::default_with_big_encryption())
}
#[wasm_bindgen]
pub fn enable_custom_integers(
pub fn use_custom_parameters(
self,
block_parameters: crate::js_on_wasm_api::shortint::ShortintParameters,
) -> Self {
Self(self.0.enable_custom_integers(block_parameters.0, None))
Self(self.0.use_custom_parameters(block_parameters.0, None))
}
#[wasm_bindgen]

View File

@@ -82,15 +82,8 @@ impl TfhePublicKey {
#[wasm_bindgen]
pub fn new(client_key: &TfheClientKey) -> Result<TfhePublicKey, JsError> {
catch_panic_result(|| {
let uses_big_params = client_key
.0
.integer_key
.block_parameters()
.map(|key| {
key.encryption_key_choice()
== crate::shortint::parameters::EncryptionKeyChoice::Big
})
.unwrap_or(false);
let uses_big_params = client_key.0.key.block_parameters().encryption_key_choice()
== crate::shortint::parameters::EncryptionKeyChoice::Big;
if uses_big_params {
return Err(JsError::new(
"PublicKey using big parameters not compatible wasm",

View File

@@ -53,10 +53,10 @@ pub use js_on_wasm_api::*;
mod test_user_docs;
/// cbindgen:ignore
#[cfg(any(feature = "boolean", feature = "integer"))]
#[cfg(feature = "integer")]
pub(crate) mod high_level_api;
#[cfg(any(feature = "boolean", feature = "integer"))]
#[cfg(feature = "integer")]
pub use high_level_api::*;
/// cbindgen:ignore

View File

@@ -167,9 +167,7 @@ mod test_integer {
#[test]
fn safe_desererialization_ct() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _server_key) = generate_keys(config);
@@ -218,9 +216,7 @@ mod test_integer {
#[test]
fn safe_desererialization_ct_list() {
let config = ConfigBuilder::all_disabled()
.enable_default_integers()
.build();
let config = ConfigBuilder::default().build();
let (client_key, _server_key) = generate_keys(config);

View File

@@ -46,9 +46,7 @@ function append_param_name(bench_results, params_name) {
}
async function compressedPublicKeyTest() {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
.build();
let config = TfheConfigBuilder.default_with_small_encryption().build();
console.time('ClientKey Gen')
let clientKey = TfheClientKey.generate(config);
@@ -77,8 +75,8 @@ async function compressedPublicKeyTest() {
}
async function publicKeyTest() {
let config = TfheConfigBuilder.all_disabled()
.enable_default_integers_small()
let config = TfheConfigBuilder.default()
.use_small_encryption()
.build();
console.time('ClientKey Gen')
@@ -148,16 +146,16 @@ async function compactPublicKeyTest32BitOnConfig(config) {
async function compactPublicKeyTest32BitBig() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compactPublicKeyTest32BitOnConfig(config)
}
async function compactPublicKeyTest32BitSmall() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compactPublicKeyTest32BitOnConfig(config)
}
@@ -220,8 +218,8 @@ async function compactPublicKeyBench32BitOnConfig(config) {
async function compactPublicKeyBench32BitBig() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
return append_param_name(
await compactPublicKeyBench32BitOnConfig(config),
@@ -231,8 +229,8 @@ async function compactPublicKeyBench32BitBig() {
async function compactPublicKeyBench32BitSmall() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
return append_param_name(
await compactPublicKeyBench32BitOnConfig(config),
@@ -286,16 +284,16 @@ async function compactPublicKeyTest256BitOnConfig(config) {
async function compactPublicKeyTest256BitBig() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compactPublicKeyTest256BitOnConfig(config)
}
async function compactPublicKeyTest256BitSmall() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compactPublicKeyTest256BitOnConfig(config)
}
@@ -351,16 +349,16 @@ async function compressedCompactPublicKeyTest256BitOnConfig(config) {
async function compressedCompactPublicKeyTest256BitBig() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compressedCompactPublicKeyTest256BitOnConfig(config)
}
async function compressedCompactPublicKeyTest256BitSmall() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
await compressedCompactPublicKeyTest256BitOnConfig(config)
}
@@ -423,8 +421,8 @@ async function compactPublicKeyBench256BitOnConfig(config) {
async function compactPublicKeyBench256BitBig() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_KS_PBS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
return append_param_name(
await compactPublicKeyBench256BitOnConfig(config),
@@ -434,8 +432,8 @@ async function compactPublicKeyBench256BitBig() {
async function compactPublicKeyBench256BitSmall() {
const block_params = new ShortintParameters(ShortintParametersName.PARAM_MESSAGE_2_CARRY_2_COMPACT_PK_PBS_KS);
let config = TfheConfigBuilder.all_disabled()
.enable_custom_integers(block_params)
let config = TfheConfigBuilder.default()
.use_custom_parameters(block_params)
.build();
return append_param_name(
await compactPublicKeyBench256BitOnConfig(config),