Skip to content

Instantly share code, notes, and snippets.

@jumbojets
Last active February 17, 2023 23:34
Show Gist options
  • Save jumbojets/1a5e45b6da58c41524e17ed8f7080955 to your computer and use it in GitHub Desktop.
Save jumbojets/1a5e45b6da58c41524e17ed8f7080955 to your computer and use it in GitHub Desktop.
tfhe-rs execution context example
use tfhe::shortint::{gen_keys, Parameters, context::{ExecutionContext, OperationFlavor}};
let (client_key, server_key) = gen_key(Parameters::default());
let msg1 = 1;
let msg2 = 0;
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let ct_3 = ExecutionContext::new(&server_key, OperationFlavor::Unchecked).execute(|| ct_1 + ct_2);
let output = client_key.decrypt(&ct_3);
assert_eq!(output, 1);
use tfhe::shortint::{gen_keys, Parameters, context::{self, ExecutionContext, OperationFlavor}};
let (_client_key, server_key) = gen_key(Parameters::default());
ExecutionContext::new(&server_key, OperationFlavor::Unchecked)
.execute(|| {
assert_eq!(&server_key, context::server_key());
assert_eq!(OperationFlavor::Unchecked, context::operation_flavor());
});
// context::server_key(); // would probably panic outside of an `ExecutionContext`
impl Add<Ciphertext> for Ciphertext {
type Output = Ciphertext;
fn add(self, rhs: Self) -> Self::Output {
let server_key = context::server_key();
match context::operation_flavor() {
OperationFlavor::Unchecked => server_key.unchecked_add(&self, &rhs),
// would have to panic instead. caller could either `catch_unwind` or call
// `ServerKey::checked_add` from within context manually
OperationFlavor::Checked => server_key.checked_add(&self, &rhs)
.expect("failed checked_add from within execution context"),
OperationFlavor::Smart => server_key.smart_add(&self, &rhs),
}
}
}
@jumbojets
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment